Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

       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['tabindex'] = '-1';
    2376              $attributes['aria-hidden'] = 'true';
    2377          }
    2378  
    2379          if ($userpicture->popup) {
    2380              $id = html_writer::random_id('userpicture');
    2381              $attributes['id'] = $id;
    2382              $this->add_action_handler(new popup_action('click', $url), $id);
    2383          }
    2384  
    2385          return html_writer::tag('a', $output, $attributes);
    2386      }
    2387  
    2388      /**
    2389       * Internal implementation of file tree viewer items rendering.
    2390       *
    2391       * @param array $dir
    2392       * @return string
    2393       */
    2394      public function htmllize_file_tree($dir) {
    2395          if (empty($dir['subdirs']) and empty($dir['files'])) {
    2396              return '';
    2397          }
    2398          $result = '<ul>';
    2399          foreach ($dir['subdirs'] as $subdir) {
    2400              $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
    2401          }
    2402          foreach ($dir['files'] as $file) {
    2403              $filename = $file->get_filename();
    2404              $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
    2405          }
    2406          $result .= '</ul>';
    2407  
    2408          return $result;
    2409      }
    2410  
    2411      /**
    2412       * Returns HTML to display the file picker
    2413       *
    2414       * <pre>
    2415       * $OUTPUT->file_picker($options);
    2416       * </pre>
    2417       *
    2418       * Theme developers: DO NOT OVERRIDE! Please override function
    2419       * {@link core_renderer::render_file_picker()} instead.
    2420       *
    2421       * @param array $options associative array with file manager options
    2422       *   options are:
    2423       *       maxbytes=>-1,
    2424       *       itemid=>0,
    2425       *       client_id=>uniqid(),
    2426       *       acepted_types=>'*',
    2427       *       return_types=>FILE_INTERNAL,
    2428       *       context=>$PAGE->context
    2429       * @return string HTML fragment
    2430       */
    2431      public function file_picker($options) {
    2432          $fp = new file_picker($options);
    2433          return $this->render($fp);
    2434      }
    2435  
    2436      /**
    2437       * Internal implementation of file picker rendering.
    2438       *
    2439       * @param file_picker $fp
    2440       * @return string
    2441       */
    2442      public function render_file_picker(file_picker $fp) {
    2443          global $CFG, $OUTPUT, $USER;
    2444          $options = $fp->options;
    2445          $client_id = $options->client_id;
    2446          $strsaved = get_string('filesaved', 'repository');
    2447          $straddfile = get_string('openpicker', 'repository');
    2448          $strloading  = get_string('loading', 'repository');
    2449          $strdndenabled = get_string('dndenabled_inbox', 'moodle');
    2450          $strdroptoupload = get_string('droptoupload', 'moodle');
    2451          $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';
    2452  
    2453          $currentfile = $options->currentfile;
    2454          if (empty($currentfile)) {
    2455              $currentfile = '';
    2456          } else {
    2457              $currentfile .= ' - ';
    2458          }
    2459          if ($options->maxbytes) {
    2460              $size = $options->maxbytes;
    2461          } else {
    2462              $size = get_max_upload_file_size();
    2463          }
    2464          if ($size == -1) {
    2465              $maxsize = '';
    2466          } else {
    2467              $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
    2468          }
    2469          if ($options->buttonname) {
    2470              $buttonname = ' name="' . $options->buttonname . '"';
    2471          } else {
    2472              $buttonname = '';
    2473          }
    2474          $html = <<<EOD
    2475  <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
    2476  $icon_progress
    2477  </div>
    2478  <div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
    2479      <div>
    2480          <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
    2481          <span> $maxsize </span>
    2482      </div>
    2483  EOD;
    2484          if ($options->env != 'url') {
    2485              $html .= <<<EOD
    2486      <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
    2487      <div class="filepicker-filename">
    2488          <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
    2489          <div class="dndupload-progressbars"></div>
    2490      </div>
    2491      <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
    2492      </div>
    2493  EOD;
    2494          }
    2495          $html .= '</div>';
    2496          return $html;
    2497      }
    2498  
    2499      /**
    2500       * Returns HTML to display the 'Update this Modulename' button that appears on module pages.
    2501       *
    2502       * @param string $cmid the course_module id.
    2503       * @param string $modulename the module name, eg. "forum", "quiz" or "workshop"
    2504       * @return string the HTML for the button, if this user has permission to edit it, else an empty string.
    2505       */
    2506      public function update_module_button($cmid, $modulename) {
    2507          global $CFG;
    2508          if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
    2509              $modulename = get_string('modulename', $modulename);
    2510              $string = get_string('updatethis', '', $modulename);
    2511              $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey()));
    2512              return $this->single_button($url, $string);
    2513          } else {
    2514              return '';
    2515          }
    2516      }
    2517  
    2518      /**
    2519       * Returns HTML to display a "Turn editing on/off" button in a form.
    2520       *
    2521       * @param moodle_url $url The URL + params to send through when clicking the button
    2522       * @return string HTML the button
    2523       */
    2524      public function edit_button(moodle_url $url) {
    2525  
    2526          $url->param('sesskey', sesskey());
    2527          if ($this->page->user_is_editing()) {
    2528              $url->param('edit', 'off');
    2529              $editstring = get_string('turneditingoff');
    2530          } else {
    2531              $url->param('edit', 'on');
    2532              $editstring = get_string('turneditingon');
    2533          }
    2534  
    2535          return $this->single_button($url, $editstring);
    2536      }
    2537  
    2538      /**
    2539       * Returns HTML to display a simple button to close a window
    2540       *
    2541       * @param string $text The lang string for the button's label (already output from get_string())
    2542       * @return string html fragment
    2543       */
    2544      public function close_window_button($text='') {
    2545          if (empty($text)) {
    2546              $text = get_string('closewindow');
    2547          }
    2548          $button = new single_button(new moodle_url('#'), $text, 'get');
    2549          $button->add_action(new component_action('click', 'close_window'));
    2550  
    2551          return $this->container($this->render($button), 'closewindow');
    2552      }
    2553  
    2554      /**
    2555       * Output an error message. By default wraps the error message in <span class="error">.
    2556       * If the error message is blank, nothing is output.
    2557       *
    2558       * @param string $message the error message.
    2559       * @return string the HTML to output.
    2560       */
    2561      public function error_text($message) {
    2562          if (empty($message)) {
    2563              return '';
    2564          }
    2565          $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
    2566          return html_writer::tag('span', $message, array('class' => 'error'));
    2567      }
    2568  
    2569      /**
    2570       * Do not call this function directly.
    2571       *
    2572       * To terminate the current script with a fatal error, call the {@link print_error}
    2573       * function, or throw an exception. Doing either of those things will then call this
    2574       * function to display the error, before terminating the execution.
    2575       *
    2576       * @param string $message The message to output
    2577       * @param string $moreinfourl URL where more info can be found about the error
    2578       * @param string $link Link for the Continue button
    2579       * @param array $backtrace The execution backtrace
    2580       * @param string $debuginfo Debugging information
    2581       * @return string the HTML to output.
    2582       */
    2583      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
    2584          global $CFG;
    2585  
    2586          $output = '';
    2587          $obbuffer = '';
    2588  
    2589          if ($this->has_started()) {
    2590              // we can not always recover properly here, we have problems with output buffering,
    2591              // html tables, etc.
    2592              $output .= $this->opencontainers->pop_all_but_last();
    2593  
    2594          } else {
    2595              // It is really bad if library code throws exception when output buffering is on,
    2596              // because the buffered text would be printed before our start of page.
    2597              // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
    2598              error_reporting(0); // disable notices from gzip compression, etc.
    2599              while (ob_get_level() > 0) {
    2600                  $buff = ob_get_clean();
    2601                  if ($buff === false) {
    2602                      break;
    2603                  }
    2604                  $obbuffer .= $buff;
    2605              }
    2606              error_reporting($CFG->debug);
    2607  
    2608              // Output not yet started.
    2609              $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
    2610              if (empty($_SERVER['HTTP_RANGE'])) {
    2611                  @header($protocol . ' 404 Not Found');
    2612              } else {
    2613                  // Must stop byteserving attempts somehow,
    2614                  // this is weird but Chrome PDF viewer can be stopped only with 407!
    2615                  @header($protocol . ' 407 Proxy Authentication Required');
    2616              }
    2617  
    2618              $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
    2619              $this->page->set_url('/'); // no url
    2620              //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
    2621              $this->page->set_title(get_string('error'));
    2622              $this->page->set_heading($this->page->course->fullname);
    2623              $output .= $this->header();
    2624          }
    2625  
    2626          $message = '<p class="errormessage">' . $message . '</p>'.
    2627                  '<p class="errorcode"><a href="' . $moreinfourl . '">' .
    2628                  get_string('moreinformation') . '</a></p>';
    2629          if (empty($CFG->rolesactive)) {
    2630              $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
    2631              //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.
    2632          }
    2633          $output .= $this->box($message, 'errorbox', null, array('data-rel' => 'fatalerror'));
    2634  
    2635          if ($CFG->debugdeveloper) {
    2636              if (!empty($debuginfo)) {
    2637                  $debuginfo = s($debuginfo); // removes all nasty JS
    2638                  $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
    2639                  $output .= $this->notification('<strong>Debug info:</strong> '.$debuginfo, 'notifytiny');
    2640              }
    2641              if (!empty($backtrace)) {
    2642                  $output .= $this->notification('<strong>Stack trace:</strong> '.format_backtrace($backtrace), 'notifytiny');
    2643              }
    2644              if ($obbuffer !== '' ) {
    2645                  $output .= $this->notification('<strong>Output buffer:</strong> '.s($obbuffer), 'notifytiny');
    2646              }
    2647          }
    2648  
    2649          if (empty($CFG->rolesactive)) {
    2650              // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
    2651          } else if (!empty($link)) {
    2652              $output .= $this->continue_button($link);
    2653          }
    2654  
    2655          $output .= $this->footer();
    2656  
    2657          // Padding to encourage IE to display our error page, rather than its own.
    2658          $output .= str_repeat(' ', 512);
    2659  
    2660          return $output;
    2661      }
    2662  
    2663      /**
    2664       * Output a notification (that is, a status message about something that has
    2665       * just happened).
    2666       *
    2667       * @param string $message the message to print out
    2668       * @param string $classes normally 'notifyproblem' or 'notifysuccess'.
    2669       * @return string the HTML to output.
    2670       */
    2671      public function notification($message, $classes = 'notifyproblem') {
    2672          return html_writer::tag('div', clean_text($message), array('class' => renderer_base::prepare_classes($classes)));
    2673      }
    2674  
    2675      /**
    2676       * Returns HTML to display a continue button that goes to a particular URL.
    2677       *
    2678       * @param string|moodle_url $url The url the button goes to.
    2679       * @return string the HTML to output.
    2680       */
    2681      public function continue_button($url) {
    2682          if (!($url instanceof moodle_url)) {
    2683              $url = new moodle_url($url);
    2684          }
    2685          $button = new single_button($url, get_string('continue'), 'get');
    2686          $button->class = 'continuebutton';
    2687  
    2688          return $this->render($button);
    2689      }
    2690  
    2691      /**
    2692       * Returns HTML to display a single paging bar to provide access to other pages  (usually in a search)
    2693       *
    2694       * Theme developers: DO NOT OVERRIDE! Please override function
    2695       * {@link core_renderer::render_paging_bar()} instead.
    2696       *
    2697       * @param int $totalcount The total number of entries available to be paged through
    2698       * @param int $page The page you are currently viewing
    2699       * @param int $perpage The number of entries that should be shown per page
    2700       * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
    2701       * @param string $pagevar name of page parameter that holds the page number
    2702       * @return string the HTML to output.
    2703       */
    2704      public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
    2705          $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
    2706          return $this->render($pb);
    2707      }
    2708  
    2709      /**
    2710       * Internal implementation of paging bar rendering.
    2711       *
    2712       * @param paging_bar $pagingbar
    2713       * @return string
    2714       */
    2715      protected function render_paging_bar(paging_bar $pagingbar) {
    2716          $output = '';
    2717          $pagingbar = clone($pagingbar);
    2718          $pagingbar->prepare($this, $this->page, $this->target);
    2719  
    2720          if ($pagingbar->totalcount > $pagingbar->perpage) {
    2721              $output .= get_string('page') . ':';
    2722  
    2723              if (!empty($pagingbar->previouslink)) {
    2724                  $output .= ' (' . $pagingbar->previouslink . ') ';
    2725              }
    2726  
    2727              if (!empty($pagingbar->firstlink)) {
    2728                  $output .= ' ' . $pagingbar->firstlink . ' ...';
    2729              }
    2730  
    2731              foreach ($pagingbar->pagelinks as $link) {
    2732                  $output .= "  $link";
    2733              }
    2734  
    2735              if (!empty($pagingbar->lastlink)) {
    2736                  $output .= ' ...' . $pagingbar->lastlink . ' ';
    2737              }
    2738  
    2739              if (!empty($pagingbar->nextlink)) {
    2740                  $output .= '  (' . $pagingbar->nextlink . ')';
    2741              }
    2742          }
    2743  
    2744          return html_writer::tag('div', $output, array('class' => 'paging'));
    2745      }
    2746  
    2747      /**
    2748       * Output the place a skip link goes to.
    2749       *
    2750       * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
    2751       * @return string the HTML to output.
    2752       */
    2753      public function skip_link_target($id = null) {
    2754          return html_writer::tag('span', '', array('id' => $id));
    2755      }
    2756  
    2757      /**
    2758       * Outputs a heading
    2759       *
    2760       * @param string $text The text of the heading
    2761       * @param int $level The level of importance of the heading. Defaulting to 2
    2762       * @param string $classes A space-separated list of CSS classes. Defaulting to null
    2763       * @param string $id An optional ID
    2764       * @return string the HTML to output.
    2765       */
    2766      public function heading($text, $level = 2, $classes = null, $id = null) {
    2767          $level = (integer) $level;
    2768          if ($level < 1 or $level > 6) {
    2769              throw new coding_exception('Heading level must be an integer between 1 and 6.');
    2770          }
    2771          return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
    2772      }
    2773  
    2774      /**
    2775       * Outputs a box.
    2776       *
    2777       * @param string $contents The contents of the box
    2778       * @param string $classes A space-separated list of CSS classes
    2779       * @param string $id An optional ID
    2780       * @param array $attributes An array of other attributes to give the box.
    2781       * @return string the HTML to output.
    2782       */
    2783      public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
    2784          return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
    2785      }
    2786  
    2787      /**
    2788       * Outputs the opening section of a box.
    2789       *
    2790       * @param string $classes A space-separated list of CSS classes
    2791       * @param string $id An optional ID
    2792       * @param array $attributes An array of other attributes to give the box.
    2793       * @return string the HTML to output.
    2794       */
    2795      public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
    2796          $this->opencontainers->push('box', html_writer::end_tag('div'));
    2797          $attributes['id'] = $id;
    2798          $attributes['class'] = 'box ' . renderer_base::prepare_classes($classes);
    2799          return html_writer::start_tag('div', $attributes);
    2800      }
    2801  
    2802      /**
    2803       * Outputs the closing section of a box.
    2804       *
    2805       * @return string the HTML to output.
    2806       */
    2807      public function box_end() {
    2808          return $this->opencontainers->pop('box');
    2809      }
    2810  
    2811      /**
    2812       * Outputs a container.
    2813       *
    2814       * @param string $contents The contents of the box
    2815       * @param string $classes A space-separated list of CSS classes
    2816       * @param string $id An optional ID
    2817       * @return string the HTML to output.
    2818       */
    2819      public function container($contents, $classes = null, $id = null) {
    2820          return $this->container_start($classes, $id) . $contents . $this->container_end();
    2821      }
    2822  
    2823      /**
    2824       * Outputs the opening section of a container.
    2825       *
    2826       * @param string $classes A space-separated list of CSS classes
    2827       * @param string $id An optional ID
    2828       * @return string the HTML to output.
    2829       */
    2830      public function container_start($classes = null, $id = null) {
    2831          $this->opencontainers->push('container', html_writer::end_tag('div'));
    2832          return html_writer::start_tag('div', array('id' => $id,
    2833                  'class' => renderer_base::prepare_classes($classes)));
    2834      }
    2835  
    2836      /**
    2837       * Outputs the closing section of a container.
    2838       *
    2839       * @return string the HTML to output.
    2840       */
    2841      public function container_end() {
    2842          return $this->opencontainers->pop('container');
    2843      }
    2844  
    2845      /**
    2846       * Make nested HTML lists out of the items
    2847       *
    2848       * The resulting list will look something like this:
    2849       *
    2850       * <pre>
    2851       * <<ul>>
    2852       * <<li>><div class='tree_item parent'>(item contents)</div>
    2853       *      <<ul>
    2854       *      <<li>><div class='tree_item'>(item contents)</div><</li>>
    2855       *      <</ul>>
    2856       * <</li>>
    2857       * <</ul>>
    2858       * </pre>
    2859       *
    2860       * @param array $items
    2861       * @param array $attrs html attributes passed to the top ofs the list
    2862       * @return string HTML
    2863       */
    2864      public function tree_block_contents($items, $attrs = array()) {
    2865          // exit if empty, we don't want an empty ul element
    2866          if (empty($items)) {
    2867              return '';
    2868          }
    2869          // array of nested li elements
    2870          $lis = array();
    2871          foreach ($items as $item) {
    2872              // this applies to the li item which contains all child lists too
    2873              $content = $item->content($this);
    2874              $liclasses = array($item->get_css_type());
    2875              if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0  && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
    2876                  $liclasses[] = 'collapsed';
    2877              }
    2878              if ($item->isactive === true) {
    2879                  $liclasses[] = 'current_branch';
    2880              }
    2881              $liattr = array('class'=>join(' ',$liclasses));
    2882              // class attribute on the div item which only contains the item content
    2883              $divclasses = array('tree_item');
    2884              if ($item->children->count()>0  || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
    2885                  $divclasses[] = 'branch';
    2886              } else {
    2887                  $divclasses[] = 'leaf';
    2888              }
    2889              if (!empty($item->classes) && count($item->classes)>0) {
    2890                  $divclasses[] = join(' ', $item->classes);
    2891              }
    2892              $divattr = array('class'=>join(' ', $divclasses));
    2893              if (!empty($item->id)) {
    2894                  $divattr['id'] = $item->id;
    2895              }
    2896              $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
    2897              if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
    2898                  $content = html_writer::empty_tag('hr') . $content;
    2899              }
    2900              $content = html_writer::tag('li', $content, $liattr);
    2901              $lis[] = $content;
    2902          }
    2903          return html_writer::tag('ul', implode("\n", $lis), $attrs);
    2904      }
    2905  
    2906      /**
    2907       * Construct a user menu, returning HTML that can be echoed out by a
    2908       * layout file.
    2909       *
    2910       * @param stdClass $user A user object, usually $USER.
    2911       * @param bool $withlinks true if a dropdown should be built.
    2912       * @return string HTML fragment.
    2913       */
    2914      public function user_menu($user = null, $withlinks = null) {
    2915          global $USER, $CFG;
    2916          require_once($CFG->dirroot . '/user/lib.php');
    2917  
    2918          if (is_null($user)) {
    2919              $user = $USER;
    2920          }
    2921  
    2922          // Note: this behaviour is intended to match that of core_renderer::login_info,
    2923          // but should not be considered to be good practice; layout options are
    2924          // intended to be theme-specific. Please don't copy this snippet anywhere else.
    2925          if (is_null($withlinks)) {
    2926              $withlinks = empty($this->page->layout_options['nologinlinks']);
    2927          }
    2928  
    2929          // Add a class for when $withlinks is false.
    2930          $usermenuclasses = 'usermenu';
    2931          if (!$withlinks) {
    2932              $usermenuclasses .= ' withoutlinks';
    2933          }
    2934  
    2935          $returnstr = "";
    2936  
    2937          // If during initial install, return the empty return string.
    2938          if (during_initial_install()) {
    2939              return $returnstr;
    2940          }
    2941  
    2942          $loginpage = ((string)$this->page->url === get_login_url());
    2943          $loginurl = get_login_url();
    2944          // If not logged in, show the typical not-logged-in string.
    2945          if (!isloggedin()) {
    2946              $returnstr = get_string('loggedinnot', 'moodle');
    2947              if (!$loginpage) {
    2948                  $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
    2949              }
    2950              return html_writer::div(
    2951                  html_writer::span(
    2952                      $returnstr,
    2953                      'login'
    2954                  ),
    2955                  $usermenuclasses
    2956              );
    2957  
    2958          }
    2959  
    2960          // If logged in as a guest user, show a string to that effect.
    2961          if (isguestuser()) {
    2962              $returnstr = get_string('loggedinasguest');
    2963              if (!$loginpage && $withlinks) {
    2964                  $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
    2965              }
    2966  
    2967              return html_writer::div(
    2968                  html_writer::span(
    2969                      $returnstr,
    2970                      'login'
    2971                  ),
    2972                  $usermenuclasses
    2973              );
    2974          }
    2975  
    2976          // Get some navigation opts.
    2977          $opts = user_get_user_navigation_info($user, $this->page, $this->page->course);
    2978  
    2979          $avatarclasses = "avatars";
    2980          $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
    2981          $usertextcontents = $opts->metadata['userfullname'];
    2982  
    2983          // Other user.
    2984          if (!empty($opts->metadata['asotheruser'])) {
    2985              $avatarcontents .= html_writer::span(
    2986                  $opts->metadata['realuseravatar'],
    2987                  'avatar realuser'
    2988              );
    2989              $usertextcontents = $opts->metadata['realuserfullname'];
    2990              $usertextcontents .= html_writer::tag(
    2991                  'span',
    2992                  get_string(
    2993                      'loggedinas',
    2994                      'moodle',
    2995                      html_writer::span(
    2996                          $opts->metadata['userfullname'],
    2997                          'value'
    2998                      )
    2999                  ),
    3000                  array('class' => 'meta viewingas')
    3001              );
    3002          }
    3003  
    3004          // Role.
    3005          if (!empty($opts->metadata['asotherrole'])) {
    3006              $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
    3007              $usertextcontents .= html_writer::span(
    3008                  $opts->metadata['rolename'],
    3009                  'meta role role-' . $role
    3010              );
    3011          }
    3012  
    3013          // User login failures.
    3014          if (!empty($opts->metadata['userloginfail'])) {
    3015              $usertextcontents .= html_writer::span(
    3016                  $opts->metadata['userloginfail'],
    3017                  'meta loginfailures'
    3018              );
    3019          }
    3020  
    3021          // MNet.
    3022          if (!empty($opts->metadata['asmnetuser'])) {
    3023              $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
    3024              $usertextcontents .= html_writer::span(
    3025                  $opts->metadata['mnetidprovidername'],
    3026                  'meta mnet mnet-' . $mnet
    3027              );
    3028          }
    3029  
    3030          $returnstr .= html_writer::span(
    3031              html_writer::span($usertextcontents, 'usertext') .
    3032              html_writer::span($avatarcontents, $avatarclasses),
    3033              'userbutton'
    3034          );
    3035  
    3036          // Create a divider (well, a filler).
    3037          $divider = new action_menu_filler();
    3038          $divider->primary = false;
    3039  
    3040          $am = new action_menu();
    3041          $am->initialise_js($this->page);
    3042          $am->set_menu_trigger(
    3043              $returnstr
    3044          );
    3045          $am->set_alignment(action_menu::TR, action_menu::BR);
    3046          $am->set_nowrap_on_items();
    3047          if ($withlinks) {
    3048              $navitemcount = count($opts->navitems);
    3049              $idx = 0;
    3050              foreach ($opts->navitems as $key => $value) {
    3051  
    3052                  switch ($value->itemtype) {
    3053                      case 'divider':
    3054                          // If the nav item is a divider, add one and skip link processing.
    3055                          $am->add($divider);
    3056                          break;
    3057  
    3058                      case 'invalid':
    3059                          // Silently skip invalid entries (should we post a notification?).
    3060                          break;
    3061  
    3062                      case 'link':
    3063                          // Process this as a link item.
    3064                          $pix = null;
    3065                          if (isset($value->pix) && !empty($value->pix)) {
    3066                              $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
    3067                          } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
    3068                              $value->title = html_writer::img(
    3069                                  $value->imgsrc,
    3070                                  $value->title,
    3071                                  array('class' => 'iconsmall')
    3072                              ) . $value->title;
    3073                          }
    3074                          $al = new action_menu_link_secondary(
    3075                              $value->url,
    3076                              $pix,
    3077                              $value->title,
    3078                              array('class' => 'icon')
    3079                          );
    3080                          $am->add($al);
    3081                          break;
    3082                  }
    3083  
    3084                  $idx++;
    3085  
    3086                  // Add dividers after the first item and before the last item.
    3087                  if ($idx == 1 || $idx == $navitemcount - 1) {
    3088                      $am->add($divider);
    3089                  }
    3090              }
    3091          }
    3092  
    3093          return html_writer::div(
    3094              $this->render($am),
    3095              $usermenuclasses
    3096          );
    3097      }
    3098  
    3099      /**
    3100       * Return the navbar content so that it can be echoed out by the layout
    3101       *
    3102       * @return string XHTML navbar
    3103       */
    3104      public function navbar() {
    3105          $items = $this->page->navbar->get_items();
    3106          $itemcount = count($items);
    3107          if ($itemcount === 0) {
    3108              return '';
    3109          }
    3110  
    3111          $htmlblocks = array();
    3112          // Iterate the navarray and display each node
    3113          $separator = get_separator();
    3114          for ($i=0;$i < $itemcount;$i++) {
    3115              $item = $items[$i];
    3116              $item->hideicon = true;
    3117              if ($i===0) {
    3118                  $content = html_writer::tag('li', $this->render($item));
    3119              } else {
    3120                  $content = html_writer::tag('li', $separator.$this->render($item));
    3121              }
    3122              $htmlblocks[] = $content;
    3123          }
    3124  
    3125          //accessibility: heading for navbar list  (MDL-20446)
    3126          $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class'=>'accesshide'));
    3127          $navbarcontent .= html_writer::tag('nav', html_writer::tag('ul', join('', $htmlblocks)));
    3128          // XHTML
    3129          return $navbarcontent;
    3130      }
    3131  
    3132      /**
    3133       * Renders a navigation node object.
    3134       *
    3135       * @param navigation_node $item The navigation node to render.
    3136       * @return string HTML fragment
    3137       */
    3138      protected function render_navigation_node(navigation_node $item) {
    3139          $content = $item->get_content();
    3140          $title = $item->get_title();
    3141          if ($item->icon instanceof renderable && !$item->hideicon) {
    3142              $icon = $this->render($item->icon);
    3143              $content = $icon.$content; // use CSS for spacing of icons
    3144          }
    3145          if ($item->helpbutton !== null) {
    3146              $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
    3147          }
    3148          if ($content === '') {
    3149              return '';
    3150          }
    3151          if ($item->action instanceof action_link) {
    3152              $link = $item->action;
    3153              if ($item->hidden) {
    3154                  $link->add_class('dimmed');
    3155              }
    3156              if (!empty($content)) {
    3157                  // Providing there is content we will use that for the link content.
    3158                  $link->text = $content;
    3159              }
    3160              $content = $this->render($link);
    3161          } else if ($item->action instanceof moodle_url) {
    3162              $attributes = array();
    3163              if ($title !== '') {
    3164                  $attributes['title'] = $title;
    3165              }
    3166              if ($item->hidden) {
    3167                  $attributes['class'] = 'dimmed_text';
    3168              }
    3169              $content = html_writer::link($item->action, $content, $attributes);
    3170  
    3171          } else if (is_string($item->action) || empty($item->action)) {
    3172              $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
    3173              if ($title !== '') {
    3174                  $attributes['title'] = $title;
    3175              }
    3176              if ($item->hidden) {
    3177                  $attributes['class'] = 'dimmed_text';
    3178              }
    3179              $content = html_writer::tag('span', $content, $attributes);
    3180          }
    3181          return $content;
    3182      }
    3183  
    3184      /**
    3185       * Accessibility: Right arrow-like character is
    3186       * used in the breadcrumb trail, course navigation menu
    3187       * (previous/next activity), calendar, and search forum block.
    3188       * If the theme does not set characters, appropriate defaults
    3189       * are set automatically. Please DO NOT
    3190       * use &lt; &gt; &raquo; - these are confusing for blind users.
    3191       *
    3192       * @return string
    3193       */
    3194      public function rarrow() {
    3195          return $this->page->theme->rarrow;
    3196      }
    3197  
    3198      /**
    3199       * Accessibility: Left arrow-like character is
    3200       * used in the breadcrumb trail, course navigation menu
    3201       * (previous/next activity), calendar, and search forum block.
    3202       * If the theme does not set characters, appropriate defaults
    3203       * are set automatically. Please DO NOT
    3204       * use &lt; &gt; &raquo; - these are confusing for blind users.
    3205       *
    3206       * @return string
    3207       */
    3208      public function larrow() {
    3209          return $this->page->theme->larrow;
    3210      }
    3211  
    3212      /**
    3213       * Returns the custom menu if one has been set
    3214       *
    3215       * A custom menu can be configured by browsing to
    3216       *    Settings: Administration > Appearance > Themes > Theme settings
    3217       * and then configuring the custommenu config setting as described.
    3218       *
    3219       * Theme developers: DO NOT OVERRIDE! Please override function
    3220       * {@link core_renderer::render_custom_menu()} instead.
    3221       *
    3222       * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
    3223       * @return string
    3224       */
    3225      public function custom_menu($custommenuitems = '') {
    3226          global $CFG;
    3227          if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
    3228              $custommenuitems = $CFG->custommenuitems;
    3229          }
    3230          if (empty($custommenuitems)) {
    3231              return '';
    3232          }
    3233          $custommenu = new custom_menu($custommenuitems, current_language());
    3234          return $this->render($custommenu);
    3235      }
    3236  
    3237      /**
    3238       * Renders a custom menu object (located in outputcomponents.php)
    3239       *
    3240       * The custom menu this method produces makes use of the YUI3 menunav widget
    3241       * and requires very specific html elements and classes.
    3242       *
    3243       * @staticvar int $menucount
    3244       * @param custom_menu $menu
    3245       * @return string
    3246       */
    3247      protected function render_custom_menu(custom_menu $menu) {
    3248          static $menucount = 0;
    3249          // If the menu has no children return an empty string
    3250          if (!$menu->has_children()) {
    3251              return '';
    3252          }
    3253          // Increment the menu count. This is used for ID's that get worked with
    3254          // in JavaScript as is essential
    3255          $menucount++;
    3256          // Initialise this custom menu (the custom menu object is contained in javascript-static
    3257          $jscode = js_writer::function_call_with_Y('M.core_custom_menu.init', array('custom_menu_'.$menucount));
    3258          $jscode = "(function(){{$jscode}})";
    3259          $this->page->requires->yui_module('node-menunav', $jscode);
    3260          // Build the root nodes as required by YUI
    3261          $content = html_writer::start_tag('div', array('id'=>'custom_menu_'.$menucount, 'class'=>'yui3-menu yui3-menu-horizontal javascript-disabled custom-menu'));
    3262          $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
    3263          $content .= html_writer::start_tag('ul');
    3264          // Render each child
    3265          foreach ($menu->get_children() as $item) {
    3266              $content .= $this->render_custom_menu_item($item);
    3267          }
    3268          // Close the open tags
    3269          $content .= html_writer::end_tag('ul');
    3270          $content .= html_writer::end_tag('div');
    3271          $content .= html_writer::end_tag('div');
    3272          // Return the custom menu
    3273          return $content;
    3274      }
    3275  
    3276      /**
    3277       * Renders a custom menu node as part of a submenu
    3278       *
    3279       * The custom menu this method produces makes use of the YUI3 menunav widget
    3280       * and requires very specific html elements and classes.
    3281       *
    3282       * @see core:renderer::render_custom_menu()
    3283       *
    3284       * @staticvar int $submenucount
    3285       * @param custom_menu_item $menunode
    3286       * @return string
    3287       */
    3288      protected function render_custom_menu_item(custom_menu_item $menunode) {
    3289          // Required to ensure we get unique trackable id's
    3290          static $submenucount = 0;
    3291          if ($menunode->has_children()) {
    3292              // If the child has menus render it as a sub menu
    3293              $submenucount++;
    3294              $content = html_writer::start_tag('li');
    3295              if ($menunode->get_url() !== null) {
    3296                  $url = $menunode->get_url();
    3297              } else {
    3298                  $url = '#cm_submenu_'.$submenucount;
    3299              }
    3300              $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
    3301              $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
    3302              $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
    3303              $content .= html_writer::start_tag('ul');
    3304              foreach ($menunode->get_children() as $menunode) {
    3305                  $content .= $this->render_custom_menu_item($menunode);
    3306              }
    3307              $content .= html_writer::end_tag('ul');
    3308              $content .= html_writer::end_tag('div');
    3309              $content .= html_writer::end_tag('div');
    3310              $content .= html_writer::end_tag('li');
    3311          } else {
    3312              // The node doesn't have children so produce a final menuitem.
    3313              // Also, if the node's text matches '####', add a class so we can treat it as a divider.
    3314              $content = '';
    3315              if (preg_match("/^#+$/", $menunode->get_text())) {
    3316  
    3317                  // This is a divider.
    3318                  $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
    3319              } else {
    3320                  $content = html_writer::start_tag(
    3321                      'li',
    3322                      array(
    3323                          'class' => 'yui3-menuitem'
    3324                      )
    3325                  );
    3326                  if ($menunode->get_url() !== null) {
    3327                      $url = $menunode->get_url();
    3328                  } else {
    3329                      $url = '#';
    3330                  }
    3331                  $content .= html_writer::link(
    3332                      $url,
    3333                      $menunode->get_text(),
    3334                      array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
    3335                  );
    3336              }
    3337              $content .= html_writer::end_tag('li');
    3338          }
    3339          // Return the sub menu
    3340          return $content;
    3341      }
    3342  
    3343      /**
    3344       * Renders theme links for switching between default and other themes.
    3345       *
    3346       * @return string
    3347       */
    3348      protected function theme_switch_links() {
    3349  
    3350          $actualdevice = core_useragent::get_device_type();
    3351          $currentdevice = $this->page->devicetypeinuse;
    3352          $switched = ($actualdevice != $currentdevice);
    3353  
    3354          if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
    3355              // The user is using the a default device and hasn't switched so don't shown the switch
    3356              // device links.
    3357              return '';
    3358          }
    3359  
    3360          if ($switched) {
    3361              $linktext = get_string('switchdevicerecommended');
    3362              $devicetype = $actualdevice;
    3363          } else {
    3364              $linktext = get_string('switchdevicedefault');
    3365              $devicetype = 'default';
    3366          }
    3367          $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
    3368  
    3369          $content  = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
    3370          $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
    3371          $content .= html_writer::end_tag('div');
    3372  
    3373          return $content;
    3374      }
    3375  
    3376      /**
    3377       * Renders tabs
    3378       *
    3379       * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
    3380       *
    3381       * Theme developers: In order to change how tabs are displayed please override functions
    3382       * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
    3383       *
    3384       * @param array $tabs array of tabs, each of them may have it's own ->subtree
    3385       * @param string|null $selected which tab to mark as selected, all parent tabs will
    3386       *     automatically be marked as activated
    3387       * @param array|string|null $inactive list of ids of inactive tabs, regardless of
    3388       *     their level. Note that you can as weel specify tabobject::$inactive for separate instances
    3389       * @return string
    3390       */
    3391      public final function tabtree($tabs, $selected = null, $inactive = null) {
    3392          return $this->render(new tabtree($tabs, $selected, $inactive));
    3393      }
    3394  
    3395      /**
    3396       * Renders tabtree
    3397       *
    3398       * @param tabtree $tabtree
    3399       * @return string
    3400       */
    3401      protected function render_tabtree(tabtree $tabtree) {
    3402          if (empty($tabtree->subtree)) {
    3403              return '';
    3404          }
    3405          $str = '';
    3406          $str .= html_writer::start_tag('div', array('class' => 'tabtree'));
    3407          $str .= $this->render_tabobject($tabtree);
    3408          $str .= html_writer::end_tag('div').
    3409                  html_writer::tag('div', ' ', array('class' => 'clearer'));
    3410          return $str;
    3411      }
    3412  
    3413      /**
    3414       * Renders tabobject (part of tabtree)
    3415       *
    3416       * This function is called from {@link core_renderer::render_tabtree()}
    3417       * and also it calls itself when printing the $tabobject subtree recursively.
    3418       *
    3419       * Property $tabobject->level indicates the number of row of tabs.
    3420       *
    3421       * @param tabobject $tabobject
    3422       * @return string HTML fragment
    3423       */
    3424      protected function render_tabobject(tabobject $tabobject) {
    3425          $str = '';
    3426  
    3427          // Print name of the current tab.
    3428          if ($tabobject instanceof tabtree) {
    3429              // No name for tabtree root.
    3430          } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
    3431              // Tab name without a link. The <a> tag is used for styling.
    3432              $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
    3433          } else {
    3434              // Tab name with a link.
    3435              if (!($tabobject->link instanceof moodle_url)) {
    3436                  // backward compartibility when link was passed as quoted string
    3437                  $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
    3438              } else {
    3439                  $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
    3440              }
    3441          }
    3442  
    3443          if (empty($tabobject->subtree)) {
    3444              if ($tabobject->selected) {
    3445                  $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
    3446              }
    3447              return $str;
    3448          }
    3449  
    3450          // Print subtree
    3451          $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
    3452          $cnt = 0;
    3453          foreach ($tabobject->subtree as $tab) {
    3454              $liclass = '';
    3455              if (!$cnt) {
    3456                  $liclass .= ' first';
    3457              }
    3458              if ($cnt == count($tabobject->subtree) - 1) {
    3459                  $liclass .= ' last';
    3460              }
    3461              if ((empty($tab->subtree)) && (!empty($tab->selected))) {
    3462                  $liclass .= ' onerow';
    3463              }
    3464  
    3465              if ($tab->selected) {
    3466                  $liclass .= ' here selected';
    3467              } else if ($tab->activated) {
    3468                  $liclass .= ' here active';
    3469              }
    3470  
    3471              // This will recursively call function render_tabobject() for each item in subtree
    3472              $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
    3473              $cnt++;
    3474          }
    3475          $str .= html_writer::end_tag('ul');
    3476  
    3477          return $str;
    3478      }
    3479  
    3480      /**
    3481       * Get the HTML for blocks in the given region.
    3482       *
    3483       * @since Moodle 2.5.1 2.6
    3484       * @param string $region The region to get HTML for.
    3485       * @return string HTML.
    3486       */
    3487      public function blocks($region, $classes = array(), $tag = 'aside') {
    3488          $displayregion = $this->page->apply_theme_region_manipulations($region);
    3489          $classes = (array)$classes;
    3490          $classes[] = 'block-region';
    3491          $attributes = array(
    3492              'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
    3493              'class' => join(' ', $classes),
    3494              'data-blockregion' => $displayregion,
    3495              'data-droptarget' => '1'
    3496          );
    3497          if ($this->page->blocks->region_has_content($displayregion, $this)) {
    3498              $content = $this->blocks_for_region($displayregion);
    3499          } else {
    3500              $content = '';
    3501          }
    3502          return html_writer::tag($tag, $content, $attributes);
    3503      }
    3504  
    3505      /**
    3506       * Renders a custom block region.
    3507       *
    3508       * Use this method if you want to add an additional block region to the content of the page.
    3509       * Please note this should only be used in special situations.
    3510       * We want to leave the theme is control where ever possible!
    3511       *
    3512       * This method must use the same method that the theme uses within its layout file.
    3513       * As such it asks the theme what method it is using.
    3514       * It can be one of two values, blocks or blocks_for_region (deprecated).
    3515       *
    3516       * @param string $regionname The name of the custom region to add.
    3517       * @return string HTML for the block region.
    3518       */
    3519      public function custom_block_region($regionname) {
    3520          if ($this->page->theme->get_block_render_method() === 'blocks') {
    3521              return $this->blocks($regionname);
    3522          } else {
    3523              return $this->blocks_for_region($regionname);
    3524          }
    3525      }
    3526  
    3527      /**
    3528       * Returns the CSS classes to apply to the body tag.
    3529       *
    3530       * @since Moodle 2.5.1 2.6
    3531       * @param array $additionalclasses Any additional classes to apply.
    3532       * @return string
    3533       */
    3534      public function body_css_classes(array $additionalclasses = array()) {
    3535          // Add a class for each block region on the page.
    3536          // We use the block manager here because the theme object makes get_string calls.
    3537          foreach ($this->page->blocks->get_regions() as $region) {
    3538              $additionalclasses[] = 'has-region-'.$region;
    3539              if ($this->page->blocks->region_has_content($region, $this)) {
    3540                  $additionalclasses[] = 'used-region-'.$region;
    3541              } else {
    3542                  $additionalclasses[] = 'empty-region-'.$region;
    3543              }
    3544              if ($this->page->blocks->region_completely_docked($region, $this)) {
    3545                  $additionalclasses[] = 'docked-region-'.$region;
    3546              }
    3547          }
    3548          foreach ($this->page->layout_options as $option => $value) {
    3549              if ($value) {
    3550                  $additionalclasses[] = 'layout-option-'.$option;
    3551              }
    3552          }
    3553          $css = $this->page->bodyclasses .' '. join(' ', $additionalclasses);
    3554          return $css;
    3555      }
    3556  
    3557      /**
    3558       * The ID attribute to apply to the body tag.
    3559       *
    3560       * @since Moodle 2.5.1 2.6
    3561       * @return string
    3562       */
    3563      public function body_id() {
    3564          return $this->page->bodyid;
    3565      }
    3566  
    3567      /**
    3568       * Returns HTML attributes to use within the body tag. This includes an ID and classes.
    3569       *
    3570       * @since Moodle 2.5.1 2.6
    3571       * @param string|array $additionalclasses Any additional classes to give the body tag,
    3572       * @return string
    3573       */
    3574      public function body_attributes($additionalclasses = array()) {
    3575          if (!is_array($additionalclasses)) {
    3576              $additionalclasses = explode(' ', $additionalclasses);
    3577          }
    3578          return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
    3579      }
    3580  
    3581      /**
    3582       * Gets HTML for the page heading.
    3583       *
    3584       * @since Moodle 2.5.1 2.6
    3585       * @param string $tag The tag to encase the heading in. h1 by default.
    3586       * @return string HTML.
    3587       */
    3588      public function page_heading($tag = 'h1') {
    3589          return html_writer::tag($tag, $this->page->heading);
    3590      }
    3591  
    3592      /**
    3593       * Gets the HTML for the page heading button.
    3594       *
    3595       * @since Moodle 2.5.1 2.6
    3596       * @return string HTML.
    3597       */
    3598      public function page_heading_button() {
    3599          return $this->page->button;
    3600      }
    3601  
    3602      /**
    3603       * Returns the Moodle docs link to use for this page.
    3604       *
    3605       * @since Moodle 2.5.1 2.6
    3606       * @param string $text
    3607       * @return string
    3608       */
    3609      public function page_doc_link($text = null) {
    3610          if ($text === null) {
    3611              $text = get_string('moodledocslink');
    3612          }
    3613          $path = page_get_doc_link_path($this->page);
    3614          if (!$path) {
    3615              return '';
    3616          }
    3617          return $this->doc_link($path, $text);
    3618      }
    3619  
    3620      /**
    3621       * Returns the page heading menu.
    3622       *
    3623       * @since Moodle 2.5.1 2.6
    3624       * @return string HTML.
    3625       */
    3626      public function page_heading_menu() {
    3627          return $this->page->headingmenu;
    3628      }
    3629  
    3630      /**
    3631       * Returns the title to use on the page.
    3632       *
    3633       * @since Moodle 2.5.1 2.6
    3634       * @return string
    3635       */
    3636      public function page_title() {
    3637          return $this->page->title;
    3638      }
    3639  
    3640      /**
    3641       * Returns the URL for the favicon.
    3642       *
    3643       * @since Moodle 2.5.1 2.6
    3644       * @return string The favicon URL
    3645       */
    3646      public function favicon() {
    3647          return $this->pix_url('favicon', 'theme');
    3648      }
    3649  }
    3650  
    3651  /**
    3652   * A renderer that generates output for command-line scripts.
    3653   *
    3654   * The implementation of this renderer is probably incomplete.
    3655   *
    3656   * @copyright 2009 Tim Hunt
    3657   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3658   * @since Moodle 2.0
    3659   * @package core
    3660   * @category output
    3661   */
    3662  class core_renderer_cli extends core_renderer {
    3663  
    3664      /**
    3665       * Returns the page header.
    3666       *
    3667       * @return string HTML fragment
    3668       */
    3669      public function header() {
    3670          return $this->page->heading . "\n";
    3671      }
    3672  
    3673      /**
    3674       * Returns a template fragment representing a Heading.
    3675       *
    3676       * @param string $text The text of the heading
    3677       * @param int $level The level of importance of the heading
    3678       * @param string $classes A space-separated list of CSS classes
    3679       * @param string $id An optional ID
    3680       * @return string A template fragment for a heading
    3681       */
    3682      public function heading($text, $level = 2, $classes = 'main', $id = null) {
    3683          $text .= "\n";
    3684          switch ($level) {
    3685              case 1:
    3686                  return '=>' . $text;
    3687              case 2:
    3688                  return '-->' . $text;
    3689              default:
    3690                  return $text;
    3691          }
    3692      }
    3693  
    3694      /**
    3695       * Returns a template fragment representing a fatal error.
    3696       *
    3697       * @param string $message The message to output
    3698       * @param string $moreinfourl URL where more info can be found about the error
    3699       * @param string $link Link for the Continue button
    3700       * @param array $backtrace The execution backtrace
    3701       * @param string $debuginfo Debugging information
    3702       * @return string A template fragment for a fatal error
    3703       */
    3704      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
    3705          global $CFG;
    3706  
    3707          $output = "!!! $message !!!\n";
    3708  
    3709          if ($CFG->debugdeveloper) {
    3710              if (!empty($debuginfo)) {
    3711                  $output .= $this->notification($debuginfo, 'notifytiny');
    3712              }
    3713              if (!empty($backtrace)) {
    3714                  $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
    3715              }
    3716          }
    3717  
    3718          return $output;
    3719      }
    3720  
    3721      /**
    3722       * Returns a template fragment representing a notification.
    3723       *
    3724       * @param string $message The message to include
    3725       * @param string $classes A space-separated list of CSS classes
    3726       * @return string A template fragment for a notification
    3727       */
    3728      public function notification($message, $classes = 'notifyproblem') {
    3729          $message = clean_text($message);
    3730          if ($classes === 'notifysuccess') {
    3731              return "++ $message ++\n";
    3732          }
    3733          return "!! $message !!\n";
    3734      }
    3735  
    3736      /**
    3737       * There is no footer for a cli request, however we must override the
    3738       * footer method to prevent the default footer.
    3739       */
    3740      public function footer() {}
    3741  }
    3742  
    3743  
    3744  /**
    3745   * A renderer that generates output for ajax scripts.
    3746   *
    3747   * This renderer prevents accidental sends back only json
    3748   * encoded error messages, all other output is ignored.
    3749   *
    3750   * @copyright 2010 Petr Skoda
    3751   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3752   * @since Moodle 2.0
    3753   * @package core
    3754   * @category output
    3755   */
    3756  class core_renderer_ajax extends core_renderer {
    3757  
    3758      /**
    3759       * Returns a template fragment representing a fatal error.
    3760       *
    3761       * @param string $message The message to output
    3762       * @param string $moreinfourl URL where more info can be found about the error
    3763       * @param string $link Link for the Continue button
    3764       * @param array $backtrace The execution backtrace
    3765       * @param string $debuginfo Debugging information
    3766       * @return string A template fragment for a fatal error
    3767       */
    3768      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
    3769          global $CFG;
    3770  
    3771          $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
    3772  
    3773          $e = new stdClass();
    3774          $e->error      = $message;
    3775          $e->stacktrace = NULL;
    3776          $e->debuginfo  = NULL;
    3777          $e->reproductionlink = NULL;
    3778          if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
    3779              $link = (string) $link;
    3780              if ($link) {
    3781                  $e->reproductionlink = $link;
    3782              }
    3783              if (!empty($debuginfo)) {
    3784                  $e->debuginfo = $debuginfo;
    3785              }
    3786              if (!empty($backtrace)) {
    3787                  $e->stacktrace = format_backtrace($backtrace, true);
    3788              }
    3789          }
    3790          $this->header();
    3791          return json_encode($e);
    3792      }
    3793  
    3794      /**
    3795       * Used to display a notification.
    3796       * For the AJAX notifications are discarded.
    3797       *
    3798       * @param string $message
    3799       * @param string $classes
    3800       */
    3801      public function notification($message, $classes = 'notifyproblem') {}
    3802  
    3803      /**
    3804       * Used to display a redirection message.
    3805       * AJAX redirections should not occur and as such redirection messages
    3806       * are discarded.
    3807       *
    3808       * @param moodle_url|string $encodedurl
    3809       * @param string $message
    3810       * @param int $delay
    3811       * @param bool $debugdisableredirect
    3812       */
    3813      public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {}
    3814  
    3815      /**
    3816       * Prepares the start of an AJAX output.
    3817       */
    3818      public function header() {
    3819          // unfortunately YUI iframe upload does not support application/json
    3820          if (!empty($_FILES)) {
    3821              @header('Content-type: text/plain; charset=utf-8');
    3822              if (!core_useragent::supports_json_contenttype()) {
    3823                  @header('X-Content-Type-Options: nosniff');
    3824              }
    3825          } else if (!core_useragent::supports_json_contenttype()) {
    3826              @header('Content-type: text/plain; charset=utf-8');
    3827              @header('X-Content-Type-Options: nosniff');
    3828          } else {
    3829              @header('Content-type: application/json; charset=utf-8');
    3830          }
    3831  
    3832          // Headers to make it not cacheable and json
    3833          @header('Cache-Control: no-store, no-cache, must-revalidate');
    3834          @header('Cache-Control: post-check=0, pre-check=0', false);
    3835          @header('Pragma: no-cache');
    3836          @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
    3837          @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    3838          @header('Accept-Ranges: none');
    3839      }
    3840  
    3841      /**
    3842       * There is no footer for an AJAX request, however we must override the
    3843       * footer method to prevent the default footer.
    3844       */
    3845      public function footer() {}
    3846  
    3847      /**
    3848       * No need for headers in an AJAX request... this should never happen.
    3849       * @param string $text
    3850       * @param int $level
    3851       * @param string $classes
    3852       * @param string $id
    3853       */
    3854      public function heading($text, $level = 2, $classes = 'main', $id = null) {}
    3855  }
    3856  
    3857  
    3858  /**
    3859   * Renderer for media files.
    3860   *
    3861   * Used in file resources, media filter, and any other places that need to
    3862   * output embedded media.
    3863   *
    3864   * @copyright 2011 The Open University
    3865   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3866   */
    3867  class core_media_renderer extends plugin_renderer_base {
    3868      /** @var array Array of available 'player' objects */
    3869      private $players;
    3870      /** @var string Regex pattern for links which may contain embeddable content */
    3871      private $embeddablemarkers;
    3872  
    3873      /**
    3874       * Constructor requires medialib.php.
    3875       *
    3876       * This is needed in the constructor (not later) so that you can use the
    3877       * constants and static functions that are defined in core_media class
    3878       * before you call renderer functions.
    3879       */
    3880      public function __construct() {
    3881          global $CFG;
    3882          require_once($CFG->libdir . '/medialib.php');
    3883      }
    3884  
    3885      /**
    3886       * Obtains the list of core_media_player objects currently in use to render
    3887       * items.
    3888       *
    3889       * The list is in rank order (highest first) and does not include players
    3890       * which are disabled.
    3891       *
    3892       * @return array Array of core_media_player objects in rank order
    3893       */
    3894      protected function get_players() {
    3895          global $CFG;
    3896  
    3897          // Save time by only building the list once.
    3898          if (!$this->players) {
    3899              // Get raw list of players.
    3900              $players = $this->get_players_raw();
    3901  
    3902              // Chuck all the ones that are disabled.
    3903              foreach ($players as $key => $player) {
    3904                  if (!$player->is_enabled()) {
    3905                      unset($players[$key]);
    3906                  }
    3907              }
    3908  
    3909              // Sort in rank order (highest first).
    3910              usort($players, array('core_media_player', 'compare_by_rank'));
    3911              $this->players = $players;
    3912          }
    3913          return $this->players;
    3914      }
    3915  
    3916      /**
    3917       * Obtains a raw list of player objects that includes objects regardless
    3918       * of whether they are disabled or not, and without sorting.
    3919       *
    3920       * You can override this in a subclass if you need to add additional
    3921       * players.
    3922       *
    3923       * The return array is be indexed by player name to make it easier to
    3924       * remove players in a subclass.
    3925       *
    3926       * @return array $players Array of core_media_player objects in any order
    3927       */
    3928      protected function get_players_raw() {
    3929          return array(
    3930              'vimeo' => new core_media_player_vimeo(),
    3931              'youtube' => new core_media_player_youtube(),
    3932              'youtube_playlist' => new core_media_player_youtube_playlist(),
    3933              'html5video' => new core_media_player_html5video(),
    3934              'html5audio' => new core_media_player_html5audio(),
    3935              'mp3' => new core_media_player_mp3(),
    3936              'flv' => new core_media_player_flv(),
    3937              'wmp' => new core_media_player_wmp(),
    3938              'qt' => new core_media_player_qt(),
    3939              'rm' => new core_media_player_rm(),
    3940              'swf' => new core_media_player_swf(),
    3941              'link' => new core_media_player_link(),
    3942          );
    3943      }
    3944  
    3945      /**
    3946       * Renders a media file (audio or video) using suitable embedded player.
    3947       *
    3948       * See embed_alternatives function for full description of parameters.
    3949       * This function calls through to that one.
    3950       *
    3951       * When using this function you can also specify width and height in the
    3952       * URL by including ?d=100x100 at the end. If specified in the URL, this
    3953       * will override the $width and $height parameters.
    3954       *
    3955       * @param moodle_url $url Full URL of media file
    3956       * @param string $name Optional user-readable name to display in download link
    3957       * @param int $width Width in pixels (optional)
    3958       * @param int $height Height in pixels (optional)
    3959       * @param array $options Array of key/value pairs
    3960       * @return string HTML content of embed
    3961       */
    3962      public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
    3963              $options = array()) {
    3964  
    3965          // Get width and height from URL if specified (overrides parameters in
    3966          // function call).
    3967          $rawurl = $url->out(false);
    3968          if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
    3969              $width = $matches[1];
    3970              $height = $matches[2];
    3971              $url = new moodle_url(str_replace($matches[0], '', $rawurl));
    3972          }
    3973  
    3974          // Defer to array version of function.
    3975          return $this->embed_alternatives(array($url), $name, $width, $height, $options);
    3976      }
    3977  
    3978      /**
    3979       * Renders media files (audio or video) using suitable embedded player.
    3980       * The list of URLs should be alternative versions of the same content in
    3981       * multiple formats. If there is only one format it should have a single
    3982       * entry.
    3983       *
    3984       * If the media files are not in a supported format, this will give students
    3985       * a download link to each format. The download link uses the filename
    3986       * unless you supply the optional name parameter.
    3987       *
    3988       * Width and height are optional. If specified, these are suggested sizes
    3989       * and should be the exact values supplied by the user, if they come from
    3990       * user input. These will be treated as relating to the size of the video
    3991       * content, not including any player control bar.
    3992       *
    3993       * For audio files, height will be ignored. For video files, a few formats
    3994       * work if you specify only width, but in general if you specify width
    3995       * you must specify height as well.
    3996       *
    3997       * The $options array is passed through to the core_media_player classes
    3998       * that render the object tag. The keys can contain values from
    3999       * core_media::OPTION_xx.
    4000       *
    4001       * @param array $alternatives Array of moodle_url to media files
    4002       * @param string $name Optional user-readable name to display in download link
    4003       * @param int $width Width in pixels (optional)
    4004       * @param int $height Height in pixels (optional)
    4005       * @param array $options Array of key/value pairs
    4006       * @return string HTML content of embed
    4007       */
    4008      public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
    4009              $options = array()) {
    4010  
    4011          // Get list of player plugins (will also require the library).
    4012          $players = $this->get_players();
    4013  
    4014          // Set up initial text which will be replaced by first player that
    4015          // supports any of the formats.
    4016          $out = core_media_player::PLACEHOLDER;
    4017  
    4018          // Loop through all players that support any of these URLs.
    4019          foreach ($players as $player) {
    4020              // Option: When no other player matched, don't do the default link player.
    4021              if (!empty($options[core_media::OPTION_FALLBACK_TO_BLANK]) &&
    4022                      $player->get_rank() === 0 && $out === core_media_player::PLACEHOLDER) {
    4023                  continue;
    4024              }
    4025  
    4026              $supported = $player->list_supported_urls($alternatives, $options);
    4027              if ($supported) {
    4028                  // Embed.
    4029                  $text = $player->embed($supported, $name, $width, $height, $options);
    4030  
    4031                  // Put this in place of the 'fallback' slot in the previous text.
    4032                  $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
    4033              }
    4034          }
    4035  
    4036          // Remove 'fallback' slot from final version and return it.
    4037          $out = str_replace(core_media_player::PLACEHOLDER, '', $out);
    4038          if (!empty($options[core_media::OPTION_BLOCK]) && $out !== '') {
    4039              $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
    4040          }
    4041          return $out;
    4042      }
    4043  
    4044      /**
    4045       * Checks whether a file can be embedded. If this returns true you will get
    4046       * an embedded player; if this returns false, you will just get a download
    4047       * link.
    4048       *
    4049       * This is a wrapper for can_embed_urls.
    4050       *
    4051       * @param moodle_url $url URL of media file
    4052       * @param array $options Options (same as when embedding)
    4053       * @return bool True if file can be embedded
    4054       */
    4055      public function can_embed_url(moodle_url $url, $options = array()) {
    4056          return $this->can_embed_urls(array($url), $options);
    4057      }
    4058  
    4059      /**
    4060       * Checks whether a file can be embedded. If this returns true you will get
    4061       * an embedded player; if this returns false, you will just get a download
    4062       * link.
    4063       *
    4064       * @param array $urls URL of media file and any alternatives (moodle_url)
    4065       * @param array $options Options (same as when embedding)
    4066       * @return bool True if file can be embedded
    4067       */
    4068      public function can_embed_urls(array $urls, $options = array()) {
    4069          // Check all players to see if any of them support it.
    4070          foreach ($this->get_players() as $player) {
    4071              // Link player (always last on list) doesn't count!
    4072              if ($player->get_rank() <= 0) {
    4073                  break;
    4074              }
    4075              // First player that supports it, return true.
    4076              if ($player->list_supported_urls($urls, $options)) {
    4077                  return true;
    4078              }
    4079          }
    4080          return false;
    4081      }
    4082  
    4083      /**
    4084       * Obtains a list of markers that can be used in a regular expression when
    4085       * searching for URLs that can be embedded by any player type.
    4086       *
    4087       * This string is used to improve peformance of regex matching by ensuring
    4088       * that the (presumably C) regex code can do a quick keyword check on the
    4089       * URL part of a link to see if it matches one of these, rather than having
    4090       * to go into PHP code for every single link to see if it can be embedded.
    4091       *
    4092       * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
    4093       */
    4094      public function