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

/lib/outputrenderers.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 4036 lines | 2040 code | 409 blank | 1587 comment | 444 complexity | 4862e94af8a96ce6044417edac40dbff MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-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. defined('MOODLE_INTERNAL') || die();
  37. /**
  38. * Simple base class for Moodle renderers.
  39. *
  40. * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
  41. *
  42. * Also has methods to facilitate generating HTML output.
  43. *
  44. * @copyright 2009 Tim Hunt
  45. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  46. * @since Moodle 2.0
  47. * @package core
  48. * @category output
  49. */
  50. class renderer_base {
  51. /**
  52. * @var xhtml_container_stack The xhtml_container_stack to use.
  53. */
  54. protected $opencontainers;
  55. /**
  56. * @var moodle_page The Moodle page the renderer has been created to assist with.
  57. */
  58. protected $page;
  59. /**
  60. * @var string The requested rendering target.
  61. */
  62. protected $target;
  63. /**
  64. * Constructor
  65. *
  66. * The constructor takes two arguments. The first is the page that the renderer
  67. * has been created to assist with, and the second is the target.
  68. * The target is an additional identifier that can be used to load different
  69. * renderers for different options.
  70. *
  71. * @param moodle_page $page the page we are doing output for.
  72. * @param string $target one of rendering target constants
  73. */
  74. public function __construct(moodle_page $page, $target) {
  75. $this->opencontainers = $page->opencontainers;
  76. $this->page = $page;
  77. $this->target = $target;
  78. }
  79. /**
  80. * Returns rendered widget.
  81. *
  82. * The provided widget needs to be an object that extends the renderable
  83. * interface.
  84. * If will then be rendered by a method based upon the classname for the widget.
  85. * For instance a widget of class `crazywidget` will be rendered by a protected
  86. * render_crazywidget method of this renderer.
  87. *
  88. * @param renderable $widget instance with renderable interface
  89. * @return string
  90. */
  91. public function render(renderable $widget) {
  92. $rendermethod = 'render_'.get_class($widget);
  93. if (method_exists($this, $rendermethod)) {
  94. return $this->$rendermethod($widget);
  95. }
  96. throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
  97. }
  98. /**
  99. * Adds a JS action for the element with the provided id.
  100. *
  101. * This method adds a JS event for the provided component action to the page
  102. * and then returns the id that the event has been attached to.
  103. * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
  104. *
  105. * @param component_action $action
  106. * @param string $id
  107. * @return string id of element, either original submitted or random new if not supplied
  108. */
  109. public function add_action_handler(component_action $action, $id = null) {
  110. if (!$id) {
  111. $id = html_writer::random_id($action->event);
  112. }
  113. $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
  114. return $id;
  115. }
  116. /**
  117. * Returns true is output has already started, and false if not.
  118. *
  119. * @return boolean true if the header has been printed.
  120. */
  121. public function has_started() {
  122. return $this->page->state >= moodle_page::STATE_IN_BODY;
  123. }
  124. /**
  125. * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
  126. *
  127. * @param mixed $classes Space-separated string or array of classes
  128. * @return string HTML class attribute value
  129. */
  130. public static function prepare_classes($classes) {
  131. if (is_array($classes)) {
  132. return implode(' ', array_unique($classes));
  133. }
  134. return $classes;
  135. }
  136. /**
  137. * Return the moodle_url for an image.
  138. *
  139. * The exact image location and extension is determined
  140. * automatically by searching for gif|png|jpg|jpeg, please
  141. * note there can not be diferent images with the different
  142. * extension. The imagename is for historical reasons
  143. * a relative path name, it may be changed later for core
  144. * images. It is recommended to not use subdirectories
  145. * in plugin and theme pix directories.
  146. *
  147. * There are three types of images:
  148. * 1/ theme images - stored in theme/mytheme/pix/,
  149. * use component 'theme'
  150. * 2/ core images - stored in /pix/,
  151. * overridden via theme/mytheme/pix_core/
  152. * 3/ plugin images - stored in mod/mymodule/pix,
  153. * overridden via theme/mytheme/pix_plugins/mod/mymodule/,
  154. * example: pix_url('comment', 'mod_glossary')
  155. *
  156. * @param string $imagename the pathname of the image
  157. * @param string $component full plugin name (aka component) or 'theme'
  158. * @return moodle_url
  159. */
  160. public function pix_url($imagename, $component = 'moodle') {
  161. return $this->page->theme->pix_url($imagename, $component);
  162. }
  163. }
  164. /**
  165. * Basis for all plugin renderers.
  166. *
  167. * @copyright Petr Skoda (skodak)
  168. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  169. * @since Moodle 2.0
  170. * @package core
  171. * @category output
  172. */
  173. class plugin_renderer_base extends renderer_base {
  174. /**
  175. * @var renderer_base|core_renderer A reference to the current renderer.
  176. * The renderer provided here will be determined by the page but will in 90%
  177. * of cases by the {@link core_renderer}
  178. */
  179. protected $output;
  180. /**
  181. * Constructor method, calls the parent constructor
  182. *
  183. * @param moodle_page $page
  184. * @param string $target one of rendering target constants
  185. */
  186. public function __construct(moodle_page $page, $target) {
  187. if (empty($target) && $page->pagelayout === 'maintenance') {
  188. // If the page is using the maintenance layout then we're going to force the target to maintenance.
  189. // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
  190. // unavailable for this page layout.
  191. $target = RENDERER_TARGET_MAINTENANCE;
  192. }
  193. $this->output = $page->get_renderer('core', null, $target);
  194. parent::__construct($page, $target);
  195. }
  196. /**
  197. * Renders the provided widget and returns the HTML to display it.
  198. *
  199. * @param renderable $widget instance with renderable interface
  200. * @return string
  201. */
  202. public function render(renderable $widget) {
  203. $rendermethod = 'render_'.get_class($widget);
  204. if (method_exists($this, $rendermethod)) {
  205. return $this->$rendermethod($widget);
  206. }
  207. // pass to core renderer if method not found here
  208. return $this->output->render($widget);
  209. }
  210. /**
  211. * Magic method used to pass calls otherwise meant for the standard renderer
  212. * to it to ensure we don't go causing unnecessary grief.
  213. *
  214. * @param string $method
  215. * @param array $arguments
  216. * @return mixed
  217. */
  218. public function __call($method, $arguments) {
  219. if (method_exists('renderer_base', $method)) {
  220. throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
  221. }
  222. if (method_exists($this->output, $method)) {
  223. return call_user_func_array(array($this->output, $method), $arguments);
  224. } else {
  225. throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
  226. }
  227. }
  228. }
  229. /**
  230. * The standard implementation of the core_renderer interface.
  231. *
  232. * @copyright 2009 Tim Hunt
  233. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  234. * @since Moodle 2.0
  235. * @package core
  236. * @category output
  237. */
  238. class core_renderer extends renderer_base {
  239. /**
  240. * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
  241. * in layout files instead.
  242. * @deprecated
  243. * @var string used in {@link core_renderer::header()}.
  244. */
  245. const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
  246. /**
  247. * @var string Used to pass information from {@link core_renderer::doctype()} to
  248. * {@link core_renderer::standard_head_html()}.
  249. */
  250. protected $contenttype;
  251. /**
  252. * @var string Used by {@link core_renderer::redirect_message()} method to communicate
  253. * with {@link core_renderer::header()}.
  254. */
  255. protected $metarefreshtag = '';
  256. /**
  257. * @var string Unique token for the closing HTML
  258. */
  259. protected $unique_end_html_token;
  260. /**
  261. * @var string Unique token for performance information
  262. */
  263. protected $unique_performance_info_token;
  264. /**
  265. * @var string Unique token for the main content.
  266. */
  267. protected $unique_main_content_token;
  268. /**
  269. * Constructor
  270. *
  271. * @param moodle_page $page the page we are doing output for.
  272. * @param string $target one of rendering target constants
  273. */
  274. public function __construct(moodle_page $page, $target) {
  275. $this->opencontainers = $page->opencontainers;
  276. $this->page = $page;
  277. $this->target = $target;
  278. $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
  279. $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
  280. $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
  281. }
  282. /**
  283. * Get the DOCTYPE declaration that should be used with this page. Designed to
  284. * be called in theme layout.php files.
  285. *
  286. * @return string the DOCTYPE declaration that should be used.
  287. */
  288. public function doctype() {
  289. if ($this->page->theme->doctype === 'html5') {
  290. $this->contenttype = 'text/html; charset=utf-8';
  291. return "<!DOCTYPE html>\n";
  292. } else if ($this->page->theme->doctype === 'xhtml5') {
  293. $this->contenttype = 'application/xhtml+xml; charset=utf-8';
  294. return "<!DOCTYPE html>\n";
  295. } else {
  296. // legacy xhtml 1.0
  297. $this->contenttype = 'text/html; charset=utf-8';
  298. return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
  299. }
  300. }
  301. /**
  302. * The attributes that should be added to the <html> tag. Designed to
  303. * be called in theme layout.php files.
  304. *
  305. * @return string HTML fragment.
  306. */
  307. public function htmlattributes() {
  308. $return = get_html_lang(true);
  309. if ($this->page->theme->doctype !== 'html5') {
  310. $return .= ' xmlns="http://www.w3.org/1999/xhtml"';
  311. }
  312. return $return;
  313. }
  314. /**
  315. * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
  316. * that should be included in the <head> tag. Designed to be called in theme
  317. * layout.php files.
  318. *
  319. * @return string HTML fragment.
  320. */
  321. public function standard_head_html() {
  322. global $CFG, $SESSION;
  323. // Before we output any content, we need to ensure that certain
  324. // page components are set up.
  325. // Blocks must be set up early as they may require javascript which
  326. // has to be included in the page header before output is created.
  327. foreach ($this->page->blocks->get_regions() as $region) {
  328. $this->page->blocks->ensure_content_created($region, $this);
  329. }
  330. $output = '';
  331. $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
  332. $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
  333. if (!$this->page->cacheable) {
  334. $output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
  335. $output .= '<meta http-equiv="expires" content="0" />' . "\n";
  336. }
  337. // This is only set by the {@link redirect()} method
  338. $output .= $this->metarefreshtag;
  339. // Check if a periodic refresh delay has been set and make sure we arn't
  340. // already meta refreshing
  341. if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
  342. $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
  343. }
  344. // flow player embedding support
  345. $this->page->requires->js_function_call('M.util.load_flowplayer');
  346. // Set up help link popups for all links with the helptooltip class
  347. $this->page->requires->js_init_call('M.util.help_popups.setup');
  348. // Setup help icon overlays.
  349. $this->page->requires->yui_module('moodle-core-popuphelp', 'M.core.init_popuphelp');
  350. $this->page->requires->strings_for_js(array(
  351. 'morehelp',
  352. 'loadinghelp',
  353. ), 'moodle');
  354. $this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
  355. $focus = $this->page->focuscontrol;
  356. if (!empty($focus)) {
  357. if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
  358. // This is a horrifically bad way to handle focus but it is passed in
  359. // through messy formslib::moodleform
  360. $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
  361. } else if (strpos($focus, '.')!==false) {
  362. // Old style of focus, bad way to do it
  363. 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);
  364. $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
  365. } else {
  366. // Focus element with given id
  367. $this->page->requires->js_function_call('focuscontrol', array($focus));
  368. }
  369. }
  370. // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
  371. // any other custom CSS can not be overridden via themes and is highly discouraged
  372. $urls = $this->page->theme->css_urls($this->page);
  373. foreach ($urls as $url) {
  374. $this->page->requires->css_theme($url);
  375. }
  376. // Get the theme javascript head and footer
  377. if ($jsurl = $this->page->theme->javascript_url(true)) {
  378. $this->page->requires->js($jsurl, true);
  379. }
  380. if ($jsurl = $this->page->theme->javascript_url(false)) {
  381. $this->page->requires->js($jsurl);
  382. }
  383. // Get any HTML from the page_requirements_manager.
  384. $output .= $this->page->requires->get_head_code($this->page, $this);
  385. // List alternate versions.
  386. foreach ($this->page->alternateversions as $type => $alt) {
  387. $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
  388. 'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
  389. }
  390. if (!empty($CFG->additionalhtmlhead)) {
  391. $output .= "\n".$CFG->additionalhtmlhead;
  392. }
  393. return $output;
  394. }
  395. /**
  396. * The standard tags (typically skip links) that should be output just inside
  397. * the start of the <body> tag. Designed to be called in theme layout.php files.
  398. *
  399. * @return string HTML fragment.
  400. */
  401. public function standard_top_of_body_html() {
  402. global $CFG;
  403. $output = $this->page->requires->get_top_of_body_code();
  404. if (!empty($CFG->additionalhtmltopofbody)) {
  405. $output .= "\n".$CFG->additionalhtmltopofbody;
  406. }
  407. $output .= $this->maintenance_warning();
  408. return $output;
  409. }
  410. /**
  411. * Scheduled maintenance warning message.
  412. *
  413. * Note: This is a nasty hack to display maintenance notice, this should be moved
  414. * to some general notification area once we have it.
  415. *
  416. * @return string
  417. */
  418. public function maintenance_warning() {
  419. global $CFG;
  420. $output = '';
  421. if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
  422. $output .= $this->box_start('errorbox maintenancewarning');
  423. $output .= get_string('maintenancemodeisscheduled', 'admin', (int)(($CFG->maintenance_later-time())/60));
  424. $output .= $this->box_end();
  425. }
  426. return $output;
  427. }
  428. /**
  429. * The standard tags (typically performance information and validation links,
  430. * if we are in developer debug mode) that should be output in the footer area
  431. * of the page. Designed to be called in theme layout.php files.
  432. *
  433. * @return string HTML fragment.
  434. */
  435. public function standard_footer_html() {
  436. global $CFG, $SCRIPT;
  437. if (during_initial_install()) {
  438. // Debugging info can not work before install is finished,
  439. // in any case we do not want any links during installation!
  440. return '';
  441. }
  442. // This function is normally called from a layout.php file in {@link core_renderer::header()}
  443. // but some of the content won't be known until later, so we return a placeholder
  444. // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
  445. $output = $this->unique_performance_info_token;
  446. if ($this->page->devicetypeinuse == 'legacy') {
  447. // The legacy theme is in use print the notification
  448. $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
  449. }
  450. // Get links to switch device types (only shown for users not on a default device)
  451. $output .= $this->theme_switch_links();
  452. if (!empty($CFG->debugpageinfo)) {
  453. $output .= '<div class="performanceinfo pageinfo">This page is: ' . $this->page->debug_summary() . '</div>';
  454. }
  455. if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode
  456. // Add link to profiling report if necessary
  457. if (function_exists('profiling_is_running') && profiling_is_running()) {
  458. $txt = get_string('profiledscript', 'admin');
  459. $title = get_string('profiledscriptview', 'admin');
  460. $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
  461. $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
  462. $output .= '<div class="profilingfooter">' . $link . '</div>';
  463. }
  464. $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
  465. 'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
  466. $output .= '<div class="purgecaches">' .
  467. html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
  468. }
  469. if (!empty($CFG->debugvalidators)) {
  470. // NOTE: this is not a nice hack, $PAGE->url is not always accurate and $FULLME neither, it is not a bug if it fails. --skodak
  471. $output .= '<div class="validators"><ul>
  472. <li><a href="http://validator.w3.org/check?verbose=1&amp;ss=1&amp;uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
  473. <li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&amp;url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
  474. <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>
  475. </ul></div>';
  476. }
  477. return $output;
  478. }
  479. /**
  480. * Returns standard main content placeholder.
  481. * Designed to be called in theme layout.php files.
  482. *
  483. * @return string HTML fragment.
  484. */
  485. public function main_content() {
  486. // This is here because it is the only place we can inject the "main" role over the entire main content area
  487. // without requiring all theme's to manually do it, and without creating yet another thing people need to
  488. // remember in the theme.
  489. // This is an unfortunate hack. DO NO EVER add anything more here.
  490. // DO NOT add classes.
  491. // DO NOT add an id.
  492. return '<div role="main">'.$this->unique_main_content_token.'</div>';
  493. }
  494. /**
  495. * The standard tags (typically script tags that are not needed earlier) that
  496. * should be output after everything else. Designed to be called in theme layout.php files.
  497. *
  498. * @return string HTML fragment.
  499. */
  500. public function standard_end_of_body_html() {
  501. global $CFG;
  502. // This function is normally called from a layout.php file in {@link core_renderer::header()}
  503. // but some of the content won't be known until later, so we return a placeholder
  504. // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
  505. $output = '';
  506. if (!empty($CFG->additionalhtmlfooter)) {
  507. $output .= "\n".$CFG->additionalhtmlfooter;
  508. }
  509. $output .= $this->unique_end_html_token;
  510. return $output;
  511. }
  512. /**
  513. * Return the standard string that says whether you are logged in (and switched
  514. * roles/logged in as another user).
  515. * @param bool $withlinks if false, then don't include any links in the HTML produced.
  516. * If not set, the default is the nologinlinks option from the theme config.php file,
  517. * and if that is not set, then links are included.
  518. * @return string HTML fragment.
  519. */
  520. public function login_info($withlinks = null) {
  521. global $USER, $CFG, $DB, $SESSION;
  522. if (during_initial_install()) {
  523. return '';
  524. }
  525. if (is_null($withlinks)) {
  526. $withlinks = empty($this->page->layout_options['nologinlinks']);
  527. }
  528. $loginpage = ((string)$this->page->url === get_login_url());
  529. $course = $this->page->course;
  530. if (\core\session\manager::is_loggedinas()) {
  531. $realuser = \core\session\manager::get_realuser();
  532. $fullname = fullname($realuser, true);
  533. if ($withlinks) {
  534. $loginastitle = get_string('loginas');
  535. $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
  536. $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
  537. } else {
  538. $realuserinfo = " [$fullname] ";
  539. }
  540. } else {
  541. $realuserinfo = '';
  542. }
  543. $loginurl = get_login_url();
  544. if (empty($course->id)) {
  545. // $course->id is not defined during installation
  546. return '';
  547. } else if (isloggedin()) {
  548. $context = context_course::instance($course->id);
  549. $fullname = fullname($USER, true);
  550. // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
  551. if ($withlinks) {
  552. $linktitle = get_string('viewprofile');
  553. $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
  554. } else {
  555. $username = $fullname;
  556. }
  557. if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
  558. if ($withlinks) {
  559. $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
  560. } else {
  561. $username .= " from {$idprovider->name}";
  562. }
  563. }
  564. if (isguestuser()) {
  565. $loggedinas = $realuserinfo.get_string('loggedinasguest');
  566. if (!$loginpage && $withlinks) {
  567. $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
  568. }
  569. } else if (is_role_switched($course->id)) { // Has switched roles
  570. $rolename = '';
  571. if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
  572. $rolename = ': '.role_get_name($role, $context);
  573. }
  574. $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
  575. if ($withlinks) {
  576. $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
  577. $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
  578. }
  579. } else {
  580. $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
  581. if ($withlinks) {
  582. $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
  583. }
  584. }
  585. } else {
  586. $loggedinas = get_string('loggedinnot', 'moodle');
  587. if (!$loginpage && $withlinks) {
  588. $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
  589. }
  590. }
  591. $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
  592. if (isset($SESSION->justloggedin)) {
  593. unset($SESSION->justloggedin);
  594. if (!empty($CFG->displayloginfailures)) {
  595. if (!isguestuser()) {
  596. if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
  597. $loggedinas .= '&nbsp;<div class="loginfailures">';
  598. if (empty($count->accounts)) {
  599. $loggedinas .= get_string('failedloginattempts', '', $count);
  600. } else {
  601. $loggedinas .= get_string('failedloginattemptsall', '', $count);
  602. }
  603. if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
  604. $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
  605. '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
  606. }
  607. $loggedinas .= '</div>';
  608. }
  609. }
  610. }
  611. }
  612. return $loggedinas;
  613. }
  614. /**
  615. * Return the 'back' link that normally appears in the footer.
  616. *
  617. * @return string HTML fragment.
  618. */
  619. public function home_link() {
  620. global $CFG, $SITE;
  621. if ($this->page->pagetype == 'site-index') {
  622. // Special case for site home page - please do not remove
  623. return '<div class="sitelink">' .
  624. '<a title="Moodle" href="http://moodle.org/">' .
  625. '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
  626. } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
  627. // Special case for during install/upgrade.
  628. return '<div class="sitelink">'.
  629. '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
  630. '<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
  631. } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
  632. return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
  633. get_string('home') . '</a></div>';
  634. } else {
  635. return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
  636. format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
  637. }
  638. }
  639. /**
  640. * Redirects the user by any means possible given the current state
  641. *
  642. * This function should not be called directly, it should always be called using
  643. * the redirect function in lib/weblib.php
  644. *
  645. * The redirect function should really only be called before page output has started
  646. * however it will allow itself to be called during the state STATE_IN_BODY
  647. *
  648. * @param string $encodedurl The URL to send to encoded if required
  649. * @param string $message The message to display to the user if any
  650. * @param int $delay The delay before redirecting a user, if $message has been
  651. * set this is a requirement and defaults to 3, set to 0 no delay
  652. * @param boolean $debugdisableredirect this redirect has been disabled for
  653. * debugging purposes. Display a message that explains, and don't
  654. * trigger the redirect.
  655. * @return string The HTML to display to the user before dying, may contain
  656. * meta refresh, javascript refresh, and may have set header redirects
  657. */
  658. public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
  659. global $CFG;
  660. $url = str_replace('&amp;', '&', $encodedurl);
  661. switch ($this->page->state) {
  662. case moodle_page::STATE_BEFORE_HEADER :
  663. // No output yet it is safe to delivery the full arsenal of redirect methods
  664. if (!$debugdisableredirect) {
  665. // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
  666. $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
  667. $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
  668. }
  669. $output = $this->header();
  670. break;
  671. case moodle_page::STATE_PRINTING_HEADER :
  672. // We should hopefully never get here
  673. throw new coding_exception('You cannot redirect while printing the page header');
  674. break;
  675. case moodle_page::STATE_IN_BODY :
  676. // We really shouldn't be here but we can deal with this
  677. debugging("You should really redirect before you start page output");
  678. if (!$debugdisableredirect) {
  679. $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
  680. }
  681. $output = $this->opencontainers->pop_all_but_last();
  682. break;
  683. case moodle_page::STATE_DONE :
  684. // Too late to be calling redirect now
  685. throw new coding_exception('You cannot redirect after the entire page has been generated');
  686. break;
  687. }
  688. $output .= $this->notification($message, 'redirectmessage');
  689. $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
  690. if ($debugdisableredirect) {
  691. $output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
  692. }
  693. $output .= $this->footer();
  694. return $output;
  695. }
  696. /**
  697. * Start output by sending the HTTP headers, and printing the HTML <head>
  698. * and the start of the <body>.
  699. *
  700. * To control what is printed, you should set properties on $PAGE. If you
  701. * are familiar with the old {@link print_header()} function from Moodle 1.9
  702. * you will find that there are properties on $PAGE that correspond to most
  703. * of the old parameters to could be passed to print_header.
  704. *
  705. * Not that, in due course, the remaining $navigation, $menu parameters here
  706. * will be replaced by more properties of $PAGE, but that is still to do.
  707. *
  708. * @return string HTML that you must output this, preferably immediately.
  709. */
  710. public function header() {
  711. global $USER, $CFG;
  712. if (\core\session\manager::is_loggedinas()) {
  713. $this->page->add_body_class('userloggedinas');
  714. }
  715. // Give themes a chance to init/alter the page object.
  716. $this->page->theme->init_page($this->page);
  717. $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
  718. // Find the appropriate page layout file, based on $this->page->pagelayout.
  719. $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
  720. // Render the layout using the layout file.
  721. $rendered = $this->render_page_layout($layoutfile);
  722. // Slice the rendered output into header and footer.
  723. $cutpos = strpos($rendered, $this->unique_main_content_token);
  724. if ($cutpos === false) {
  725. $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
  726. $token = self::MAIN_CONTENT_TOKEN;
  727. } else {
  728. $token = $this->unique_main_content_token;
  729. }
  730. if ($cutpos === false) {
  731. 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.');
  732. }
  733. $header = substr($rendered, 0, $cutpos);
  734. $footer = substr($rendered, $cutpos + strlen($token));
  735. if (empty($this->contenttype)) {
  736. debugging('The page layout file did not call $OUTPUT->doctype()');
  737. $header = $this->doctype() . $header;
  738. }
  739. // If this theme version is below 2.4 release and this is a course view page
  740. if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
  741. $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
  742. // check if course content header/footer have not been output during render of theme layout
  743. $coursecontentheader = $this->course_content_header(true);
  744. $coursecontentfooter = $this->course_content_footer(true);
  745. if (!empty($coursecontentheader)) {
  746. // display debug message and add header and footer right above and below main content
  747. // Please note that course header and footer (to be displayed above and below the whole page)
  748. // are not displayed in this case at all.
  749. // Besides the content header and footer are not displayed on any other course page
  750. 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);
  751. $header .= $coursecontentheader;
  752. $footer = $coursecontentfooter. $footer;
  753. }
  754. }
  755. send_headers($this->contenttype, $this->page->cacheable);
  756. $this->opencontainers->push('header/footer', $footer);
  757. $this->page->set_state(moodle_page::STATE_IN_BODY);
  758. return $header . $this->skip_link_target('maincontent');
  759. }
  760. /**
  761. * Renders and outputs the page layout file.
  762. *
  763. * This is done by preparing the normal globals available to a script, and
  764. * then including the layout file provided by the current theme for the
  765. * requested layout.
  766. *
  767. * @param string $layoutfile The name of the layout file
  768. * @return string HTML code
  769. */
  770. protected function render_page_layout($layoutfile) {
  771. global $CFG, $SITE, $USER;
  772. // The next lines are a bit tricky. The point is, here we are in a method
  773. // of a renderer class, and this object may, or may not, be the same as
  774. // the global $OUTPUT object. When rendering the page layout file, we want to use
  775. // this object. However, people writing Moodle code expect the current
  776. // renderer to be called $OUTPUT, not $this, so define a variable called
  777. // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
  778. $OUTPUT = $this;
  779. $PAGE = $this->page;
  780. $COURSE = $this->page->course;
  781. ob_start();
  782. include($layoutfile);
  783. $rendered = ob_get_contents();
  784. ob_end_clean();
  785. return $rendered;
  786. }
  787. /**
  788. * Outputs the page's footer
  789. *
  790. * @return string HTML fragment
  791. */
  792. public function footer() {
  793. global $CFG, $DB;
  794. $output = $this->container_end_all(true);
  795. $footer = $this->opencontainers->pop('header/footer');
  796. if (debugging() and $DB and $DB->is_transaction_started()) {
  797. // TODO: MDL-20625 print warning - transaction will be rolled back
  798. }
  799. // Provide some performance info if required
  800. $performanceinfo = '';
  801. if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
  802. $perf = get_performance_info();
  803. if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
  804. $performanceinfo = $perf['html'];
  805. }
  806. }
  807. // We always want performance data when running a performance test, even if the user is redirected to another page.
  808. if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
  809. $footer = $this->unique_performance_info_token . $footer;
  810. }
  811. $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
  812. $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
  813. $this->page->set_state(moodle_page::STATE_DONE);
  814. return $output . $footer;
  815. }
  816. /**
  817. * Close all but the last open container. This is useful in places like error
  818. * handling, where you want to close all the open containers (apart from <body>)
  819. * before outputting the error message.
  820. *
  821. * @param bool $shouldbenone assert that the stack should be empty now - causes a
  822. * developer debug warning if it isn't.
  823. * @return string the HTML required to close any open containers inside <body>.
  824. */
  825. public function container_end_all($shouldbenone = false) {
  826. return $this->opencontainers->pop_all_but_last($shouldbenone);
  827. }
  828. /**
  829. * Returns course-specific information to be output immediately above content on any course page
  830. * (for the current course)
  831. *
  832. * @param bool $onlyifnotcalledbefore output content only if it has not been output before
  833. * @return string
  834. */
  835. public function course_content_header($onlyifnotcalledbefore = false) {
  836. global $CFG;
  837. if ($this->page->course->id == SITEID) {
  838. // return immediately and do not include /course/lib.php if not necessary
  839. return '';
  840. }
  841. static $functioncalled = false;
  842. if ($functioncalled && $onlyifnotcalledbefore) {
  843. // we have already output the content header
  844. return '';
  845. }
  846. require_once($CFG->dirroot.'/course/lib.php');
  847. $functioncalled = true;
  848. $courseformat = course_get_format($this->page->course);
  849. if (($obj = $courseformat->course_content_header()) !== null) {
  850. return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
  851. }
  852. return '';
  853. }
  854. /**
  855. * Returns course-specific information to be output immediately below content on any course page
  856. * (for the current course)
  857. *
  858. * @param bool $onlyifnotcalledbefore output content only if it has not been output before
  859. * @return string
  860. */
  861. public function course_content_footer($onlyifnotcalledbefore = false) {
  862. global $CFG;
  863. if ($this->page->course->id == SITEID) {
  864. // return immediately and do not include /course/lib.php if not necessary
  865. return '';
  866. }
  867. static $functioncalled = false;
  868. if ($functioncalled && $onlyifnotcalledbefore) {
  869. // we have already output the content footer
  870. return '';
  871. }
  872. $functioncalled = true;
  873. require_once($CFG->dirroot.'/course/lib.php');
  874. $courseformat = course_get_format($this->page->course);
  875. if (($obj = $courseformat->course_content_footer()) !== null) {
  876. return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
  877. }
  878. return '';
  879. }
  880. /**
  881. * Returns course-specific information to be output on any course page in the header area
  882. * (for the current course)
  883. *
  884. * @return string
  885. */
  886. public function course_header() {
  887. global $CFG;
  888. if ($this->page->course->id == SITEID) {
  889. // return immediately and do not include /course/lib.php if not necessary
  890. return '';
  891. }
  892. require_once($CFG->dirroot.'/course/lib.php');
  893. $courseformat = course_get_format($this->page->course);
  894. if (($obj = $courseformat->course_header()) !== null) {
  895. return $courseformat->get_renderer($this->page)->render($obj);
  896. }
  897. return '';
  898. }
  899. /**
  900. * Returns course-specific information to be output on any course page in the footer area
  901. * (for the current course)
  902. *
  903. * @return string
  904. */
  905. public function course_footer() {
  906. global $CFG;
  907. if ($this->page->course->id == SITEID) {
  908. // return immediately and do not include /course/lib.php if not necessary
  909. return '';
  910. }
  911. require_once($CFG->dirroot.'/course/lib.php');
  912. $courseformat = course_get_format($this->page->course);
  913. if (($obj = $courseformat->course_footer()) !== null) {
  914. return $courseformat->get_renderer($this->page)->render($obj);
  915. }
  916. return '';
  917. }
  918. /**
  919. * Returns lang menu or '', this method also checks forcing of languages in courses.
  920. *
  921. * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
  922. *
  923. * @return string The lang menu HTML or empty string
  924. */
  925. public function lang_menu() {
  926. global $CFG;
  927. if (empty($CFG->langmenu)) {
  928. return '';
  929. }
  930. if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
  931. // do not show lang menu if language forced
  932. return '';
  933. }
  934. $currlang = current_language();
  935. $langs = get_string_manager()->get_list_of_translations();
  936. if (count($langs) < 2) {
  937. return '';
  938. }
  939. $s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
  940. $s->label = get_accesshide(get_string('language'));
  941. $s->class = 'langmenu';
  942. return $this->render($s);
  943. }
  944. /**
  945. * Output the row of editing icons for a block, as defined by the controls array.
  946. *
  947. * @param array $controls an array like {@link block_contents::$controls}.
  948. * @param string $blockid The ID given to the block.
  949. * @return string HTML fragment.
  950. */
  951. public function block_controls($actions, $blockid = null) {
  952. global $CFG;
  953. if (empty($actions)) {
  954. return '';
  955. }
  956. $menu = new action_menu($actions);
  957. if ($blockid !== null) {
  958. $menu->set_owner_selector('#'.$blockid);
  959. }
  960. $menu->set_constraint('.block-region');
  961. $menu->attributes['class'] .= ' block-control-actions commands';
  962. if (isset($CFG->blockeditingmenu) && !$CFG->blockeditingmenu) {
  963. $menu->do_not_enhance();
  964. }
  965. return $this->render($menu);
  966. }
  967. /**
  968. * Renders an action menu component.
  969. *
  970. * ARIA references:
  971. * - http://www.w3.org/WAI/GL/wiki/Using_ARIA_menus
  972. * - http://stackoverflow.com/questions/12279113/recommended-wai-aria-implementation-for-navigation-bar-menu
  973. *
  974. * @param action_menu $menu
  975. * @return string HTML
  976. */
  977. public function render_action_menu(action_menu $menu) {
  978. $menu->initialise_js($this->page);
  979. $output = html_writer::start_tag('div', $menu->attributes);
  980. $output .= html_writer::start_tag('ul', $menu->attributesprimary);
  981. foreach ($menu->get_primary_actions($this) as $action) {
  982. if ($action instanceof renderable) {
  983. $content = $this->render($action);
  984. } else {
  985. $content = $action;
  986. }
  987. $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
  988. }
  989. $output .= html_writer::end_tag('ul');
  990. $output .= html_writer::start_tag('ul', $menu->attributessecondary);
  991. foreach ($menu->get_secondary_actions() as $action) {
  992. if ($action instanceof renderable) {
  993. $content = $this->render($action);
  994. } else {
  995. $content = $action;
  996. }
  997. $output .= html_writer::tag('li', $content, array('role' => 'presentation'));
  998. }
  999. $output .= html_writer::end_tag('ul');
  1000. $output .= html_writer::end_tag('div');
  1001. return $output;
  1002. }
  1003. /**
  1004. * Renders an action_menu_link item.
  1005. *
  1006. * @param action_menu_link $action
  1007. * @return string HTML fragment
  1008. */
  1009. protected function render_action_menu_link(action_menu_link $action) {
  1010. static $actioncount = 0;
  1011. $actioncount++;
  1012. $comparetoalt = '';
  1013. $text = '';
  1014. if (!$action->icon || $action->primary === false) {
  1015. $text .= html_writer::start_tag('span', array('class'=>'menu-action-text', 'id' => 'actionmenuaction-'.$actioncount));
  1016. if ($action->text instanceof renderable) {
  1017. $text .= $this->render($action->text);
  1018. } else {
  1019. $text .= $action->text;
  1020. $comparetoalt = (string)$action->text;
  1021. }
  1022. $text .= html_writer::end_tag('span');
  1023. }
  1024. $icon = '';
  1025. if ($action->icon) {
  1026. $icon = $action->icon;
  1027. if ($action->primary || !$action->actionmenu->will_be_enhanced()) {
  1028. $action->attributes['title'] = $action->text;
  1029. }
  1030. if (!$action->primary && $action->actionmenu->will_be_enhanced()) {
  1031. if ((string)$icon->attributes['alt'] === $comparetoalt) {
  1032. $icon->attributes['alt'] = '';
  1033. }
  1034. if (isset($icon->attributes['title']) && (string)$icon->attributes['title'] === $comparetoalt) {
  1035. unset($icon->attributes['title']);
  1036. }
  1037. }
  1038. $icon = $this->render($icon);
  1039. }
  1040. // A disabled link is rendered as formatted text.
  1041. if (!empty($action->attributes['disabled'])) {
  1042. // Do not use div here due to nesting restriction in xhtml strict.
  1043. return html_writer::tag('span', $icon.$text, array('class'=>'currentlink', 'role' => 'menuitem'));
  1044. }
  1045. $attributes = $action->attributes;
  1046. unset($action->attributes['disabled']);
  1047. $attributes['href'] = $action->url;
  1048. if ($text !== '') {
  1049. $attributes['aria-labelledby'] = 'actionmenuaction-'.$actioncount;
  1050. }
  1051. return html_writer::tag('a', $icon.$text, $attributes);
  1052. }
  1053. /**
  1054. * Renders a primary action_menu_filler item.
  1055. *
  1056. * @param action_menu_link_filler $action
  1057. * @return string HTML fragment
  1058. */
  1059. protected function render_action_menu_filler(action_menu_filler $action) {
  1060. return html_writer::span('&nbsp;', 'filler');
  1061. }
  1062. /**
  1063. * Renders a primary action_menu_link item.
  1064. *
  1065. * @param action_menu_link_primary $action
  1066. * @return string HTML fragment
  1067. */
  1068. protected function render_action_menu_link_primary(action_menu_link_primary $action) {
  1069. return $this->render_action_menu_link($action);
  1070. }
  1071. /**
  1072. * Renders a secondary action_menu_link item.
  1073. *
  1074. * @param action_menu_link_secondary $action
  1075. * @return string HTML fragment
  1076. */
  1077. protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
  1078. return $this->render_action_menu_link($action);
  1079. }
  1080. /**
  1081. * Prints a nice side block with an optional header.
  1082. *
  1083. * The content is described
  1084. * by a {@link core_renderer::block_contents} object.
  1085. *
  1086. * <div id="inst{$instanceid}" class="block_{$blockname} block">
  1087. * <div class="header"></div>
  1088. * <div class="content">
  1089. * ...CONTENT...
  1090. * <div class="footer">
  1091. * </div>
  1092. * </div>
  1093. * <div class="annotation">
  1094. * </div>
  1095. * </div>
  1096. *
  1097. * @param block_contents $bc HTML for the content
  1098. * @param string $region the region the block is appearing in.
  1099. * @return string the HTML to be output.
  1100. */
  1101. public function block(block_contents $bc, $region) {
  1102. $bc = clone($bc); // Avoid messing up the object passed in.
  1103. if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
  1104. $bc->collapsible = block_contents::NOT_HIDEABLE;
  1105. }
  1106. if (!empty($bc->blockinstanceid)) {
  1107. $bc->attributes['data-instanceid'] = $bc->blockinstanceid;
  1108. }
  1109. $skiptitle = strip_tags($bc->title);
  1110. if ($bc->blockinstanceid && !empty($skiptitle)) {
  1111. $bc->attributes['aria-labelledby'] = 'instance-'.$bc->blockinstanceid.'-header';
  1112. } else if (!empty($bc->arialabel)) {
  1113. $bc->attributes['aria-label'] = $bc->arialabel;
  1114. }
  1115. if ($bc->dockable) {
  1116. $bc->attributes['data-dockable'] = 1;
  1117. }
  1118. if ($bc->collapsible == block_contents::HIDDEN) {
  1119. $bc->add_class('hidden');
  1120. }
  1121. if (!empty($bc->controls)) {
  1122. $bc->add_class('block_with_controls');
  1123. }
  1124. if (empty($skiptitle)) {
  1125. $output = '';
  1126. $skipdest = '';
  1127. } else {
  1128. $output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
  1129. $skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
  1130. }
  1131. $output .= html_writer::start_tag('div', $bc->attributes);
  1132. $output .= $this->block_header($bc);
  1133. $output .= $this->block_content($bc);
  1134. $output .= html_writer::end_tag('div');
  1135. $output .= $this->block_annotation($bc);
  1136. $output .= $skipdest;
  1137. $this->init_block_hider_js($bc);
  1138. return $output;
  1139. }
  1140. /**
  1141. * Produces a header for a block
  1142. *
  1143. * @param block_contents $bc
  1144. * @return string
  1145. */
  1146. protected function block_header(block_contents $bc) {
  1147. $title = '';
  1148. if ($bc->title) {
  1149. $attributes = array();
  1150. if ($bc->blockinstanceid) {
  1151. $attributes['id'] = 'instance-'.$bc->blockinstanceid.'-header';
  1152. }
  1153. $title = html_writer::tag('h2', $bc->title, $attributes);
  1154. }
  1155. $blockid = null;
  1156. if (isset($bc->attributes['id'])) {
  1157. $blockid = $bc->attributes['id'];
  1158. }
  1159. $controlshtml = $this->block_controls($bc->controls, $blockid);
  1160. $output = '';
  1161. if ($title || $controlshtml) {
  1162. $output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
  1163. }
  1164. return $output;
  1165. }
  1166. /**
  1167. * Produces the content area for a block
  1168. *
  1169. * @param block_contents $bc
  1170. * @return string
  1171. */
  1172. protected function block_content(block_contents $bc) {
  1173. $output = html_writer::start_tag('div', array('class' => 'content'));
  1174. if (!$bc->title && !$this->block_controls($bc->controls)) {
  1175. $output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
  1176. }
  1177. $output .= $bc->content;
  1178. $output .= $this->block_footer($bc);
  1179. $output .= html_writer::end_tag('div');
  1180. return $output;
  1181. }
  1182. /**
  1183. * Produces the footer for a block
  1184. *
  1185. * @param block_contents $bc
  1186. * @return string
  1187. */
  1188. protected function block_footer(block_contents $bc) {
  1189. $output = '';
  1190. if ($bc->footer) {
  1191. $output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
  1192. }
  1193. return $output;
  1194. }
  1195. /**
  1196. * Produces the annotation for a block
  1197. *
  1198. * @param block_contents $bc
  1199. * @return string
  1200. */
  1201. protected function block_annotation(block_contents $bc) {
  1202. $output = '';
  1203. if ($bc->annotation) {
  1204. $output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
  1205. }
  1206. return $output;
  1207. }
  1208. /**
  1209. * Calls the JS require function to hide a block.
  1210. *
  1211. * @param block_contents $bc A block_contents object
  1212. */
  1213. protected function init_block_hider_js(block_contents $bc) {
  1214. if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
  1215. $config = new stdClass;
  1216. $config->id = $bc->attributes['id'];
  1217. $config->title = strip_tags($bc->title);
  1218. $config->preference = 'block' . $bc->blockinstanceid . 'hidden';
  1219. $config->tooltipVisible = get_string('hideblocka', 'access', $config->title);
  1220. $config->tooltipHidden = get_string('showblocka', 'access', $config->title);
  1221. $this->page->requires->js_init_call('M.util.init_block_hider', array($config));
  1222. user_preference_allow_ajax_update($config->preference, PARAM_BOOL);
  1223. }
  1224. }
  1225. /**
  1226. * Render the contents of a block_list.
  1227. *
  1228. * @param array $icons the icon for each item.
  1229. * @param array $items the content of each item.
  1230. * @return string HTML
  1231. */
  1232. public function list_block_contents($icons, $items) {
  1233. $row = 0;
  1234. $lis = array();
  1235. foreach ($items as $key => $string) {
  1236. $item = html_writer::start_tag('li', array('class' => 'r' . $row));
  1237. if (!empty($icons[$key])) { //test if the content has an assigned icon
  1238. $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
  1239. }
  1240. $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
  1241. $item .= html_writer::end_tag('li');
  1242. $lis[] = $item;
  1243. $row = 1 - $row; // Flip even/odd.
  1244. }
  1245. return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
  1246. }
  1247. /**
  1248. * Output all the blocks in a particular region.
  1249. *
  1250. * @param string $region the name of a region on this page.
  1251. * @return string the HTML to be output.
  1252. */
  1253. public function blocks_for_region($region) {
  1254. $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
  1255. $blocks = $this->page->blocks->get_blocks_for_region($region);
  1256. $lastblock = null;
  1257. $zones = array();
  1258. foreach ($blocks as $block) {
  1259. $zones[] = $block->title;
  1260. }
  1261. $output = '';
  1262. foreach ($blockcontents as $bc) {
  1263. if ($bc instanceof block_contents) {
  1264. $output .= $this->block($bc, $region);
  1265. $lastblock = $bc->title;
  1266. } else if ($bc instanceof block_move_target) {
  1267. $output .= $this->block_move_target($bc, $zones, $lastblock);
  1268. } else {
  1269. throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
  1270. }
  1271. }
  1272. return $output;
  1273. }
  1274. /**
  1275. * Output a place where the block that is currently being moved can be dropped.
  1276. *
  1277. * @param block_move_target $target with the necessary details.
  1278. * @param array $zones array of areas where the block can be moved to
  1279. * @param string $previous the block located before the area currently being rendered.
  1280. * @return string the HTML to be output.
  1281. */
  1282. public function block_move_target($target, $zones, $previous) {
  1283. if ($previous == null) {
  1284. if (empty($zones)) {
  1285. // There are no zones, probably because there are no blocks.
  1286. $position = get_string('moveblockhere', 'block');
  1287. } else {
  1288. $position = get_string('moveblockbefore', 'block', $zones[0]);
  1289. }
  1290. } else {
  1291. $position = get_string('moveblockafter', 'block', $previous);
  1292. }
  1293. return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
  1294. }
  1295. /**
  1296. * Renders a special html link with attached action
  1297. *
  1298. * Theme developers: DO NOT OVERRIDE! Please override function
  1299. * {@link core_renderer::render_action_link()} instead.
  1300. *
  1301. * @param string|moodle_url $url
  1302. * @param string $text HTML fragment
  1303. * @param component_action $action
  1304. * @param array $attributes associative array of html link attributes + disabled
  1305. * @param pix_icon optional pix icon to render with the link
  1306. * @return string HTML fragment
  1307. */
  1308. public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
  1309. if (!($url instanceof moodle_url)) {
  1310. $url = new moodle_url($url);
  1311. }
  1312. $link = new action_link($url, $text, $action, $attributes, $icon);
  1313. return $this->render($link);
  1314. }
  1315. /**
  1316. * Renders an action_link object.
  1317. *
  1318. * The provided link is renderer and the HTML returned. At the same time the
  1319. * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
  1320. *
  1321. * @param action_link $link
  1322. * @return string HTML fragment
  1323. */
  1324. protected function render_action_link(action_link $link) {
  1325. global $CFG;
  1326. $text = '';
  1327. if ($link->icon) {
  1328. $text .= $this->render($link->icon);
  1329. }
  1330. if ($link->text instanceof renderable) {
  1331. $text .= $this->render($link->text);
  1332. } else {
  1333. $text .= $link->text;
  1334. }
  1335. // A disabled link is rendered as formatted text
  1336. if (!empty($link->attributes['disabled'])) {
  1337. // do not use div here due to nesting restriction in xhtml strict
  1338. return html_writer::tag('span', $text, array('class'=>'currentlink'));
  1339. }
  1340. $attributes = $link->attributes;
  1341. unset($link->attributes['disabled']);
  1342. $attributes['href'] = $link->url;
  1343. if ($link->actions) {
  1344. if (empty($attributes['id'])) {
  1345. $id = html_writer::random_id('action_link');
  1346. $attributes['id'] = $id;
  1347. } else {
  1348. $id = $attributes['id'];
  1349. }
  1350. foreach ($link->actions as $action) {
  1351. $this->add_action_handler($action, $id);
  1352. }
  1353. }
  1354. return html_writer::tag('a', $text, $attributes);
  1355. }
  1356. /**
  1357. * Renders an action_icon.
  1358. *
  1359. * This function uses the {@link core_renderer::action_link()} method for the
  1360. * most part. What it does different is prepare the icon as HTML and use it
  1361. * as the link text.
  1362. *
  1363. * Theme developers: If you want to change how action links and/or icons are rendered,
  1364. * consider overriding function {@link core_renderer::render_action_link()} and
  1365. * {@link core_renderer::render_pix_icon()}.
  1366. *
  1367. * @param string|moodle_url $url A string URL or moodel_url
  1368. * @param pix_icon $pixicon
  1369. * @param component_action $action
  1370. * @param array $attributes associative array of html link attributes + disabled
  1371. * @param bool $linktext show title next to image in link
  1372. * @return string HTML fragment
  1373. */
  1374. public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
  1375. if (!($url instanceof moodle_url)) {
  1376. $url = new moodle_url($url);
  1377. }
  1378. $attributes = (array)$attributes;
  1379. if (empty($attributes['class'])) {
  1380. // let ppl override the class via $options
  1381. $attributes['class'] = 'action-icon';
  1382. }
  1383. $icon = $this->render($pixicon);
  1384. if ($linktext) {
  1385. $text = $pixicon->attributes['alt'];
  1386. } else {
  1387. $text = '';
  1388. }
  1389. return $this->action_link($url, $text.$icon, $action, $attributes);
  1390. }
  1391. /**
  1392. * Print a message along with button choices for Continue/Cancel
  1393. *
  1394. * If a string or moodle_url is given instead of a single_button, method defaults to post.
  1395. *
  1396. * @param string $message The question to ask the user
  1397. * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
  1398. * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
  1399. * @return string HTML fragment
  1400. */
  1401. public function confirm($message, $continue, $cancel) {
  1402. if ($continue instanceof single_button) {
  1403. // ok
  1404. } else if (is_string($continue)) {
  1405. $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
  1406. } else if ($continue instanceof moodle_url) {
  1407. $continue = new single_button($continue, get_string('continue'), 'post');
  1408. } else {
  1409. throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
  1410. }
  1411. if ($cancel instanceof single_button) {
  1412. // ok
  1413. } else if (is_string($cancel)) {
  1414. $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
  1415. } else if ($cancel instanceof moodle_url) {
  1416. $cancel = new single_button($cancel, get_string('cancel'), 'get');
  1417. } else {
  1418. throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
  1419. }
  1420. $output = $this->box_start('generalbox', 'notice');
  1421. $output .= html_writer::tag('p', $message);
  1422. $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
  1423. $output .= $this->box_end();
  1424. return $output;
  1425. }
  1426. /**
  1427. * Returns a form with a single button.
  1428. *
  1429. * Theme developers: DO NOT OVERRIDE! Please override function
  1430. * {@link core_renderer::render_single_button()} instead.
  1431. *
  1432. * @param string|moodle_url $url
  1433. * @param string $label button text
  1434. * @param string $method get or post submit method
  1435. * @param array $options associative array {disabled, title, etc.}
  1436. * @return string HTML fragment
  1437. */
  1438. public function single_button($url, $label, $method='post', array $options=null) {
  1439. if (!($url instanceof moodle_url)) {
  1440. $url = new moodle_url($url);
  1441. }
  1442. $button = new single_button($url, $label, $method);
  1443. foreach ((array)$options as $key=>$value) {
  1444. if (array_key_exists($key, $button)) {
  1445. $button->$key = $value;
  1446. }
  1447. }
  1448. return $this->render($button);
  1449. }
  1450. /**
  1451. * Renders a single button widget.
  1452. *
  1453. * This will return HTML to display a form containing a single button.
  1454. *
  1455. * @param single_button $button
  1456. * @return string HTML fragment
  1457. */
  1458. protected function render_single_button(single_button $button) {
  1459. $attributes = array('type' => 'submit',
  1460. 'value' => $button->label,
  1461. 'disabled' => $button->disabled ? 'disabled' : null,
  1462. 'title' => $button->tooltip);
  1463. if ($button->actions) {
  1464. $id = html_writer::random_id('single_button');
  1465. $attributes['id'] = $id;
  1466. foreach ($button->actions as $action) {
  1467. $this->add_action_handler($action, $id);
  1468. }
  1469. }
  1470. // first the input element
  1471. $output = html_writer::empty_tag('input', $attributes);
  1472. // then hidden fields
  1473. $params = $button->url->params();
  1474. if ($button->method === 'post') {
  1475. $params['sesskey'] = sesskey();
  1476. }
  1477. foreach ($params as $var => $val) {
  1478. $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $var, 'value' => $val));
  1479. }
  1480. // then div wrapper for xhtml strictness
  1481. $output = html_writer::tag('div', $output);
  1482. // now the form itself around it
  1483. if ($button->method === 'get') {
  1484. $url = $button->url->out_omit_querystring(true); // url without params, the anchor part allowed
  1485. } else {
  1486. $url = $button->url->out_omit_querystring(); // url without params, the anchor part not allowed
  1487. }
  1488. if ($url === '') {
  1489. $url = '#'; // there has to be always some action
  1490. }
  1491. $attributes = array('method' => $button->method,
  1492. 'action' => $url,
  1493. 'id' => $button->formid);
  1494. $output = html_writer::tag('form', $output, $attributes);
  1495. // and finally one more wrapper with class
  1496. return html_writer::tag('div', $output, array('class' => $button->class));
  1497. }
  1498. /**
  1499. * Returns a form with a single select widget.
  1500. *
  1501. * Theme developers: DO NOT OVERRIDE! Please override function
  1502. * {@link core_renderer::render_single_select()} instead.
  1503. *
  1504. * @param moodle_url $url form action target, includes hidden fields
  1505. * @param string $name name of selection field - the changing parameter in url
  1506. * @param array $options list of options
  1507. * @param string $selected selected element
  1508. * @param array $nothing
  1509. * @param string $formid
  1510. * @return string HTML fragment
  1511. */
  1512. public function single_select($url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
  1513. if (!($url instanceof moodle_url)) {
  1514. $url = new moodle_url($url);
  1515. }
  1516. $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
  1517. return $this->render($select);
  1518. }
  1519. /**
  1520. * Internal implementation of single_select rendering
  1521. *
  1522. * @param single_select $select
  1523. * @return string HTML fragment
  1524. */
  1525. protected function render_single_select(single_select $select) {
  1526. $select = clone($select);
  1527. if (empty($select->formid)) {
  1528. $select->formid = html_writer::random_id('single_select_f');
  1529. }
  1530. $output = '';
  1531. $params = $select->url->params();
  1532. if ($select->method === 'post') {
  1533. $params['sesskey'] = sesskey();
  1534. }
  1535. foreach ($params as $name=>$value) {
  1536. $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$name, 'value'=>$value));
  1537. }
  1538. if (empty($select->attributes['id'])) {
  1539. $select->attributes['id'] = html_writer::random_id('single_select');
  1540. }
  1541. if ($select->disabled) {
  1542. $select->attributes['disabled'] = 'disabled';
  1543. }
  1544. if ($select->tooltip) {
  1545. $select->attributes['title'] = $select->tooltip;
  1546. }
  1547. $select->attributes['class'] = 'autosubmit';
  1548. if ($select->class) {
  1549. $select->attributes['class'] .= ' ' . $select->class;
  1550. }
  1551. if ($select->label) {
  1552. $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
  1553. }
  1554. if ($select->helpicon instanceof help_icon) {
  1555. $output .= $this->render($select->helpicon);
  1556. }
  1557. $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes);
  1558. $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
  1559. $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
  1560. $nothing = empty($select->nothing) ? false : key($select->nothing);
  1561. $this->page->requires->yui_module('moodle-core-formautosubmit',
  1562. 'M.core.init_formautosubmit',
  1563. array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
  1564. );
  1565. // then div wrapper for xhtml strictness
  1566. $output = html_writer::tag('div', $output);
  1567. // now the form itself around it
  1568. if ($select->method === 'get') {
  1569. $url = $select->url->out_omit_querystring(true); // url without params, the anchor part allowed
  1570. } else {
  1571. $url = $select->url->out_omit_querystring(); // url without params, the anchor part not allowed
  1572. }
  1573. $formattributes = array('method' => $select->method,
  1574. 'action' => $url,
  1575. 'id' => $select->formid);
  1576. $output = html_writer::tag('form', $output, $formattributes);
  1577. // and finally one more wrapper with class
  1578. return html_writer::tag('div', $output, array('class' => $select->class));
  1579. }
  1580. /**
  1581. * Returns a form with a url select widget.
  1582. *
  1583. * Theme developers: DO NOT OVERRIDE! Please override function
  1584. * {@link core_renderer::render_url_select()} instead.
  1585. *
  1586. * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
  1587. * @param string $selected selected element
  1588. * @param array $nothing
  1589. * @param string $formid
  1590. * @return string HTML fragment
  1591. */
  1592. public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
  1593. $select = new url_select($urls, $selected, $nothing, $formid);
  1594. return $this->render($select);
  1595. }
  1596. /**
  1597. * Internal implementation of url_select rendering
  1598. *
  1599. * @param url_select $select
  1600. * @return string HTML fragment
  1601. */
  1602. protected function render_url_select(url_select $select) {
  1603. global $CFG;
  1604. $select = clone($select);
  1605. if (empty($select->formid)) {
  1606. $select->formid = html_writer::random_id('url_select_f');
  1607. }
  1608. if (empty($select->attributes['id'])) {
  1609. $select->attributes['id'] = html_writer::random_id('url_select');
  1610. }
  1611. if ($select->disabled) {
  1612. $select->attributes['disabled'] = 'disabled';
  1613. }
  1614. if ($select->tooltip) {
  1615. $select->attributes['title'] = $select->tooltip;
  1616. }
  1617. $output = '';
  1618. if ($select->label) {
  1619. $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes);
  1620. }
  1621. $classes = array();
  1622. if (!$select->showbutton) {
  1623. $classes[] = 'autosubmit';
  1624. }
  1625. if ($select->class) {
  1626. $classes[] = $select->class;
  1627. }
  1628. if (count($classes)) {
  1629. $select->attributes['class'] = implode(' ', $classes);
  1630. }
  1631. if ($select->helpicon instanceof help_icon) {
  1632. $output .= $this->render($select->helpicon);
  1633. }
  1634. // For security reasons, the script course/jumpto.php requires URL starting with '/'. To keep
  1635. // backward compatibility, we are removing heading $CFG->wwwroot from URLs here.
  1636. $urls = array();
  1637. foreach ($select->urls as $k=>$v) {
  1638. if (is_array($v)) {
  1639. // optgroup structure
  1640. foreach ($v as $optgrouptitle => $optgroupoptions) {
  1641. foreach ($optgroupoptions as $optionurl => $optiontitle) {
  1642. if (empty($optionurl)) {
  1643. $safeoptionurl = '';
  1644. } else if (strpos($optionurl, $CFG->wwwroot.'/') === 0) {
  1645. // debugging('URLs passed to url_select should be in local relative form - please fix the code.', DEBUG_DEVELOPER);
  1646. $safeoptionurl = str_replace($CFG->wwwroot, '', $optionurl);
  1647. } else if (strpos($optionurl, '/') !== 0) {
  1648. debugging("Invalid url_select urls parameter inside optgroup: url '$optionurl' is not local relative url!");
  1649. continue;
  1650. } else {
  1651. $safeoptionurl = $optionurl;
  1652. }
  1653. $urls[$k][$optgrouptitle][$safeoptionurl] = $optiontitle;
  1654. }
  1655. }
  1656. } else {
  1657. // plain list structure
  1658. if (empty($k)) {
  1659. // nothing selected option
  1660. } else if (strpos($k, $CFG->wwwroot.'/') === 0) {
  1661. $k = str_replace($CFG->wwwroot, '', $k);
  1662. } else if (strpos($k, '/') !== 0) {
  1663. debugging("Invalid url_select urls parameter: url '$k' is not local relative url!");
  1664. continue;
  1665. }
  1666. $urls[$k] = $v;
  1667. }
  1668. }
  1669. $selected = $select->selected;
  1670. if (!empty($selected)) {
  1671. if (strpos($select->selected, $CFG->wwwroot.'/') === 0) {
  1672. $selected = str_replace($CFG->wwwroot, '', $selected);
  1673. } else if (strpos($selected, '/') !== 0) {
  1674. debugging("Invalid value of parameter 'selected': url '$selected' is not local relative url!");
  1675. }
  1676. }
  1677. $output .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=>sesskey()));
  1678. $output .= html_writer::select($urls, 'jump', $selected, $select->nothing, $select->attributes);
  1679. if (!$select->showbutton) {
  1680. $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go')));
  1681. $output .= html_writer::tag('noscript', html_writer::tag('div', $go), array('class' => 'inline'));
  1682. $nothing = empty($select->nothing) ? false : key($select->nothing);
  1683. $this->page->requires->yui_module('moodle-core-formautosubmit',
  1684. 'M.core.init_formautosubmit',
  1685. array(array('selectid' => $select->attributes['id'], 'nothing' => $nothing))
  1686. );
  1687. } else {
  1688. $output .= html_writer::empty_tag('input', array('type'=>'submit', 'value'=>$select->showbutton));
  1689. }
  1690. // then div wrapper for xhtml strictness
  1691. $output = html_writer::tag('div', $output);
  1692. // now the form itself around it
  1693. $formattributes = array('method' => 'post',
  1694. 'action' => new moodle_url('/course/jumpto.php'),
  1695. 'id' => $select->formid);
  1696. $output = html_writer::tag('form', $output, $formattributes);
  1697. // and finally one more wrapper with class
  1698. return html_writer::tag('div', $output, array('class' => $select->class));
  1699. }
  1700. /**
  1701. * Returns a string containing a link to the user documentation.
  1702. * Also contains an icon by default. Shown to teachers and admin only.
  1703. *
  1704. * @param string $path The page link after doc root and language, no leading slash.
  1705. * @param string $text The text to be displayed for the link
  1706. * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
  1707. * @return string
  1708. */
  1709. public function doc_link($path, $text = '', $forcepopup = false) {
  1710. global $CFG;
  1711. $icon = $this->pix_icon('docs', $text, 'moodle', array('class'=>'iconhelp icon-pre'));
  1712. $url = new moodle_url(get_docs_url($path));
  1713. $attributes = array('href'=>$url);
  1714. if (!empty($CFG->doctonewwindow) || $forcepopup) {
  1715. $attributes['class'] = 'helplinkpopup';
  1716. }
  1717. return html_writer::tag('a', $icon.$text, $attributes);
  1718. }
  1719. /**
  1720. * Return HTML for a pix_icon.
  1721. *
  1722. * Theme developers: DO NOT OVERRIDE! Please override function
  1723. * {@link core_renderer::render_pix_icon()} instead.
  1724. *
  1725. * @param string $pix short pix name
  1726. * @param string $alt mandatory alt attribute
  1727. * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
  1728. * @param array $attributes htm lattributes
  1729. * @return string HTML fragment
  1730. */
  1731. public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
  1732. $icon = new pix_icon($pix, $alt, $component, $attributes);
  1733. return $this->render($icon);
  1734. }
  1735. /**
  1736. * Renders a pix_icon widget and returns the HTML to display it.
  1737. *
  1738. * @param pix_icon $icon
  1739. * @return string HTML fragment
  1740. */
  1741. protected function render_pix_icon(pix_icon $icon) {
  1742. $attributes = $icon->attributes;
  1743. $attributes['src'] = $this->pix_url($icon->pix, $icon->component);
  1744. return html_writer::empty_tag('img', $attributes);
  1745. }
  1746. /**
  1747. * Return HTML to display an emoticon icon.
  1748. *
  1749. * @param pix_emoticon $emoticon
  1750. * @return string HTML fragment
  1751. */
  1752. protected function render_pix_emoticon(pix_emoticon $emoticon) {
  1753. $attributes = $emoticon->attributes;
  1754. $attributes['src'] = $this->pix_url($emoticon->pix, $emoticon->component);
  1755. return html_writer::empty_tag('img', $attributes);
  1756. }
  1757. /**
  1758. * Produces the html that represents this rating in the UI
  1759. *
  1760. * @param rating $rating the page object on which this rating will appear
  1761. * @return string
  1762. */
  1763. function render_rating(rating $rating) {
  1764. global $CFG, $USER;
  1765. if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
  1766. return null;//ratings are turned off
  1767. }
  1768. $ratingmanager = new rating_manager();
  1769. // Initialise the JavaScript so ratings can be done by AJAX.
  1770. $ratingmanager->initialise_rating_javascript($this->page);
  1771. $strrate = get_string("rate", "rating");
  1772. $ratinghtml = ''; //the string we'll return
  1773. // permissions check - can they view the aggregate?
  1774. if ($rating->user_can_view_aggregate()) {
  1775. $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
  1776. $aggregatestr = $rating->get_aggregate_string();
  1777. $aggregatehtml = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
  1778. if ($rating->count > 0) {
  1779. $countstr = "({$rating->count})";
  1780. } else {
  1781. $countstr = '-';
  1782. }
  1783. $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
  1784. $ratinghtml .= html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
  1785. if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
  1786. $nonpopuplink = $rating->get_view_ratings_url();
  1787. $popuplink = $rating->get_view_ratings_url(true);
  1788. $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
  1789. $ratinghtml .= $this->action_link($nonpopuplink, $aggregatehtml, $action);
  1790. } else {
  1791. $ratinghtml .= $aggregatehtml;
  1792. }
  1793. }
  1794. $formstart = null;
  1795. // if the item doesn't belong to the current user, the user has permission to rate
  1796. // and we're within the assessable period
  1797. if ($rating->user_can_rate()) {
  1798. $rateurl = $rating->get_rate_url();
  1799. $inputs = $rateurl->params();
  1800. //start the rating form
  1801. $formattrs = array(
  1802. 'id' => "postrating{$rating->itemid}",
  1803. 'class' => 'postratingform',
  1804. 'method' => 'post',
  1805. 'action' => $rateurl->out_omit_querystring()
  1806. );
  1807. $formstart = html_writer::start_tag('form', $formattrs);
  1808. $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
  1809. // add the hidden inputs
  1810. foreach ($inputs as $name => $value) {
  1811. $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
  1812. $formstart .= html_writer::empty_tag('input', $attributes);
  1813. }
  1814. if (empty($ratinghtml)) {
  1815. $ratinghtml .= $strrate.': ';
  1816. }
  1817. $ratinghtml = $formstart.$ratinghtml;
  1818. $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
  1819. $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
  1820. $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
  1821. $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
  1822. //output submit button
  1823. $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
  1824. $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
  1825. $ratinghtml .= html_writer::empty_tag('input', $attributes);
  1826. if (!$rating->settings->scale->isnumeric) {
  1827. // If a global scale, try to find current course ID from the context
  1828. if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
  1829. $courseid = $coursecontext->instanceid;
  1830. } else {
  1831. $courseid = $rating->settings->scale->courseid;
  1832. }
  1833. $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
  1834. }
  1835. $ratinghtml .= html_writer::end_tag('span');
  1836. $ratinghtml .= html_writer::end_tag('div');
  1837. $ratinghtml .= html_writer::end_tag('form');
  1838. }
  1839. return $ratinghtml;
  1840. }
  1841. /**
  1842. * Centered heading with attached help button (same title text)
  1843. * and optional icon attached.
  1844. *
  1845. * @param string $text A heading text
  1846. * @param string $helpidentifier The keyword that defines a help page
  1847. * @param string $component component name
  1848. * @param string|moodle_url $icon
  1849. * @param string $iconalt icon alt text
  1850. * @param int $level The level of importance of the heading. Defaulting to 2
  1851. * @param string $classnames A space-separated list of CSS classes. Defaulting to null
  1852. * @return string HTML fragment
  1853. */
  1854. public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
  1855. $image = '';
  1856. if ($icon) {
  1857. $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
  1858. }
  1859. $help = '';
  1860. if ($helpidentifier) {
  1861. $help = $this->help_icon($helpidentifier, $component);
  1862. }
  1863. return $this->heading($image.$text.$help, $level, $classnames);
  1864. }
  1865. /**
  1866. * Returns HTML to display a help icon.
  1867. *
  1868. * @deprecated since Moodle 2.0
  1869. */
  1870. public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
  1871. throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
  1872. }
  1873. /**
  1874. * Returns HTML to display a help icon.
  1875. *
  1876. * Theme developers: DO NOT OVERRIDE! Please override function
  1877. * {@link core_renderer::render_help_icon()} instead.
  1878. *
  1879. * @param string $identifier The keyword that defines a help page
  1880. * @param string $component component name
  1881. * @param string|bool $linktext true means use $title as link text, string means link text value
  1882. * @return string HTML fragment
  1883. */
  1884. public function help_icon($identifier, $component = 'moodle', $linktext = '') {
  1885. $icon = new help_icon($identifier, $component);
  1886. $icon->diag_strings();
  1887. if ($linktext === true) {
  1888. $icon->linktext = get_string($icon->identifier, $icon->component);
  1889. } else if (!empty($linktext)) {
  1890. $icon->linktext = $linktext;
  1891. }
  1892. return $this->render($icon);
  1893. }
  1894. /**
  1895. * Implementation of user image rendering.
  1896. *
  1897. * @param help_icon $helpicon A help icon instance
  1898. * @return string HTML fragment
  1899. */
  1900. protected function render_help_icon(help_icon $helpicon) {
  1901. global $CFG;
  1902. // first get the help image icon
  1903. $src = $this->pix_url('help');
  1904. $title = get_string($helpicon->identifier, $helpicon->component);
  1905. if (empty($helpicon->linktext)) {
  1906. $alt = get_string('helpprefix2', '', trim($title, ". \t"));
  1907. } else {
  1908. $alt = get_string('helpwiththis');
  1909. }
  1910. $attributes = array('src'=>$src, 'alt'=>$alt, 'class'=>'iconhelp');
  1911. $output = html_writer::empty_tag('img', $attributes);
  1912. // add the link text if given
  1913. if (!empty($helpicon->linktext)) {
  1914. // the spacing has to be done through CSS
  1915. $output .= $helpicon->linktext;
  1916. }
  1917. // now create the link around it - we need https on loginhttps pages
  1918. $url = new moodle_url($CFG->httpswwwroot.'/help.php', array('component' => $helpicon->component, 'identifier' => $helpicon->identifier, 'lang'=>current_language()));
  1919. // note: this title is displayed only if JS is disabled, otherwise the link will have the new ajax tooltip
  1920. $title = get_string('helpprefix2', '', trim($title, ". \t"));
  1921. $attributes = array('href' => $url, 'title' => $title, 'aria-haspopup' => 'true', 'target'=>'_blank');
  1922. $output = html_writer::tag('a', $output, $attributes);
  1923. // and finally span
  1924. return html_writer::tag('span', $output, array('class' => 'helptooltip'));
  1925. }
  1926. /**
  1927. * Returns HTML to display a scale help icon.
  1928. *
  1929. * @param int $courseid
  1930. * @param stdClass $scale instance
  1931. * @return string HTML fragment
  1932. */
  1933. public function help_icon_scale($courseid, stdClass $scale) {
  1934. global $CFG;
  1935. $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
  1936. $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
  1937. $scaleid = abs($scale->id);
  1938. $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
  1939. $action = new popup_action('click', $link, 'ratingscale');
  1940. return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
  1941. }
  1942. /**
  1943. * Creates and returns a spacer image with optional line break.
  1944. *
  1945. * @param array $attributes Any HTML attributes to add to the spaced.
  1946. * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
  1947. * laxy do it with CSS which is a much better solution.
  1948. * @return string HTML fragment
  1949. */
  1950. public function spacer(array $attributes = null, $br = false) {
  1951. $attributes = (array)$attributes;
  1952. if (empty($attributes['width'])) {
  1953. $attributes['width'] = 1;
  1954. }
  1955. if (empty($attributes['height'])) {
  1956. $attributes['height'] = 1;
  1957. }
  1958. $attributes['class'] = 'spacer';
  1959. $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
  1960. if (!empty($br)) {
  1961. $output .= '<br />';
  1962. }
  1963. return $output;
  1964. }
  1965. /**
  1966. * Returns HTML to display the specified user's avatar.
  1967. *
  1968. * User avatar may be obtained in two ways:
  1969. * <pre>
  1970. * // Option 1: (shortcut for simple cases, preferred way)
  1971. * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
  1972. * $OUTPUT->user_picture($user, array('popup'=>true));
  1973. *
  1974. * // Option 2:
  1975. * $userpic = new user_picture($user);
  1976. * // Set properties of $userpic
  1977. * $userpic->popup = true;
  1978. * $OUTPUT->render($userpic);
  1979. * </pre>
  1980. *
  1981. * Theme developers: DO NOT OVERRIDE! Please override function
  1982. * {@link core_renderer::render_user_picture()} instead.
  1983. *
  1984. * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
  1985. * If any of these are missing, the database is queried. Avoid this
  1986. * if at all possible, particularly for reports. It is very bad for performance.
  1987. * @param array $options associative array with user picture options, used only if not a user_picture object,
  1988. * options are:
  1989. * - courseid=$this->page->course->id (course id of user profile in link)
  1990. * - size=35 (size of image)
  1991. * - link=true (make image clickable - the link leads to user profile)
  1992. * - popup=false (open in popup)
  1993. * - alttext=true (add image alt attribute)
  1994. * - class = image class attribute (default 'userpicture')
  1995. * @return string HTML fragment
  1996. */
  1997. public function user_picture(stdClass $user, array $options = null) {
  1998. $userpicture = new user_picture($user);
  1999. foreach ((array)$options as $key=>$value) {
  2000. if (array_key_exists($key, $userpicture)) {
  2001. $userpicture->$key = $value;
  2002. }
  2003. }
  2004. return $this->render($userpicture);
  2005. }
  2006. /**
  2007. * Internal implementation of user image rendering.
  2008. *
  2009. * @param user_picture $userpicture
  2010. * @return string
  2011. */
  2012. protected function render_user_picture(user_picture $userpicture) {
  2013. global $CFG, $DB;
  2014. $user = $userpicture->user;
  2015. if ($userpicture->alttext) {
  2016. if (!empty($user->imagealt)) {
  2017. $alt = $user->imagealt;
  2018. } else {
  2019. $alt = get_string('pictureof', '', fullname($user));
  2020. }
  2021. } else {
  2022. $alt = '';
  2023. }
  2024. if (empty($userpicture->size)) {
  2025. $size = 35;
  2026. } else if ($userpicture->size === true or $userpicture->size == 1) {
  2027. $size = 100;
  2028. } else {
  2029. $size = $userpicture->size;
  2030. }
  2031. $class = $userpicture->class;
  2032. if ($user->picture == 0) {
  2033. $class .= ' defaultuserpic';
  2034. }
  2035. $src = $userpicture->get_url($this->page, $this);
  2036. $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size);
  2037. // get the image html output fisrt
  2038. $output = html_writer::empty_tag('img', $attributes);
  2039. // then wrap it in link if needed
  2040. if (!$userpicture->link) {
  2041. return $output;
  2042. }
  2043. if (empty($userpicture->courseid)) {
  2044. $courseid = $this->page->course->id;
  2045. } else {
  2046. $courseid = $userpicture->courseid;
  2047. }
  2048. if ($courseid == SITEID) {
  2049. $url = new moodle_url('/user/profile.php', array('id' => $user->id));
  2050. } else {
  2051. $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
  2052. }
  2053. $attributes = array('href'=>$url);
  2054. if ($userpicture->popup) {
  2055. $id = html_writer::random_id('userpicture');
  2056. $attributes['id'] = $id;
  2057. $this->add_action_handler(new popup_action('click', $url), $id);
  2058. }
  2059. return html_writer::tag('a', $output, $attributes);
  2060. }
  2061. /**
  2062. * Internal implementation of file tree viewer items rendering.
  2063. *
  2064. * @param array $dir
  2065. * @return string
  2066. */
  2067. public function htmllize_file_tree($dir) {
  2068. if (empty($dir['subdirs']) and empty($dir['files'])) {
  2069. return '';
  2070. }
  2071. $result = '<ul>';
  2072. foreach ($dir['subdirs'] as $subdir) {
  2073. $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
  2074. }
  2075. foreach ($dir['files'] as $file) {
  2076. $filename = $file->get_filename();
  2077. $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
  2078. }
  2079. $result .= '</ul>';
  2080. return $result;
  2081. }
  2082. /**
  2083. * Returns HTML to display the file picker
  2084. *
  2085. * <pre>
  2086. * $OUTPUT->file_picker($options);
  2087. * </pre>
  2088. *
  2089. * Theme developers: DO NOT OVERRIDE! Please override function
  2090. * {@link core_renderer::render_file_picker()} instead.
  2091. *
  2092. * @param array $options associative array with file manager options
  2093. * options are:
  2094. * maxbytes=>-1,
  2095. * itemid=>0,
  2096. * client_id=>uniqid(),
  2097. * acepted_types=>'*',
  2098. * return_types=>FILE_INTERNAL,
  2099. * context=>$PAGE->context
  2100. * @return string HTML fragment
  2101. */
  2102. public function file_picker($options) {
  2103. $fp = new file_picker($options);
  2104. return $this->render($fp);
  2105. }
  2106. /**
  2107. * Internal implementation of file picker rendering.
  2108. *
  2109. * @param file_picker $fp
  2110. * @return string
  2111. */
  2112. public function render_file_picker(file_picker $fp) {
  2113. global $CFG, $OUTPUT, $USER;
  2114. $options = $fp->options;
  2115. $client_id = $options->client_id;
  2116. $strsaved = get_string('filesaved', 'repository');
  2117. $straddfile = get_string('openpicker', 'repository');
  2118. $strloading = get_string('loading', 'repository');
  2119. $strdndenabled = get_string('dndenabled_inbox', 'moodle');
  2120. $strdroptoupload = get_string('droptoupload', 'moodle');
  2121. $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
  2122. $currentfile = $options->currentfile;
  2123. if (empty($currentfile)) {
  2124. $currentfile = '';
  2125. } else {
  2126. $currentfile .= ' - ';
  2127. }
  2128. if ($options->maxbytes) {
  2129. $size = $options->maxbytes;
  2130. } else {
  2131. $size = get_max_upload_file_size();
  2132. }
  2133. if ($size == -1) {
  2134. $maxsize = '';
  2135. } else {
  2136. $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
  2137. }
  2138. if ($options->buttonname) {
  2139. $buttonname = ' name="' . $options->buttonname . '"';
  2140. } else {
  2141. $buttonname = '';
  2142. }
  2143. $html = <<<EOD
  2144. <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
  2145. $icon_progress
  2146. </div>
  2147. <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
  2148. <div>
  2149. <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
  2150. <span> $maxsize </span>
  2151. </div>
  2152. EOD;
  2153. if ($options->env != 'url') {
  2154. $html .= <<<EOD
  2155. <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
  2156. <div class="filepicker-filename">
  2157. <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
  2158. <div class="dndupload-progressbars"></div>
  2159. </div>
  2160. <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
  2161. </div>
  2162. EOD;
  2163. }
  2164. $html .= '</div>';
  2165. return $html;
  2166. }
  2167. /**
  2168. * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
  2169. *
  2170. * @param string $cmid the course_module id.
  2171. * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
  2172. * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
  2173. */
  2174. public function update_module_button($cmid, $modulename) {
  2175. global $CFG;
  2176. if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
  2177. $modulename = get_string('modulename', $modulename);
  2178. $string = get_string('updatethis', '', $modulename);
  2179. $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
  2180. return $this->single_button($url, $string);
  2181. } else {
  2182. return '';
  2183. }
  2184. }
  2185. /**
  2186. * Returns HTML to display a "Turn editing on/off" button in a form.
  2187. *
  2188. * @param moodle_url $url The URL + params to send through when clicking the button
  2189. * @return string HTML the button
  2190. */
  2191. public function edit_button(moodle_url $url) {
  2192. $url->param('sesskey', sesskey());
  2193. if ($this->page->user_is_editing()) {
  2194. $url->param('edit', 'off');
  2195. $editstring = get_string('turneditingoff');
  2196. } else {
  2197. $url->param('edit', 'on');
  2198. $editstring = get_string('turneditingon');
  2199. }
  2200. return $this->single_button($url, $editstring);
  2201. }
  2202. /**
  2203. * Returns HTML to display a simple button to close a window
  2204. *
  2205. * @param string $text The lang string for the button's label (already output from get_string())
  2206. * @return string html fragment
  2207. */
  2208. public function close_window_button($text='') {
  2209. if (empty($text)) {
  2210. $text = get_string('closewindow');
  2211. }
  2212. $button = new single_button(new moodle_url('#'), $text, 'get');
  2213. $button->add_action(new component_action('click', 'close_window'));
  2214. return $this->container($this->render($button), 'closewindow');
  2215. }
  2216. /**
  2217. * Output an error message. By default wraps the error message in <span class="error">.
  2218. * If the error message is blank, nothing is output.
  2219. *
  2220. * @param string $message the error message.
  2221. * @return string the HTML to output.
  2222. */
  2223. public function error_text($message) {
  2224. if (empty($message)) {
  2225. return '';
  2226. }
  2227. $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
  2228. return html_writer::tag('span', $message, array('class' => 'error'));
  2229. }
  2230. /**
  2231. * Do not call this function directly.
  2232. *
  2233. * To terminate the current script with a fatal error, call the {@link print_error}
  2234. * function, or throw an exception. Doing either of those things will then call this
  2235. * function to display the error, before terminating the execution.
  2236. *
  2237. * @param string $message The message to output
  2238. * @param string $moreinfourl URL where more info can be found about the error
  2239. * @param string $link Link for the Continue button
  2240. * @param array $backtrace The execution backtrace
  2241. * @param string $debuginfo Debugging information
  2242. * @return string the HTML to output.
  2243. */
  2244. public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
  2245. global $CFG;
  2246. $output = '';
  2247. $obbuffer = '';
  2248. if ($this->has_started()) {
  2249. // we can not always recover properly here, we have problems with output buffering,
  2250. // html tables, etc.
  2251. $output .= $this->opencontainers->pop_all_but_last();
  2252. } else {
  2253. // It is really bad if library code throws exception when output buffering is on,
  2254. // because the buffered text would be printed before our start of page.
  2255. // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
  2256. error_reporting(0); // disable notices from gzip compression, etc.
  2257. while (ob_get_level() > 0) {
  2258. $buff = ob_get_clean();
  2259. if ($buff === false) {
  2260. break;
  2261. }
  2262. $obbuffer .= $buff;
  2263. }
  2264. error_reporting($CFG->debug);
  2265. // Output not yet started.
  2266. $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
  2267. if (empty($_SERVER['HTTP_RANGE'])) {
  2268. @header($protocol . ' 404 Not Found');
  2269. } else {
  2270. // Must stop byteserving attempts somehow,
  2271. // this is weird but Chrome PDF viewer can be stopped only with 407!
  2272. @header($protocol . ' 407 Proxy Authentication Required');
  2273. }
  2274. $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
  2275. $this->page->set_url('/'); // no url
  2276. //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
  2277. $this->page->set_title(get_string('error'));
  2278. $this->page->set_heading($this->page->course->fullname);
  2279. $output .= $this->header();
  2280. }
  2281. $message = '<p class="errormessage">' . $message . '</p>'.
  2282. '<p class="errorcode"><a href="' . $moreinfourl . '">' .
  2283. get_string('moreinformation') . '</a></p>';
  2284. if (empty($CFG->rolesactive)) {
  2285. $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
  2286. //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.
  2287. }
  2288. $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
  2289. if ($CFG->debugdeveloper) {
  2290. if (!empty($debuginfo)) {
  2291. $debuginfo = s($debuginfo); // removes all nasty JS
  2292. $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
  2293. $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
  2294. }
  2295. if (!empty($backtrace)) {
  2296. $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
  2297. }
  2298. if ($obbuffer !== '' ) {
  2299. $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
  2300. }
  2301. }
  2302. if (empty($CFG->rolesactive)) {
  2303. // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
  2304. } else if (!empty($link)) {
  2305. $output .= $this->continue_button($link);
  2306. }
  2307. $output .= $this->footer();
  2308. // Padding to encourage IE to display our error page, rather than its own.
  2309. $output .= str_repeat(' ', 512);
  2310. return $output;
  2311. }
  2312. /**
  2313. * Output a notification (that is, a status message about something that has
  2314. * just happened).
  2315. *
  2316. * @param string $message the message to print out
  2317. * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
  2318. * @return string the HTML to output.
  2319. */
  2320. public function notification($message, $classes = 'notifyproblem') {
  2321. return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
  2322. }
  2323. /**
  2324. * Returns HTML to display a continue button that goes to a particular URL.
  2325. *
  2326. * @param string|moodle_url $url The url the button goes to.
  2327. * @return string the HTML to output.
  2328. */
  2329. public function continue_button($url) {
  2330. if (!($url instanceof moodle_url)) {
  2331. $url = new moodle_url($url);
  2332. }
  2333. $button = new single_button($url, get_string('continue'), 'get');
  2334. $button->class = 'continuebutton';
  2335. return $this->render($button);
  2336. }
  2337. /**
  2338. * Returns HTML to display a single paging bar to provide access to other pages (usually in a search)
  2339. *
  2340. * Theme developers: DO NOT OVERRIDE! Please override function
  2341. * {@link core_renderer::render_paging_bar()} instead.
  2342. *
  2343. * @param int $totalcount The total number of entries available to be paged through
  2344. * @param int $page The page you are currently viewing
  2345. * @param int $perpage The number of entries that should be shown per page
  2346. * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
  2347. * @param string $pagevar name of page parameter that holds the page number
  2348. * @return string the HTML to output.
  2349. */
  2350. public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
  2351. $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
  2352. return $this->render($pb);
  2353. }
  2354. /**
  2355. * Internal implementation of paging bar rendering.
  2356. *
  2357. * @param paging_bar $pagingbar
  2358. * @return string
  2359. */
  2360. protected function render_paging_bar(paging_bar $pagingbar) {
  2361. $output = '';
  2362. $pagingbar = clone($pagingbar);
  2363. $pagingbar->prepare($this, $this->page, $this->target);
  2364. if ($pagingbar->totalcount > $pagingbar->perpage) {
  2365. $output .= get_string('page') . ':';
  2366. if (!empty($pagingbar->previouslink)) {
  2367. $output .= '&#160;(' . $pagingbar->previouslink . ')&#160;';
  2368. }
  2369. if (!empty($pagingbar->firstlink)) {
  2370. $output .= '&#160;' . $pagingbar->firstlink . '&#160;...';
  2371. }
  2372. foreach ($pagingbar->pagelinks as $link) {
  2373. $output .= "&#160;&#160;$link";
  2374. }
  2375. if (!empty($pagingbar->lastlink)) {
  2376. $output .= '&#160;...' . $pagingbar->lastlink . '&#160;';
  2377. }
  2378. if (!empty($pagingbar->nextlink)) {
  2379. $output .= '&#160;&#160;(' . $pagingbar->nextlink . ')';
  2380. }
  2381. }
  2382. return html_writer::tag('div', $output, array('class' => 'paging'));
  2383. }
  2384. /**
  2385. * Output the place a skip link goes to.
  2386. *
  2387. * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
  2388. * @return string the HTML to output.
  2389. */
  2390. public function skip_link_target($id = null) {
  2391. return html_writer::tag('span', '', array('id' => $id));
  2392. }
  2393. /**
  2394. * Outputs a heading
  2395. *
  2396. * @param string $text The text of the heading
  2397. * @param int $level The level of importance of the heading. Defaulting to 2
  2398. * @param string $classes A space-separated list of CSS classes. Defaulting to null
  2399. * @param string $id An optional ID
  2400. * @return string the HTML to output.
  2401. */
  2402. public function heading($text, $level = 2, $classes = null, $id = null) {
  2403. $level = (integer) $level;
  2404. if ($level < 1 or $level > 6) {
  2405. throw new coding_exception('Heading level must be an integer between 1 and 6.');
  2406. }
  2407. return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
  2408. }
  2409. /**
  2410. * Outputs a box.
  2411. *
  2412. * @param string $contents The contents of the box
  2413. * @param string $classes A space-separated list of CSS classes
  2414. * @param string $id An optional ID
  2415. * @param array $attributes An array of other attributes to give the box.
  2416. * @return string the HTML to output.
  2417. */
  2418. public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
  2419. return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
  2420. }
  2421. /**
  2422. * Outputs the opening section of a box.
  2423. *
  2424. * @param string $classes A space-separated list of CSS classes
  2425. * @param string $id An optional ID
  2426. * @param array $attributes An array of other attributes to give the box.
  2427. * @return string the HTML to output.
  2428. */
  2429. public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
  2430. $this->opencontainers->push('box', html_writer::end_tag('div'));
  2431. $attributes['id'] = $id;
  2432. $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
  2433. return html_writer::start_tag('div', $attributes);
  2434. }
  2435. /**
  2436. * Outputs the closing section of a box.
  2437. *
  2438. * @return string the HTML to output.
  2439. */
  2440. public function box_end() {
  2441. return $this->opencontainers->pop('box');
  2442. }
  2443. /**
  2444. * Outputs a container.
  2445. *
  2446. * @param string $contents The contents of the box
  2447. * @param string $classes A space-separated list of CSS classes
  2448. * @param string $id An optional ID
  2449. * @return string the HTML to output.
  2450. */
  2451. public function container($contents, $classes = null, $id = null) {
  2452. return $this->container_start($classes, $id) . $contents . $this->container_end();
  2453. }
  2454. /**
  2455. * Outputs the opening section of a container.
  2456. *
  2457. * @param string $classes A space-separated list of CSS classes
  2458. * @param string $id An optional ID
  2459. * @return string the HTML to output.
  2460. */
  2461. public function container_start($classes = null, $id = null) {
  2462. $this->opencontainers->push('container', html_writer::end_tag('div'));
  2463. return html_writer::start_tag('div', array('id' => $id,
  2464. 'class' => renderer_base::prepare_classes($classes)));
  2465. }
  2466. /**
  2467. * Outputs the closing section of a container.
  2468. *
  2469. * @return string the HTML to output.
  2470. */
  2471. public function container_end() {
  2472. return $this->opencontainers->pop('container');
  2473. }
  2474. /**
  2475. * Make nested HTML lists out of the items
  2476. *
  2477. * The resulting list will look something like this:
  2478. *
  2479. * <pre>
  2480. * <<ul>>
  2481. * <<li>><div class='tree_item parent'>(item contents)</div>
  2482. * <<ul>
  2483. * <<li>><div class='tree_item'>(item contents)</div><</li>>
  2484. * <</ul>>
  2485. * <</li>>
  2486. * <</ul>>
  2487. * </pre>
  2488. *
  2489. * @param array $items
  2490. * @param array $attrs html attributes passed to the top ofs the list
  2491. * @return string HTML
  2492. */
  2493. public function tree_block_contents($items, $attrs = array()) {
  2494. // exit if empty, we don't want an empty ul element
  2495. if (empty($items)) {
  2496. return '';
  2497. }
  2498. // array of nested li elements
  2499. $lis = array();
  2500. foreach ($items as $item) {
  2501. // this applies to the li item which contains all child lists too
  2502. $content = $item->content($this);
  2503. $liclasses = array($item->get_css_type());
  2504. if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0 && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
  2505. $liclasses[] = 'collapsed';
  2506. }
  2507. if ($item->isactive === true) {
  2508. $liclasses[] = 'current_branch';
  2509. }
  2510. $liattr = array('class'=>join(' ',$liclasses));
  2511. // class attribute on the div item which only contains the item content
  2512. $divclasses = array('tree_item');
  2513. if ($item->children->count()>0 || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
  2514. $divclasses[] = 'branch';
  2515. } else {
  2516. $divclasses[] = 'leaf';
  2517. }
  2518. if (!empty($item->classes) && count($item->classes)>0) {
  2519. $divclasses[] = join(' ', $item->classes);
  2520. }
  2521. $divattr = array('class'=>join(' ', $divclasses));
  2522. if (!empty($item->id)) {
  2523. $divattr['id'] = $item->id;
  2524. }
  2525. $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
  2526. if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
  2527. $content = html_writer::empty_tag('hr') . $content;
  2528. }
  2529. $content = html_writer::tag('li', $content, $liattr);
  2530. $lis[] = $content;
  2531. }
  2532. return html_writer::tag('ul', implode("\n", $lis), $attrs);
  2533. }
  2534. /**
  2535. * Return the navbar content so that it can be echoed out by the layout
  2536. *
  2537. * @return string XHTML navbar
  2538. */
  2539. public function navbar() {
  2540. $items = $this->page->navbar->get_items();
  2541. $itemcount = count($items);
  2542. if ($itemcount === 0) {
  2543. return '';
  2544. }
  2545. $htmlblocks = array();
  2546. // Iterate the navarray and display each node
  2547. $separator = get_separator();
  2548. for ($i=0;$i < $itemcount;$i++) {
  2549. $item = $items[$i];
  2550. $item->hideicon = true;
  2551. if ($i===0) {
  2552. $content = html_writer::tag('li', $this->render($item));
  2553. } else {
  2554. $content = html_writer::tag('li', $separator.$this->render($item));
  2555. }
  2556. $htmlblocks[] = $content;
  2557. }
  2558. //accessibility: heading for navbar list (MDL-20446)
  2559. $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
  2560. $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
  2561. // XHTML
  2562. return $navbarcontent;
  2563. }
  2564. /**
  2565. * Renders a navigation node object.
  2566. *
  2567. * @param navigation_node $item The navigation node to render.
  2568. * @return string HTML fragment
  2569. */
  2570. protected function render_navigation_node(navigation_node $item) {
  2571. $content = $item->get_content();
  2572. $title = $item->get_title();
  2573. if ($item->icon instanceof renderable && !$item->hideicon) {
  2574. $icon = $this->render($item->icon);
  2575. $content = $icon.$content; // use CSS for spacing of icons
  2576. }
  2577. if ($item->helpbutton !== null) {
  2578. $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
  2579. }
  2580. if ($content === '') {
  2581. return '';
  2582. }
  2583. if ($item->action instanceof action_link) {
  2584. $link = $item->action;
  2585. if ($item->hidden) {
  2586. $link->add_class('dimmed');
  2587. }
  2588. if (!empty($content)) {
  2589. // Providing there is content we will use that for the link content.
  2590. $link->text = $content;
  2591. }
  2592. $content = $this->render($link);
  2593. } else if ($item->action instanceof moodle_url) {
  2594. $attributes = array();
  2595. if ($title !== '') {
  2596. $attributes['title'] = $title;
  2597. }
  2598. if ($item->hidden) {
  2599. $attributes['class'] = 'dimmed_text';
  2600. }
  2601. $content = html_writer::link($item->action, $content, $attributes);
  2602. } else if (is_string($item->action) || empty($item->action)) {
  2603. $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
  2604. if ($title !== '') {
  2605. $attributes['title'] = $title;
  2606. }
  2607. if ($item->hidden) {
  2608. $attributes['class'] = 'dimmed_text';
  2609. }
  2610. $content = html_writer::tag('span', $content, $attributes);
  2611. }
  2612. return $content;
  2613. }
  2614. /**
  2615. * Accessibility: Right arrow-like character is
  2616. * used in the breadcrumb trail, course navigation menu
  2617. * (previous/next activity), calendar, and search forum block.
  2618. * If the theme does not set characters, appropriate defaults
  2619. * are set automatically. Please DO NOT
  2620. * use &lt; &gt; &raquo; - these are confusing for blind users.
  2621. *
  2622. * @return string
  2623. */
  2624. public function rarrow() {
  2625. return $this->page->theme->rarrow;
  2626. }
  2627. /**
  2628. * Accessibility: Right arrow-like character is
  2629. * used in the breadcrumb trail, course navigation menu
  2630. * (previous/next activity), calendar, and search forum block.
  2631. * If the theme does not set characters, appropriate defaults
  2632. * are set automatically. Please DO NOT
  2633. * use &lt; &gt; &raquo; - these are confusing for blind users.
  2634. *
  2635. * @return string
  2636. */
  2637. public function larrow() {
  2638. return $this->page->theme->larrow;
  2639. }
  2640. /**
  2641. * Returns the custom menu if one has been set
  2642. *
  2643. * A custom menu can be configured by browsing to
  2644. * Settings: Administration > Appearance > Themes > Theme settings
  2645. * and then configuring the custommenu config setting as described.
  2646. *
  2647. * Theme developers: DO NOT OVERRIDE! Please override function
  2648. * {@link core_renderer::render_custom_menu()} instead.
  2649. *
  2650. * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
  2651. * @return string
  2652. */
  2653. public function custom_menu($custommenuitems = '') {
  2654. global $CFG;
  2655. if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
  2656. $custommenuitems = $CFG->custommenuitems;
  2657. }
  2658. if (empty($custommenuitems)) {
  2659. return '';
  2660. }
  2661. $custommenu = new custom_menu($custommenuitems, current_language());
  2662. return $this->render($custommenu);
  2663. }
  2664. /**
  2665. * Renders a custom menu object (located in outputcomponents.php)
  2666. *
  2667. * The custom menu this method produces makes use of the YUI3 menunav widget
  2668. * and requires very specific html elements and classes.
  2669. *
  2670. * @staticvar int $menucount
  2671. * @param custom_menu $menu
  2672. * @return string
  2673. */
  2674. protected function render_custom_menu(custom_menu $menu) {
  2675. static $menucount = 0;
  2676. // If the menu has no children return an empty string
  2677. if (!$menu->has_children()) {
  2678. return '';
  2679. }
  2680. // Increment the menu count. This is used for ID's that get worked with
  2681. // in JavaScript as is essential
  2682. $menucount++;
  2683. // Initialise this custom menu (the custom menu object is contained in javascript-static
  2684. $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
  2685. $jscode = "(function(){{$jscode}})";
  2686. $this->page->requires->yui_module('node-menunav', $jscode);
  2687. // Build the root nodes as required by YUI
  2688. $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
  2689. $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
  2690. $content .= html_writer::start_tag('ul');
  2691. // Render each child
  2692. foreach ($menu->get_children() as $item) {
  2693. $content .= $this->render_custom_menu_item($item);
  2694. }
  2695. // Close the open tags
  2696. $content .= html_writer::end_tag('ul');
  2697. $content .= html_writer::end_tag('div');
  2698. $content .= html_writer::end_tag('div');
  2699. // Return the custom menu
  2700. return $content;
  2701. }
  2702. /**
  2703. * Renders a custom menu node as part of a submenu
  2704. *
  2705. * The custom menu this method produces makes use of the YUI3 menunav widget
  2706. * and requires very specific html elements and classes.
  2707. *
  2708. * @see core:renderer::render_custom_menu()
  2709. *
  2710. * @staticvar int $submenucount
  2711. * @param custom_menu_item $menunode
  2712. * @return string
  2713. */
  2714. protected function render_custom_menu_item(custom_menu_item $menunode) {
  2715. // Required to ensure we get unique trackable id's
  2716. static $submenucount = 0;
  2717. if ($menunode->has_children()) {
  2718. // If the child has menus render it as a sub menu
  2719. $submenucount++;
  2720. $content = html_writer::start_tag('li');
  2721. if ($menunode->get_url() !== null) {
  2722. $url = $menunode->get_url();
  2723. } else {
  2724. $url = '#cm_submenu_'.$submenucount;
  2725. }
  2726. $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
  2727. $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
  2728. $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
  2729. $content .= html_writer::start_tag('ul');
  2730. foreach ($menunode->get_children() as $menunode) {
  2731. $content .= $this->render_custom_menu_item($menunode);
  2732. }
  2733. $content .= html_writer::end_tag('ul');
  2734. $content .= html_writer::end_tag('div');
  2735. $content .= html_writer::end_tag('div');
  2736. $content .= html_writer::end_tag('li');
  2737. } else {
  2738. // The node doesn't have children so produce a final menuitem
  2739. $content = html_writer::start_tag('li', array('class'=>'yui3-menuitem'));
  2740. if ($menunode->get_url() !== null) {
  2741. $url = $menunode->get_url();
  2742. } else {
  2743. $url = '#';
  2744. }
  2745. $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menuitem-content', 'title'=>$menunode->get_title()));
  2746. $content .= html_writer::end_tag('li');
  2747. }
  2748. // Return the sub menu
  2749. return $content;
  2750. }
  2751. /**
  2752. * Renders theme links for switching between default and other themes.
  2753. *
  2754. * @return string
  2755. */
  2756. protected function theme_switch_links() {
  2757. $actualdevice = core_useragent::get_device_type();
  2758. $currentdevice = $this->page->devicetypeinuse;
  2759. $switched = ($actualdevice != $currentdevice);
  2760. if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
  2761. // The user is using the a default device and hasn't switched so don't shown the switch
  2762. // device links.
  2763. return '';
  2764. }
  2765. if ($switched) {
  2766. $linktext = get_string('switchdevicerecommended');
  2767. $devicetype = $actualdevice;
  2768. } else {
  2769. $linktext = get_string('switchdevicedefault');
  2770. $devicetype = 'default';
  2771. }
  2772. $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
  2773. $content = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
  2774. $content .= html_writer::link($linkurl, $linktext);
  2775. $content .= html_writer::end_tag('div');
  2776. return $content;
  2777. }
  2778. /**
  2779. * Renders tabs
  2780. *
  2781. * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
  2782. *
  2783. * Theme developers: In order to change how tabs are displayed please override functions
  2784. * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
  2785. *
  2786. * @param array $tabs array of tabs, each of them may have it's own ->subtree
  2787. * @param string|null $selected which tab to mark as selected, all parent tabs will
  2788. * automatically be marked as activated
  2789. * @param array|string|null $inactive list of ids of inactive tabs, regardless of
  2790. * their level. Note that you can as weel specify tabobject::$inactive for separate instances
  2791. * @return string
  2792. */
  2793. public final function tabtree($tabs, $selected = null, $inactive = null) {
  2794. return $this->render(new tabtree($tabs, $selected, $inactive));
  2795. }
  2796. /**
  2797. * Renders tabtree
  2798. *
  2799. * @param tabtree $tabtree
  2800. * @return string
  2801. */
  2802. protected function render_tabtree(tabtree $tabtree) {
  2803. if (empty($tabtree->subtree)) {
  2804. return '';
  2805. }
  2806. $str = '';
  2807. $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
  2808. $str .= $this->render_tabobject($tabtree);
  2809. $str .= html_writer::end_tag('div').
  2810. html_writer::tag('div', ' ', array('class' => 'clearer'));
  2811. return $str;
  2812. }
  2813. /**
  2814. * Renders tabobject (part of tabtree)
  2815. *
  2816. * This function is called from {@link core_renderer::render_tabtree()}
  2817. * and also it calls itself when printing the $tabobject subtree recursively.
  2818. *
  2819. * Property $tabobject->level indicates the number of row of tabs.
  2820. *
  2821. * @param tabobject $tabobject
  2822. * @return string HTML fragment
  2823. */
  2824. protected function render_tabobject(tabobject $tabobject) {
  2825. $str = '';
  2826. // Print name of the current tab.
  2827. if ($tabobject instanceof tabtree) {
  2828. // No name for tabtree root.
  2829. } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
  2830. // Tab name without a link. The <a> tag is used for styling.
  2831. $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
  2832. } else {
  2833. // Tab name with a link.
  2834. if (!($tabobject->link instanceof moodle_url)) {
  2835. // backward compartibility when link was passed as quoted string
  2836. $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
  2837. } else {
  2838. $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
  2839. }
  2840. }
  2841. if (empty($tabobject->subtree)) {
  2842. if ($tabobject->selected) {
  2843. $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
  2844. }
  2845. return $str;
  2846. }
  2847. // Print subtree
  2848. $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
  2849. $cnt = 0;
  2850. foreach ($tabobject->subtree as $tab) {
  2851. $liclass = '';
  2852. if (!$cnt) {
  2853. $liclass .= ' first';
  2854. }
  2855. if ($cnt == count($tabobject->subtree) - 1) {
  2856. $liclass .= ' last';
  2857. }
  2858. if ((empty($tab->subtree)) && (!empty($tab->selected))) {
  2859. $liclass .= ' onerow';
  2860. }
  2861. if ($tab->selected) {
  2862. $liclass .= ' here selected';
  2863. } else if ($tab->activated) {
  2864. $liclass .= ' here active';
  2865. }
  2866. // This will recursively call function render_tabobject() for each item in subtree
  2867. $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
  2868. $cnt++;
  2869. }
  2870. $str .= html_writer::end_tag('ul');
  2871. return $str;
  2872. }
  2873. /**
  2874. * Get the HTML for blocks in the given region.
  2875. *
  2876. * @since 2.5.1 2.6
  2877. * @param string $region The region to get HTML for.
  2878. * @return string HTML.
  2879. */
  2880. public function blocks($region, $classes = array(), $tag = 'aside') {
  2881. $displayregion = $this->page->apply_theme_region_manipulations($region);
  2882. $classes = (array)$classes;
  2883. $classes[] = 'block-region';
  2884. $attributes = array(
  2885. 'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
  2886. 'class' => join(' ', $classes),
  2887. 'data-blockregion' => $displayregion,
  2888. 'data-droptarget' => '1'
  2889. );
  2890. if ($this->page->blocks->region_has_content($displayregion, $this)) {
  2891. $content = $this->blocks_for_region($displayregion);
  2892. } else {
  2893. $content = '';
  2894. }
  2895. return html_writer::tag($tag, $content, $attributes);
  2896. }
  2897. /**
  2898. * Renders a custom block region.
  2899. *
  2900. * Use this method if you want to add an additional block region to the content of the page.
  2901. * Please note this should only be used in special situations.
  2902. * We want to leave the theme is control where ever possible!
  2903. *
  2904. * This method must use the same method that the theme uses within its layout file.
  2905. * As such it asks the theme what method it is using.
  2906. * It can be one of two values, blocks or blocks_for_region (deprecated).
  2907. *
  2908. * @param string $regionname The name of the custom region to add.
  2909. * @return string HTML for the block region.
  2910. */
  2911. public function custom_block_region($regionname) {
  2912. if ($this->page->theme->get_block_render_method() === 'blocks') {
  2913. return $this->blocks($regionname);
  2914. } else {
  2915. return $this->blocks_for_region($regionname);
  2916. }
  2917. }
  2918. /**
  2919. * Returns the CSS classes to apply to the body tag.
  2920. *
  2921. * @since 2.5.1 2.6
  2922. * @param array $additionalclasses Any additional classes to apply.
  2923. * @return string
  2924. */
  2925. public function body_css_classes(array $additionalclasses = array()) {
  2926. // Add a class for each block region on the page.
  2927. // We use the block manager here because the theme object makes get_string calls.
  2928. foreach ($this->page->blocks->get_regions() as $region) {
  2929. $additionalclasses[] = 'has-region-'.$region;
  2930. if ($this->page->blocks->region_has_content($region, $this)) {
  2931. $additionalclasses[] = 'used-region-'.$region;
  2932. } else {
  2933. $additionalclasses[] = 'empty-region-'.$region;
  2934. }
  2935. if ($this->page->blocks->region_completely_docked($region, $this)) {
  2936. $additionalclasses[] = 'docked-region-'.$region;
  2937. }
  2938. }
  2939. foreach ($this->page->layout_options as $option => $value) {
  2940. if ($value) {
  2941. $additionalclasses[] = 'layout-option-'.$option;
  2942. }
  2943. }
  2944. $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
  2945. return $css;
  2946. }
  2947. /**
  2948. * The ID attribute to apply to the body tag.
  2949. *
  2950. * @since 2.5.1 2.6
  2951. * @return string
  2952. */
  2953. public function body_id() {
  2954. return $this->page->bodyid;
  2955. }
  2956. /**
  2957. * Returns HTML attributes to use within the body tag. This includes an ID and classes.
  2958. *
  2959. * @since 2.5.1 2.6
  2960. * @param string|array $additionalclasses Any additional classes to give the body tag,
  2961. * @return string
  2962. */
  2963. public function body_attributes($additionalclasses = array()) {
  2964. if (!is_array($additionalclasses)) {
  2965. $additionalclasses = explode(' ', $additionalclasses);
  2966. }
  2967. return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
  2968. }
  2969. /**
  2970. * Gets HTML for the page heading.
  2971. *
  2972. * @since 2.5.1 2.6
  2973. * @param string $tag The tag to encase the heading in. h1 by default.
  2974. * @return string HTML.
  2975. */
  2976. public function page_heading($tag = 'h1') {
  2977. return html_writer::tag($tag, $this->page->heading);
  2978. }
  2979. /**
  2980. * Gets the HTML for the page heading button.
  2981. *
  2982. * @since 2.5.1 2.6
  2983. * @return string HTML.
  2984. */
  2985. public function page_heading_button() {
  2986. return $this->page->button;
  2987. }
  2988. /**
  2989. * Returns the Moodle docs link to use for this page.
  2990. *
  2991. * @since 2.5.1 2.6
  2992. * @param string $text
  2993. * @return string
  2994. */
  2995. public function page_doc_link($text = null) {
  2996. if ($text === null) {
  2997. $text = get_string('moodledocslink');
  2998. }
  2999. $path = page_get_doc_link_path($this->page);
  3000. if (!$path) {
  3001. return '';
  3002. }
  3003. return $this->doc_link($path, $text);
  3004. }
  3005. /**
  3006. * Returns the page heading menu.
  3007. *
  3008. * @since 2.5.1 2.6
  3009. * @return string HTML.
  3010. */
  3011. public function page_heading_menu() {
  3012. return $this->page->headingmenu;
  3013. }
  3014. /**
  3015. * Returns the title to use on the page.
  3016. *
  3017. * @since 2.5.1 2.6
  3018. * @return string
  3019. */
  3020. public function page_title() {
  3021. return $this->page->title;
  3022. }
  3023. /**
  3024. * Returns the URL for the favicon.
  3025. *
  3026. * @since 2.5.1 2.6
  3027. * @return string The favicon URL
  3028. */
  3029. public function favicon() {
  3030. return $this->pix_url('favicon', 'theme');
  3031. }
  3032. }
  3033. /**
  3034. * A renderer that generates output for command-line scripts.
  3035. *
  3036. * The implementation of this renderer is probably incomplete.
  3037. *
  3038. * @copyright 2009 Tim Hunt
  3039. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3040. * @since Moodle 2.0
  3041. * @package core
  3042. * @category output
  3043. */
  3044. class core_renderer_cli extends core_renderer {
  3045. /**
  3046. * Returns the page header.
  3047. *
  3048. * @return string HTML fragment
  3049. */
  3050. public function header() {
  3051. return $this->page->heading . "\n";
  3052. }
  3053. /**
  3054. * Returns a template fragment representing a Heading.
  3055. *
  3056. * @param string $text The text of the heading
  3057. * @param int $level The level of importance of the heading
  3058. * @param string $classes A space-separated list of CSS classes
  3059. * @param string $id An optional ID
  3060. * @return string A template fragment for a heading
  3061. */
  3062. public function heading($text, $level = 2, $classes = 'main', $id = null) {
  3063. $text .= "\n";
  3064. switch ($level) {
  3065. case 1:
  3066. return '=>' . $text;
  3067. case 2:
  3068. return '-->' . $text;
  3069. default:
  3070. return $text;
  3071. }
  3072. }
  3073. /**
  3074. * Returns a template fragment representing a fatal error.
  3075. *
  3076. * @param string $message The message to output
  3077. * @param string $moreinfourl URL where more info can be found about the error
  3078. * @param string $link Link for the Continue button
  3079. * @param array $backtrace The execution backtrace
  3080. * @param string $debuginfo Debugging information
  3081. * @return string A template fragment for a fatal error
  3082. */
  3083. public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
  3084. global $CFG;
  3085. $output = "!!! $message !!!\n";
  3086. if ($CFG->debugdeveloper) {
  3087. if (!empty($debuginfo)) {
  3088. $output .= $this->notification($debuginfo, 'notifytiny');
  3089. }
  3090. if (!empty($backtrace)) {
  3091. $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
  3092. }
  3093. }
  3094. return $output;
  3095. }
  3096. /**
  3097. * Returns a template fragment representing a notification.
  3098. *
  3099. * @param string $message The message to include
  3100. * @param string $classes A space-separated list of CSS classes
  3101. * @return string A template fragment for a notification
  3102. */
  3103. public function notification($message, $classes = 'notifyproblem') {
  3104. $message = clean_text($message);
  3105. if ($classes === 'notifysuccess') {
  3106. return "++ $message ++\n";
  3107. }
  3108. return "!! $message !!\n";
  3109. }
  3110. }
  3111. /**
  3112. * A renderer that generates output for ajax scripts.
  3113. *
  3114. * This renderer prevents accidental sends back only json
  3115. * encoded error messages, all other output is ignored.
  3116. *
  3117. * @copyright 2010 Petr Skoda
  3118. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3119. * @since Moodle 2.0
  3120. * @package core
  3121. * @category output
  3122. */
  3123. class core_renderer_ajax extends core_renderer {
  3124. /**
  3125. * Returns a template fragment representing a fatal error.
  3126. *
  3127. * @param string $message The message to output
  3128. * @param string $moreinfourl URL where more info can be found about the error
  3129. * @param string $link Link for the Continue button
  3130. * @param array $backtrace The execution backtrace
  3131. * @param string $debuginfo Debugging information
  3132. * @return string A template fragment for a fatal error
  3133. */
  3134. public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
  3135. global $CFG;
  3136. $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
  3137. $e = new stdClass();
  3138. $e->error = $message;
  3139. $e->stacktrace = NULL;
  3140. $e->debuginfo = NULL;
  3141. $e->reproductionlink = NULL;
  3142. if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
  3143. $link = (string) $link;
  3144. if ($link) {
  3145. $e->reproductionlink = $link;
  3146. }
  3147. if (!empty($debuginfo)) {
  3148. $e->debuginfo = $debuginfo;
  3149. }
  3150. if (!empty($backtrace)) {
  3151. $e->stacktrace = format_backtrace($backtrace, true);
  3152. }
  3153. }
  3154. $this->header();
  3155. return json_encode($e);
  3156. }
  3157. /**
  3158. * Used to display a notification.
  3159. * For the AJAX notifications are discarded.
  3160. *
  3161. * @param string $message
  3162. * @param string $classes
  3163. */
  3164. public function notification($message, $classes = 'notifyproblem') {}
  3165. /**
  3166. * Used to display a redirection message.
  3167. * AJAX redirections should not occur and as such redirection messages
  3168. * are discarded.
  3169. *
  3170. * @param moodle_url|string $encodedurl
  3171. * @param string $message
  3172. * @param int $delay
  3173. * @param bool $debugdisableredirect
  3174. */
  3175. public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
  3176. /**
  3177. * Prepares the start of an AJAX output.
  3178. */
  3179. public function header() {
  3180. // unfortunately YUI iframe upload does not support application/json
  3181. if (!empty($_FILES)) {
  3182. @header('Content-type: text/plain; charset=utf-8');
  3183. if (!core_useragent::supports_json_contenttype()) {
  3184. @header('X-Content-Type-Options: nosniff');
  3185. }
  3186. } else if (!core_useragent::supports_json_contenttype()) {
  3187. @header('Content-type: text/plain; charset=utf-8');
  3188. @header('X-Content-Type-Options: nosniff');
  3189. } else {
  3190. @header('Content-type: application/json; charset=utf-8');
  3191. }
  3192. // Headers to make it not cacheable and json
  3193. @header('Cache-Control: no-store, no-cache, must-revalidate');
  3194. @header('Cache-Control: post-check=0, pre-check=0', false);
  3195. @header('Pragma: no-cache');
  3196. @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
  3197. @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  3198. @header('Accept-Ranges: none');
  3199. }
  3200. /**
  3201. * There is no footer for an AJAX request, however we must override the
  3202. * footer method to prevent the default footer.
  3203. */
  3204. public function footer() {}
  3205. /**
  3206. * No need for headers in an AJAX request... this should never happen.
  3207. * @param string $text
  3208. * @param int $level
  3209. * @param string $classes
  3210. * @param string $id
  3211. */
  3212. public function heading($text, $level = 2, $classes = 'main', $id = null) {}
  3213. }
  3214. /**
  3215. * Renderer for media files.
  3216. *
  3217. * Used in file resources, media filter, and any other places that need to
  3218. * output embedded media.
  3219. *
  3220. * @copyright 2011 The Open University
  3221. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3222. */
  3223. class core_media_renderer extends plugin_renderer_base {
  3224. /** @var array Array of available 'player' objects */
  3225. private $players;
  3226. /** @var string Regex pattern for links which may contain embeddable content */
  3227. private $embeddablemarkers;
  3228. /**
  3229. * Constructor requires medialib.php.
  3230. *
  3231. * This is needed in the constructor (not later) so that you can use the
  3232. * constants and static functions that are defined in core_media class
  3233. * before you call renderer functions.
  3234. */
  3235. public function __construct() {
  3236. global $CFG;
  3237. require_once($CFG->libdir . '/medialib.php');
  3238. }
  3239. /**
  3240. * Obtains the list of core_media_player objects currently in use to render
  3241. * items.
  3242. *
  3243. * The list is in rank order (highest first) and does not include players
  3244. * which are disabled.
  3245. *
  3246. * @return array Array of core_media_player objects in rank order
  3247. */
  3248. protected function get_players() {
  3249. global $CFG;
  3250. // Save time by only building the list once.
  3251. if (!$this->players) {
  3252. // Get raw list of players.
  3253. $players = $this->get_players_raw();
  3254. // Chuck all the ones that are disabled.
  3255. foreach ($players as $key => $player) {
  3256. if (!$player->is_enabled()) {
  3257. unset($players[$key]);
  3258. }
  3259. }
  3260. // Sort in rank order (highest first).
  3261. usort($players, array('core_media_player', 'compare_by_rank'));
  3262. $this->players = $players;
  3263. }
  3264. return $this->players;
  3265. }
  3266. /**
  3267. * Obtains a raw list of player objects that includes objects regardless
  3268. * of whether they are disabled or not, and without sorting.
  3269. *
  3270. * You can override this in a subclass if you need to add additional
  3271. * players.
  3272. *
  3273. * The return array is be indexed by player name to make it easier to
  3274. * remove players in a subclass.
  3275. *
  3276. * @return array $players Array of core_media_player objects in any order
  3277. */
  3278. protected function get_players_raw() {
  3279. return array(
  3280. 'vimeo' => new core_media_player_vimeo(),
  3281. 'youtube' => new core_media_player_youtube(),
  3282. 'youtube_playlist' => new core_media_player_youtube_playlist(),
  3283. 'html5video' => new core_media_player_html5video(),
  3284. 'html5audio' => new core_media_player_html5audio(),
  3285. 'mp3' => new core_media_player_mp3(),
  3286. 'flv' => new core_media_player_flv(),
  3287. 'wmp' => new core_media_player_wmp(),
  3288. 'qt' => new core_media_player_qt(),
  3289. 'rm' => new core_media_player_rm(),
  3290. 'swf' => new core_media_player_swf(),
  3291. 'link' => new core_media_player_link(),
  3292. );
  3293. }
  3294. /**
  3295. * Renders a media file (audio or video) using suitable embedded player.
  3296. *
  3297. * See embed_alternatives function for full description of parameters.
  3298. * This function calls through to that one.
  3299. *
  3300. * When using this function you can also specify width and height in the
  3301. * URL by including ?d=100x100 at the end. If specified in the URL, this
  3302. * will override the $width and $height parameters.
  3303. *
  3304. * @param moodle_url $url Full URL of media file
  3305. * @param string $name Optional user-readable name to display in download link
  3306. * @param int $width Width in pixels (optional)
  3307. * @param int $height Height in pixels (optional)
  3308. * @param array $options Array of key/value pairs
  3309. * @return string HTML content of embed
  3310. */
  3311. public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
  3312. $options = array()) {
  3313. // Get width and height from URL if specified (overrides parameters in
  3314. // function call).
  3315. $rawurl = $url->out(false);
  3316. if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
  3317. $width = $matches[1];
  3318. $height = $matches[2];
  3319. $url = new moodle_url(str_replace($matches[0], '', $rawurl));
  3320. }
  3321. // Defer to array version of function.
  3322. return $this->embed_alternatives(array($url), $name, $width, $height, $options);
  3323. }
  3324. /**
  3325. * Renders media files (audio or video) using suitable embedded player.
  3326. * The list of URLs should be alternative versions of the same content in
  3327. * multiple formats. If there is only one format it should have a single
  3328. * entry.
  3329. *
  3330. * If the media files are not in a supported format, this will give students
  3331. * a download link to each format. The download link uses the filename
  3332. * unless you supply the optional name parameter.
  3333. *
  3334. * Width and height are optional. If specified, these are suggested sizes
  3335. * and should be the exact values supplied by the user, if they come from
  3336. * user input. These will be treated as relating to the size of the video
  3337. * content, not including any player control bar.
  3338. *
  3339. * For audio files, height will be ignored. For video files, a few formats
  3340. * work if you specify only width, but in general if you specify width
  3341. * you must specify height as well.
  3342. *
  3343. * The $options array is passed through to the core_media_player classes
  3344. * that render the object tag. The keys can contain values from
  3345. * core_media::OPTION_xx.
  3346. *
  3347. * @param array $alternatives Array of moodle_url to media files
  3348. * @param string $name Optional user-readable name to display in download link
  3349. * @param int $width Width in pixels (optional)
  3350. * @param int $height Height in pixels (optional)
  3351. * @param array $options Array of key/value pairs
  3352. * @return string HTML content of embed
  3353. */
  3354. public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
  3355. $options = array()) {
  3356. // Get list of player plugins (will also require the library).
  3357. $players = $this->get_players();
  3358. // Set up initial text which will be replaced by first player that
  3359. // supports any of the formats.
  3360. $out = core_media_player::PLACEHOLDER;
  3361. // Loop through all players that support any of these URLs.
  3362. foreach ($players as $player) {
  3363. // Option: When no other player matched, don't do the default link player.
  3364. if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
  3365. $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
  3366. continue;
  3367. }
  3368. $supported = $player->list_supported_urls($alternatives, $options);
  3369. if ($supported) {
  3370. // Embed.
  3371. $text = $player->embed($supported, $name, $width, $height, $options);
  3372. // Put this in place of the 'fallback' slot in the previous text.
  3373. $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
  3374. }
  3375. }
  3376. // Remove 'fallback' slot from final version and return it.
  3377. $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
  3378. if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
  3379. $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
  3380. }
  3381. return $out;
  3382. }
  3383. /**
  3384. * Checks whether a file can be embedded. If this returns true you will get
  3385. * an embedded player; if this returns false, you will just get a download
  3386. * link.
  3387. *
  3388. * This is a wrapper for can_embed_urls.
  3389. *
  3390. * @param moodle_url $url URL of media file
  3391. * @param array $options Options (same as when embedding)
  3392. * @return bool True if file can be embedded
  3393. */
  3394. public function can_embed_url(moodle_url $url, $options = array()) {
  3395. return $this->can_embed_urls(array($url), $options);
  3396. }
  3397. /**
  3398. * Checks whether a file can be embedded. If this returns true you will get
  3399. * an embedded player; if this returns false, you will just get a download
  3400. * link.
  3401. *
  3402. * @param array $urls URL of media file and any alternatives (moodle_url)
  3403. * @param array $options Options (same as when embedding)
  3404. * @return bool True if file can be embedded
  3405. */
  3406. public function can_embed_urls(array $urls, $options = array()) {
  3407. // Check all players to see if any of them support it.
  3408. foreach ($this->get_players() as $player) {
  3409. // Link player (always last on list) doesn't count!
  3410. if ($player->get_rank() <= 0) {
  3411. break;
  3412. }
  3413. // First player that supports it, return true.
  3414. if ($player->list_supported_urls($urls, $options)) {
  3415. return true;
  3416. }
  3417. }
  3418. return false;
  3419. }
  3420. /**
  3421. * Obtains a list of markers that can be used in a regular expression when
  3422. * searching for URLs that can be embedded by any player type.
  3423. *
  3424. * This string is used to improve peformance of regex matching by ensuring
  3425. * that the (presumably C) regex code can do a quick keyword check on the
  3426. * URL part of a link to see if it matches one of these, rather than having
  3427. * to go into PHP code for every single link to see if it can be embedded.
  3428. *
  3429. * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
  3430. */
  3431. public function get_embeddable_markers() {
  3432. if (empty($this->embeddablemarkers)) {
  3433. $markers = '';
  3434. foreach ($this->get_players() as $player) {
  3435. foreach ($player->get_embeddable_markers() as $marker) {
  3436. if ($markers !== '') {
  3437. $markers .= '|';
  3438. }
  3439. $markers .= preg_quote($marker);
  3440. }
  3441. }
  3442. $this->embeddablemarkers = $markers;
  3443. }
  3444. return $this->embeddablemarkers;
  3445. }
  3446. }
  3447. /**
  3448. * The maintenance renderer.
  3449. *
  3450. * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
  3451. * is running a maintenance related task.
  3452. * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
  3453. *
  3454. * @since 2.6
  3455. * @package core
  3456. * @category output
  3457. * @copyright 2013 Sam Hemelryk
  3458. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3459. */
  3460. class core_renderer_maintenance extends core_renderer {
  3461. /**
  3462. * Initialises the renderer instance.
  3463. * @param moodle_page $page
  3464. * @param string $target
  3465. * @throws coding_exception
  3466. */
  3467. public function __construct(moodle_page $page, $target) {
  3468. if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
  3469. throw new coding_exception('Invalid request for the maintenance renderer.');
  3470. }
  3471. parent::__construct($page, $target);
  3472. }
  3473. /**
  3474. * Does nothing. The maintenance renderer cannot produce blocks.
  3475. *
  3476. * @param block_contents $bc
  3477. * @param string $region
  3478. * @return string
  3479. */
  3480. public function block(block_contents $bc, $region) {
  3481. // Computer says no blocks.
  3482. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3483. return '';
  3484. }
  3485. /**
  3486. * Does nothing. The maintenance renderer cannot produce blocks.
  3487. *
  3488. * @param string $region
  3489. * @param array $classes
  3490. * @param string $tag
  3491. * @return string
  3492. */
  3493. public function blocks($region, $classes = array(), $tag = 'aside') {
  3494. // Computer says no blocks.
  3495. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3496. return '';
  3497. }
  3498. /**
  3499. * Does nothing. The maintenance renderer cannot produce blocks.
  3500. *
  3501. * @param string $region
  3502. * @return string
  3503. */
  3504. public function blocks_for_region($region) {
  3505. // Computer says no blocks for region.
  3506. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3507. return '';
  3508. }
  3509. /**
  3510. * Does nothing. The maintenance renderer cannot produce a course content header.
  3511. *
  3512. * @param bool $onlyifnotcalledbefore
  3513. * @return string
  3514. */
  3515. public function course_content_header($onlyifnotcalledbefore = false) {
  3516. // Computer says no course content header.
  3517. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3518. return '';
  3519. }
  3520. /**
  3521. * Does nothing. The maintenance renderer cannot produce a course content footer.
  3522. *
  3523. * @param bool $onlyifnotcalledbefore
  3524. * @return string
  3525. */
  3526. public function course_content_footer($onlyifnotcalledbefore = false) {
  3527. // Computer says no course content footer.
  3528. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3529. return '';
  3530. }
  3531. /**
  3532. * Does nothing. The maintenance renderer cannot produce a course header.
  3533. *
  3534. * @return string
  3535. */
  3536. public function course_header() {
  3537. // Computer says no course header.
  3538. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3539. return '';
  3540. }
  3541. /**
  3542. * Does nothing. The maintenance renderer cannot produce a course footer.
  3543. *
  3544. * @return string
  3545. */
  3546. public function course_footer() {
  3547. // Computer says no course footer.
  3548. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3549. return '';
  3550. }
  3551. /**
  3552. * Does nothing. The maintenance renderer cannot produce a custom menu.
  3553. *
  3554. * @param string $custommenuitems
  3555. * @return string
  3556. */
  3557. public function custom_menu($custommenuitems = '') {
  3558. // Computer says no custom menu.
  3559. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3560. return '';
  3561. }
  3562. /**
  3563. * Does nothing. The maintenance renderer cannot produce a file picker.
  3564. *
  3565. * @param array $options
  3566. * @return string
  3567. */
  3568. public function file_picker($options) {
  3569. // Computer says no file picker.
  3570. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3571. return '';
  3572. }
  3573. /**
  3574. * Does nothing. The maintenance renderer cannot produce and HTML file tree.
  3575. *
  3576. * @param array $dir
  3577. * @return string
  3578. */
  3579. public function htmllize_file_tree($dir) {
  3580. // Hell no we don't want no htmllized file tree.
  3581. // Also why on earth is this function on the core renderer???
  3582. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3583. return '';
  3584. }
  3585. /**
  3586. * Does nothing. The maintenance renderer does not support JS.
  3587. *
  3588. * @param block_contents $bc
  3589. */
  3590. public function init_block_hider_js(block_contents $bc) {
  3591. // Computer says no JavaScript.
  3592. // Do nothing, ridiculous method.
  3593. }
  3594. /**
  3595. * Does nothing. The maintenance renderer cannot produce language menus.
  3596. *
  3597. * @return string
  3598. */
  3599. public function lang_menu() {
  3600. // Computer says no lang menu.
  3601. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3602. return '';
  3603. }
  3604. /**
  3605. * Does nothing. The maintenance renderer has no need for login information.
  3606. *
  3607. * @param null $withlinks
  3608. * @return string
  3609. */
  3610. public function login_info($withlinks = null) {
  3611. // Computer says no login info.
  3612. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3613. return '';
  3614. }
  3615. /**
  3616. * Does nothing. The maintenance renderer cannot produce user pictures.
  3617. *
  3618. * @param stdClass $user
  3619. * @param array $options
  3620. * @return string
  3621. */
  3622. public function user_picture(stdClass $user, array $options = null) {
  3623. // Computer says no user pictures.
  3624. // debugging('Please do not use $OUTPUT->'.__FUNCTION__.'() when performing maintenance tasks.', DEBUG_DEVELOPER);
  3625. return '';
  3626. }
  3627. }