PageRenderTime 49ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/outputrenderers.php

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