[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/ -> outputrenderers.php (source)

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


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1