PageRenderTime 76ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/outputrenderers.php

http://github.com/moodle/moodle
PHP | 5233 lines | 2800 code | 543 blank | 1890 comment | 574 complexity | c161263a7273691547007b21380ca2c9 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Classes for rendering HTML output for Moodle.
  18. *
  19. * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
  20. * for an overview.
  21. *
  22. * Included in this file are the primary renderer classes:
  23. * - renderer_base: The renderer outline class that all renderers
  24. * should inherit from.
  25. * - core_renderer: The standard HTML renderer.
  26. * - core_renderer_cli: An adaption of the standard renderer for CLI scripts.
  27. * - core_renderer_ajax: An adaption of the standard renderer for AJAX scripts.
  28. * - plugin_renderer_base: A renderer class that should be extended by all
  29. * plugin renderers.
  30. *
  31. * @package core
  32. * @category output
  33. * @copyright 2009 Tim Hunt
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. */
  36. defined('MOODLE_INTERNAL') || die();
  37. /**
  38. * Simple base class for Moodle renderers.
  39. *
  40. * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
  41. *
  42. * Also has methods to facilitate generating HTML output.
  43. *
  44. * @copyright 2009 Tim Hunt
  45. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  46. * @since Moodle 2.0
  47. * @package core
  48. * @category output
  49. */
  50. class renderer_base {
  51. /**
  52. * @var xhtml_container_stack The xhtml_container_stack to use.
  53. */
  54. protected $opencontainers;
  55. /**
  56. * @var moodle_page The Moodle page the renderer has been created to assist with.
  57. */
  58. protected $page;
  59. /**
  60. * @var string The requested rendering target.
  61. */
  62. protected $target;
  63. /**
  64. * @var Mustache_Engine $mustache The mustache template compiler
  65. */
  66. private $mustache;
  67. /**
  68. * Return an instance of the mustache class.
  69. *
  70. * @since 2.9
  71. * @return Mustache_Engine
  72. */
  73. protected function get_mustache() {
  74. global $CFG;
  75. if ($this->mustache === null) {
  76. require_once("{$CFG->libdir}/filelib.php");
  77. $themename = $this->page->theme->name;
  78. $themerev = theme_get_revision();
  79. // Create new localcache directory.
  80. $cachedir = make_localcache_directory("mustache/$themerev/$themename");
  81. // Remove old localcache directories.
  82. $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
  83. foreach ($mustachecachedirs as $localcachedir) {
  84. $cachedrev = [];
  85. preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
  86. $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
  87. if ($cachedrev > 0 && $cachedrev < $themerev) {
  88. fulldelete($localcachedir);
  89. }
  90. }
  91. $loader = new \core\output\mustache_filesystem_loader();
  92. $stringhelper = new \core\output\mustache_string_helper();
  93. $quotehelper = new \core\output\mustache_quote_helper();
  94. $jshelper = new \core\output\mustache_javascript_helper($this->page);
  95. $pixhelper = new \core\output\mustache_pix_helper($this);
  96. $shortentexthelper = new \core\output\mustache_shorten_text_helper();
  97. $userdatehelper = new \core\output\mustache_user_date_helper();
  98. // We only expose the variables that are exposed to JS templates.
  99. $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
  100. $helpers = array('config' => $safeconfig,
  101. 'str' => array($stringhelper, 'str'),
  102. 'quote' => array($quotehelper, 'quote'),
  103. 'js' => array($jshelper, 'help'),
  104. 'pix' => array($pixhelper, 'pix'),
  105. 'shortentext' => array($shortentexthelper, 'shorten'),
  106. 'userdate' => array($userdatehelper, 'transform'),
  107. );
  108. $this->mustache = new \core\output\mustache_engine(array(
  109. 'cache' => $cachedir,
  110. 'escape' => 's',
  111. 'loader' => $loader,
  112. 'helpers' => $helpers,
  113. 'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
  114. // Don't allow the JavaScript helper to be executed from within another
  115. // helper. If it's allowed it can be used by users to inject malicious
  116. // JS into the page.
  117. 'blacklistednestedhelpers' => ['js']));
  118. }
  119. return $this->mustache;
  120. }
  121. /**
  122. * Constructor
  123. *
  124. * The constructor takes two arguments. The first is the page that the renderer
  125. * has been created to assist with, and the second is the target.
  126. * The target is an additional identifier that can be used to load different
  127. * renderers for different options.
  128. *
  129. * @param moodle_page $page the page we are doing output for.
  130. * @param string $target one of rendering target constants
  131. */
  132. public function __construct(moodle_page $page, $target) {
  133. $this->opencontainers = $page->opencontainers;
  134. $this->page = $page;
  135. $this->target = $target;
  136. }
  137. /**
  138. * Renders a template by name with the given context.
  139. *
  140. * The provided data needs to be array/stdClass made up of only simple types.
  141. * Simple types are array,stdClass,bool,int,float,string
  142. *
  143. * @since 2.9
  144. * @param array|stdClass $context Context containing data for the template.
  145. * @return string|boolean
  146. */
  147. public function render_from_template($templatename, $context) {
  148. static $templatecache = array();
  149. $mustache = $this->get_mustache();
  150. try {
  151. // Grab a copy of the existing helper to be restored later.
  152. $uniqidhelper = $mustache->getHelper('uniqid');
  153. } catch (Mustache_Exception_UnknownHelperException $e) {
  154. // Helper doesn't exist.
  155. $uniqidhelper = null;
  156. }
  157. // Provide 1 random value that will not change within a template
  158. // but will be different from template to template. This is useful for
  159. // e.g. aria attributes that only work with id attributes and must be
  160. // unique in a page.
  161. $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
  162. if (isset($templatecache[$templatename])) {
  163. $template = $templatecache[$templatename];
  164. } else {
  165. try {
  166. $template = $mustache->loadTemplate($templatename);
  167. $templatecache[$templatename] = $template;
  168. } catch (Mustache_Exception_UnknownTemplateException $e) {
  169. throw new moodle_exception('Unknown template: ' . $templatename);
  170. }
  171. }
  172. $renderedtemplate = trim($template->render($context));
  173. // If we had an existing uniqid helper then we need to restore it to allow
  174. // handle nested calls of render_from_template.
  175. if ($uniqidhelper) {
  176. $mustache->addHelper('uniqid', $uniqidhelper);
  177. }
  178. return $renderedtemplate;
  179. }
  180. /**
  181. * Returns rendered widget.
  182. *
  183. * The provided widget needs to be an object that extends the renderable
  184. * interface.
  185. * If will then be rendered by a method based upon the classname for the widget.
  186. * For instance a widget of class `crazywidget` will be rendered by a protected
  187. * render_crazywidget method of this renderer.
  188. * If no render_crazywidget method exists and crazywidget implements templatable,
  189. * look for the 'crazywidget' template in the same component and render that.
  190. *
  191. * @param renderable $widget instance with renderable interface
  192. * @return string
  193. */
  194. public function render(renderable $widget) {
  195. $classparts = explode('\\', get_class($widget));
  196. // Strip namespaces.
  197. $classname = array_pop($classparts);
  198. // Remove _renderable suffixes
  199. $classname = preg_replace('/_renderable$/', '', $classname);
  200. $rendermethod = 'render_'.$classname;
  201. if (method_exists($this, $rendermethod)) {
  202. return $this->$rendermethod($widget);
  203. }
  204. if ($widget instanceof templatable) {
  205. $component = array_shift($classparts);
  206. if (!$component) {
  207. $component = 'core';
  208. }
  209. $template = $component . '/' . $classname;
  210. $context = $widget->export_for_template($this);
  211. return $this->render_from_template($template, $context);
  212. }
  213. throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
  214. }
  215. /**
  216. * Adds a JS action for the element with the provided id.
  217. *
  218. * This method adds a JS event for the provided component action to the page
  219. * and then returns the id that the event has been attached to.
  220. * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
  221. *
  222. * @param component_action $action
  223. * @param string $id
  224. * @return string id of element, either original submitted or random new if not supplied
  225. */
  226. public function add_action_handler(component_action $action, $id = null) {
  227. if (!$id) {
  228. $id = html_writer::random_id($action->event);
  229. }
  230. $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
  231. return $id;
  232. }
  233. /**
  234. * Returns true is output has already started, and false if not.
  235. *
  236. * @return boolean true if the header has been printed.
  237. */
  238. public function has_started() {
  239. return $this->page->state >= moodle_page::STATE_IN_BODY;
  240. }
  241. /**
  242. * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
  243. *
  244. * @param mixed $classes Space-separated string or array of classes
  245. * @return string HTML class attribute value
  246. */
  247. public static function prepare_classes($classes) {
  248. if (is_array($classes)) {
  249. return implode(' ', array_unique($classes));
  250. }
  251. return $classes;
  252. }
  253. /**
  254. * Return the direct URL for an image from the pix folder.
  255. *
  256. * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
  257. *
  258. * @deprecated since Moodle 3.3
  259. * @param string $imagename the name of the icon.
  260. * @param string $component specification of one plugin like in get_string()
  261. * @return moodle_url
  262. */
  263. public function pix_url($imagename, $component = 'moodle') {
  264. debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
  265. return $this->page->theme->image_url($imagename, $component);
  266. }
  267. /**
  268. * Return the moodle_url for an image.
  269. *
  270. * The exact image location and extension is determined
  271. * automatically by searching for gif|png|jpg|jpeg, please
  272. * note there can not be diferent images with the different
  273. * extension. The imagename is for historical reasons
  274. * a relative path name, it may be changed later for core
  275. * images. It is recommended to not use subdirectories
  276. * in plugin and theme pix directories.
  277. *
  278. * There are three types of images:
  279. * 1/ theme images - stored in theme/mytheme/pix/,
  280. * use component 'theme'
  281. * 2/ core images - stored in /pix/,
  282. * overridden via theme/mytheme/pix_core/
  283. * 3/ plugin images - stored in mod/mymodule/pix,
  284. * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
  285. * example: image_url('comment', 'mod_glossary')
  286. *
  287. * @param string $imagename the pathname of the image
  288. * @param string $component full plugin name (aka component) or 'theme'
  289. * @return moodle_url
  290. */
  291. public function image_url($imagename, $component = 'moodle') {
  292. return $this->page->theme->image_url($imagename, $component);
  293. }
  294. /**
  295. * Return the site's logo URL, if any.
  296. *
  297. * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
  298. * @param int $maxheight The maximum height, or null when the maximum height does not matter.
  299. * @return moodle_url|false
  300. */
  301. public function get_logo_url($maxwidth = null, $maxheight = 200) {
  302. global $CFG;
  303. $logo = get_config('core_admin', 'logo');
  304. if (empty($logo)) {
  305. return false;
  306. }
  307. // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
  308. // It's not worth the overhead of detecting and serving 2 different images based on the device.
  309. // Hide the requested size in the file path.
  310. $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
  311. // Use $CFG->themerev to prevent browser caching when the file changes.
  312. return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
  313. theme_get_revision(), $logo);
  314. }
  315. /**
  316. * Return the site's compact logo URL, if any.
  317. *
  318. * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
  319. * @param int $maxheight The maximum height, or null when the maximum height does not matter.
  320. * @return moodle_url|false
  321. */
  322. public function get_compact_logo_url($maxwidth = 100, $maxheight = 100) {
  323. global $CFG;
  324. $logo = get_config('core_admin', 'logocompact');
  325. if (empty($logo)) {
  326. return false;
  327. }
  328. // Hide the requested size in the file path.
  329. $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
  330. // Use $CFG->themerev to prevent browser caching when the file changes.
  331. return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
  332. theme_get_revision(), $logo);
  333. }
  334. /**
  335. * Whether we should display the logo in the navbar.
  336. *
  337. * We will when there are no main logos, and we have compact logo.
  338. *
  339. * @return bool
  340. */
  341. public function should_display_navbar_logo() {
  342. $logo = $this->get_compact_logo_url();
  343. return !empty($logo) && !$this->should_display_main_logo();
  344. }
  345. /**
  346. * Whether we should display the main logo.
  347. *
  348. * @param int $headinglevel The heading level we want to check against.
  349. * @return bool
  350. */
  351. public function should_display_main_logo($headinglevel = 1) {
  352. // Only render the logo if we're on the front page or login page and the we have a logo.
  353. $logo = $this->get_logo_url();
  354. if ($headinglevel == 1 && !empty($logo)) {
  355. if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
  356. return true;
  357. }
  358. }
  359. return false;
  360. }
  361. }
  362. /**
  363. * Basis for all plugin renderers.
  364. *
  365. * @copyright Petr Skoda (skodak)
  366. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  367. * @since Moodle 2.0
  368. * @package core
  369. * @category output
  370. */
  371. class plugin_renderer_base extends renderer_base {
  372. /**
  373. * @var renderer_base|core_renderer A reference to the current renderer.
  374. * The renderer provided here will be determined by the page but will in 90%
  375. * of cases by the {@link core_renderer}
  376. */
  377. protected $output;
  378. /**
  379. * Constructor method, calls the parent constructor
  380. *
  381. * @param moodle_page $page
  382. * @param string $target one of rendering target constants
  383. */
  384. public function __construct(moodle_page $page, $target) {
  385. if (empty($target) && $page->pagelayout === 'maintenance') {
  386. // If the page is using the maintenance layout then we're going to force the target to maintenance.
  387. // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
  388. // unavailable for this page layout.
  389. $target = RENDERER_TARGET_MAINTENANCE;
  390. }
  391. $this->output = $page->get_renderer('core', null, $target);
  392. parent::__construct($page, $target);
  393. }
  394. /**
  395. * Renders the provided widget and returns the HTML to display it.
  396. *
  397. * @param renderable $widget instance with renderable interface
  398. * @return string
  399. */
  400. public function render(renderable $widget) {
  401. $classname = get_class($widget);
  402. // Strip namespaces.
  403. $classname = preg_replace('/^.*\\\/', '', $classname);
  404. // Keep a copy at this point, we may need to look for a deprecated method.
  405. $deprecatedmethod = 'render_'.$classname;
  406. // Remove _renderable suffixes
  407. $classname = preg_replace('/_renderable$/', '', $classname);
  408. $rendermethod = 'render_'.$classname;
  409. if (method_exists($this, $rendermethod)) {
  410. return $this->$rendermethod($widget);
  411. }
  412. if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
  413. // This is exactly where we don't want to be.
  414. // If you have arrived here you have a renderable component within your plugin that has the name
  415. // blah_renderable, and you have a render method render_blah_renderable on your plugin.
  416. // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
  417. // and the _renderable suffix now gets removed when looking for a render method.
  418. // You need to change your renderers render_blah_renderable to render_blah.
  419. // Until you do this it will not be possible for a theme to override the renderer to override your method.
  420. // Please do it ASAP.
  421. static $debugged = array();
  422. if (!isset($debugged[$deprecatedmethod])) {
  423. debugging(sprintf('Deprecated call. Please rename your renderables render method from %s to %s.',
  424. $deprecatedmethod, $rendermethod), DEBUG_DEVELOPER);
  425. $debugged[$deprecatedmethod] = true;
  426. }
  427. return $this->$deprecatedmethod($widget);
  428. }
  429. // pass to core renderer if method not found here
  430. return $this->output->render($widget);
  431. }
  432. /**
  433. * Magic method used to pass calls otherwise meant for the standard renderer
  434. * to it to ensure we don't go causing unnecessary grief.
  435. *
  436. * @param string $method
  437. * @param array $arguments
  438. * @return mixed
  439. */
  440. public function __call($method, $arguments) {
  441. if (method_exists('renderer_base', $method)) {
  442. throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
  443. }
  444. if (method_exists($this->output, $method)) {
  445. return call_user_func_array(array($this->output, $method), $arguments);
  446. } else {
  447. throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
  448. }
  449. }
  450. }
  451. /**
  452. * The standard implementation of the core_renderer interface.
  453. *
  454. * @copyright 2009 Tim Hunt
  455. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  456. * @since Moodle 2.0
  457. * @package core
  458. * @category output
  459. */
  460. class core_renderer extends renderer_base {
  461. /**
  462. * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
  463. * in layout files instead.
  464. * @deprecated
  465. * @var string used in {@link core_renderer::header()}.
  466. */
  467. const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
  468. /**
  469. * @var string Used to pass information from {@link core_renderer::doctype()} to
  470. * {@link core_renderer::standard_head_html()}.
  471. */
  472. protected $contenttype;
  473. /**
  474. * @var string Used by {@link core_renderer::redirect_message()} method to communicate
  475. * with {@link core_renderer::header()}.
  476. */
  477. protected $metarefreshtag = '';
  478. /**
  479. * @var string Unique token for the closing HTML
  480. */
  481. protected $unique_end_html_token;
  482. /**
  483. * @var string Unique token for performance information
  484. */
  485. protected $unique_performance_info_token;
  486. /**
  487. * @var string Unique token for the main content.
  488. */
  489. protected $unique_main_content_token;
  490. /** @var custom_menu_item language The language menu if created */
  491. protected $language = null;
  492. /**
  493. * Constructor
  494. *
  495. * @param moodle_page $page the page we are doing output for.
  496. * @param string $target one of rendering target constants
  497. */
  498. public function __construct(moodle_page $page, $target) {
  499. $this->opencontainers = $page->opencontainers;
  500. $this->page = $page;
  501. $this->target = $target;
  502. $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
  503. $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
  504. $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
  505. }
  506. /**
  507. * Get the DOCTYPE declaration that should be used with this page. Designed to
  508. * be called in theme layout.php files.
  509. *
  510. * @return string the DOCTYPE declaration that should be used.
  511. */
  512. public function doctype() {
  513. if ($this->page->theme->doctype === 'html5') {
  514. $this->contenttype = 'text/html; charset=utf-8';
  515. return "<!DOCTYPE html>\n";
  516. } else if ($this->page->theme->doctype === 'xhtml5') {
  517. $this->contenttype = 'application/xhtml+xml; charset=utf-8';
  518. return "<!DOCTYPE html>\n";
  519. } else {
  520. // legacy xhtml 1.0
  521. $this->contenttype = 'text/html; charset=utf-8';
  522. return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
  523. }
  524. }
  525. /**
  526. * The attributes that should be added to the <html> tag. Designed to
  527. * be called in theme layout.php files.
  528. *
  529. * @return string HTML fragment.
  530. */
  531. public function htmlattributes() {
  532. $return = get_html_lang(true);
  533. $attributes = array();
  534. if ($this->page->theme->doctype !== 'html5') {
  535. $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
  536. }
  537. // Give plugins an opportunity to add things like xml namespaces to the html element.
  538. // This function should return an array of html attribute names => values.
  539. $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
  540. foreach ($pluginswithfunction as $plugins) {
  541. foreach ($plugins as $function) {
  542. $newattrs = $function();
  543. unset($newattrs['dir']);
  544. unset($newattrs['lang']);
  545. unset($newattrs['xmlns']);
  546. unset($newattrs['xml:lang']);
  547. $attributes += $newattrs;
  548. }
  549. }
  550. foreach ($attributes as $key => $val) {
  551. $val = s($val);
  552. $return .= " $key=\"$val\"";
  553. }
  554. return $return;
  555. }
  556. /**
  557. * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
  558. * that should be included in the <head> tag. Designed to be called in theme
  559. * layout.php files.
  560. *
  561. * @return string HTML fragment.
  562. */
  563. public function standard_head_html() {
  564. global $CFG, $SESSION, $SITE;
  565. // Before we output any content, we need to ensure that certain
  566. // page components are set up.
  567. // Blocks must be set up early as they may require javascript which
  568. // has to be included in the page header before output is created.
  569. foreach ($this->page->blocks->get_regions() as $region) {
  570. $this->page->blocks->ensure_content_created($region, $this);
  571. }
  572. $output = '';
  573. // Give plugins an opportunity to add any head elements. The callback
  574. // must always return a string containing valid html head content.
  575. $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
  576. foreach ($pluginswithfunction as $plugins) {
  577. foreach ($plugins as $function) {
  578. $output .= $function();
  579. }
  580. }
  581. // Allow a url_rewrite plugin to setup any dynamic head content.
  582. if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
  583. $class = $CFG->urlrewriteclass;
  584. $output .= $class::html_head_setup();
  585. }
  586. $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
  587. $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
  588. // This is only set by the {@link redirect()} method
  589. $output .= $this->metarefreshtag;
  590. // Check if a periodic refresh delay has been set and make sure we arn't
  591. // already meta refreshing
  592. if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
  593. $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
  594. }
  595. // Set up help link popups for all links with the helptooltip class
  596. $this->page->requires->js_init_call('M.util.help_popups.setup');
  597. $focus = $this->page->focuscontrol;
  598. if (!empty($focus)) {
  599. if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
  600. // This is a horrifically bad way to handle focus but it is passed in
  601. // through messy formslib::moodleform
  602. $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
  603. } else if (strpos($focus, '.')!==false) {
  604. // Old style of focus, bad way to do it
  605. debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
  606. $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
  607. } else {
  608. // Focus element with given id
  609. $this->page->requires->js_function_call('focuscontrol', array($focus));
  610. }
  611. }
  612. // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
  613. // any other custom CSS can not be overridden via themes and is highly discouraged
  614. $urls = $this->page->theme->css_urls($this->page);
  615. foreach ($urls as $url) {
  616. $this->page->requires->css_theme($url);
  617. }
  618. // Get the theme javascript head and footer
  619. if ($jsurl = $this->page->theme->javascript_url(true)) {
  620. $this->page->requires->js($jsurl, true);
  621. }
  622. if ($jsurl = $this->page->theme->javascript_url(false)) {
  623. $this->page->requires->js($jsurl);
  624. }
  625. // Get any HTML from the page_requirements_manager.
  626. $output .= $this->page->requires->get_head_code($this->page, $this);
  627. // List alternate versions.
  628. foreach ($this->page->alternateversions as $type => $alt) {
  629. $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
  630. 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
  631. }
  632. // Add noindex tag if relevant page and setting applied.
  633. $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
  634. $loginpages = array('login-index', 'login-signup');
  635. if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
  636. if (!isset($CFG->additionalhtmlhead)) {
  637. $CFG->additionalhtmlhead = '';
  638. }
  639. $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
  640. }
  641. if (!empty($CFG->additionalhtmlhead)) {
  642. $output .= "\n".$CFG->additionalhtmlhead;
  643. }
  644. if ($this->page->pagelayout == 'frontpage') {
  645. $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
  646. if (!empty($summary)) {
  647. $output .= "<meta name=\"description\" content=\"$summary\" />\n";
  648. }
  649. }
  650. return $output;
  651. }
  652. /**
  653. * The standard tags (typically skip links) that should be output just inside
  654. * the start of the <body> tag. Designed to be called in theme layout.php files.
  655. *
  656. * @return string HTML fragment.
  657. */
  658. public function standard_top_of_body_html() {
  659. global $CFG;
  660. $output = $this->page->requires->get_top_of_body_code($this);
  661. if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
  662. $output .= "\n".$CFG->additionalhtmltopofbody;
  663. }
  664. // Give subsystems an opportunity to inject extra html content. The callback
  665. // must always return a string containing valid html.
  666. foreach (\core_component::get_core_subsystems() as $name => $path) {
  667. if ($path) {
  668. $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
  669. }
  670. }
  671. // Give plugins an opportunity to inject extra html content. The callback
  672. // must always return a string containing valid html.
  673. $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
  674. foreach ($pluginswithfunction as $plugins) {
  675. foreach ($plugins as $function) {
  676. $output .= $function();
  677. }
  678. }
  679. $output .= $this->maintenance_warning();
  680. return $output;
  681. }
  682. /**
  683. * Scheduled maintenance warning message.
  684. *
  685. * Note: This is a nasty hack to display maintenance notice, this should be moved
  686. * to some general notification area once we have it.
  687. *
  688. * @return string
  689. */
  690. public function maintenance_warning() {
  691. global $CFG;
  692. $output = '';
  693. if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
  694. $timeleft = $CFG->maintenance_later - time();
  695. // If timeleft less than 30 sec, set the class on block to error to highlight.
  696. $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
  697. $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-a-1 alert');
  698. $a = new stdClass();
  699. $a->hour = (int)($timeleft / 3600);
  700. $a->min = (int)(($timeleft / 60) % 60);
  701. $a->sec = (int)($timeleft % 60);
  702. if ($a->hour > 0) {
  703. $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
  704. } else {
  705. $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
  706. }
  707. $output .= $this->box_end();
  708. $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
  709. array(array('timeleftinsec' => $timeleft)));
  710. $this->page->requires->strings_for_js(
  711. array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
  712. 'admin');
  713. }
  714. return $output;
  715. }
  716. /**
  717. * The standard tags (typically performance information and validation links,
  718. * if we are in developer debug mode) that should be output in the footer area
  719. * of the page. Designed to be called in theme layout.php files.
  720. *
  721. * @return string HTML fragment.
  722. */
  723. public function standard_footer_html() {
  724. global $CFG, $SCRIPT;
  725. $output = '';
  726. if (during_initial_install()) {
  727. // Debugging info can not work before install is finished,
  728. // in any case we do not want any links during installation!
  729. return $output;
  730. }
  731. // Give plugins an opportunity to add any footer elements.
  732. // The callback must always return a string containing valid html footer content.
  733. $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
  734. foreach ($pluginswithfunction as $plugins) {
  735. foreach ($plugins as $function) {
  736. $output .= $function();
  737. }
  738. }
  739. // This function is normally called from a layout.php file in {@link core_renderer::header()}
  740. // but some of the content won't be known until later, so we return a placeholder
  741. // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
  742. $output .= $this->unique_performance_info_token;
  743. if ($this->page->devicetypeinuse == 'legacy') {
  744. // The legacy theme is in use print the notification
  745. $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
  746. }
  747. // Get links to switch device types (only shown for users not on a default device)
  748. $output .= $this->theme_switch_links();
  749. if (!empty($CFG->debugpageinfo)) {
  750. $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
  751. $this->page->debug_summary()) . '</div>';
  752. }
  753. if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
  754. // Add link to profiling report if necessary
  755. if (function_exists('profiling_is_running') && profiling_is_running()) {
  756. $txt = get_string('profiledscript', 'admin');
  757. $title = get_string('profiledscriptview', 'admin');
  758. $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
  759. $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
  760. $output .= '<div class="profilingfooter">' . $link . '</div>';
  761. }
  762. $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
  763. 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
  764. $output .= '<div class="purgecaches">' .
  765. html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
  766. }
  767. if (!empty($CFG->debugvalidators)) {
  768. // NOTE: this is not a nice hack, $this->page->url is not always accurate and
  769. // $FULLME neither, it is not a bug if it fails. --skodak.
  770. $output .= '<div class="validators"><ul class="list-unstyled ml-1">
  771. <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
  772. <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
  773. <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&amp;warnp2n3e=1&amp;url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
  774. </ul></div>';
  775. }
  776. return $output;
  777. }
  778. /**
  779. * Returns standard main content placeholder.
  780. * Designed to be called in theme layout.php files.
  781. *
  782. * @return string HTML fragment.
  783. */
  784. public function main_content() {
  785. // This is here because it is the only place we can inject the "main" role over the entire main content area
  786. // without requiring all theme's to manually do it, and without creating yet another thing people need to
  787. // remember in the theme.
  788. // This is an unfortunate hack. DO NO EVER add anything more here.
  789. // DO NOT add classes.
  790. // DO NOT add an id.
  791. return '<div role="main">'.$this->unique_main_content_token.'</div>';
  792. }
  793. /**
  794. * Returns standard navigation between activities in a course.
  795. *
  796. * @return string the navigation HTML.
  797. */
  798. public function activity_navigation() {
  799. // First we should check if we want to add navigation.
  800. $context = $this->page->context;
  801. if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
  802. || $context->contextlevel != CONTEXT_MODULE) {
  803. return '';
  804. }
  805. // If the activity is in stealth mode, show no links.
  806. if ($this->page->cm->is_stealth()) {
  807. return '';
  808. }
  809. // Get a list of all the activities in the course.
  810. $course = $this->page->cm->get_course();
  811. $modules = get_fast_modinfo($course->id)->get_cms();
  812. // Put the modules into an array in order by the position they are shown in the course.
  813. $mods = [];
  814. $activitylist = [];
  815. foreach ($modules as $module) {
  816. // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
  817. if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
  818. continue;
  819. }
  820. $mods[$module->id] = $module;
  821. // No need to add the current module to the list for the activity dropdown menu.
  822. if ($module->id == $this->page->cm->id) {
  823. continue;
  824. }
  825. // Module name.
  826. $modname = $module->get_formatted_name();
  827. // Display the hidden text if necessary.
  828. if (!$module->visible) {
  829. $modname .= ' ' . get_string('hiddenwithbrackets');
  830. }
  831. // Module URL.
  832. $linkurl = new moodle_url($module->url, array('forceview' => 1));
  833. // Add module URL (as key) and name (as value) to the activity list array.
  834. $activitylist[$linkurl->out(false)] = $modname;
  835. }
  836. $nummods = count($mods);
  837. // If there is only one mod then do nothing.
  838. if ($nummods == 1) {
  839. return '';
  840. }
  841. // Get an array of just the course module ids used to get the cmid value based on their position in the course.
  842. $modids = array_keys($mods);
  843. // Get the position in the array of the course module we are viewing.
  844. $position = array_search($this->page->cm->id, $modids);
  845. $prevmod = null;
  846. $nextmod = null;
  847. // Check if we have a previous mod to show.
  848. if ($position > 0) {
  849. $prevmod = $mods[$modids[$position - 1]];
  850. }
  851. // Check if we have a next mod to show.
  852. if ($position < ($nummods - 1)) {
  853. $nextmod = $mods[$modids[$position + 1]];
  854. }
  855. $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
  856. $renderer = $this->page->get_renderer('core', 'course');
  857. return $renderer->render($activitynav);
  858. }
  859. /**
  860. * The standard tags (typically script tags that are not needed earlier) that
  861. * should be output after everything else. Designed to be called in theme layout.php files.
  862. *
  863. * @return string HTML fragment.
  864. */
  865. public function standard_end_of_body_html() {
  866. global $CFG;
  867. // This function is normally called from a layout.php file in {@link core_renderer::header()}
  868. // but some of the content won't be known until later, so we return a placeholder
  869. // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
  870. $output = '';
  871. if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
  872. $output .= "\n".$CFG->additionalhtmlfooter;
  873. }
  874. $output .= $this->unique_end_html_token;
  875. return $output;
  876. }
  877. /**
  878. * The standard HTML that should be output just before the <footer> tag.
  879. * Designed to be called in theme layout.php files.
  880. *
  881. * @return string HTML fragment.
  882. */
  883. public function standard_after_main_region_html() {
  884. global $CFG;
  885. $output = '';
  886. if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
  887. $output .= "\n".$CFG->additionalhtmlbottomofbody;
  888. }
  889. // Give subsystems an opportunity to inject extra html content. The callback
  890. // must always return a string containing valid html.
  891. foreach (\core_component::get_core_subsystems() as $name => $path) {
  892. if ($path) {
  893. $output .= component_callback($name, 'standard_after_main_region_html', [], '');
  894. }
  895. }
  896. // Give plugins an opportunity to inject extra html content. The callback
  897. // must always return a string containing valid html.
  898. $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
  899. foreach ($pluginswithfunction as $plugins) {
  900. foreach ($plugins as $function) {
  901. $output .= $function();
  902. }
  903. }
  904. return $output;
  905. }
  906. /**
  907. * Return the standard string that says whether you are logged in (and switched
  908. * roles/logged in as another user).
  909. * @param bool $withlinks if false, then don't include any links in the HTML produced.
  910. * If not set, the default is the nologinlinks option from the theme config.php file,
  911. * and if that is not set, then links are included.
  912. * @return string HTML fragment.
  913. */
  914. public function login_info($withlinks = null) {
  915. global $USER, $CFG, $DB, $SESSION;
  916. if (during_initial_install()) {
  917. return '';
  918. }
  919. if (is_null($withlinks)) {
  920. $withlinks = empty($this->page->layout_options['nologinlinks']);
  921. }
  922. $course = $this->page->course;
  923. if (\core\session\manager::is_loggedinas()) {
  924. $realuser = \core\session\manager::get_realuser();
  925. $fullname = fullname($realuser, true);
  926. if ($withlinks) {
  927. $loginastitle = get_string('loginas');
  928. $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
  929. $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
  930. } else {
  931. $realuserinfo = " [$fullname] ";
  932. }
  933. } else {
  934. $realuserinfo = '';
  935. }
  936. $loginpage = $this->is_login_page();
  937. $loginurl = get_login_url();
  938. if (empty($course->id)) {
  939. // $course->id is not defined during installation
  940. return '';
  941. } else if (isloggedin()) {
  942. $context = context_course::instance($course->id);
  943. $fullname = fullname($USER, true);
  944. // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
  945. if ($withlinks) {
  946. $linktitle = get_string('viewprofile');
  947. $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
  948. } else {
  949. $username = $fullname;
  950. }
  951. if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
  952. if ($withlinks) {
  953. $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
  954. } else {
  955. $username .= " from {$idprovider->name}";
  956. }
  957. }
  958. if (isguestuser()) {
  959. $loggedinas = $realuserinfo.get_string('loggedinasguest');
  960. if (!$loginpage && $withlinks) {
  961. $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
  962. }
  963. } else if (is_role_switched($course->id)) { // Has switched roles
  964. $rolename = '';
  965. if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
  966. $rolename = ': '.role_get_name($role, $context);
  967. }
  968. $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
  969. if ($withlinks) {
  970. $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
  971. $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
  972. }
  973. } else {
  974. $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
  975. if ($withlinks) {
  976. $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
  977. }
  978. }
  979. } else {
  980. $loggedinas = get_string('loggedinnot', 'moodle');
  981. if (!$loginpage && $withlinks) {
  982. $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
  983. }
  984. }
  985. $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
  986. if (isset($SESSION->justloggedin)) {
  987. unset($SESSION->justloggedin);
  988. if (!empty($CFG->displayloginfailures)) {
  989. if (!isguestuser()) {
  990. // Include this file only when required.
  991. require_once($CFG->dirroot . '/user/lib.php');
  992. if ($count = user_count_login_failures($USER)) {
  993. $loggedinas .= '<div class="loginfailures">';
  994. $a = new stdClass();
  995. $a->attempts = $count;
  996. $loggedinas .= get_string('failedloginattempts', '', $a);
  997. if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
  998. $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
  999. 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
  1000. }
  1001. $loggedinas .= '</div>';
  1002. }
  1003. }
  1004. }
  1005. }
  1006. return $loggedinas;
  1007. }
  1008. /**
  1009. * Check whether the current page is a login page.
  1010. *
  1011. * @since Moodle 2.9
  1012. * @return bool
  1013. */
  1014. protected function is_login_page() {
  1015. // This is a real bit of a hack, but its a rarety that we need to do something like this.
  1016. // In fact the login pages should be only these two pages and as exposing this as an option for all pages
  1017. // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
  1018. return in_array(
  1019. $this->page->url->out_as_local_url(false, array()),
  1020. array(
  1021. '/login/index.php',
  1022. '/login/forgot_password.php',
  1023. )
  1024. );
  1025. }
  1026. /**
  1027. * Return the 'back' link that normally appears in the footer.
  1028. *
  1029. * @return string HTML fragment.
  1030. */
  1031. public function home_link() {
  1032. global $CFG, $SITE;
  1033. if ($this->page->pagetype == 'site-index') {
  1034. // Special case for site home page - please do not remove
  1035. return '<div class="sitelink">' .
  1036. '<a title="Moodle" href="http://moodle.org/">' .
  1037. '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
  1038. } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
  1039. // Special case for during install/upgrade.
  1040. return '<div class="sitelink">'.
  1041. '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
  1042. '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
  1043. } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
  1044. return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
  1045. get_string('home') . '</a></div>';
  1046. } else {
  1047. return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
  1048. format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
  1049. }
  1050. }
  1051. /**
  1052. * Redirects the user by any means possible given the current state
  1053. *
  1054. * This function should not be called directly, it should always be called using
  1055. * the redirect function in lib/weblib.php
  1056. *
  1057. * The redirect function should really only be called before page output has started
  1058. * however it will allow itself to be called during the state STATE_IN_BODY
  1059. *
  1060. * @param string $encodedurl The URL to send to encoded if required
  1061. * @param string $message The message to display to the user if any
  1062. * @param int $delay The delay before redirecting a user, if $message has been
  1063. * set this is a requirement and defaults to 3, set to 0 no delay
  1064. * @param boolean $debugdisableredirect this redirect has been disabled for
  1065. * debugging purposes. Display a message that explains, and don't
  1066. * trigger the redirect.
  1067. * @param string $messagetype The type of notification to show the message in.
  1068. * See constants on \core\output\notification.
  1069. * @return string The HTML to display to the user before dying, may contain
  1070. * meta refresh, javascript refresh, and may have set header redirects
  1071. */
  1072. public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
  1073. $messagetype = \core\output\notification::NOTIFY_INFO) {
  1074. global $CFG;
  1075. $url = str_replace('&amp;', '&', $encodedurl);
  1076. switch ($this->page->state) {
  1077. case moodle_page::STATE_BEFORE_HEADER :
  1078. // No output yet it is safe to delivery the full arsenal of redirect methods
  1079. if (!$debugdisableredirect) {
  1080. // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
  1081. $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
  1082. $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
  1083. }
  1084. $output = $this->header();
  1085. break;
  1086. case moodle_page::STATE_PRINTING_HEADER :
  1087. // We should hopefully never get here
  1088. throw new coding_exception('You cannot redirect while printing the page header');
  1089. break;
  1090. case moodle_page::STATE_IN_BODY :
  1091. // We really shouldn't be here but we can deal with this
  1092. debugging("You should really redirect before you start page output");
  1093. if (!$debugdisableredirect) {
  1094. $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
  1095. }
  1096. $output = $this->opencontainers->pop_all_but_last();
  1097. break;
  1098. case moodle_page::STATE_DONE :
  1099. // Too late to be calling redirect now
  1100. throw new coding_exception('You cannot redirect after the entire page has been generated');
  1101. break;
  1102. }
  1103. $output .= $this->notification($message, $messagetype);
  1104. $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
  1105. if ($debugdisableredirect) {
  1106. $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
  1107. }
  1108. $output .= $this->footer();
  1109. return $output;
  1110. }
  1111. /**
  1112. * Start output by sending the HTTP headers, and printing the HTML <head>
  1113. * and the start of the <body>.
  1114. *
  1115. * To control what is printed, you should set properties on $PAGE.
  1116. *
  1117. * @return string HTML that you must output this, preferably immediately.
  1118. */
  1119. public function header() {
  1120. global $USER, $CFG, $SESSION;
  1121. // Give plugins an opportunity touch things before the http headers are sent
  1122. // such as adding additional headers. The return value is ignored.
  1123. $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
  1124. foreach ($pluginswithfunction as $plugins) {
  1125. foreach ($plugins as $function) {
  1126. $function();
  1127. }
  1128. }
  1129. if (\core\session\manager::is_loggedinas()) {
  1130. $this->page->add_body_class('userloggedinas');
  1131. }
  1132. if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
  1133. require_once($CFG->dirroot . '/user/lib.php');
  1134. // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
  1135. if ($count = user_count_login_failures($USER, false)) {
  1136. $this->page->add_body_class('loginfailures');
  1137. }
  1138. }
  1139. // If the user is logged in, and we're not in initial install,
  1140. // check to see if the user is role-switched and add the appropriate
  1141. // CSS class to the body element.
  1142. if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
  1143. $this->page->add_body_class('userswitchedrole');
  1144. }
  1145. // Give themes a chance to init/alter the page object.
  1146. $this->page->theme->init_page($this->page);
  1147. $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
  1148. // Find the appropriate page layout file, based on $this->page->pagelayout.
  1149. $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
  1150. // Render the layout using the layout file.
  1151. $rendered = $this->render_page_layout($layoutfile);
  1152. // Slice the rendered output into header and footer.
  1153. $cutpos = strpos($rendered, $this->unique_main_content_token);
  1154. if ($cutpos === false) {
  1155. $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
  1156. $token = self::MAIN_CONTENT_TOKEN;
  1157. } else {
  1158. $token = $this->unique_main_content_token;
  1159. }
  1160. if ($cutpos === false) {
  1161. throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
  1162. }
  1163. $header = substr($rendered, 0, $cutpos);
  1164. $footer = substr($rendered, $cutpos + strlen($token));
  1165. if (empty($this->contenttype)) {
  1166. debugging('The page layout file did not call $OUTPUT->doctype()');
  1167. $header = $this->doctype() . $header;
  1168. }
  1169. // If this theme version is below 2.4 release and this is a course view page
  1170. if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
  1171. $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
  1172. // check if course content header/footer have not been output during render of theme layout
  1173. $coursecontentheader = $this->course_content_header(true);
  1174. $coursecontentfooter = $this->course_content_footer(true);
  1175. if (!empty($coursecontentheader)) {
  1176. // display debug message and add header and footer right above and below main content
  1177. // Please note that course header and footer (to be displayed above and below the whole page)
  1178. // are not displayed in this case at all.
  1179. // Besides the content header and footer are not displayed on any other course page
  1180. debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
  1181. $header .= $coursecontentheader;
  1182. $footer = $coursecontentfooter. $footer;
  1183. }
  1184. }
  1185. send_headers($this->contenttype, $this->page->cacheable);
  1186. $this->opencontainers->push('header/footer', $footer);
  1187. $this->page->set_state(moodle_page::STATE_IN_BODY);
  1188. return $header . $this->skip_link_target('maincontent');
  1189. }
  1190. /**
  1191. * Renders and outputs the page layout file.
  1192. *
  1193. * This is done by preparing the normal globals available to a script, and
  1194. * then including the layout file provided by the current theme for the
  1195. * requested layout.
  1196. *
  1197. * @param string $layoutfile The name of the layout file
  1198. * @return string HTML code
  1199. */
  1200. protected function render_page_layout($layoutfile) {
  1201. global $CFG, $SITE, $USER;
  1202. // The next lines are a bit tricky. The point is, here we are in a method
  1203. // of a renderer class, and this object may, or may not, be the same as
  1204. // the global $OUTPUT object. When rendering the page layout file, we want to use
  1205. // this object. However, people writing Moodle code expect the current
  1206. // renderer to be called $OUTPUT, not $this, so define a variable called
  1207. // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
  1208. $OUTPUT = $this;
  1209. $PAGE = $this->page;
  1210. $COURSE = $this->page->course;
  1211. ob_start();
  1212. include($layoutfile);
  1213. $rendered = ob_get_contents();
  1214. ob_end_clean();
  1215. return $rendered;
  1216. }
  1217. /**
  1218. * Outputs the page's footer
  1219. *
  1220. * @return string HTML fragment
  1221. */
  1222. public function footer() {
  1223. global $CFG, $DB;
  1224. // Give plugins an opportunity to touch the page before JS is finalized.
  1225. $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
  1226. foreach ($pluginswithfunction as $plugins) {
  1227. foreach ($plugins as $function) {
  1228. $function();
  1229. }
  1230. }
  1231. $output = $this->container_end_all(true);
  1232. $footer = $this->opencontainers->pop('header/footer');
  1233. if (debugging() and $DB and $DB->is_transaction_started()) {
  1234. // TODO: MDL-20625 print warning - transaction will be rolled back
  1235. }
  1236. // Provide some performance info if required
  1237. $performanceinfo = '';
  1238. if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
  1239. $perf = get_performance_info();
  1240. if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
  1241. $performanceinfo = $perf['html'];
  1242. }
  1243. }
  1244. // We always want performance data when running a performance test, even if the user is redirected to another page.
  1245. if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
  1246. $footer = $this->unique_performance_info_token . $footer;
  1247. }
  1248. $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
  1249. // Only show notifications when the current page has a context id.
  1250. if (!empty($this->page->context->id)) {
  1251. $this->page->requires->js_call_amd('core/notification', 'init', array(
  1252. $this->page->context->id,
  1253. \core\notification::fetch_as_array($this)
  1254. ));
  1255. }
  1256. $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
  1257. $this->page->set_state(moodle_page::STATE_DONE);
  1258. return $output . $footer;
  1259. }
  1260. /**
  1261. * Close all but the last open container. This is useful in places like error
  1262. * handling, where you want to close all the open containers (apart from <body>)
  1263. * before outputting the error message.
  1264. *
  1265. * @param bool $shouldbenone assert that the stack should be empty now - causes a
  1266. * developer debug warning if it isn't.
  1267. * @return string the HTML required to close any open containers inside <body>.
  1268. */
  1269. public function container_end_all($shouldbenone = false) {
  1270. return $this->opencontainers->pop_all_but_last($shouldbenone);
  1271. }
  1272. /**
  1273. * Returns course-specific information to be output immediately above content on any course page
  1274. * (for the current course)
  1275. *
  1276. * @param bool $onlyifnotcalledbefore output content only if it has not been output before
  1277. * @return string
  1278. */
  1279. public function course_content_header($onlyifnotcalledbefore = false) {
  1280. global $CFG;
  1281. static $functioncalled = false;
  1282. if ($functioncalled && $onlyifnotcalledbefore) {
  1283. // we have already output the content header
  1284. return '';
  1285. }
  1286. // Output any session notification.
  1287. $notifications = \core\notification::fetch();
  1288. $bodynotifications = '';
  1289. foreach ($notifications as $notification) {
  1290. $bodynotifications .= $this->render_from_template(
  1291. $notification->get_template_name(),
  1292. $notification->export_for_template($this)
  1293. );
  1294. }
  1295. $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
  1296. if ($this->page->course->id == SITEID) {
  1297. // return immediately and do not include /course/lib.php if not necessary
  1298. return $output;
  1299. }
  1300. require_once($CFG->dirroot.'/course/lib.php');
  1301. $functioncalled = true;
  1302. $courseformat = course_get_format($this->page->course);
  1303. if (($obj = $courseformat->course_content_header()) !== null) {
  1304. $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
  1305. }
  1306. return $output;
  1307. }
  1308. /**
  1309. * Returns course-specific information to be output immediately below content on any course page
  1310. * (for the current course)
  1311. *
  1312. * @param bool $onlyifnotcalledbefore output content only if it has not been output before
  1313. * @return string
  1314. */
  1315. public function course_content_footer($onlyifnotcalledbefore = false) {
  1316. global $CFG;
  1317. if ($this->page->course->id == SITEID) {
  1318. // return immediately and do not include /course/lib.php if not necessary
  1319. return '';
  1320. }
  1321. static $functioncalled = false;
  1322. if ($functioncalled && $onlyifnotcalledbefore) {
  1323. // we have already output the content footer
  1324. return '';
  1325. }
  1326. $functioncalled = true;
  1327. require_once($CFG->dirroot.'/course/lib.php');
  1328. $courseformat = course_get_format($this->page->course);
  1329. if (($obj = $courseformat->course_content_footer()) !== null) {
  1330. return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
  1331. }
  1332. return '';
  1333. }
  1334. /**
  1335. * Returns course-specific information to be output on any course page in the header area
  1336. * (for the current course)
  1337. *
  1338. * @return string
  1339. */
  1340. public function course_header() {
  1341. global $CFG;
  1342. if ($this->page->course->id == SITEID) {
  1343. // return immediately and do not include /course/lib.php if not necessary
  1344. return '';
  1345. }
  1346. require_once($CFG->dirroot.'/course/lib.php');
  1347. $courseformat = course_get_format($this->page->course);
  1348. if (($obj = $courseformat->course_header()) !== null) {
  1349. return $courseformat->get_renderer($this->page)->render($obj);
  1350. }
  1351. return '';
  1352. }
  1353. /**
  1354. * Returns course-specific information to be output on any course page in the footer area
  1355. * (for the current course)
  1356. *
  1357. * @return string
  1358. */
  1359. public function course_footer() {
  1360. global $CFG;
  1361. if ($this->page->course->id == SITEID) {
  1362. // return immediately and do not include /course/lib.php if not necessary
  1363. return '';
  1364. }
  1365. require_once($CFG->dirroot.'/course/lib.php');
  1366. $courseformat = course_get_format($this->page->course);
  1367. if (($obj = $courseformat->course_footer()) !== null) {
  1368. return $courseformat->get_renderer($this->page)->render($obj);
  1369. }
  1370. return '';
  1371. }
  1372. /**
  1373. * Get the course pattern datauri to show on a course card.
  1374. *
  1375. * The datauri is an encoded svg that can be passed as a url.
  1376. * @param int $id Id to use when generating the pattern
  1377. * @return string datauri
  1378. */
  1379. public function get_generated_image_for_id($id) {
  1380. $color = $this->get_generated_color_for_id($id);
  1381. $pattern = new \core_geopattern();
  1382. $pattern->setColor($color);
  1383. $pattern->patternbyid($id);
  1384. return $pattern->datauri();
  1385. }
  1386. /**
  1387. * Get the course color to show on a course card.
  1388. *
  1389. * @param int $id Id to use when generating the color.
  1390. * @return string hex color code.
  1391. */
  1392. public function get_generated_color_for_id($id) {
  1393. $colornumbers = range(1, 10);
  1394. $basecolors = [];
  1395. foreach ($colornumbers as $number) {
  1396. $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
  1397. }
  1398. $color = $basecolors[$id % 10];
  1399. return $color;
  1400. }
  1401. /**
  1402. * Returns lang menu or '', this method also checks forcing of languages in courses.
  1403. *
  1404. * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
  1405. *
  1406. * @return string The lang menu HTML or empty string
  1407. */
  1408. public function lang_menu() {
  1409. global $CFG;
  1410. if (empty($CFG->langmenu)) {
  1411. return '';
  1412. }
  1413. if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
  1414. // do not show lang menu if language forced
  1415. return '';
  1416. }
  1417. $currlang = current_language();
  1418. $langs = get_string_manager()->get_list_of_translations();
  1419. if (count($langs) < 2) {
  1420. return '';
  1421. }
  1422. $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
  1423. $s->label = get_accesshide(get_string('language'));
  1424. $s->class = 'langmenu';
  1425. return $this->render($s);
  1426. }
  1427. /**
  1428. * Output the row of editing icons for a block, as defined by the controls array.
  1429. *
  1430. * @param array $controls an array like {@link block_contents::$controls}.
  1431. * @param string $blockid The ID given to the block.
  1432. * @return string HTML fragment.
  1433. */
  1434. public function block_controls($actions, $blockid = null) {
  1435. global $CFG;
  1436. if (empty($actions)) {
  1437. return '';
  1438. }
  1439. $menu = new action_menu($actions);
  1440. if ($blockid !== null) {
  1441. $menu->set_owner_selector('#'.$blockid);
  1442. }
  1443. $menu->set_constraint('.block-region');
  1444. $menu->attributes['class'] .= ' block-control-actions commands';
  1445. return $this->render($menu);
  1446. }
  1447. /**
  1448. * Returns the HTML for a basic textarea field.
  1449. *
  1450. * @param string $name Name to use for the textarea element
  1451. * @param string $id The id to use fort he textarea element
  1452. * @param string $value Initial content to display in the textarea
  1453. * @param int $rows Number of rows to display
  1454. * @param int $cols Number of columns to display
  1455. * @return string the HTML to display
  1456. */
  1457. public function print_textarea($name, $id, $value, $rows, $cols) {
  1458. editors_head_setup();
  1459. $editor = editors_get_preferred_editor(FORMAT_HTML);
  1460. $editor->set_text($value);
  1461. $editor->use_editor($id, []);
  1462. $context = [
  1463. 'id' => $id,
  1464. 'name' => $name,
  1465. 'value' => $value,
  1466. 'rows' => $rows,
  1467. 'cols' => $cols
  1468. ];
  1469. return $this->render_from_template('core_form/editor_textarea', $context);
  1470. }
  1471. /**
  1472. * Renders an action menu component.
  1473. *
  1474. * @param action_menu $menu
  1475. * @return string HTML
  1476. */
  1477. public function render_action_menu(action_menu $menu) {
  1478. // We don't want the class icon there!
  1479. foreach ($menu->get_secondary_actions() as $action) {
  1480. if ($action instanceof \action_menu_link && $action->has_class('icon')) {
  1481. $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
  1482. }
  1483. }
  1484. if ($menu->is_empty()) {
  1485. return '';
  1486. }
  1487. $context = $menu->export_for_template($this);
  1488. return $this->render_from_template('core/action_menu', $context);
  1489. }
  1490. /**
  1491. * Renders a Check API result
  1492. *
  1493. * @param result $result
  1494. * @return string HTML fragment
  1495. */
  1496. protected function render_check_result(core\check\result $result) {
  1497. return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
  1498. }
  1499. /**
  1500. * Renders a Check API result
  1501. *
  1502. * @param result $result
  1503. * @return string HTML fragment
  1504. */
  1505. public function check_result(core\check\result $result) {
  1506. return $this->render_check_result($result);
  1507. }
  1508. /**
  1509. * Renders an action_menu_link item.
  1510. *
  1511. * @param action_menu_link $action
  1512. * @return string HTML fragment
  1513. */
  1514. protected function render_action_menu_link(action_menu_link $action) {
  1515. return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
  1516. }
  1517. /**
  1518. * Renders a primary action_menu_filler item.
  1519. *
  1520. * @param action_menu_link_filler $action
  1521. * @return string HTML fragment
  1522. */
  1523. protected function render_action_menu_filler(action_menu_filler $action) {
  1524. return html_writer::span('&nbsp;', 'filler');
  1525. }
  1526. /**
  1527. * Renders a primary action_menu_link item.
  1528. *
  1529. * @param action_menu_link_primary $action
  1530. * @return string HTML fragment
  1531. */
  1532. protected function render_action_menu_link_primary(action_menu_link_primary $action) {
  1533. return $this->render_action_menu_link($action);
  1534. }
  1535. /**
  1536. * Renders a secondary action_menu_link item.
  1537. *
  1538. * @param action_menu_link_secondary $action
  1539. * @return string HTML fragment
  1540. */
  1541. protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
  1542. return $this->render_action_menu_link($action);
  1543. }
  1544. /**
  1545. * Prints a nice side block with an optional header.
  1546. *
  1547. * @param block_contents $bc HTML for the content
  1548. * @param string $region the region the block is appearing in.
  1549. * @return string the HTML to be output.
  1550. */
  1551. public function block(block_contents $bc, $region) {
  1552. $bc = clone($bc); // Avoid messing up the object passed in.
  1553. if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
  1554. $bc->collapsible = block_contents::NOT_HIDEABLE;
  1555. }
  1556. $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
  1557. $context = new stdClass();
  1558. $context->skipid = $bc->skipid;
  1559. $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
  1560. $context->dockable = $bc->dockable;
  1561. $context->id = $id;
  1562. $context->hidden = $bc->collapsible == block_contents::HIDDEN;
  1563. $context->skiptitle = strip_tags($bc->title);
  1564. $context->showskiplink = !empty($context->skiptitle);
  1565. $context->arialabel = $bc->arialabel;
  1566. $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
  1567. $context->class = $bc->attributes['class'];
  1568. $context->type = $bc->attributes['data-block'];
  1569. $context->title = $bc->title;
  1570. $context->content = $bc->content;
  1571. $context->annotation = $bc->annotation;
  1572. $context->footer = $bc->footer;
  1573. $context->hascontrols = !empty($bc->controls);
  1574. if ($context->hascontrols) {
  1575. $context->controls = $this->block_controls($bc->controls, $id);
  1576. }
  1577. return $this->render_from_template('core/block', $context);
  1578. }
  1579. /**
  1580. * Render the contents of a block_list.
  1581. *
  1582. * @param array $icons the icon for each item.
  1583. * @param array $items the content of each item.
  1584. * @return string HTML
  1585. */
  1586. public function list_block_contents($icons, $items) {
  1587. $row = 0;
  1588. $lis = array();
  1589. foreach ($items as $key => $string) {
  1590. $item = html_writer::start_tag('li', array('class' => 'r' . $row));
  1591. if (!empty($icons[$key])) { //test if the content has an assigned icon
  1592. $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
  1593. }
  1594. $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
  1595. $item .= html_writer::end_tag('li');
  1596. $lis[] = $item;
  1597. $row = 1 - $row; // Flip even/odd.
  1598. }
  1599. return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
  1600. }
  1601. /**
  1602. * Output all the blocks in a particular region.
  1603. *
  1604. * @param string $region the name of a region on this page.
  1605. * @return string the HTML to be output.
  1606. */
  1607. public function blocks_for_region($region) {
  1608. $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
  1609. $blocks = $this->page->blocks->get_blocks_for_region($region);
  1610. $lastblock = null;
  1611. $zones = array();
  1612. foreach ($blocks as $block) {
  1613. $zones[] = $block->title;
  1614. }
  1615. $output = '';
  1616. foreach ($blockcontents as $bc) {
  1617. if ($bc instanceof block_contents) {
  1618. $output .= $this->block($bc, $region);
  1619. $lastblock = $bc->title;
  1620. } else if ($bc instanceof block_move_target) {
  1621. $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
  1622. } else {
  1623. throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
  1624. }
  1625. }
  1626. return $output;
  1627. }
  1628. /**
  1629. * Output a place where the block that is currently being moved can be dropped.
  1630. *
  1631. * @param block_move_target $target with the necessary details.
  1632. * @param array $zones array of areas where the block can be moved to
  1633. * @param string $previous the block located before the area currently being rendered.
  1634. * @param string $region the name of the region
  1635. * @return string the HTML to be output.
  1636. */
  1637. public function block_move_target($target, $zones, $previous, $region) {
  1638. if ($previous == null) {
  1639. if (empty($zones)) {
  1640. // There are no zones, probably because there are no blocks.
  1641. $regions = $this->page->theme->get_all_block_regions();
  1642. $position = get_string('moveblockinregion', 'block', $regions[$region]);
  1643. } else {
  1644. $position = get_string('moveblockbefore', 'block', $zones[0]);
  1645. }
  1646. } else {
  1647. $position = get_string('moveblockafter', 'block', $previous);
  1648. }
  1649. return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
  1650. }
  1651. /**
  1652. * Renders a special html link with attached action
  1653. *
  1654. * Theme developers: DO NOT OVERRIDE! Please override function
  1655. * {@link core_renderer::render_action_link()} instead.
  1656. *
  1657. * @param string|moodle_url $url
  1658. * @param string $text HTML fragment
  1659. * @param component_action $action
  1660. * @param array $attributes associative array of html link attributes + disabled
  1661. * @param pix_icon optional pix icon to render with the link
  1662. * @return string HTML fragment
  1663. */
  1664. public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
  1665. if (!($url instanceof moodle_url)) {
  1666. $url = new moodle_url($url);
  1667. }
  1668. $link = new action_link($url, $text, $action, $attributes, $icon);
  1669. return $this->render($link);
  1670. }
  1671. /**
  1672. * Renders an action_link object.
  1673. *
  1674. * The provided link is renderer and the HTML returned. At the same time the
  1675. * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
  1676. *
  1677. * @param action_link $link
  1678. * @return string HTML fragment
  1679. */
  1680. protected function render_action_link(action_link $link) {
  1681. return $this->render_from_template('core/action_link', $link->export_for_template($this));
  1682. }
  1683. /**
  1684. * Renders an action_icon.
  1685. *
  1686. * This function uses the {@link core_renderer::action_link()} method for the
  1687. * most part. What it does different is prepare the icon as HTML and use it
  1688. * as the link text.
  1689. *
  1690. * Theme developers: If you want to change how action links and/or icons are rendered,
  1691. * consider overriding function {@link core_renderer::render_action_link()} and
  1692. * {@link core_renderer::render_pix_icon()}.
  1693. *
  1694. * @param string|moodle_url $url A string URL or moodel_url
  1695. * @param pix_icon $pixicon
  1696. * @param component_action $action
  1697. * @param array $attributes associative array of html link attributes + disabled
  1698. * @param bool $linktext show title next to image in link
  1699. * @return string HTML fragment
  1700. */
  1701. public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
  1702. if (!($url instanceof moodle_url)) {
  1703. $url = new moodle_url($url);
  1704. }
  1705. $attributes = (array)$attributes;
  1706. if (empty($attributes['class'])) {
  1707. // let ppl override the class via $options
  1708. $attributes['class'] = 'action-icon';
  1709. }
  1710. $icon = $this->render($pixicon);
  1711. if ($linktext) {
  1712. $text = $pixicon->attributes['alt'];
  1713. } else {
  1714. $text = '';
  1715. }
  1716. return $this->action_link($url, $text.$icon, $action, $attributes);
  1717. }
  1718. /**
  1719. * Print a message along with button choices for Continue/Cancel
  1720. *
  1721. * If a string or moodle_url is given instead of a single_button, method defaults to post.
  1722. *
  1723. * @param string $message The question to ask the user
  1724. * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
  1725. * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
  1726. * @return string HTML fragment
  1727. */
  1728. public function confirm($message, $continue, $cancel) {
  1729. if ($continue instanceof single_button) {
  1730. // ok
  1731. $continue->primary = true;
  1732. } else if (is_string($continue)) {
  1733. $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
  1734. } else if ($continue instanceof moodle_url) {
  1735. $continue = new single_button($continue, get_string('continue'), 'post', true);
  1736. } else {
  1737. throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
  1738. }
  1739. if ($cancel instanceof single_button) {
  1740. // ok
  1741. } else if (is_string($cancel)) {
  1742. $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
  1743. } else if ($cancel instanceof moodle_url) {
  1744. $cancel = new single_button($cancel, get_string('cancel'), 'get');
  1745. } else {
  1746. throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
  1747. }
  1748. $attributes = [
  1749. 'role'=>'alertdialog',
  1750. 'aria-labelledby'=>'modal-header',
  1751. 'aria-describedby'=>'modal-body',
  1752. 'aria-modal'=>'true'
  1753. ];
  1754. $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
  1755. $output .= $this->box_start('modal-content', 'modal-content');
  1756. $output .= $this->box_start('modal-header p-x-1', 'modal-header');
  1757. $output .= html_writer::tag('h4', get_string('confirm'));
  1758. $output .= $this->box_end();
  1759. $attributes = [
  1760. 'role'=>'alert',
  1761. 'data-aria-autofocus'=>'true'
  1762. ];
  1763. $output .= $this->box_start('modal-body', 'modal-body', $attributes);
  1764. $output .= html_writer::tag('p', $message);
  1765. $output .= $this->box_end();
  1766. $output .= $this->box_start('modal-footer', 'modal-footer');
  1767. $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
  1768. $output .= $this->box_end();
  1769. $output .= $this->box_end();
  1770. $output .= $this->box_end();
  1771. return $output;
  1772. }
  1773. /**
  1774. * Returns a form with a single button.
  1775. *
  1776. * Theme developers: DO NOT OVERRIDE! Please override function
  1777. * {@link core_renderer::render_single_button()} instead.
  1778. *
  1779. * @param string|moodle_url $url
  1780. * @param string $label button text
  1781. * @param string $method get or post submit method
  1782. * @param array $options associative array {disabled, title, etc.}
  1783. * @return string HTML fragment
  1784. */
  1785. public function single_button($url, $label, $method='post', array $options=null) {
  1786. if (!($url instanceof moodle_url)) {
  1787. $url = new moodle_url($url);
  1788. }
  1789. $button = new single_button($url, $label, $method);
  1790. foreach ((array)$options as $key=>$value) {
  1791. if (property_exists($button, $key)) {
  1792. $button->$key = $value;
  1793. } else {
  1794. $button->set_attribute($key, $value);
  1795. }
  1796. }
  1797. return $this->render($button);
  1798. }
  1799. /**
  1800. * Renders a single button widget.
  1801. *
  1802. * This will return HTML to display a form containing a single button.
  1803. *
  1804. * @param single_button $button
  1805. * @return string HTML fragment
  1806. */
  1807. protected function render_single_button(single_button $button) {
  1808. return $this->render_from_template('core/single_button', $button->export_for_template($this));
  1809. }
  1810. /**
  1811. * Returns a form with a single select widget.
  1812. *
  1813. * Theme developers: DO NOT OVERRIDE! Please override function
  1814. * {@link core_renderer::render_single_select()} instead.
  1815. *
  1816. * @param moodle_url $url form action target, includes hidden fields
  1817. * @param string $name name of selection field - the changing parameter in url
  1818. * @param array $options list of options
  1819. * @param string $selected selected element
  1820. * @param array $nothing
  1821. * @param string $formid
  1822. * @param array $attributes other attributes for the single select
  1823. * @return string HTML fragment
  1824. */
  1825. public function single_select($url, $name, array $options, $selected = '',
  1826. $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
  1827. if (!($url instanceof moodle_url)) {
  1828. $url = new moodle_url($url);
  1829. }
  1830. $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
  1831. if (array_key_exists('label', $attributes)) {
  1832. $select->set_label($attributes['label']);
  1833. unset($attributes['label']);
  1834. }
  1835. $select->attributes = $attributes;
  1836. return $this->render($select);
  1837. }
  1838. /**
  1839. * Returns a dataformat selection and download form
  1840. *
  1841. * @param string $label A text label
  1842. * @param moodle_url|string $base The download page url
  1843. * @param string $name The query param which will hold the type of the download
  1844. * @param array $params Extra params sent to the download page
  1845. * @return string HTML fragment
  1846. */
  1847. public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
  1848. $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
  1849. $options = array();
  1850. foreach ($formats as $format) {
  1851. if ($format->is_enabled()) {
  1852. $options[] = array(
  1853. 'value' => $format->name,
  1854. 'label' => get_string('dataformat', $format->component),
  1855. );
  1856. }
  1857. }
  1858. $hiddenparams = array();
  1859. foreach ($params as $key => $value) {
  1860. $hiddenparams[] = array(
  1861. 'name' => $key,
  1862. 'value' => $value,
  1863. );
  1864. }
  1865. $data = array(
  1866. 'label' => $label,
  1867. 'base' => $base,
  1868. 'name' => $name,
  1869. 'params' => $hiddenparams,
  1870. 'options' => $options,
  1871. 'sesskey' => sesskey(),
  1872. 'submit' => get_string('download'),
  1873. );
  1874. return $this->render_from_template('core/dataformat_selector', $data);
  1875. }
  1876. /**
  1877. * Internal implementation of single_select rendering
  1878. *
  1879. * @param single_select $select
  1880. * @return string HTML fragment
  1881. */
  1882. protected function render_single_select(single_select $select) {
  1883. return $this->render_from_template('core/single_select', $select->export_for_template($this));
  1884. }
  1885. /**
  1886. * Returns a form with a url select widget.
  1887. *
  1888. * Theme developers: DO NOT OVERRIDE! Please override function
  1889. * {@link core_renderer::render_url_select()} instead.
  1890. *
  1891. * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
  1892. * @param string $selected selected element
  1893. * @param array $nothing
  1894. * @param string $formid
  1895. * @return string HTML fragment
  1896. */
  1897. public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
  1898. $select = new url_select($urls, $selected, $nothing, $formid);
  1899. return $this->render($select);
  1900. }
  1901. /**
  1902. * Internal implementation of url_select rendering
  1903. *
  1904. * @param url_select $select
  1905. * @return string HTML fragment
  1906. */
  1907. protected function render_url_select(url_select $select) {
  1908. return $this->render_from_template('core/url_select', $select->export_for_template($this));
  1909. }
  1910. /**
  1911. * Returns a string containing a link to the user documentation.
  1912. * Also contains an icon by default. Shown to teachers and admin only.
  1913. *
  1914. * @param string $path The page link after doc root and language, no leading slash.
  1915. * @param string $text The text to be displayed for the link
  1916. * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
  1917. * @param array $attributes htm attributes
  1918. * @return string
  1919. */
  1920. public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
  1921. global $CFG;
  1922. $icon = $this->pix_icon('docs', '', 'moodle', array('class'=>'iconhelp icon-pre', 'role'=>'presentation'));
  1923. $attributes['href'] = new moodle_url(get_docs_url($path));
  1924. if (!empty($CFG->doctonewwindow) || $forcepopup) {
  1925. $attributes['class'] = 'helplinkpopup';
  1926. }
  1927. return html_writer::tag('a', $icon.$text, $attributes);
  1928. }
  1929. /**
  1930. * Return HTML for an image_icon.
  1931. *
  1932. * Theme developers: DO NOT OVERRIDE! Please override function
  1933. * {@link core_renderer::render_image_icon()} instead.
  1934. *
  1935. * @param string $pix short pix name
  1936. * @param string $alt mandatory alt attribute
  1937. * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
  1938. * @param array $attributes htm attributes
  1939. * @return string HTML fragment
  1940. */
  1941. public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
  1942. $icon = new image_icon($pix, $alt, $component, $attributes);
  1943. return $this->render($icon);
  1944. }
  1945. /**
  1946. * Renders a pix_icon widget and returns the HTML to display it.
  1947. *
  1948. * @param image_icon $icon
  1949. * @return string HTML fragment
  1950. */
  1951. protected function render_image_icon(image_icon $icon) {
  1952. $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
  1953. return $system->render_pix_icon($this, $icon);
  1954. }
  1955. /**
  1956. * Return HTML for a pix_icon.
  1957. *
  1958. * Theme developers: DO NOT OVERRIDE! Please override function
  1959. * {@link core_renderer::render_pix_icon()} instead.
  1960. *
  1961. * @param string $pix short pix name
  1962. * @param string $alt mandatory alt attribute
  1963. * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
  1964. * @param array $attributes htm lattributes
  1965. * @return string HTML fragment
  1966. */
  1967. public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
  1968. $icon = new pix_icon($pix, $alt, $component, $attributes);
  1969. return $this->render($icon);
  1970. }
  1971. /**
  1972. * Renders a pix_icon widget and returns the HTML to display it.
  1973. *
  1974. * @param pix_icon $icon
  1975. * @return string HTML fragment
  1976. */
  1977. protected function render_pix_icon(pix_icon $icon) {
  1978. $system = \core\output\icon_system::instance();
  1979. return $system->render_pix_icon($this, $icon);
  1980. }
  1981. /**
  1982. * Return HTML to display an emoticon icon.
  1983. *
  1984. * @param pix_emoticon $emoticon
  1985. * @return string HTML fragment
  1986. */
  1987. protected function render_pix_emoticon(pix_emoticon $emoticon) {
  1988. $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
  1989. return $system->render_pix_icon($this, $emoticon);
  1990. }
  1991. /**
  1992. * Produces the html that represents this rating in the UI
  1993. *
  1994. * @param rating $rating the page object on which this rating will appear
  1995. * @return string
  1996. */
  1997. function render_rating(rating $rating) {
  1998. global $CFG, $USER;
  1999. if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
  2000. return null;//ratings are turned off
  2001. }
  2002. $ratingmanager = new rating_manager();
  2003. // Initialise the JavaScript so ratings can be done by AJAX.
  2004. $ratingmanager->initialise_rating_javascript($this->page);
  2005. $strrate = get_string("rate", "rating");
  2006. $ratinghtml = ''; //the string we'll return
  2007. // permissions check - can they view the aggregate?
  2008. if ($rating->user_can_view_aggregate()) {
  2009. $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
  2010. $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
  2011. $aggregatestr = $rating->get_aggregate_string();
  2012. $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
  2013. if ($rating->count > 0) {
  2014. $countstr = "({$rating->count})";
  2015. } else {
  2016. $countstr = '-';
  2017. }
  2018. $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
  2019. if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
  2020. $nonpopuplink = $rating->get_view_ratings_url();
  2021. $popuplink = $rating->get_view_ratings_url(true);
  2022. $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
  2023. $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
  2024. }
  2025. $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
  2026. }
  2027. $formstart = null;
  2028. // if the item doesn't belong to the current user, the user has permission to rate
  2029. // and we're within the assessable period
  2030. if ($rating->user_can_rate()) {
  2031. $rateurl = $rating->get_rate_url();
  2032. $inputs = $rateurl->params();
  2033. //start the rating form
  2034. $formattrs = array(
  2035. 'id' => "postrating{$rating->itemid}",
  2036. 'class' => 'postratingform',
  2037. 'method' => 'post',
  2038. 'action' => $rateurl->out_omit_querystring()
  2039. );
  2040. $formstart = html_writer::start_tag('form', $formattrs);
  2041. $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
  2042. // add the hidden inputs
  2043. foreach ($inputs as $name => $value) {
  2044. $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
  2045. $formstart .= html_writer::empty_tag('input', $attributes);
  2046. }
  2047. if (empty($ratinghtml)) {
  2048. $ratinghtml .= $strrate.': ';
  2049. }
  2050. $ratinghtml = $formstart.$ratinghtml;
  2051. $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
  2052. $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
  2053. $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
  2054. $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
  2055. //output submit button
  2056. $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
  2057. $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
  2058. $ratinghtml .= html_writer::empty_tag('input', $attributes);
  2059. if (!$rating->settings->scale->isnumeric) {
  2060. // If a global scale, try to find current course ID from the context
  2061. if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
  2062. $courseid = $coursecontext->instanceid;
  2063. } else {
  2064. $courseid = $rating->settings->scale->courseid;
  2065. }
  2066. $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
  2067. }
  2068. $ratinghtml .= html_writer::end_tag('span');
  2069. $ratinghtml .= html_writer::end_tag('div');
  2070. $ratinghtml .= html_writer::end_tag('form');
  2071. }
  2072. return $ratinghtml;
  2073. }
  2074. /**
  2075. * Centered heading with attached help button (same title text)
  2076. * and optional icon attached.
  2077. *
  2078. * @param string $text A heading text
  2079. * @param string $helpidentifier The keyword that defines a help page
  2080. * @param string $component component name
  2081. * @param string|moodle_url $icon
  2082. * @param string $iconalt icon alt text
  2083. * @param int $level The level of importance of the heading. Defaulting to 2
  2084. * @param string $classnames A space-separated list of CSS classes. Defaulting to null
  2085. * @return string HTML fragment
  2086. */
  2087. public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
  2088. $image = '';
  2089. if ($icon) {
  2090. $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
  2091. }
  2092. $help = '';
  2093. if ($helpidentifier) {
  2094. $help = $this->help_icon($helpidentifier, $component);
  2095. }
  2096. return $this->heading($image.$text.$help, $level, $classnames);
  2097. }
  2098. /**
  2099. * Returns HTML to display a help icon.
  2100. *
  2101. * @deprecated since Moodle 2.0
  2102. */
  2103. public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
  2104. throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
  2105. }
  2106. /**
  2107. * Returns HTML to display a help icon.
  2108. *
  2109. * Theme developers: DO NOT OVERRIDE! Please override function
  2110. * {@link core_renderer::render_help_icon()} instead.
  2111. *
  2112. * @param string $identifier The keyword that defines a help page
  2113. * @param string $component component name
  2114. * @param string|bool $linktext true means use $title as link text, string means link text value
  2115. * @return string HTML fragment
  2116. */
  2117. public function help_icon($identifier, $component = 'moodle', $linktext = '') {
  2118. $icon = new help_icon($identifier, $component);
  2119. $icon->diag_strings();
  2120. if ($linktext === true) {
  2121. $icon->linktext = get_string($icon->identifier, $icon->component);
  2122. } else if (!empty($linktext)) {
  2123. $icon->linktext = $linktext;
  2124. }
  2125. return $this->render($icon);
  2126. }
  2127. /**
  2128. * Implementation of user image rendering.
  2129. *
  2130. * @param help_icon $helpicon A help icon instance
  2131. * @return string HTML fragment
  2132. */
  2133. protected function render_help_icon(help_icon $helpicon) {
  2134. $context = $helpicon->export_for_template($this);
  2135. return $this->render_from_template('core/help_icon', $context);
  2136. }
  2137. /**
  2138. * Returns HTML to display a scale help icon.
  2139. *
  2140. * @param int $courseid
  2141. * @param stdClass $scale instance
  2142. * @return string HTML fragment
  2143. */
  2144. public function help_icon_scale($courseid, stdClass $scale) {
  2145. global $CFG;
  2146. $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
  2147. $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
  2148. $scaleid = abs($scale->id);
  2149. $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
  2150. $action = new popup_action('click', $link, 'ratingscale');
  2151. return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
  2152. }
  2153. /**
  2154. * Creates and returns a spacer image with optional line break.
  2155. *
  2156. * @param array $attributes Any HTML attributes to add to the spaced.
  2157. * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
  2158. * laxy do it with CSS which is a much better solution.
  2159. * @return string HTML fragment
  2160. */
  2161. public function spacer(array $attributes = null, $br = false) {
  2162. $attributes = (array)$attributes;
  2163. if (empty($attributes['width'])) {
  2164. $attributes['width'] = 1;
  2165. }
  2166. if (empty($attributes['height'])) {
  2167. $attributes['height'] = 1;
  2168. }
  2169. $attributes['class'] = 'spacer';
  2170. $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
  2171. if (!empty($br)) {
  2172. $output .= '<br />';
  2173. }
  2174. return $output;
  2175. }
  2176. /**
  2177. * Returns HTML to display the specified user's avatar.
  2178. *
  2179. * User avatar may be obtained in two ways:
  2180. * <pre>
  2181. * // Option 1: (shortcut for simple cases, preferred way)
  2182. * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
  2183. * $OUTPUT->user_picture($user, array('popup'=>true));
  2184. *
  2185. * // Option 2:
  2186. * $userpic = new user_picture($user);
  2187. * // Set properties of $userpic
  2188. * $userpic->popup = true;
  2189. * $OUTPUT->render($userpic);
  2190. * </pre>
  2191. *
  2192. * Theme developers: DO NOT OVERRIDE! Please override function
  2193. * {@link core_renderer::render_user_picture()} instead.
  2194. *
  2195. * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
  2196. * If any of these are missing, the database is queried. Avoid this
  2197. * if at all possible, particularly for reports. It is very bad for performance.
  2198. * @param array $options associative array with user picture options, used only if not a user_picture object,
  2199. * options are:
  2200. * - courseid=$this->page->course->id (course id of user profile in link)
  2201. * - size=35 (size of image)
  2202. * - link=true (make image clickable - the link leads to user profile)
  2203. * - popup=false (open in popup)
  2204. * - alttext=true (add image alt attribute)
  2205. * - class = image class attribute (default 'userpicture')
  2206. * - visibletoscreenreaders=true (whether to be visible to screen readers)
  2207. * - includefullname=false (whether to include the user's full name together with the user picture)
  2208. * - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
  2209. * @return string HTML fragment
  2210. */
  2211. public function user_picture(stdClass $user, array $options = null) {
  2212. $userpicture = new user_picture($user);
  2213. foreach ((array)$options as $key=>$value) {
  2214. if (property_exists($userpicture, $key)) {
  2215. $userpicture->$key = $value;
  2216. }
  2217. }
  2218. return $this->render($userpicture);
  2219. }
  2220. /**
  2221. * Internal implementation of user image rendering.
  2222. *
  2223. * @param user_picture $userpicture
  2224. * @return string
  2225. */
  2226. protected function render_user_picture(user_picture $userpicture) {
  2227. global $CFG, $DB;
  2228. $user = $userpicture->user;
  2229. $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
  2230. if ($userpicture->alttext) {
  2231. if (!empty($user->imagealt)) {
  2232. $alt = $user->imagealt;
  2233. } else {
  2234. $alt = get_string('pictureof', '', fullname($user, $canviewfullnames));
  2235. }
  2236. } else {
  2237. $alt = '';
  2238. }
  2239. if (empty($userpicture->size)) {
  2240. $size = 35;
  2241. } else if ($userpicture->size === true or $userpicture->size == 1) {
  2242. $size = 100;
  2243. } else {
  2244. $size = $userpicture->size;
  2245. }
  2246. $class = $userpicture->class;
  2247. if ($user->picture == 0) {
  2248. $class .= ' defaultuserpic';
  2249. }
  2250. $src = $userpicture->get_url($this->page, $this);
  2251. $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
  2252. if (!$userpicture->visibletoscreenreaders) {
  2253. $alt = '';
  2254. $attributes['aria-hidden'] = 'true';
  2255. }
  2256. if (!empty($alt)) {
  2257. $attributes['alt'] = $alt;
  2258. $attributes['title'] = $alt;
  2259. }
  2260. // get the image html output fisrt
  2261. $output = html_writer::empty_tag('img', $attributes);
  2262. // Show fullname together with the picture when desired.
  2263. if ($userpicture->includefullname) {
  2264. $output .= fullname($userpicture->user, $canviewfullnames);
  2265. }
  2266. // then wrap it in link if needed
  2267. if (!$userpicture->link) {
  2268. return $output;
  2269. }
  2270. if (empty($userpicture->courseid)) {
  2271. $courseid = $this->page->course->id;
  2272. } else {
  2273. $courseid = $userpicture->courseid;
  2274. }
  2275. if ($courseid == SITEID) {
  2276. $url = new moodle_url('/user/profile.php', array('id' => $user->id));
  2277. } else {
  2278. $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
  2279. }
  2280. $attributes = array('href'=>$url);
  2281. if (!$userpicture->visibletoscreenreaders) {
  2282. $attributes['tabindex'] = '-1';
  2283. $attributes['aria-hidden'] = 'true';
  2284. }
  2285. if ($userpicture->popup) {
  2286. $id = html_writer::random_id('userpicture');
  2287. $attributes['id'] = $id;
  2288. $this->add_action_handler(new popup_action('click', $url), $id);
  2289. }
  2290. return html_writer::tag('a', $output, $attributes);
  2291. }
  2292. /**
  2293. * Internal implementation of file tree viewer items rendering.
  2294. *
  2295. * @param array $dir
  2296. * @return string
  2297. */
  2298. public function htmllize_file_tree($dir) {
  2299. if (empty($dir['subdirs']) and empty($dir['files'])) {
  2300. return '';
  2301. }
  2302. $result = '<ul>';
  2303. foreach ($dir['subdirs'] as $subdir) {
  2304. $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
  2305. }
  2306. foreach ($dir['files'] as $file) {
  2307. $filename = $file->get_filename();
  2308. $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
  2309. }
  2310. $result .= '</ul>';
  2311. return $result;
  2312. }
  2313. /**
  2314. * Returns HTML to display the file picker
  2315. *
  2316. * <pre>
  2317. * $OUTPUT->file_picker($options);
  2318. * </pre>
  2319. *
  2320. * Theme developers: DO NOT OVERRIDE! Please override function
  2321. * {@link core_renderer::render_file_picker()} instead.
  2322. *
  2323. * @param array $options associative array with file manager options
  2324. * options are:
  2325. * maxbytes=>-1,
  2326. * itemid=>0,
  2327. * client_id=>uniqid(),
  2328. * acepted_types=>'*',
  2329. * return_types=>FILE_INTERNAL,
  2330. * context=>current page context
  2331. * @return string HTML fragment
  2332. */
  2333. public function file_picker($options) {
  2334. $fp = new file_picker($options);
  2335. return $this->render($fp);
  2336. }
  2337. /**
  2338. * Internal implementation of file picker rendering.
  2339. *
  2340. * @param file_picker $fp
  2341. * @return string
  2342. */
  2343. public function render_file_picker(file_picker $fp) {
  2344. $options = $fp->options;
  2345. $client_id = $options->client_id;
  2346. $strsaved = get_string('filesaved', 'repository');
  2347. $straddfile = get_string('openpicker', 'repository');
  2348. $strloading = get_string('loading', 'repository');
  2349. $strdndenabled = get_string('dndenabled_inbox', 'moodle');
  2350. $strdroptoupload = get_string('droptoupload', 'moodle');
  2351. $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
  2352. $currentfile = $options->currentfile;
  2353. if (empty($currentfile)) {
  2354. $currentfile = '';
  2355. } else {
  2356. $currentfile .= ' - ';
  2357. }
  2358. if ($options->maxbytes) {
  2359. $size = $options->maxbytes;
  2360. } else {
  2361. $size = get_max_upload_file_size();
  2362. }
  2363. if ($size == -1) {
  2364. $maxsize = '';
  2365. } else {
  2366. $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
  2367. }
  2368. if ($options->buttonname) {
  2369. $buttonname = ' name="' . $options->buttonname . '"';
  2370. } else {
  2371. $buttonname = '';
  2372. }
  2373. $html = <<<EOD
  2374. <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
  2375. $iconprogress
  2376. </div>
  2377. <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
  2378. <div>
  2379. <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
  2380. <span> $maxsize </span>
  2381. </div>
  2382. EOD;
  2383. if ($options->env != 'url') {
  2384. $html .= <<<EOD
  2385. <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist border" style="position: relative">
  2386. <div class="filepicker-filename">
  2387. <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
  2388. <div class="dndupload-progressbars"></div>
  2389. </div>
  2390. <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
  2391. </div>
  2392. EOD;
  2393. }
  2394. $html .= '</div>';
  2395. return $html;
  2396. }
  2397. /**
  2398. * @deprecated since Moodle 3.2
  2399. */
  2400. public function update_module_button() {
  2401. throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
  2402. 'modules should not add the edit module button, the link is already available in the Administration block. ' .
  2403. 'Themes can choose to display the link in the buttons row consistently for all module types.');
  2404. }
  2405. /**
  2406. * Returns HTML to display a "Turn editing on/off" button in a form.
  2407. *
  2408. * @param moodle_url $url The URL + params to send through when clicking the button
  2409. * @return string HTML the button
  2410. */
  2411. public function edit_button(moodle_url $url) {
  2412. $url->param('sesskey', sesskey());
  2413. if ($this->page->user_is_editing()) {
  2414. $url->param('edit', 'off');
  2415. $editstring = get_string('turneditingoff');
  2416. } else {
  2417. $url->param('edit', 'on');
  2418. $editstring = get_string('turneditingon');
  2419. }
  2420. return $this->single_button($url, $editstring);
  2421. }
  2422. /**
  2423. * Returns HTML to display a simple button to close a window
  2424. *
  2425. * @param string $text The lang string for the button's label (already output from get_string())
  2426. * @return string html fragment
  2427. */
  2428. public function close_window_button($text='') {
  2429. if (empty($text)) {
  2430. $text = get_string('closewindow');
  2431. }
  2432. $button = new single_button(new moodle_url('#'), $text, 'get');
  2433. $button->add_action(new component_action('click', 'close_window'));
  2434. return $this->container($this->render($button), 'closewindow');
  2435. }
  2436. /**
  2437. * Output an error message. By default wraps the error message in <span class="error">.
  2438. * If the error message is blank, nothing is output.
  2439. *
  2440. * @param string $message the error message.
  2441. * @return string the HTML to output.
  2442. */
  2443. public function error_text($message) {
  2444. if (empty($message)) {
  2445. return '';
  2446. }
  2447. $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
  2448. return html_writer::tag('span', $message, array('class' => 'error'));
  2449. }
  2450. /**
  2451. * Do not call this function directly.
  2452. *
  2453. * To terminate the current script with a fatal error, call the {@link print_error}
  2454. * function, or throw an exception. Doing either of those things will then call this
  2455. * function to display the error, before terminating the execution.
  2456. *
  2457. * @param string $message The message to output
  2458. * @param string $moreinfourl URL where more info can be found about the error
  2459. * @param string $link Link for the Continue button
  2460. * @param array $backtrace The execution backtrace
  2461. * @param string $debuginfo Debugging information
  2462. * @return string the HTML to output.
  2463. */
  2464. public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
  2465. global $CFG;
  2466. $output = '';
  2467. $obbuffer = '';
  2468. if ($this->has_started()) {
  2469. // we can not always recover properly here, we have problems with output buffering,
  2470. // html tables, etc.
  2471. $output .= $this->opencontainers->pop_all_but_last();
  2472. } else {
  2473. // It is really bad if library code throws exception when output buffering is on,
  2474. // because the buffered text would be printed before our start of page.
  2475. // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
  2476. error_reporting(0); // disable notices from gzip compression, etc.
  2477. while (ob_get_level() > 0) {
  2478. $buff = ob_get_clean();
  2479. if ($buff === false) {
  2480. break;
  2481. }
  2482. $obbuffer .= $buff;
  2483. }
  2484. error_reporting($CFG->debug);
  2485. // Output not yet started.
  2486. $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
  2487. if (empty($_SERVER['HTTP_RANGE'])) {
  2488. @header($protocol . ' 404 Not Found');
  2489. } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
  2490. // Coax iOS 10 into sending the session cookie.
  2491. @header($protocol . ' 403 Forbidden');
  2492. } else {
  2493. // Must stop byteserving attempts somehow,
  2494. // this is weird but Chrome PDF viewer can be stopped only with 407!
  2495. @header($protocol . ' 407 Proxy Authentication Required');
  2496. }
  2497. $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
  2498. $this->page->set_url('/'); // no url
  2499. //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
  2500. $this->page->set_title(get_string('error'));
  2501. $this->page->set_heading($this->page->course->fullname);
  2502. $output .= $this->header();
  2503. }
  2504. $message = '<p class="errormessage">' . s($message) . '</p>'.
  2505. '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
  2506. get_string('moreinformation') . '</a></p>';
  2507. if (empty($CFG->rolesactive)) {
  2508. $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
  2509. //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation.
  2510. }
  2511. $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
  2512. if ($CFG->debugdeveloper) {
  2513. $labelsep = get_string('labelsep', 'langconfig');
  2514. if (!empty($debuginfo)) {
  2515. $debuginfo = s($debuginfo); // removes all nasty JS
  2516. $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
  2517. $label = get_string('debuginfo', 'debug') . $labelsep;
  2518. $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
  2519. }
  2520. if (!empty($backtrace)) {
  2521. $label = get_string('stacktrace', 'debug') . $labelsep;
  2522. $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
  2523. }
  2524. if ($obbuffer !== '' ) {
  2525. $label = get_string('outputbuffer', 'debug') . $labelsep;
  2526. $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
  2527. }
  2528. }
  2529. if (empty($CFG->rolesactive)) {
  2530. // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
  2531. } else if (!empty($link)) {
  2532. $output .= $this->continue_button($link);
  2533. }
  2534. $output .= $this->footer();
  2535. // Padding to encourage IE to display our error page, rather than its own.
  2536. $output .= str_repeat(' ', 512);
  2537. return $output;
  2538. }
  2539. /**
  2540. * Output a notification (that is, a status message about something that has just happened).
  2541. *
  2542. * Note: \core\notification::add() may be more suitable for your usage.
  2543. *
  2544. * @param string $message The message to print out.
  2545. * @param string $type The type of notification. See constants on \core\output\notification.
  2546. * @return string the HTML to output.
  2547. */
  2548. public function notification($message, $type = null) {
  2549. $typemappings = [
  2550. // Valid types.
  2551. 'success' => \core\output\notification::NOTIFY_SUCCESS,
  2552. 'info' => \core\output\notification::NOTIFY_INFO,
  2553. 'warning' => \core\output\notification::NOTIFY_WARNING,
  2554. 'error' => \core\output\notification::NOTIFY_ERROR,
  2555. // Legacy types mapped to current types.
  2556. 'notifyproblem' => \core\output\notification::NOTIFY_ERROR,
  2557. 'notifytiny' => \core\output\notification::NOTIFY_ERROR,
  2558. 'notifyerror' => \core\output\notification::NOTIFY_ERROR,
  2559. 'notifysuccess' => \core\output\notification::NOTIFY_SUCCESS,
  2560. 'notifymessage' => \core\output\notification::NOTIFY_INFO,
  2561. 'notifyredirect' => \core\output\notification::NOTIFY_INFO,
  2562. 'redirectmessage' => \core\output\notification::NOTIFY_INFO,
  2563. ];
  2564. $extraclasses = [];
  2565. if ($type) {
  2566. if (strpos($type, ' ') === false) {
  2567. // No spaces in the list of classes, therefore no need to loop over and determine the class.
  2568. if (isset($typemappings[$type])) {
  2569. $type = $typemappings[$type];
  2570. } else {
  2571. // The value provided did not match a known type. It must be an extra class.
  2572. $extraclasses = [$type];
  2573. }
  2574. } else {
  2575. // Identify what type of notification this is.
  2576. $classarray = explode(' ', self::prepare_classes($type));
  2577. // Separate out the type of notification from the extra classes.
  2578. foreach ($classarray as $class) {
  2579. if (isset($typemappings[$class])) {
  2580. $type = $typemappings[$class];
  2581. } else {
  2582. $extraclasses[] = $class;
  2583. }
  2584. }
  2585. }
  2586. }
  2587. $notification = new \core\output\notification($message, $type);
  2588. if (count($extraclasses)) {
  2589. $notification->set_extra_classes($extraclasses);
  2590. }
  2591. // Return the rendered template.
  2592. return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
  2593. }
  2594. /**
  2595. * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
  2596. */
  2597. public function notify_problem() {
  2598. throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
  2599. 'please use \core\notification::add(), or \core\output\notification as required.');
  2600. }
  2601. /**
  2602. * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
  2603. */
  2604. public function notify_success() {
  2605. throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
  2606. 'please use \core\notification::add(), or \core\output\notification as required.');
  2607. }
  2608. /**
  2609. * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
  2610. */
  2611. public function notify_message() {
  2612. throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
  2613. 'please use \core\notification::add(), or \core\output\notification as required.');
  2614. }
  2615. /**
  2616. * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
  2617. */
  2618. public function notify_redirect() {
  2619. throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
  2620. 'please use \core\notification::add(), or \core\output\notification as required.');
  2621. }
  2622. /**
  2623. * Render a notification (that is, a status message about something that has
  2624. * just happened).
  2625. *
  2626. * @param \core\output\notification $notification the notification to print out
  2627. * @return string the HTML to output.
  2628. */
  2629. protected function render_notification(\core\output\notification $notification) {
  2630. return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
  2631. }
  2632. /**
  2633. * Returns HTML to display a continue button that goes to a particular URL.
  2634. *
  2635. * @param string|moodle_url $url The url the button goes to.
  2636. * @return string the HTML to output.
  2637. */
  2638. public function continue_button($url) {
  2639. if (!($url instanceof moodle_url)) {
  2640. $url = new moodle_url($url);
  2641. }
  2642. $button = new single_button($url, get_string('continue'), 'get', true);
  2643. $button->class = 'continuebutton';
  2644. return $this->render($button);
  2645. }
  2646. /**
  2647. * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
  2648. *
  2649. * Theme developers: DO NOT OVERRIDE! Please override function
  2650. * {@link core_renderer::render_paging_bar()} instead.
  2651. *
  2652. * @param int $totalcount The total number of entries available to be paged through
  2653. * @param int $page The page you are currently viewing
  2654. * @param int $perpage The number of entries that should be shown per page
  2655. * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
  2656. * @param string $pagevar name of page parameter that holds the page number
  2657. * @return string the HTML to output.
  2658. */
  2659. public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
  2660. $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
  2661. return $this->render($pb);
  2662. }
  2663. /**
  2664. * Returns HTML to display the paging bar.
  2665. *
  2666. * @param paging_bar $pagingbar
  2667. * @return string the HTML to output.
  2668. */
  2669. protected function render_paging_bar(paging_bar $pagingbar) {
  2670. // Any more than 10 is not usable and causes weird wrapping of the pagination.
  2671. $pagingbar->maxdisplay = 10;
  2672. return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
  2673. }
  2674. /**
  2675. * Returns HTML to display initials bar to provide access to other pages (usually in a search)
  2676. *
  2677. * @param string $current the currently selected letter.
  2678. * @param string $class class name to add to this initial bar.
  2679. * @param string $title the name to put in front of this initial bar.
  2680. * @param string $urlvar URL parameter name for this initial.
  2681. * @param string $url URL object.
  2682. * @param array $alpha of letters in the alphabet.
  2683. * @return string the HTML to output.
  2684. */
  2685. public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
  2686. $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
  2687. return $this->render($ib);
  2688. }
  2689. /**
  2690. * Internal implementation of initials bar rendering.
  2691. *
  2692. * @param initials_bar $initialsbar
  2693. * @return string
  2694. */
  2695. protected function render_initials_bar(initials_bar $initialsbar) {
  2696. return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
  2697. }
  2698. /**
  2699. * Output the place a skip link goes to.
  2700. *
  2701. * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
  2702. * @return string the HTML to output.
  2703. */
  2704. public function skip_link_target($id = null) {
  2705. return html_writer::span('', '', array('id' => $id));
  2706. }
  2707. /**
  2708. * Outputs a heading
  2709. *
  2710. * @param string $text The text of the heading
  2711. * @param int $level The level of importance of the heading. Defaulting to 2
  2712. * @param string $classes A space-separated list of CSS classes. Defaulting to null
  2713. * @param string $id An optional ID
  2714. * @return string the HTML to output.
  2715. */
  2716. public function heading($text, $level = 2, $classes = null, $id = null) {
  2717. $level = (integer) $level;
  2718. if ($level < 1 or $level > 6) {
  2719. throw new coding_exception('Heading level must be an integer between 1 and 6.');
  2720. }
  2721. return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
  2722. }
  2723. /**
  2724. * Outputs a box.
  2725. *
  2726. * @param string $contents The contents of the box
  2727. * @param string $classes A space-separated list of CSS classes
  2728. * @param string $id An optional ID
  2729. * @param array $attributes An array of other attributes to give the box.
  2730. * @return string the HTML to output.
  2731. */
  2732. public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
  2733. return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
  2734. }
  2735. /**
  2736. * Outputs the opening section of a box.
  2737. *
  2738. * @param string $classes A space-separated list of CSS classes
  2739. * @param string $id An optional ID
  2740. * @param array $attributes An array of other attributes to give the box.
  2741. * @return string the HTML to output.
  2742. */
  2743. public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
  2744. $this->opencontainers->push('box', html_writer::end_tag('div'));
  2745. $attributes['id'] = $id;
  2746. $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
  2747. return html_writer::start_tag('div', $attributes);
  2748. }
  2749. /**
  2750. * Outputs the closing section of a box.
  2751. *
  2752. * @return string the HTML to output.
  2753. */
  2754. public function box_end() {
  2755. return $this->opencontainers->pop('box');
  2756. }
  2757. /**
  2758. * Outputs a container.
  2759. *
  2760. * @param string $contents The contents of the box
  2761. * @param string $classes A space-separated list of CSS classes
  2762. * @param string $id An optional ID
  2763. * @return string the HTML to output.
  2764. */
  2765. public function container($contents, $classes = null, $id = null) {
  2766. return $this->container_start($classes, $id) . $contents . $this->container_end();
  2767. }
  2768. /**
  2769. * Outputs the opening section of a container.
  2770. *
  2771. * @param string $classes A space-separated list of CSS classes
  2772. * @param string $id An optional ID
  2773. * @return string the HTML to output.
  2774. */
  2775. public function container_start($classes = null, $id = null) {
  2776. $this->opencontainers->push('container', html_writer::end_tag('div'));
  2777. return html_writer::start_tag('div', array('id' => $id,
  2778. 'class' => renderer_base::prepare_classes($classes)));
  2779. }
  2780. /**
  2781. * Outputs the closing section of a container.
  2782. *
  2783. * @return string the HTML to output.
  2784. */
  2785. public function container_end() {
  2786. return $this->opencontainers->pop('container');
  2787. }
  2788. /**
  2789. * Make nested HTML lists out of the items
  2790. *
  2791. * The resulting list will look something like this:
  2792. *
  2793. * <pre>
  2794. * <<ul>>
  2795. * <<li>><div class='tree_item parent'>(item contents)</div>
  2796. * <<ul>
  2797. * <<li>><div class='tree_item'>(item contents)</div><</li>>
  2798. * <</ul>>
  2799. * <</li>>
  2800. * <</ul>>
  2801. * </pre>
  2802. *
  2803. * @param array $items
  2804. * @param array $attrs html attributes passed to the top ofs the list
  2805. * @return string HTML
  2806. */
  2807. public function tree_block_contents($items, $attrs = array()) {
  2808. // exit if empty, we don't want an empty ul element
  2809. if (empty($items)) {
  2810. return '';
  2811. }
  2812. // array of nested li elements
  2813. $lis = array();
  2814. foreach ($items as $item) {
  2815. // this applies to the li item which contains all child lists too
  2816. $content = $item->content($this);
  2817. $liclasses = array($item->get_css_type());
  2818. if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
  2819. $liclasses[] = 'collapsed';
  2820. }
  2821. if ($item->isactive === true) {
  2822. $liclasses[] = 'current_branch';
  2823. }
  2824. $liattr = array('class'=>join(' ',$liclasses));
  2825. // class attribute on the div item which only contains the item content
  2826. $divclasses = array('tree_item');
  2827. if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
  2828. $divclasses[] = 'branch';
  2829. } else {
  2830. $divclasses[] = 'leaf';
  2831. }
  2832. if (!empty($item->classes) && count($item->classes)>0) {
  2833. $divclasses[] = join(' ', $item->classes);
  2834. }
  2835. $divattr = array('class'=>join(' ', $divclasses));
  2836. if (!empty($item->id)) {
  2837. $divattr['id'] = $item->id;
  2838. }
  2839. $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
  2840. if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
  2841. $content = html_writer::empty_tag('hr') . $content;
  2842. }
  2843. $content = html_writer::tag('li', $content, $liattr);
  2844. $lis[] = $content;
  2845. }
  2846. return html_writer::tag('ul', implode("\n", $lis), $attrs);
  2847. }
  2848. /**
  2849. * Returns a search box.
  2850. *
  2851. * @param string $id The search box wrapper div id, defaults to an autogenerated one.
  2852. * @return string HTML with the search form hidden by default.
  2853. */
  2854. public function search_box($id = false) {
  2855. global $CFG;
  2856. // Accessing $CFG directly as using \core_search::is_global_search_enabled would
  2857. // result in an extra included file for each site, even the ones where global search
  2858. // is disabled.
  2859. if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
  2860. return '';
  2861. }
  2862. if ($id == false) {
  2863. $id = uniqid();
  2864. } else {
  2865. // Needs to be cleaned, we use it for the input id.
  2866. $id = clean_param($id, PARAM_ALPHANUMEXT);
  2867. }
  2868. // JS to animate the form.
  2869. $this->page->requires->js_call_amd('core/search-input', 'init', array($id));
  2870. $searchicon = html_writer::tag('div', $this->pix_icon('a/search', get_string('search', 'search'), 'moodle'),
  2871. array('role' => 'button', 'tabindex' => 0));
  2872. $formattrs = array('class' => 'search-input-form', 'action' => $CFG->wwwroot . '/search/index.php');
  2873. $inputattrs = array('type' => 'text', 'name' => 'q', 'placeholder' => get_string('search', 'search'),
  2874. 'size' => 13, 'tabindex' => -1, 'id' => 'id_q_' . $id, 'class' => 'form-control');
  2875. $contents = html_writer::tag('label', get_string('enteryoursearchquery', 'search'),
  2876. array('for' => 'id_q_' . $id, 'class' => 'accesshide')) . html_writer::empty_tag('input', $inputattrs);
  2877. if ($this->page->context && $this->page->context->contextlevel !== CONTEXT_SYSTEM) {
  2878. $contents .= html_writer::empty_tag('input', ['type' => 'hidden',
  2879. 'name' => 'context', 'value' => $this->page->context->id]);
  2880. }
  2881. $searchinput = html_writer::tag('form', $contents, $formattrs);
  2882. return html_writer::tag('div', $searchicon . $searchinput, array('class' => 'search-input-wrapper nav-link', 'id' => $id));
  2883. }
  2884. /**
  2885. * Allow plugins to provide some content to be rendered in the navbar.
  2886. * The plugin must define a PLUGIN_render_navbar_output function that returns
  2887. * the HTML they wish to add to the navbar.
  2888. *
  2889. * @return string HTML for the navbar
  2890. */
  2891. public function navbar_plugin_output() {
  2892. $output = '';
  2893. // Give subsystems an opportunity to inject extra html content. The callback
  2894. // must always return a string containing valid html.
  2895. foreach (\core_component::get_core_subsystems() as $name => $path) {
  2896. if ($path) {
  2897. $output .= component_callback($name, 'render_navbar_output', [$this], '');
  2898. }
  2899. }
  2900. if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
  2901. foreach ($pluginsfunction as $plugintype => $plugins) {
  2902. foreach ($plugins as $pluginfunction) {
  2903. $output .= $pluginfunction($this);
  2904. }
  2905. }
  2906. }
  2907. return $output;
  2908. }
  2909. /**
  2910. * Construct a user menu, returning HTML that can be echoed out by a
  2911. * layout file.
  2912. *
  2913. * @param stdClass $user A user object, usually $USER.
  2914. * @param bool $withlinks true if a dropdown should be built.
  2915. * @return string HTML fragment.
  2916. */
  2917. public function user_menu($user = null, $withlinks = null) {
  2918. global $USER, $CFG;
  2919. require_once($CFG->dirroot . '/user/lib.php');
  2920. if (is_null($user)) {
  2921. $user = $USER;
  2922. }
  2923. // Note: this behaviour is intended to match that of core_renderer::login_info,
  2924. // but should not be considered to be good practice; layout options are
  2925. // intended to be theme-specific. Please don't copy this snippet anywhere else.
  2926. if (is_null($withlinks)) {
  2927. $withlinks = empty($this->page->layout_options['nologinlinks']);
  2928. }
  2929. // Add a class for when $withlinks is false.
  2930. $usermenuclasses = 'usermenu';
  2931. if (!$withlinks) {
  2932. $usermenuclasses .= ' withoutlinks';
  2933. }
  2934. $returnstr = "";
  2935. // If during initial install, return the empty return string.
  2936. if (during_initial_install()) {
  2937. return $returnstr;
  2938. }
  2939. $loginpage = $this->is_login_page();
  2940. $loginurl = get_login_url();
  2941. // If not logged in, show the typical not-logged-in string.
  2942. if (!isloggedin()) {
  2943. $returnstr = get_string('loggedinnot', 'moodle');
  2944. if (!$loginpage) {
  2945. $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
  2946. }
  2947. return html_writer::div(
  2948. html_writer::span(
  2949. $returnstr,
  2950. 'login'
  2951. ),
  2952. $usermenuclasses
  2953. );
  2954. }
  2955. // If logged in as a guest user, show a string to that effect.
  2956. if (isguestuser()) {
  2957. $returnstr = get_string('loggedinasguest');
  2958. if (!$loginpage && $withlinks) {
  2959. $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
  2960. }
  2961. return html_writer::div(
  2962. html_writer::span(
  2963. $returnstr,
  2964. 'login'
  2965. ),
  2966. $usermenuclasses
  2967. );
  2968. }
  2969. // Get some navigation opts.
  2970. $opts = user_get_user_navigation_info($user, $this->page);
  2971. $avatarclasses = "avatars";
  2972. $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
  2973. $usertextcontents = $opts->metadata['userfullname'];
  2974. // Other user.
  2975. if (!empty($opts->metadata['asotheruser'])) {
  2976. $avatarcontents .= html_writer::span(
  2977. $opts->metadata['realuseravatar'],
  2978. 'avatar realuser'
  2979. );
  2980. $usertextcontents = $opts->metadata['realuserfullname'];
  2981. $usertextcontents .= html_writer::tag(
  2982. 'span',
  2983. get_string(
  2984. 'loggedinas',
  2985. 'moodle',
  2986. html_writer::span(
  2987. $opts->metadata['userfullname'],
  2988. 'value'
  2989. )
  2990. ),
  2991. array('class' => 'meta viewingas')
  2992. );
  2993. }
  2994. // Role.
  2995. if (!empty($opts->metadata['asotherrole'])) {
  2996. $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
  2997. $usertextcontents .= html_writer::span(
  2998. $opts->metadata['rolename'],
  2999. 'meta role role-' . $role
  3000. );
  3001. }
  3002. // User login failures.
  3003. if (!empty($opts->metadata['userloginfail'])) {
  3004. $usertextcontents .= html_writer::span(
  3005. $opts->metadata['userloginfail'],
  3006. 'meta loginfailures'
  3007. );
  3008. }
  3009. // MNet.
  3010. if (!empty($opts->metadata['asmnetuser'])) {
  3011. $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
  3012. $usertextcontents .= html_writer::span(
  3013. $opts->metadata['mnetidprovidername'],
  3014. 'meta mnet mnet-' . $mnet
  3015. );
  3016. }
  3017. $returnstr .= html_writer::span(
  3018. html_writer::span($usertextcontents, 'usertext mr-1') .
  3019. html_writer::span($avatarcontents, $avatarclasses),
  3020. 'userbutton'
  3021. );
  3022. // Create a divider (well, a filler).
  3023. $divider = new action_menu_filler();
  3024. $divider->primary = false;
  3025. $am = new action_menu();
  3026. $am->set_menu_trigger(
  3027. $returnstr
  3028. );
  3029. $am->set_action_label(get_string('usermenu'));
  3030. $am->set_alignment(action_menu::TR, action_menu::BR);
  3031. $am->set_nowrap_on_items();
  3032. if ($withlinks) {
  3033. $navitemcount = count($opts->navitems);
  3034. $idx = 0;
  3035. foreach ($opts->navitems as $key => $value) {
  3036. switch ($value->itemtype) {
  3037. case 'divider':
  3038. // If the nav item is a divider, add one and skip link processing.
  3039. $am->add($divider);
  3040. break;
  3041. case 'invalid':
  3042. // Silently skip invalid entries (should we post a notification?).
  3043. break;
  3044. case 'link':
  3045. // Process this as a link item.
  3046. $pix = null;
  3047. if (isset($value->pix) && !empty($value->pix)) {
  3048. $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
  3049. } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
  3050. $value->title = html_writer::img(
  3051. $value->imgsrc,
  3052. $value->title,
  3053. array('class' => 'iconsmall')
  3054. ) . $value->title;
  3055. }
  3056. $al = new action_menu_link_secondary(
  3057. $value->url,
  3058. $pix,
  3059. $value->title,
  3060. array('class' => 'icon')
  3061. );
  3062. if (!empty($value->titleidentifier)) {
  3063. $al->attributes['data-title'] = $value->titleidentifier;
  3064. }
  3065. $am->add($al);
  3066. break;
  3067. }
  3068. $idx++;
  3069. // Add dividers after the first item and before the last item.
  3070. if ($idx == 1 || $idx == $navitemcount - 1) {
  3071. $am->add($divider);
  3072. }
  3073. }
  3074. }
  3075. return html_writer::div(
  3076. $this->render($am),
  3077. $usermenuclasses
  3078. );
  3079. }
  3080. /**
  3081. * This renders the navbar.
  3082. * Uses bootstrap compatible html.
  3083. */
  3084. public function navbar() {
  3085. return $this->render_from_template('core/navbar', $this->page->navbar);
  3086. }
  3087. /**
  3088. * Renders a breadcrumb navigation node object.
  3089. *
  3090. * @param breadcrumb_navigation_node $item The navigation node to render.
  3091. * @return string HTML fragment
  3092. */
  3093. protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
  3094. if ($item->action instanceof moodle_url) {
  3095. $content = $item->get_content();
  3096. $title = $item->get_title();
  3097. $attributes = array();
  3098. $attributes['itemprop'] = 'url';
  3099. if ($title !== '') {
  3100. $attributes['title'] = $title;
  3101. }
  3102. if ($item->hidden) {
  3103. $attributes['class'] = 'dimmed_text';
  3104. }
  3105. if ($item->is_last()) {
  3106. $attributes['aria-current'] = 'page';
  3107. }
  3108. $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
  3109. $content = html_writer::link($item->action, $content, $attributes);
  3110. $attributes = array();
  3111. $attributes['itemscope'] = '';
  3112. $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
  3113. $content = html_writer::tag('span', $content, $attributes);
  3114. } else {
  3115. $content = $this->render_navigation_node($item);
  3116. }
  3117. return $content;
  3118. }
  3119. /**
  3120. * Renders a navigation node object.
  3121. *
  3122. * @param navigation_node $item The navigation node to render.
  3123. * @return string HTML fragment
  3124. */
  3125. protected function render_navigation_node(navigation_node $item) {
  3126. $content = $item->get_content();
  3127. $title = $item->get_title();
  3128. if ($item->icon instanceof renderable && !$item->hideicon) {
  3129. $icon = $this->render($item->icon);
  3130. $content = $icon.$content; // use CSS for spacing of icons
  3131. }
  3132. if ($item->helpbutton !== null) {
  3133. $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
  3134. }
  3135. if ($content === '') {
  3136. return '';
  3137. }
  3138. if ($item->action instanceof action_link) {
  3139. $link = $item->action;
  3140. if ($item->hidden) {
  3141. $link->add_class('dimmed');
  3142. }
  3143. if (!empty($content)) {
  3144. // Providing there is content we will use that for the link content.
  3145. $link->text = $content;
  3146. }
  3147. $content = $this->render($link);
  3148. } else if ($item->action instanceof moodle_url) {
  3149. $attributes = array();
  3150. if ($title !== '') {
  3151. $attributes['title'] = $title;
  3152. }
  3153. if ($item->hidden) {
  3154. $attributes['class'] = 'dimmed_text';
  3155. }
  3156. $content = html_writer::link($item->action, $content, $attributes);
  3157. } else if (is_string($item->action) || empty($item->action)) {
  3158. $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
  3159. if ($title !== '') {
  3160. $attributes['title'] = $title;
  3161. }
  3162. if ($item->hidden) {
  3163. $attributes['class'] = 'dimmed_text';
  3164. }
  3165. $content = html_writer::tag('span', $content, $attributes);
  3166. }
  3167. return $content;
  3168. }
  3169. /**
  3170. * Accessibility: Right arrow-like character is
  3171. * used in the breadcrumb trail, course navigation menu
  3172. * (previous/next activity), calendar, and search forum block.
  3173. * If the theme does not set characters, appropriate defaults
  3174. * are set automatically. Please DO NOT
  3175. * use &lt; &gt; &raquo; - these are confusing for blind users.
  3176. *
  3177. * @return string
  3178. */
  3179. public function rarrow() {
  3180. return $this->page->theme->rarrow;
  3181. }
  3182. /**
  3183. * Accessibility: Left arrow-like character is
  3184. * used in the breadcrumb trail, course navigation menu
  3185. * (previous/next activity), calendar, and search forum block.
  3186. * If the theme does not set characters, appropriate defaults
  3187. * are set automatically. Please DO NOT
  3188. * use &lt; &gt; &raquo; - these are confusing for blind users.
  3189. *
  3190. * @return string
  3191. */
  3192. public function larrow() {
  3193. return $this->page->theme->larrow;
  3194. }
  3195. /**
  3196. * Accessibility: Up arrow-like character is used in
  3197. * the book heirarchical navigation.
  3198. * If the theme does not set characters, appropriate defaults
  3199. * are set automatically. Please DO NOT
  3200. * use ^ - this is confusing for blind users.
  3201. *
  3202. * @return string
  3203. */
  3204. public function uarrow() {
  3205. return $this->page->theme->uarrow;
  3206. }
  3207. /**
  3208. * Accessibility: Down arrow-like character.
  3209. * If the theme does not set characters, appropriate defaults
  3210. * are set automatically.
  3211. *
  3212. * @return string
  3213. */
  3214. public function darrow() {
  3215. return $this->page->theme->darrow;
  3216. }
  3217. /**
  3218. * Returns the custom menu if one has been set
  3219. *
  3220. * A custom menu can be configured by browsing to
  3221. * Settings: Administration > Appearance > Themes > Theme settings
  3222. * and then configuring the custommenu config setting as described.
  3223. *
  3224. * Theme developers: DO NOT OVERRIDE! Please override function
  3225. * {@link core_renderer::render_custom_menu()} instead.
  3226. *
  3227. * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
  3228. * @return string
  3229. */
  3230. public function custom_menu($custommenuitems = '') {
  3231. global $CFG;
  3232. if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
  3233. $custommenuitems = $CFG->custommenuitems;
  3234. }
  3235. $custommenu = new custom_menu($custommenuitems, current_language());
  3236. return $this->render_custom_menu($custommenu);
  3237. }
  3238. /**
  3239. * We want to show the custom menus as a list of links in the footer on small screens.
  3240. * Just return the menu object exported so we can render it differently.
  3241. */
  3242. public function custom_menu_flat() {
  3243. global $CFG;
  3244. $custommenuitems = '';
  3245. if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
  3246. $custommenuitems = $CFG->custommenuitems;
  3247. }
  3248. $custommenu = new custom_menu($custommenuitems, current_language());
  3249. $langs = get_string_manager()->get_list_of_translations();
  3250. $haslangmenu = $this->lang_menu() != '';
  3251. if ($haslangmenu) {
  3252. $strlang = get_string('language');
  3253. $currentlang = current_language();
  3254. if (isset($langs[$currentlang])) {
  3255. $currentlang = $langs[$currentlang];
  3256. } else {
  3257. $currentlang = $strlang;
  3258. }
  3259. $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
  3260. foreach ($langs as $langtype => $langname) {
  3261. $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
  3262. }
  3263. }
  3264. return $custommenu->export_for_template($this);
  3265. }
  3266. /**
  3267. * Renders a custom menu object (located in outputcomponents.php)
  3268. *
  3269. * The custom menu this method produces makes use of the YUI3 menunav widget
  3270. * and requires very specific html elements and classes.
  3271. *
  3272. * @staticvar int $menucount
  3273. * @param custom_menu $menu
  3274. * @return string
  3275. */
  3276. protected function render_custom_menu(custom_menu $menu) {
  3277. global $CFG;
  3278. $langs = get_string_manager()->get_list_of_translations();
  3279. $haslangmenu = $this->lang_menu() != '';
  3280. if (!$menu->has_children() && !$haslangmenu) {
  3281. return '';
  3282. }
  3283. if ($haslangmenu) {
  3284. $strlang = get_string('language');
  3285. $currentlang = current_language();
  3286. if (isset($langs[$currentlang])) {
  3287. $currentlang = $langs[$currentlang];
  3288. } else {
  3289. $currentlang = $strlang;
  3290. }
  3291. $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000);
  3292. foreach ($langs as $langtype => $langname) {
  3293. $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
  3294. }
  3295. }
  3296. $content = '';
  3297. foreach ($menu->get_children() as $item) {
  3298. $context = $item->export_for_template($this);
  3299. $content .= $this->render_from_template('core/custom_menu_item', $context);
  3300. }
  3301. return $content;
  3302. }
  3303. /**
  3304. * Renders a custom menu node as part of a submenu
  3305. *
  3306. * The custom menu this method produces makes use of the YUI3 menunav widget
  3307. * and requires very specific html elements and classes.
  3308. *
  3309. * @see core:renderer::render_custom_menu()
  3310. *
  3311. * @staticvar int $submenucount
  3312. * @param custom_menu_item $menunode
  3313. * @return string
  3314. */
  3315. protected function render_custom_menu_item(custom_menu_item $menunode) {
  3316. // Required to ensure we get unique trackable id's
  3317. static $submenucount = 0;
  3318. if ($menunode->has_children()) {
  3319. // If the child has menus render it as a sub menu
  3320. $submenucount++;
  3321. $content = html_writer::start_tag('li');
  3322. if ($menunode->get_url() !== null) {
  3323. $url = $menunode->get_url();
  3324. } else {
  3325. $url = '#cm_submenu_'.$submenucount;
  3326. }
  3327. $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
  3328. $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
  3329. $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
  3330. $content .= html_writer::start_tag('ul');
  3331. foreach ($menunode->get_children() as $menunode) {
  3332. $content .= $this->render_custom_menu_item($menunode);
  3333. }
  3334. $content .= html_writer::end_tag('ul');
  3335. $content .= html_writer::end_tag('div');
  3336. $content .= html_writer::end_tag('div');
  3337. $content .= html_writer::end_tag('li');
  3338. } else {
  3339. // The node doesn't have children so produce a final menuitem.
  3340. // Also, if the node's text matches '####', add a class so we can treat it as a divider.
  3341. $content = '';
  3342. if (preg_match("/^#+$/", $menunode->get_text())) {
  3343. // This is a divider.
  3344. $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
  3345. } else {
  3346. $content = html_writer::start_tag(
  3347. 'li',
  3348. array(
  3349. 'class' => 'yui3-menuitem'
  3350. )
  3351. );
  3352. if ($menunode->get_url() !== null) {
  3353. $url = $menunode->get_url();
  3354. } else {
  3355. $url = '#';
  3356. }
  3357. $content .= html_writer::link(
  3358. $url,
  3359. $menunode->get_text(),
  3360. array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
  3361. );
  3362. }
  3363. $content .= html_writer::end_tag('li');
  3364. }
  3365. // Return the sub menu
  3366. return $content;
  3367. }
  3368. /**
  3369. * Renders theme links for switching between default and other themes.
  3370. *
  3371. * @return string
  3372. */
  3373. protected function theme_switch_links() {
  3374. $actualdevice = core_useragent::get_device_type();
  3375. $currentdevice = $this->page->devicetypeinuse;
  3376. $switched = ($actualdevice != $currentdevice);
  3377. if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
  3378. // The user is using the a default device and hasn't switched so don't shown the switch
  3379. // device links.
  3380. return '';
  3381. }
  3382. if ($switched) {
  3383. $linktext = get_string('switchdevicerecommended');
  3384. $devicetype = $actualdevice;
  3385. } else {
  3386. $linktext = get_string('switchdevicedefault');
  3387. $devicetype = 'default';
  3388. }
  3389. $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
  3390. $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
  3391. $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
  3392. $content .= html_writer::end_tag('div');
  3393. return $content;
  3394. }
  3395. /**
  3396. * Renders tabs
  3397. *
  3398. * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
  3399. *
  3400. * Theme developers: In order to change how tabs are displayed please override functions
  3401. * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
  3402. *
  3403. * @param array $tabs array of tabs, each of them may have it's own ->subtree
  3404. * @param string|null $selected which tab to mark as selected, all parent tabs will
  3405. * automatically be marked as activated
  3406. * @param array|string|null $inactive list of ids of inactive tabs, regardless of
  3407. * their level. Note that you can as weel specify tabobject::$inactive for separate instances
  3408. * @return string
  3409. */
  3410. public final function tabtree($tabs, $selected = null, $inactive = null) {
  3411. return $this->render(new tabtree($tabs, $selected, $inactive));
  3412. }
  3413. /**
  3414. * Renders tabtree
  3415. *
  3416. * @param tabtree $tabtree
  3417. * @return string
  3418. */
  3419. protected function render_tabtree(tabtree $tabtree) {
  3420. if (empty($tabtree->subtree)) {
  3421. return '';
  3422. }
  3423. $data = $tabtree->export_for_template($this);
  3424. return $this->render_from_template('core/tabtree', $data);
  3425. }
  3426. /**
  3427. * Renders tabobject (part of tabtree)
  3428. *
  3429. * This function is called from {@link core_renderer::render_tabtree()}
  3430. * and also it calls itself when printing the $tabobject subtree recursively.
  3431. *
  3432. * Property $tabobject->level indicates the number of row of tabs.
  3433. *
  3434. * @param tabobject $tabobject
  3435. * @return string HTML fragment
  3436. */
  3437. protected function render_tabobject(tabobject $tabobject) {
  3438. $str = '';
  3439. // Print name of the current tab.
  3440. if ($tabobject instanceof tabtree) {
  3441. // No name for tabtree root.
  3442. } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
  3443. // Tab name without a link. The <a> tag is used for styling.
  3444. $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
  3445. } else {
  3446. // Tab name with a link.
  3447. if (!($tabobject->link instanceof moodle_url)) {
  3448. // backward compartibility when link was passed as quoted string
  3449. $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
  3450. } else {
  3451. $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
  3452. }
  3453. }
  3454. if (empty($tabobject->subtree)) {
  3455. if ($tabobject->selected) {
  3456. $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
  3457. }
  3458. return $str;
  3459. }
  3460. // Print subtree.
  3461. if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
  3462. $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
  3463. $cnt = 0;
  3464. foreach ($tabobject->subtree as $tab) {
  3465. $liclass = '';
  3466. if (!$cnt) {
  3467. $liclass .= ' first';
  3468. }
  3469. if ($cnt == count($tabobject->subtree) - 1) {
  3470. $liclass .= ' last';
  3471. }
  3472. if ((empty($tab->subtree)) && (!empty($tab->selected))) {
  3473. $liclass .= ' onerow';
  3474. }
  3475. if ($tab->selected) {
  3476. $liclass .= ' here selected';
  3477. } else if ($tab->activated) {
  3478. $liclass .= ' here active';
  3479. }
  3480. // This will recursively call function render_tabobject() for each item in subtree.
  3481. $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
  3482. $cnt++;
  3483. }
  3484. $str .= html_writer::end_tag('ul');
  3485. }
  3486. return $str;
  3487. }
  3488. /**
  3489. * Get the HTML for blocks in the given region.
  3490. *
  3491. * @since Moodle 2.5.1 2.6
  3492. * @param string $region The region to get HTML for.
  3493. * @return string HTML.
  3494. */
  3495. public function blocks($region, $classes = array(), $tag = 'aside') {
  3496. $displayregion = $this->page->apply_theme_region_manipulations($region);
  3497. $classes = (array)$classes;
  3498. $classes[] = 'block-region';
  3499. $attributes = array(
  3500. 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
  3501. 'class' => join(' ', $classes),
  3502. 'data-blockregion' => $displayregion,
  3503. 'data-droptarget' => '1'
  3504. );
  3505. if ($this->page->blocks->region_has_content($displayregion, $this)) {
  3506. $content = $this->blocks_for_region($displayregion);
  3507. } else {
  3508. $content = '';
  3509. }
  3510. return html_writer::tag($tag, $content, $attributes);
  3511. }
  3512. /**
  3513. * Renders a custom block region.
  3514. *
  3515. * Use this method if you want to add an additional block region to the content of the page.
  3516. * Please note this should only be used in special situations.
  3517. * We want to leave the theme is control where ever possible!
  3518. *
  3519. * This method must use the same method that the theme uses within its layout file.
  3520. * As such it asks the theme what method it is using.
  3521. * It can be one of two values, blocks or blocks_for_region (deprecated).
  3522. *
  3523. * @param string $regionname The name of the custom region to add.
  3524. * @return string HTML for the block region.
  3525. */
  3526. public function custom_block_region($regionname) {
  3527. if ($this->page->theme->get_block_render_method() === 'blocks') {
  3528. return $this->blocks($regionname);
  3529. } else {
  3530. return $this->blocks_for_region($regionname);
  3531. }
  3532. }
  3533. /**
  3534. * Returns the CSS classes to apply to the body tag.
  3535. *
  3536. * @since Moodle 2.5.1 2.6
  3537. * @param array $additionalclasses Any additional classes to apply.
  3538. * @return string
  3539. */
  3540. public function body_css_classes(array $additionalclasses = array()) {
  3541. return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
  3542. }
  3543. /**
  3544. * The ID attribute to apply to the body tag.
  3545. *
  3546. * @since Moodle 2.5.1 2.6
  3547. * @return string
  3548. */
  3549. public function body_id() {
  3550. return $this->page->bodyid;
  3551. }
  3552. /**
  3553. * Returns HTML attributes to use within the body tag. This includes an ID and classes.
  3554. *
  3555. * @since Moodle 2.5.1 2.6
  3556. * @param string|array $additionalclasses Any additional classes to give the body tag,
  3557. * @return string
  3558. */
  3559. public function body_attributes($additionalclasses = array()) {
  3560. if (!is_array($additionalclasses)) {
  3561. $additionalclasses = explode(' ', $additionalclasses);
  3562. }
  3563. return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
  3564. }
  3565. /**
  3566. * Gets HTML for the page heading.
  3567. *
  3568. * @since Moodle 2.5.1 2.6
  3569. * @param string $tag The tag to encase the heading in. h1 by default.
  3570. * @return string HTML.
  3571. */
  3572. public function page_heading($tag = 'h1') {
  3573. return html_writer::tag($tag, $this->page->heading);
  3574. }
  3575. /**
  3576. * Gets the HTML for the page heading button.
  3577. *
  3578. * @since Moodle 2.5.1 2.6
  3579. * @return string HTML.
  3580. */
  3581. public function page_heading_button() {
  3582. return $this->page->button;
  3583. }
  3584. /**
  3585. * Returns the Moodle docs link to use for this page.
  3586. *
  3587. * @since Moodle 2.5.1 2.6
  3588. * @param string $text
  3589. * @return string
  3590. */
  3591. public function page_doc_link($text = null) {
  3592. if ($text === null) {
  3593. $text = get_string('moodledocslink');
  3594. }
  3595. $path = page_get_doc_link_path($this->page);
  3596. if (!$path) {
  3597. return '';
  3598. }
  3599. return $this->doc_link($path, $text);
  3600. }
  3601. /**
  3602. * Returns the page heading menu.
  3603. *
  3604. * @since Moodle 2.5.1 2.6
  3605. * @return string HTML.
  3606. */
  3607. public function page_heading_menu() {
  3608. return $this->page->headingmenu;
  3609. }
  3610. /**
  3611. * Returns the title to use on the page.
  3612. *
  3613. * @since Moodle 2.5.1 2.6
  3614. * @return string
  3615. */
  3616. public function page_title() {
  3617. return $this->page->title;
  3618. }
  3619. /**
  3620. * Returns the moodle_url for the favicon.
  3621. *
  3622. * @since Moodle 2.5.1 2.6
  3623. * @return moodle_url The moodle_url for the favicon
  3624. */
  3625. public function favicon() {
  3626. return $this->image_url('favicon', 'theme');
  3627. }
  3628. /**
  3629. * Renders preferences groups.
  3630. *
  3631. * @param preferences_groups $renderable The renderable
  3632. * @return string The output.
  3633. */
  3634. public function render_preferences_groups(preferences_groups $renderable) {
  3635. return $this->render_from_template('core/preferences_groups', $renderable);
  3636. }
  3637. /**
  3638. * Renders preferences group.
  3639. *
  3640. * @param preferences_group $renderable The renderable
  3641. * @return string The output.
  3642. */
  3643. public function render_preferences_group(preferences_group $renderable) {
  3644. $html = '';
  3645. $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
  3646. $html .= $this->heading($renderable->title, 3);
  3647. $html .= html_writer::start_tag('ul');
  3648. foreach ($renderable->nodes as $node) {
  3649. if ($node->has_children()) {
  3650. debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
  3651. }
  3652. $html .= html_writer::tag('li', $this->render($node));
  3653. }
  3654. $html .= html_writer::end_tag('ul');
  3655. $html .= html_writer::end_tag('div');
  3656. return $html;
  3657. }
  3658. public function context_header($headerinfo = null, $headinglevel = 1) {
  3659. global $DB, $USER, $CFG, $SITE;
  3660. require_once($CFG->dirroot . '/user/lib.php');
  3661. $context = $this->page->context;
  3662. $heading = null;
  3663. $imagedata = null;
  3664. $subheader = null;
  3665. $userbuttons = null;
  3666. if ($this->should_display_main_logo($headinglevel)) {
  3667. $sitename = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID)));
  3668. return html_writer::div(html_writer::empty_tag('img', [
  3669. 'src' => $this->get_logo_url(null, 150), 'alt' => $sitename, 'class' => 'img-fluid']), 'logo');
  3670. }
  3671. // Make sure to use the heading if it has been set.
  3672. if (isset($headerinfo['heading'])) {
  3673. $heading = $headerinfo['heading'];
  3674. }
  3675. // The user context currently has images and buttons. Other contexts may follow.
  3676. if (isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) {
  3677. if (isset($headerinfo['user'])) {
  3678. $user = $headerinfo['user'];
  3679. } else {
  3680. // Look up the user information if it is not supplied.
  3681. $user = $DB->get_record('user', array('id' => $context->instanceid));
  3682. }
  3683. // If the user context is set, then use that for capability checks.
  3684. if (isset($headerinfo['usercontext'])) {
  3685. $context = $headerinfo['usercontext'];
  3686. }
  3687. // Only provide user information if the user is the current user, or a user which the current user can view.
  3688. // When checking user_can_view_profile(), either:
  3689. // If the page context is course, check the course context (from the page object) or;
  3690. // If page context is NOT course, then check across all courses.
  3691. $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
  3692. if (user_can_view_profile($user, $course)) {
  3693. // Use the user's full name if the heading isn't set.
  3694. if (!isset($heading)) {
  3695. $heading = fullname($user);
  3696. }
  3697. $imagedata = $this->user_picture($user, array('size' => 100));
  3698. // Check to see if we should be displaying a message button.
  3699. if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
  3700. $userbuttons = array(
  3701. 'messages' => array(
  3702. 'buttontype' => 'message',
  3703. 'title' => get_string('message', 'message'),
  3704. 'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
  3705. 'image' => 'message',
  3706. 'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
  3707. 'page' => $this->page
  3708. )
  3709. );
  3710. if ($USER->id != $user->id) {
  3711. $iscontact = \core_message\api::is_contact($USER->id, $user->id);
  3712. $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
  3713. $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
  3714. $contactimage = $iscontact ? 'removecontact' : 'addcontact';
  3715. $userbuttons['togglecontact'] = array(
  3716. 'buttontype' => 'togglecontact',
  3717. 'title' => get_string($contacttitle, 'message'),
  3718. 'url' => new moodle_url('/message/index.php', array(
  3719. 'user1' => $USER->id,
  3720. 'user2' => $user->id,
  3721. $contacturlaction => $user->id,
  3722. 'sesskey' => sesskey())
  3723. ),
  3724. 'image' => $contactimage,
  3725. 'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
  3726. 'page' => $this->page
  3727. );
  3728. }
  3729. $this->page->requires->string_for_js('changesmadereallygoaway', 'moodle');
  3730. }
  3731. } else {
  3732. $heading = null;
  3733. }
  3734. }
  3735. $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
  3736. return $this->render_context_header($contextheader);
  3737. }
  3738. /**
  3739. * Renders the skip links for the page.
  3740. *
  3741. * @param array $links List of skip links.
  3742. * @return string HTML for the skip links.
  3743. */
  3744. public function render_skip_links($links) {
  3745. $context = [ 'links' => []];
  3746. foreach ($links as $url => $text) {
  3747. $context['links'][] = [ 'url' => $url, 'text' => $text];
  3748. }
  3749. return $this->render_from_template('core/skip_links', $context);
  3750. }
  3751. /**
  3752. * Renders the header bar.
  3753. *
  3754. * @param context_header $contextheader Header bar object.
  3755. * @return string HTML for the header bar.
  3756. */
  3757. protected function render_context_header(context_header $contextheader) {
  3758. $showheader = empty($this->page->layout_options['nocontextheader']);
  3759. if (!$showheader) {
  3760. return '';
  3761. }
  3762. // All the html stuff goes here.
  3763. $html = html_writer::start_div('page-context-header');
  3764. // Image data.
  3765. if (isset($contextheader->imagedata)) {
  3766. // Header specific image.
  3767. $html .= html_writer::div($contextheader->imagedata, 'page-header-image');
  3768. }
  3769. // Headings.
  3770. if (!isset($contextheader->heading)) {
  3771. $headings = $this->heading($this->page->heading, $contextheader->headinglevel);
  3772. } else {
  3773. $headings = $this->heading($contextheader->heading, $contextheader->headinglevel);
  3774. }
  3775. $html .= html_writer::tag('div', $headings, array('class' => 'page-header-headings'));
  3776. // Buttons.
  3777. if (isset($contextheader->additionalbuttons)) {
  3778. $html .= html_writer::start_div('btn-group header-button-group');
  3779. foreach ($contextheader->additionalbuttons as $button) {
  3780. if (!isset($button->page)) {
  3781. // Include js for messaging.
  3782. if ($button['buttontype'] === 'togglecontact') {
  3783. \core_message\helper::togglecontact_requirejs();
  3784. }
  3785. if ($button['buttontype'] === 'message') {
  3786. \core_message\helper::messageuser_requirejs();
  3787. }
  3788. $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
  3789. 'class' => 'iconsmall',
  3790. 'role' => 'presentation'
  3791. ));
  3792. $image .= html_writer::span($button['title'], 'header-button-title');
  3793. } else {
  3794. $image = html_writer::empty_tag('img', array(
  3795. 'src' => $button['formattedimage'],
  3796. 'role' => 'presentation'
  3797. ));
  3798. }
  3799. $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
  3800. }
  3801. $html .= html_writer::end_div();
  3802. }
  3803. $html .= html_writer::end_div();
  3804. return $html;
  3805. }
  3806. /**
  3807. * Wrapper for header elements.
  3808. *
  3809. * @return string HTML to display the main header.
  3810. */
  3811. public function full_header() {
  3812. if ($this->page->include_region_main_settings_in_header_actions() &&
  3813. !$this->page->blocks->is_block_present('settings')) {
  3814. // Only include the region main settings if the page has requested it and it doesn't already have
  3815. // the settings block on it. The region main settings are included in the settings block and
  3816. // duplicating the content causes behat failures.
  3817. $this->page->add_header_action(html_writer::div(
  3818. $this->region_main_settings_menu(),
  3819. 'd-print-none',
  3820. ['id' => 'region-main-settings-menu']
  3821. ));
  3822. }
  3823. $header = new stdClass();
  3824. $header->settingsmenu = $this->context_header_settings_menu();
  3825. $header->contextheader = $this->context_header();
  3826. $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
  3827. $header->navbar = $this->navbar();
  3828. $header->pageheadingbutton = $this->page_heading_button();
  3829. $header->courseheader = $this->course_header();
  3830. $header->headeractions = $this->page->get_header_actions();
  3831. return $this->render_from_template('core/full_header', $header);
  3832. }
  3833. /**
  3834. * This is an optional menu that can be added to a layout by a theme. It contains the
  3835. * menu for the course administration, only on the course main page.
  3836. *
  3837. * @return string
  3838. */
  3839. public function context_header_settings_menu() {
  3840. $context = $this->page->context;
  3841. $menu = new action_menu();
  3842. $items = $this->page->navbar->get_items();
  3843. $currentnode = end($items);
  3844. $showcoursemenu = false;
  3845. $showfrontpagemenu = false;
  3846. $showusermenu = false;
  3847. // We are on the course home page.
  3848. if (($context->contextlevel == CONTEXT_COURSE) &&
  3849. !empty($currentnode) &&
  3850. ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
  3851. $showcoursemenu = true;
  3852. }
  3853. $courseformat = course_get_format($this->page->course);
  3854. // This is a single activity course format, always show the course menu on the activity main page.
  3855. if ($context->contextlevel == CONTEXT_MODULE &&
  3856. !$courseformat->has_view_page()) {
  3857. $this->page->navigation->initialise();
  3858. $activenode = $this->page->navigation->find_active_node();
  3859. // If the settings menu has been forced then show the menu.
  3860. if ($this->page->is_settings_menu_forced()) {
  3861. $showcoursemenu = true;
  3862. } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
  3863. $activenode->type == navigation_node::TYPE_RESOURCE)) {
  3864. // We only want to show the menu on the first page of the activity. This means
  3865. // the breadcrumb has no additional nodes.
  3866. if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
  3867. $showcoursemenu = true;
  3868. }
  3869. }
  3870. }
  3871. // This is the site front page.
  3872. if ($context->contextlevel == CONTEXT_COURSE &&
  3873. !empty($currentnode) &&
  3874. $currentnode->key === 'home') {
  3875. $showfrontpagemenu = true;
  3876. }
  3877. // This is the user profile page.
  3878. if ($context->contextlevel == CONTEXT_USER &&
  3879. !empty($currentnode) &&
  3880. ($currentnode->key === 'myprofile')) {
  3881. $showusermenu = true;
  3882. }
  3883. if ($showfrontpagemenu) {
  3884. $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
  3885. if ($settingsnode) {
  3886. // Build an action menu based on the visible nodes from this navigation tree.
  3887. $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
  3888. // We only add a list to the full settings menu if we didn't include every node in the short menu.
  3889. if ($skipped) {
  3890. $text = get_string('morenavigationlinks');
  3891. $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
  3892. $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
  3893. $menu->add_secondary_action($link);
  3894. }
  3895. }
  3896. } else if ($showcoursemenu) {
  3897. $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
  3898. if ($settingsnode) {
  3899. // Build an action menu based on the visible nodes from this navigation tree.
  3900. $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
  3901. // We only add a list to the full settings menu if we didn't include every node in the short menu.
  3902. if ($skipped) {
  3903. $text = get_string('morenavigationlinks');
  3904. $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
  3905. $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
  3906. $menu->add_secondary_action($link);
  3907. }
  3908. }
  3909. } else if ($showusermenu) {
  3910. // Get the course admin node from the settings navigation.
  3911. $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
  3912. if ($settingsnode) {
  3913. // Build an action menu based on the visible nodes from this navigation tree.
  3914. $this->build_action_menu_from_navigation($menu, $settingsnode);
  3915. }
  3916. }
  3917. return $this->render($menu);
  3918. }
  3919. /**
  3920. * Take a node in the nav tree and make an action menu out of it.
  3921. * The links are injected in the action menu.
  3922. *
  3923. * @param action_menu $menu
  3924. * @param navigation_node $node
  3925. * @param boolean $indent
  3926. * @param boolean $onlytopleafnodes
  3927. * @return boolean nodesskipped - True if nodes were skipped in building the menu
  3928. */
  3929. protected function build_action_menu_from_navigation(action_menu $menu,
  3930. navigation_node $node,
  3931. $indent = false,
  3932. $onlytopleafnodes = false) {
  3933. $skipped = false;
  3934. // Build an action menu based on the visible nodes from this navigation tree.
  3935. foreach ($node->children as $menuitem) {
  3936. if ($menuitem->display) {
  3937. if ($onlytopleafnodes && $menuitem->children->count()) {
  3938. $skipped = true;
  3939. continue;
  3940. }
  3941. if ($menuitem->action) {
  3942. if ($menuitem->action instanceof action_link) {
  3943. $link = $menuitem->action;
  3944. // Give preference to setting icon over action icon.
  3945. if (!empty($menuitem->icon)) {
  3946. $link->icon = $menuitem->icon;
  3947. }
  3948. } else {
  3949. $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
  3950. }
  3951. } else {
  3952. if ($onlytopleafnodes) {
  3953. $skipped = true;
  3954. continue;
  3955. }
  3956. $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
  3957. }
  3958. if ($indent) {
  3959. $link->add_class('ml-4');
  3960. }
  3961. if (!empty($menuitem->classes)) {
  3962. $link->add_class(implode(" ", $menuitem->classes));
  3963. }
  3964. $menu->add_secondary_action($link);
  3965. $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
  3966. }
  3967. }
  3968. return $skipped;
  3969. }
  3970. /**
  3971. * This is an optional menu that can be added to a layout by a theme. It contains the
  3972. * menu for the most specific thing from the settings block. E.g. Module administration.
  3973. *
  3974. * @return string
  3975. */
  3976. public function region_main_settings_menu() {
  3977. $context = $this->page->context;
  3978. $menu = new action_menu();
  3979. if ($context->contextlevel == CONTEXT_MODULE) {
  3980. $this->page->navigation->initialise();
  3981. $node = $this->page->navigation->find_active_node();
  3982. $buildmenu = false;
  3983. // If the settings menu has been forced then show the menu.
  3984. if ($this->page->is_settings_menu_forced()) {
  3985. $buildmenu = true;
  3986. } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
  3987. $node->type == navigation_node::TYPE_RESOURCE)) {
  3988. $items = $this->page->navbar->get_items();
  3989. $navbarnode = end($items);
  3990. // We only want to show the menu on the first page of the activity. This means
  3991. // the breadcrumb has no additional nodes.
  3992. if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
  3993. $buildmenu = true;
  3994. }
  3995. }
  3996. if ($buildmenu) {
  3997. // Get the course admin node from the settings navigation.
  3998. $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
  3999. if ($node) {
  4000. // Build an action menu based on the visible nodes from this navigation tree.
  4001. $this->build_action_menu_from_navigation($menu, $node);
  4002. }
  4003. }
  4004. } else if ($context->contextlevel == CONTEXT_COURSECAT) {
  4005. // For course category context, show category settings menu, if we're on the course category page.
  4006. if ($this->page->pagetype === 'course-index-category') {
  4007. $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
  4008. if ($node) {
  4009. // Build an action menu based on the visible nodes from this navigation tree.
  4010. $this->build_action_menu_from_navigation($menu, $node);
  4011. }
  4012. }
  4013. } else {
  4014. $items = $this->page->navbar->get_items();
  4015. $navbarnode = end($items);
  4016. if ($navbarnode && ($navbarnode->key === 'participants')) {
  4017. $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
  4018. if ($node) {
  4019. // Build an action menu based on the visible nodes from this navigation tree.
  4020. $this->build_action_menu_from_navigation($menu, $node);
  4021. }
  4022. }
  4023. }
  4024. return $this->render($menu);
  4025. }
  4026. /**
  4027. * Displays the list of tags associated with an entry
  4028. *
  4029. * @param array $tags list of instances of core_tag or stdClass
  4030. * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
  4031. * to use default, set to '' (empty string) to omit the label completely
  4032. * @param string $classes additional classes for the enclosing div element
  4033. * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
  4034. * will be appended to the end, JS will toggle the rest of the tags
  4035. * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
  4036. * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
  4037. * @return string
  4038. */
  4039. public function tag_list($tags, $label = null, $classes = '', $limit = 10,
  4040. $pagecontext = null, $accesshidelabel = false) {
  4041. $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
  4042. return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
  4043. }
  4044. /**
  4045. * Renders element for inline editing of any value
  4046. *
  4047. * @param \core\output\inplace_editable $element
  4048. * @return string
  4049. */
  4050. public function render_inplace_editable(\core\output\inplace_editable $element) {
  4051. return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
  4052. }
  4053. /**
  4054. * Renders a bar chart.
  4055. *
  4056. * @param \core\chart_bar $chart The chart.
  4057. * @return string.
  4058. */
  4059. public function render_chart_bar(\core\chart_bar $chart) {
  4060. return $this->render_chart($chart);
  4061. }
  4062. /**
  4063. * Renders a line chart.
  4064. *
  4065. * @param \core\chart_line $chart The chart.
  4066. * @return string.
  4067. */
  4068. public function render_chart_line(\core\chart_line $chart) {
  4069. return $this->render_chart($chart);
  4070. }
  4071. /**
  4072. * Renders a pie chart.
  4073. *
  4074. * @param \core\chart_pie $chart The chart.
  4075. * @return string.
  4076. */
  4077. public function render_chart_pie(\core\chart_pie $chart) {
  4078. return $this->render_chart($chart);
  4079. }
  4080. /**
  4081. * Renders a chart.
  4082. *
  4083. * @param \core\chart_base $chart The chart.
  4084. * @param bool $withtable Whether to include a data table with the chart.
  4085. * @return string.
  4086. */
  4087. public function render_chart(\core\chart_base $chart, $withtable = true) {
  4088. $chartdata = json_encode($chart);
  4089. return $this->render_from_template('core/chart', (object) [
  4090. 'chartdata' => $chartdata,
  4091. 'withtable' => $withtable
  4092. ]);
  4093. }
  4094. /**
  4095. * Renders the login form.
  4096. *
  4097. * @param \core_auth\output\login $form The renderable.
  4098. * @return string
  4099. */
  4100. public function render_login(\core_auth\output\login $form) {
  4101. global $CFG, $SITE;
  4102. $context = $form->export_for_template($this);
  4103. // Override because rendering is not supported in template yet.
  4104. if ($CFG->rememberusername == 0) {
  4105. $context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
  4106. } else {
  4107. $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
  4108. }
  4109. $context->errorformatted = $this->error_text($context->error);
  4110. $url = $this->get_logo_url();
  4111. if ($url) {
  4112. $url = $url->out(false);
  4113. }
  4114. $context->logourl = $url;
  4115. $context->sitename = format_string($SITE->fullname, true,
  4116. ['context' => context_course::instance(SITEID), "escape" => false]);
  4117. return $this->render_from_template('core/loginform', $context);
  4118. }
  4119. /**
  4120. * Renders an mform element from a template.
  4121. *
  4122. * @param HTML_QuickForm_element $element element
  4123. * @param bool $required if input is required field
  4124. * @param bool $advanced if input is an advanced field
  4125. * @param string $error error message to display
  4126. * @param bool $ingroup True if this element is rendered as part of a group
  4127. * @return mixed string|bool
  4128. */
  4129. public function mform_element($element, $required, $advanced, $error, $ingroup) {
  4130. $templatename = 'core_form/element-' . $element->getType();
  4131. if ($ingroup) {
  4132. $templatename .= "-inline";
  4133. }
  4134. try {
  4135. // We call this to generate a file not found exception if there is no template.
  4136. // We don't want to call export_for_template if there is no template.
  4137. core\output\mustache_template_finder::get_template_filepath($templatename);
  4138. if ($element instanceof templatable) {
  4139. $elementcontext = $element->export_for_template($this);
  4140. $helpbutton = '';
  4141. if (method_exists($element, 'getHelpButton')) {
  4142. $helpbutton = $element->getHelpButton();
  4143. }
  4144. $label = $element->getLabel();
  4145. $text = '';
  4146. if (method_exists($element, 'getText')) {
  4147. // There currently exists code that adds a form element with an empty label.
  4148. // If this is the case then set the label to the description.
  4149. if (empty($label)) {
  4150. $label = $element->getText();
  4151. } else {
  4152. $text = $element->getText();
  4153. }
  4154. }
  4155. // Generate the form element wrapper ids and names to pass to the template.
  4156. // This differs between group and non-group elements.
  4157. if ($element->getType() === 'group') {
  4158. // Group element.
  4159. // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
  4160. $elementcontext['wrapperid'] = $elementcontext['id'];
  4161. // Ensure group elements pass through the group name as the element name.
  4162. $elementcontext['name'] = $elementcontext['groupname'];
  4163. } else {
  4164. // Non grouped element.
  4165. // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
  4166. $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
  4167. }
  4168. $context = array(
  4169. 'element' => $elementcontext,
  4170. 'label' => $label,
  4171. 'text' => $text,
  4172. 'required' => $required,
  4173. 'advanced' => $advanced,
  4174. 'helpbutton' => $helpbutton,
  4175. 'error' => $error
  4176. );
  4177. return $this->render_from_template($templatename, $context);
  4178. }
  4179. } catch (Exception $e) {
  4180. // No template for this element.
  4181. return false;
  4182. }
  4183. }
  4184. /**
  4185. * Render the login signup form into a nice template for the theme.
  4186. *
  4187. * @param mform $form
  4188. * @return string
  4189. */
  4190. public function render_login_signup_form($form) {
  4191. global $SITE;
  4192. $context = $form->export_for_template($this);
  4193. $url = $this->get_logo_url();
  4194. if ($url) {
  4195. $url = $url->out(false);
  4196. }
  4197. $context['logourl'] = $url;
  4198. $context['sitename'] = format_string($SITE->fullname, true,
  4199. ['context' => context_course::instance(SITEID), "escape" => false]);
  4200. return $this->render_from_template('core/signup_form_layout', $context);
  4201. }
  4202. /**
  4203. * Render the verify age and location page into a nice template for the theme.
  4204. *
  4205. * @param \core_auth\output\verify_age_location_page $page The renderable
  4206. * @return string
  4207. */
  4208. protected function render_verify_age_location_page($page) {
  4209. $context = $page->export_for_template($this);
  4210. return $this->render_from_template('core/auth_verify_age_location_page', $context);
  4211. }
  4212. /**
  4213. * Render the digital minor contact information page into a nice template for the theme.
  4214. *
  4215. * @param \core_auth\output\digital_minor_page $page The renderable
  4216. * @return string
  4217. */
  4218. protected function render_digital_minor_page($page) {
  4219. $context = $page->export_for_template($this);
  4220. return $this->render_from_template('core/auth_digital_minor_page', $context);
  4221. }
  4222. /**
  4223. * Renders a progress bar.
  4224. *
  4225. * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
  4226. *
  4227. * @param progress_bar $bar The bar.
  4228. * @return string HTML fragment
  4229. */
  4230. public function render_progress_bar(progress_bar $bar) {
  4231. $data = $bar->export_for_template($this);
  4232. return $this->render_from_template('core/progress_bar', $data);
  4233. }
  4234. /**
  4235. * Renders element for a toggle-all checkbox.
  4236. *
  4237. * @param \core\output\checkbox_toggleall $element
  4238. * @return string
  4239. */
  4240. public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
  4241. return $this->render_from_template($element->get_template(), $element->export_for_template($this));
  4242. }
  4243. }
  4244. /**
  4245. * A renderer that generates output for command-line scripts.
  4246. *
  4247. * The implementation of this renderer is probably incomplete.
  4248. *
  4249. * @copyright 2009 Tim Hunt
  4250. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4251. * @since Moodle 2.0
  4252. * @package core
  4253. * @category output
  4254. */
  4255. class core_renderer_cli extends core_renderer {
  4256. /**
  4257. * Returns the page header.
  4258. *
  4259. * @return string HTML fragment
  4260. */
  4261. public function header() {
  4262. return $this->page->heading . "\n";
  4263. }
  4264. /**
  4265. * Renders a Check API result
  4266. *
  4267. * To aid in CLI consistency this status is NOT translated and the visual
  4268. * width is always exactly 10 chars.
  4269. *
  4270. * @param result $result
  4271. * @return string HTML fragment
  4272. */
  4273. protected function render_check_result(core\check\result $result) {
  4274. $status = $result->get_status();
  4275. $labels = [
  4276. core\check\result::NA => ' ' . cli_ansi_format('<colour:gray>' ) . ' NA ',
  4277. core\check\result::OK => ' ' . cli_ansi_format('<colour:green>') . ' OK ',
  4278. core\check\result::INFO => ' ' . cli_ansi_format('<colour:blue>' ) . ' INFO ',
  4279. core\check\result::UNKNOWN => ' ' . cli_ansi_format('<colour:grey>' ) . ' UNKNOWN ',
  4280. core\check\result::WARNING => ' ' . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
  4281. core\check\result::ERROR => ' ' . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
  4282. core\check\result::CRITICAL => '' . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
  4283. ];
  4284. $string = $labels[$status] . cli_ansi_format('<colour:normal>');
  4285. return $string;
  4286. }
  4287. /**
  4288. * Renders a Check API result
  4289. *
  4290. * @param result $result
  4291. * @return string fragment
  4292. */
  4293. public function check_result(core\check\result $result) {
  4294. return $this->render_check_result($result);
  4295. }
  4296. /**
  4297. * Returns a template fragment representing a Heading.
  4298. *
  4299. * @param string $text The text of the heading
  4300. * @param int $level The level of importance of the heading
  4301. * @param string $classes A space-separated list of CSS classes
  4302. * @param string $id An optional ID
  4303. * @return string A template fragment for a heading
  4304. */
  4305. public function heading($text, $level = 2, $classes = 'main', $id = null) {
  4306. $text .= "\n";
  4307. switch ($level) {
  4308. case 1:
  4309. return '=>' . $text;
  4310. case 2:
  4311. return '-->' . $text;
  4312. default:
  4313. return $text;
  4314. }
  4315. }
  4316. /**
  4317. * Returns a template fragment representing a fatal error.
  4318. *
  4319. * @param string $message The message to output
  4320. * @param string $moreinfourl URL where more info can be found about the error
  4321. * @param string $link Link for the Continue button
  4322. * @param array $backtrace The execution backtrace
  4323. * @param string $debuginfo Debugging information
  4324. * @return string A template fragment for a fatal error
  4325. */
  4326. public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
  4327. global $CFG;
  4328. $output = "!!! $message !!!\n";
  4329. if ($CFG->debugdeveloper) {
  4330. if (!empty($debuginfo)) {
  4331. $output .= $this->notification($debuginfo, 'notifytiny');
  4332. }
  4333. if (!empty($backtrace)) {
  4334. $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
  4335. }
  4336. }
  4337. return $output;
  4338. }
  4339. /**
  4340. * Returns a template fragment representing a notification.
  4341. *
  4342. * @param string $message The message to print out.
  4343. * @param string $type The type of notification. See constants on \core\output\notification.
  4344. * @return string A template fragment for a notification
  4345. */
  4346. public function notification($message, $type = null) {
  4347. $message = clean_text($message);
  4348. if ($type === 'notifysuccess' || $type === 'success') {
  4349. return "++ $message ++\n";
  4350. }
  4351. return "!! $message !!\n";
  4352. }
  4353. /**
  4354. * There is no footer for a cli request, however we must override the
  4355. * footer method to prevent the default footer.
  4356. */
  4357. public function footer() {}
  4358. /**
  4359. * Render a notification (that is, a status message about something that has
  4360. * just happened).
  4361. *
  4362. * @param \core\output\notification $notification the notification to print out
  4363. * @return string plain text output
  4364. */
  4365. public function render_notification(\core\output\notification $notification) {
  4366. return $this->notification($notification->get_message(), $notification->get_message_type());
  4367. }
  4368. }
  4369. /**
  4370. * A renderer that generates output for ajax scripts.
  4371. *
  4372. * This renderer prevents accidental sends back only json
  4373. * encoded error messages, all other output is ignored.
  4374. *
  4375. * @copyright 2010 Petr Skoda
  4376. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4377. * @since Moodle 2.0
  4378. * @package core
  4379. * @category output
  4380. */
  4381. class core_renderer_ajax extends core_renderer {
  4382. /**
  4383. * Returns a template fragment representing a fatal error.
  4384. *
  4385. * @param string $message The message to output
  4386. * @param string $moreinfourl URL where more info can be found about the error
  4387. * @param string $link Link for the Continue button
  4388. * @param array $backtrace The execution backtrace
  4389. * @param string $debuginfo Debugging information
  4390. * @return string A template fragment for a fatal error
  4391. */
  4392. public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
  4393. global $CFG;
  4394. $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
  4395. $e = new stdClass();
  4396. $e->error = $message;
  4397. $e->errorcode = $errorcode;
  4398. $e->stacktrace = NULL;
  4399. $e->debuginfo = NULL;
  4400. $e->reproductionlink = NULL;
  4401. if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
  4402. $link = (string) $link;
  4403. if ($link) {
  4404. $e->reproductionlink = $link;
  4405. }
  4406. if (!empty($debuginfo)) {
  4407. $e->debuginfo = $debuginfo;
  4408. }
  4409. if (!empty($backtrace)) {
  4410. $e->stacktrace = format_backtrace($backtrace, true);
  4411. }
  4412. }
  4413. $this->header();
  4414. return json_encode($e);
  4415. }
  4416. /**
  4417. * Used to display a notification.
  4418. * For the AJAX notifications are discarded.
  4419. *
  4420. * @param string $message The message to print out.
  4421. * @param string $type The type of notification. See constants on \core\output\notification.
  4422. */
  4423. public function notification($message, $type = null) {}
  4424. /**
  4425. * Used to display a redirection message.
  4426. * AJAX redirections should not occur and as such redirection messages
  4427. * are discarded.
  4428. *
  4429. * @param moodle_url|string $encodedurl
  4430. * @param string $message
  4431. * @param int $delay
  4432. * @param bool $debugdisableredirect
  4433. * @param string $messagetype The type of notification to show the message in.
  4434. * See constants on \core\output\notification.
  4435. */
  4436. public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
  4437. $messagetype = \core\output\notification::NOTIFY_INFO) {}
  4438. /**
  4439. * Prepares the start of an AJAX output.
  4440. */
  4441. public function header() {
  4442. // unfortunately YUI iframe upload does not support application/json
  4443. if (!empty($_FILES)) {
  4444. @header('Content-type: text/plain; charset=utf-8');
  4445. if (!core_useragent::supports_json_contenttype()) {
  4446. @header('X-Content-Type-Options: nosniff');
  4447. }
  4448. } else if (!core_useragent::supports_json_contenttype()) {
  4449. @header('Content-type: text/plain; charset=utf-8');
  4450. @header('X-Content-Type-Options: nosniff');
  4451. } else {
  4452. @header('Content-type: application/json; charset=utf-8');
  4453. }
  4454. // Headers to make it not cacheable and json
  4455. @header('Cache-Control: no-store, no-cache, must-revalidate');
  4456. @header('Cache-Control: post-check=0, pre-check=0', false);
  4457. @header('Pragma: no-cache');
  4458. @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
  4459. @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  4460. @header('Accept-Ranges: none');
  4461. }
  4462. /**
  4463. * There is no footer for an AJAX request, however we must override the
  4464. * footer method to prevent the default footer.
  4465. */
  4466. public function footer() {}
  4467. /**
  4468. * No need for headers in an AJAX request... this should never happen.
  4469. * @param string $text
  4470. * @param int $level
  4471. * @param string $classes
  4472. * @param string $id
  4473. */
  4474. public function heading($text, $level = 2, $classes = 'main', $id = null) {}
  4475. }
  4476. /**
  4477. * The maintenance renderer.
  4478. *
  4479. * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
  4480. * is running a maintenance related task.
  4481. * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
  4482. *
  4483. * @since Moodle 2.6
  4484. * @package core
  4485. * @category output
  4486. * @copyright 2013 Sam Hemelryk
  4487. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4488. */
  4489. class core_renderer_maintenance extends core_renderer {
  4490. /**
  4491. * Initialises the renderer instance.
  4492. *
  4493. * @param moodle_page $page
  4494. * @param string $target
  4495. * @throws coding_exception
  4496. */
  4497. public function __construct(moodle_page $page, $target) {
  4498. if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
  4499. throw new coding_exception('Invalid request for the maintenance renderer.');
  4500. }
  4501. parent::__construct($page, $target);
  4502. }
  4503. /**
  4504. * Does nothing. The maintenance renderer cannot produce blocks.
  4505. *
  4506. * @param block_contents $bc
  4507. * @param string $region
  4508. * @return string
  4509. */
  4510. public function block(block_contents $bc, $region) {
  4511. return '';
  4512. }
  4513. /**
  4514. * Does nothing. The maintenance renderer cannot produce blocks.
  4515. *
  4516. * @param string $region
  4517. * @param array $classes
  4518. * @param string $tag
  4519. * @return string
  4520. */
  4521. public function blocks($region, $classes = array(), $tag = 'aside') {
  4522. return '';
  4523. }
  4524. /**
  4525. * Does nothing. The maintenance renderer cannot produce blocks.
  4526. *
  4527. * @param string $region
  4528. * @return string
  4529. */
  4530. public function blocks_for_region($region) {
  4531. return '';
  4532. }
  4533. /**
  4534. * Does nothing. The maintenance renderer cannot produce a course content header.
  4535. *
  4536. * @param bool $onlyifnotcalledbefore
  4537. * @return string
  4538. */
  4539. public function course_content_header($onlyifnotcalledbefore = false) {
  4540. return '';
  4541. }
  4542. /**
  4543. * Does nothing. The maintenance renderer cannot produce a course content footer.
  4544. *
  4545. * @param bool $onlyifnotcalledbefore
  4546. * @return string
  4547. */
  4548. public function course_content_footer($onlyifnotcalledbefore = false) {
  4549. return '';
  4550. }
  4551. /**
  4552. * Does nothing. The maintenance renderer cannot produce a course header.
  4553. *
  4554. * @return string
  4555. */
  4556. public function course_header() {
  4557. return '';
  4558. }
  4559. /**
  4560. * Does nothing. The maintenance renderer cannot produce a course footer.
  4561. *
  4562. * @return string
  4563. */
  4564. public function course_footer() {
  4565. return '';
  4566. }
  4567. /**
  4568. * Does nothing. The maintenance renderer cannot produce a custom menu.
  4569. *
  4570. * @param string $custommenuitems
  4571. * @return string
  4572. */
  4573. public function custom_menu($custommenuitems = '') {
  4574. return '';
  4575. }
  4576. /**
  4577. * Does nothing. The maintenance renderer cannot produce a file picker.
  4578. *
  4579. * @param array $options
  4580. * @return string
  4581. */
  4582. public function file_picker($options) {
  4583. return '';
  4584. }
  4585. /**
  4586. * Does nothing. The maintenance renderer cannot produce and HTML file tree.
  4587. *
  4588. * @param array $dir
  4589. * @return string
  4590. */
  4591. public function htmllize_file_tree($dir) {
  4592. return '';
  4593. }
  4594. /**
  4595. * Overridden confirm message for upgrades.
  4596. *
  4597. * @param string $message The question to ask the user
  4598. * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
  4599. * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
  4600. * @return string HTML fragment
  4601. */
  4602. public function confirm($message, $continue, $cancel) {
  4603. // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
  4604. // from any previous version of Moodle).
  4605. if ($continue instanceof single_button) {
  4606. $continue->primary = true;
  4607. } else if (is_string($continue)) {
  4608. $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
  4609. } else if ($continue instanceof moodle_url) {
  4610. $continue = new single_button($continue, get_string('continue'), 'post', true);
  4611. } else {
  4612. throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
  4613. ' (string/moodle_url) or a single_button instance.');
  4614. }
  4615. if ($cancel instanceof single_button) {
  4616. $output = '';
  4617. } else if (is_string($cancel)) {
  4618. $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
  4619. } else if ($cancel instanceof moodle_url) {
  4620. $cancel = new single_button($cancel, get_string('cancel'), 'get');
  4621. } else {
  4622. throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
  4623. ' (string/moodle_url) or a single_button instance.');
  4624. }
  4625. $output = $this->box_start('generalbox', 'notice');
  4626. $output .= html_writer::tag('h4', get_string('confirm'));
  4627. $output .= html_writer::tag('p', $message);
  4628. $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
  4629. $output .= $this->box_end();
  4630. return $output;
  4631. }
  4632. /**
  4633. * Does nothing. The maintenance renderer does not support JS.
  4634. *
  4635. * @param block_contents $bc
  4636. */
  4637. public function init_block_hider_js(block_contents $bc) {
  4638. // Does nothing.
  4639. }
  4640. /**
  4641. * Does nothing. The maintenance renderer cannot produce language menus.
  4642. *
  4643. * @return string
  4644. */
  4645. public function lang_menu() {
  4646. return '';
  4647. }
  4648. /**
  4649. * Does nothing. The maintenance renderer has no need for login information.
  4650. *
  4651. * @param null $withlinks
  4652. * @return string
  4653. */
  4654. public function login_info($withlinks = null) {
  4655. return '';
  4656. }
  4657. /**
  4658. * Secure login info.
  4659. *
  4660. * @return string
  4661. */
  4662. public function secure_login_info() {
  4663. return $this->login_info(false);
  4664. }
  4665. /**
  4666. * Does nothing. The maintenance renderer cannot produce user pictures.
  4667. *
  4668. * @param stdClass $user
  4669. * @param array $options
  4670. * @return string
  4671. */
  4672. public function user_picture(stdClass $user, array $options = null) {
  4673. return '';
  4674. }
  4675. }