PageRenderTime 88ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/outputrenderers.php

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