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