Search moodle.org's
Developer Documentation

  • Bug fixes for general core bugs in 3.11.x will end 9 May 2022 (12 months).
  • Bug fixes for security issues in 3.11.x will end 14 November 2022 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
  • Differences Between: [Versions 310 and 311] [Versions 35 and 311] [Versions 36 and 311] [Versions 37 and 311] [Versions 38 and 311] [Versions 39 and 311]

       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 representing HTML elements, used by $OUTPUT methods
      19   *
      20   * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
      21   * for an overview.
      22   *
      23   * @package core
      24   * @category output
      25   * @copyright 2009 Tim Hunt
      26   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      27   */
      28  
      29  defined('MOODLE_INTERNAL') || die();
      30  
      31  /**
      32   * Interface marking other classes as suitable for renderer_base::render()
      33   *
      34   * @copyright 2010 Petr Skoda (skodak) info@skodak.org
      35   * @package core
      36   * @category output
      37   */
      38  interface renderable {
      39      // intentionally empty
      40  }
      41  
      42  /**
      43   * Interface marking other classes having the ability to export their data for use by templates.
      44   *
      45   * @copyright 2015 Damyon Wiese
      46   * @package core
      47   * @category output
      48   * @since 2.9
      49   */
      50  interface templatable {
      51  
      52      /**
      53       * Function to export the renderer data in a format that is suitable for a
      54       * mustache template. This means:
      55       * 1. No complex types - only stdClass, array, int, string, float, bool
      56       * 2. Any additional info that is required for the template is pre-calculated (e.g. capability checks).
      57       *
      58       * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
      59       * @return stdClass|array
      60       */
      61      public function export_for_template(renderer_base $output);
      62  }
      63  
      64  /**
      65   * Data structure representing a file picker.
      66   *
      67   * @copyright 2010 Dongsheng Cai
      68   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      69   * @since Moodle 2.0
      70   * @package core
      71   * @category output
      72   */
      73  class file_picker implements renderable {
      74  
      75      /**
      76       * @var stdClass An object containing options for the file picker
      77       */
      78      public $options;
      79  
      80      /**
      81       * Constructs a file picker object.
      82       *
      83       * The following are possible options for the filepicker:
      84       *    - accepted_types  (*)
      85       *    - return_types    (FILE_INTERNAL)
      86       *    - env             (filepicker)
      87       *    - client_id       (uniqid)
      88       *    - itemid          (0)
      89       *    - maxbytes        (-1)
      90       *    - maxfiles        (1)
      91       *    - buttonname      (false)
      92       *
      93       * @param stdClass $options An object containing options for the file picker.
      94       */
      95      public function __construct(stdClass $options) {
      96          global $CFG, $USER, $PAGE;
      97          require_once($CFG->dirroot. '/repository/lib.php');
      98          $defaults = array(
      99              'accepted_types'=>'*',
     100              'return_types'=>FILE_INTERNAL,
     101              'env' => 'filepicker',
     102              'client_id' => uniqid(),
     103              'itemid' => 0,
     104              'maxbytes'=>-1,
     105              'maxfiles'=>1,
     106              'buttonname'=>false
     107          );
     108          foreach ($defaults as $key=>$value) {
     109              if (empty($options->$key)) {
     110                  $options->$key = $value;
     111              }
     112          }
     113  
     114          $options->currentfile = '';
     115          if (!empty($options->itemid)) {
     116              $fs = get_file_storage();
     117              $usercontext = context_user::instance($USER->id);
     118              if (empty($options->filename)) {
     119                  if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
     120                      $file = reset($files);
     121                  }
     122              } else {
     123                  $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
     124              }
     125              if (!empty($file)) {
     126                  $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
     127              }
     128          }
     129  
     130          // initilise options, getting files in root path
     131          $this->options = initialise_filepicker($options);
     132  
     133          // copying other options
     134          foreach ($options as $name=>$value) {
     135              if (!isset($this->options->$name)) {
     136                  $this->options->$name = $value;
     137              }
     138          }
     139      }
     140  }
     141  
     142  /**
     143   * Data structure representing a user picture.
     144   *
     145   * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
     146   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     147   * @since Modle 2.0
     148   * @package core
     149   * @category output
     150   */
     151  class user_picture implements renderable {
     152      /**
     153       * @var stdClass A user object with at least fields all columns specified
     154       * in $fields array constant set.
     155       */
     156      public $user;
     157  
     158      /**
     159       * @var int The course id. Used when constructing the link to the user's
     160       * profile, page course id used if not specified.
     161       */
     162      public $courseid;
     163  
     164      /**
     165       * @var bool Add course profile link to image
     166       */
     167      public $link = true;
     168  
     169      /**
     170       * @var int Size in pixels. Special values are (true/1 = 100px) and
     171       * (false/0 = 35px)
     172       * for backward compatibility.
     173       */
     174      public $size = 35;
     175  
     176      /**
     177       * @var bool Add non-blank alt-text to the image.
     178       * Default true, set to false when image alt just duplicates text in screenreaders.
     179       */
     180      public $alttext = true;
     181  
     182      /**
     183       * @var bool Whether or not to open the link in a popup window.
     184       */
     185      public $popup = false;
     186  
     187      /**
     188       * @var string Image class attribute
     189       */
     190      public $class = 'userpicture';
     191  
     192      /**
     193       * @var bool Whether to be visible to screen readers.
     194       */
     195      public $visibletoscreenreaders = true;
     196  
     197      /**
     198       * @var bool Whether to include the fullname in the user picture link.
     199       */
     200      public $includefullname = false;
     201  
     202      /**
     203       * @var mixed Include user authentication token. True indicates to generate a token for current user, and integer value
     204       * indicates to generate a token for the user whose id is the value indicated.
     205       */
     206      public $includetoken = false;
     207  
     208      /**
     209       * User picture constructor.
     210       *
     211       * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
     212       *                 It is recommended to add also contextid of the user for performance reasons.
     213       */
     214      public function __construct(stdClass $user) {
     215          global $DB;
     216  
     217          if (empty($user->id)) {
     218              throw new coding_exception('User id is required when printing user avatar image.');
     219          }
     220  
     221          // only touch the DB if we are missing data and complain loudly...
     222          $needrec = false;
     223          foreach (\core_user\fields::get_picture_fields() as $field) {
     224              if (!property_exists($user, $field)) {
     225                  $needrec = true;
     226                  debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
     227                            .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER);
     228                  break;
     229              }
     230          }
     231  
     232          if ($needrec) {
     233              $this->user = $DB->get_record('user', array('id' => $user->id),
     234                      implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST);
     235          } else {
     236              $this->user = clone($user);
     237          }
     238      }
     239  
     240      /**
     241       * Returns a list of required user fields, useful when fetching required user info from db.
     242       *
     243       * In some cases we have to fetch the user data together with some other information,
     244       * the idalias is useful there because the id would otherwise override the main
     245       * id of the result record. Please note it has to be converted back to id before rendering.
     246       *
     247       * @param string $tableprefix name of database table prefix in query
     248       * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
     249       * @param string $idalias alias of id field
     250       * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
     251       * @return string
     252       * @deprecated since Moodle 3.11 MDL-45242
     253       * @see \core_user\fields
     254       */
     255      public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
     256          debugging('user_picture::fields() is deprecated. Please use the \core_user\fields API instead.', DEBUG_DEVELOPER);
     257          $userfields = \core_user\fields::for_userpic();
     258          if ($extrafields) {
     259              $userfields->including(...$extrafields);
     260          }
     261          $selects = $userfields->get_sql($tableprefix, false, $fieldprefix, $idalias, false)->selects;
     262          if ($tableprefix === '') {
     263              // If no table alias is specified, don't add {user}. in front of fields.
     264              $selects = str_replace('{user}.', '', $selects);
     265          }
     266          // Maintain legacy behaviour where the field list was done with 'implode' and no spaces.
     267          $selects = str_replace(', ', ',', $selects);
     268          return $selects;
     269      }
     270  
     271      /**
     272       * Extract the aliased user fields from a given record
     273       *
     274       * Given a record that was previously obtained using {@link self::fields()} with aliases,
     275       * this method extracts user related unaliased fields.
     276       *
     277       * @param stdClass $record containing user picture fields
     278       * @param array $extrafields extra fields included in the $record
     279       * @param string $idalias alias of the id field
     280       * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
     281       * @return stdClass object with unaliased user fields
     282       */
     283      public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
     284  
     285          if (empty($idalias)) {
     286              $idalias = 'id';
     287          }
     288  
     289          $return = new stdClass();
     290  
     291          foreach (\core_user\fields::get_picture_fields() as $field) {
     292              if ($field === 'id') {
     293                  if (property_exists($record, $idalias)) {
     294                      $return->id = $record->{$idalias};
     295                  }
     296              } else {
     297                  if (property_exists($record, $fieldprefix.$field)) {
     298                      $return->{$field} = $record->{$fieldprefix.$field};
     299                  }
     300              }
     301          }
     302          // add extra fields if not already there
     303          if ($extrafields) {
     304              foreach ($extrafields as $e) {
     305                  if ($e === 'id' or property_exists($return, $e)) {
     306                      continue;
     307                  }
     308                  $return->{$e} = $record->{$fieldprefix.$e};
     309              }
     310          }
     311  
     312          return $return;
     313      }
     314  
     315      /**
     316       * Works out the URL for the users picture.
     317       *
     318       * This method is recommended as it avoids costly redirects of user pictures
     319       * if requests are made for non-existent files etc.
     320       *
     321       * @param moodle_page $page
     322       * @param renderer_base $renderer
     323       * @return moodle_url
     324       */
     325      public function get_url(moodle_page $page, renderer_base $renderer = null) {
     326          global $CFG;
     327  
     328          if (is_null($renderer)) {
     329              $renderer = $page->get_renderer('core');
     330          }
     331  
     332          // Sort out the filename and size. Size is only required for the gravatar
     333          // implementation presently.
     334          if (empty($this->size)) {
     335              $filename = 'f2';
     336              $size = 35;
     337          } else if ($this->size === true or $this->size == 1) {
     338              $filename = 'f1';
     339              $size = 100;
     340          } else if ($this->size > 100) {
     341              $filename = 'f3';
     342              $size = (int)$this->size;
     343          } else if ($this->size >= 50) {
     344              $filename = 'f1';
     345              $size = (int)$this->size;
     346          } else {
     347              $filename = 'f2';
     348              $size = (int)$this->size;
     349          }
     350  
     351          $defaulturl = $renderer->image_url('u/'.$filename); // default image
     352  
     353          if ((!empty($CFG->forcelogin) and !isloggedin()) ||
     354              (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
     355              // Protect images if login required and not logged in;
     356              // also if login is required for profile images and is not logged in or guest
     357              // do not use require_login() because it is expensive and not suitable here anyway.
     358              return $defaulturl;
     359          }
     360  
     361          // First try to detect deleted users - but do not read from database for performance reasons!
     362          if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
     363              // All deleted users should have email replaced by md5 hash,
     364              // all active users are expected to have valid email.
     365              return $defaulturl;
     366          }
     367  
     368          // Did the user upload a picture?
     369          if ($this->user->picture > 0) {
     370              if (!empty($this->user->contextid)) {
     371                  $contextid = $this->user->contextid;
     372              } else {
     373                  $context = context_user::instance($this->user->id, IGNORE_MISSING);
     374                  if (!$context) {
     375                      // This must be an incorrectly deleted user, all other users have context.
     376                      return $defaulturl;
     377                  }
     378                  $contextid = $context->id;
     379              }
     380  
     381              $path = '/';
     382              if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
     383                  // We append the theme name to the file path if we have it so that
     384                  // in the circumstance that the profile picture is not available
     385                  // when the user actually requests it they still get the profile
     386                  // picture for the correct theme.
     387                  $path .= $page->theme->name.'/';
     388              }
     389              // Set the image URL to the URL for the uploaded file and return.
     390              $url = moodle_url::make_pluginfile_url(
     391                      $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
     392              $url->param('rev', $this->user->picture);
     393              return $url;
     394          }
     395  
     396          if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
     397              // Normalise the size variable to acceptable bounds
     398              if ($size < 1 || $size > 512) {
     399                  $size = 35;
     400              }
     401              // Hash the users email address
     402              $md5 = md5(strtolower(trim($this->user->email)));
     403              // Build a gravatar URL with what we know.
     404  
     405              // Find the best default image URL we can (MDL-35669)
     406              if (empty($CFG->gravatardefaulturl)) {
     407                  $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
     408                  if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
     409                      $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
     410                  } else {
     411                      $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
     412                  }
     413              } else {
     414                  $gravatardefault = $CFG->gravatardefaulturl;
     415              }
     416  
     417              // If the currently requested page is https then we'll return an
     418              // https gravatar page.
     419              if (is_https()) {
     420                  return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
     421              } else {
     422                  return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
     423              }
     424          }
     425  
     426          return $defaulturl;
     427      }
     428  }
     429  
     430  /**
     431   * Data structure representing a help icon.
     432   *
     433   * @copyright 2010 Petr Skoda (info@skodak.org)
     434   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     435   * @since Moodle 2.0
     436   * @package core
     437   * @category output
     438   */
     439  class help_icon implements renderable, templatable {
     440  
     441      /**
     442       * @var string lang pack identifier (without the "_help" suffix),
     443       * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
     444       * must exist.
     445       */
     446      public $identifier;
     447  
     448      /**
     449       * @var string Component name, the same as in get_string()
     450       */
     451      public $component;
     452  
     453      /**
     454       * @var string Extra descriptive text next to the icon
     455       */
     456      public $linktext = null;
     457  
     458      /**
     459       * Constructor
     460       *
     461       * @param string $identifier string for help page title,
     462       *  string with _help suffix is used for the actual help text.
     463       *  string with _link suffix is used to create a link to further info (if it exists)
     464       * @param string $component
     465       */
     466      public function __construct($identifier, $component) {
     467          $this->identifier = $identifier;
     468          $this->component  = $component;
     469      }
     470  
     471      /**
     472       * Verifies that both help strings exists, shows debug warnings if not
     473       */
     474      public function diag_strings() {
     475          $sm = get_string_manager();
     476          if (!$sm->string_exists($this->identifier, $this->component)) {
     477              debugging("Help title string does not exist: [$this->identifier, $this->component]");
     478          }
     479          if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
     480              debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
     481          }
     482      }
     483  
     484      /**
     485       * Export this data so it can be used as the context for a mustache template.
     486       *
     487       * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
     488       * @return array
     489       */
     490      public function export_for_template(renderer_base $output) {
     491          global $CFG;
     492  
     493          $title = get_string($this->identifier, $this->component);
     494  
     495          if (empty($this->linktext)) {
     496              $alt = get_string('helpprefix2', '', trim($title, ". \t"));
     497          } else {
     498              $alt = get_string('helpwiththis');
     499          }
     500  
     501          $data = get_formatted_help_string($this->identifier, $this->component, false);
     502  
     503          $data->alt = $alt;
     504          $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
     505          $data->linktext = $this->linktext;
     506          $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
     507  
     508          $options = [
     509              'component' => $this->component,
     510              'identifier' => $this->identifier,
     511              'lang' => current_language()
     512          ];
     513  
     514          // Debugging feature lets you display string identifier and component.
     515          if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
     516              $options['strings'] = 1;
     517          }
     518  
     519          $data->url = (new moodle_url('/help.php', $options))->out(false);
     520          $data->ltr = !right_to_left();
     521          return $data;
     522      }
     523  }
     524  
     525  
     526  /**
     527   * Data structure representing an icon font.
     528   *
     529   * @copyright 2016 Damyon Wiese
     530   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     531   * @package core
     532   * @category output
     533   */
     534  class pix_icon_font implements templatable {
     535  
     536      /**
     537       * @var pix_icon $pixicon The original icon.
     538       */
     539      private $pixicon = null;
     540  
     541      /**
     542       * @var string $key The mapped key.
     543       */
     544      private $key;
     545  
     546      /**
     547       * @var bool $mapped The icon could not be mapped.
     548       */
     549      private $mapped;
     550  
     551      /**
     552       * Constructor
     553       *
     554       * @param pix_icon $pixicon The original icon
     555       */
     556      public function __construct(pix_icon $pixicon) {
     557          global $PAGE;
     558  
     559          $this->pixicon = $pixicon;
     560          $this->mapped = false;
     561          $iconsystem = \core\output\icon_system::instance();
     562  
     563          $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
     564          if (!empty($this->key)) {
     565              $this->mapped = true;
     566          }
     567      }
     568  
     569      /**
     570       * Return true if this pix_icon was successfully mapped to an icon font.
     571       *
     572       * @return bool
     573       */
     574      public function is_mapped() {
     575          return $this->mapped;
     576      }
     577  
     578      /**
     579       * Export this data so it can be used as the context for a mustache template.
     580       *
     581       * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
     582       * @return array
     583       */
     584      public function export_for_template(renderer_base $output) {
     585  
     586          $pixdata = $this->pixicon->export_for_template($output);
     587  
     588          $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
     589          $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
     590          if (empty($title)) {
     591              $title = $alt;
     592          }
     593          $data = array(
     594              'extraclasses' => $pixdata['extraclasses'],
     595              'title' => $title,
     596              'alt' => $alt,
     597              'key' => $this->key
     598          );
     599  
     600          return $data;
     601      }
     602  }
     603  
     604  /**
     605   * Data structure representing an icon subtype.
     606   *
     607   * @copyright 2016 Damyon Wiese
     608   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     609   * @package core
     610   * @category output
     611   */
     612  class pix_icon_fontawesome extends pix_icon_font {
     613  
     614  }
     615  
     616  /**
     617   * Data structure representing an icon.
     618   *
     619   * @copyright 2010 Petr Skoda
     620   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     621   * @since Moodle 2.0
     622   * @package core
     623   * @category output
     624   */
     625  class pix_icon implements renderable, templatable {
     626  
     627      /**
     628       * @var string The icon name
     629       */
     630      var $pix;
     631  
     632      /**
     633       * @var string The component the icon belongs to.
     634       */
     635      var $component;
     636  
     637      /**
     638       * @var array An array of attributes to use on the icon
     639       */
     640      var $attributes = array();
     641  
     642      /**
     643       * Constructor
     644       *
     645       * @param string $pix short icon name
     646       * @param string $alt The alt text to use for the icon
     647       * @param string $component component name
     648       * @param array $attributes html attributes
     649       */
     650      public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
     651          global $PAGE;
     652  
     653          $this->pix = $pix;
     654          $this->component  = $component;
     655          $this->attributes = (array)$attributes;
     656  
     657          if (empty($this->attributes['class'])) {
     658              $this->attributes['class'] = '';
     659          }
     660  
     661          // Set an additional class for big icons so that they can be styled properly.
     662          if (substr($pix, 0, 2) === 'b/') {
     663              $this->attributes['class'] .= ' iconsize-big';
     664          }
     665  
     666          // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
     667          if (!is_null($alt)) {
     668              $this->attributes['alt'] = $alt;
     669  
     670              // If there is no title, set it to the attribute.
     671              if (!isset($this->attributes['title'])) {
     672                  $this->attributes['title'] = $this->attributes['alt'];
     673              }
     674          } else {
     675              unset($this->attributes['alt']);
     676          }
     677  
     678          if (empty($this->attributes['title'])) {
     679              // Remove the title attribute if empty, we probably want to use the parent node's title
     680              // and some browsers might overwrite it with an empty title.
     681              unset($this->attributes['title']);
     682          }
     683  
     684          // Hide icons from screen readers that have no alt.
     685          if (empty($this->attributes['alt'])) {
     686              $this->attributes['aria-hidden'] = 'true';
     687          }
     688      }
     689  
     690      /**
     691       * Export this data so it can be used as the context for a mustache template.
     692       *
     693       * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
     694       * @return array
     695       */
     696      public function export_for_template(renderer_base $output) {
     697          $attributes = $this->attributes;
     698          $extraclasses = '';
     699  
     700          foreach ($attributes as $key => $item) {
     701              if ($key == 'class') {
     702                  $extraclasses = $item;
     703                  unset($attributes[$key]);
     704                  break;
     705              }
     706          }
     707  
     708          $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
     709          $templatecontext = array();
     710          foreach ($attributes as $name => $value) {
     711              $templatecontext[] = array('name' => $name, 'value' => $value);
     712          }
     713          $title = isset($attributes['title']) ? $attributes['title'] : '';
     714          if (empty($title)) {
     715              $title = isset($attributes['alt']) ? $attributes['alt'] : '';
     716          }
     717          $data = array(
     718              'attributes' => $templatecontext,
     719              'extraclasses' => $extraclasses
     720          );
     721  
     722          return $data;
     723      }
     724  
     725      /**
     726       * Much simpler version of export that will produce the data required to render this pix with the
     727       * pix helper in a mustache tag.
     728       *
     729       * @return array
     730       */
     731      public function export_for_pix() {
     732          $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
     733          if (empty($title)) {
     734              $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
     735          }
     736          return [
     737              'key' => $this->pix,
     738              'component' => $this->component,
     739              'title' => $title
     740          ];
     741      }
     742  }
     743  
     744  /**
     745   * Data structure representing an activity icon.
     746   *
     747   * The difference is that activity icons will always render with the standard icon system (no font icons).
     748   *
     749   * @copyright 2017 Damyon Wiese
     750   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     751   * @package core
     752   */
     753  class image_icon extends pix_icon {
     754  }
     755  
     756  /**
     757   * Data structure representing an emoticon image
     758   *
     759   * @copyright 2010 David Mudrak
     760   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     761   * @since Moodle 2.0
     762   * @package core
     763   * @category output
     764   */
     765  class pix_emoticon extends pix_icon implements renderable {
     766  
     767      /**
     768       * Constructor
     769       * @param string $pix short icon name
     770       * @param string $alt alternative text
     771       * @param string $component emoticon image provider
     772       * @param array $attributes explicit HTML attributes
     773       */
     774      public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
     775          if (empty($attributes['class'])) {
     776              $attributes['class'] = 'emoticon';
     777          }
     778          parent::__construct($pix, $alt, $component, $attributes);
     779      }
     780  }
     781  
     782  /**
     783   * Data structure representing a simple form with only one button.
     784   *
     785   * @copyright 2009 Petr Skoda
     786   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     787   * @since Moodle 2.0
     788   * @package core
     789   * @category output
     790   */
     791  class single_button implements renderable {
     792  
     793      /**
     794       * @var moodle_url Target url
     795       */
     796      public $url;
     797  
     798      /**
     799       * @var string Button label
     800       */
     801      public $label;
     802  
     803      /**
     804       * @var string Form submit method post or get
     805       */
     806      public $method = 'post';
     807  
     808      /**
     809       * @var string Wrapping div class
     810       */
     811      public $class = 'singlebutton';
     812  
     813      /**
     814       * @var bool True if button is primary button. Used for styling.
     815       */
     816      public $primary = false;
     817  
     818      /**
     819       * @var bool True if button disabled, false if normal
     820       */
     821      public $disabled = false;
     822  
     823      /**
     824       * @var string Button tooltip
     825       */
     826      public $tooltip = null;
     827  
     828      /**
     829       * @var string Form id
     830       */
     831      public $formid;
     832  
     833      /**
     834       * @var array List of attached actions
     835       */
     836      public $actions = array();
     837  
     838      /**
     839       * @var array $params URL Params
     840       */
     841      public $params;
     842  
     843      /**
     844       * @var string Action id
     845       */
     846      public $actionid;
     847  
     848      /**
     849       * @var array
     850       */
     851      protected $attributes = [];
     852  
     853      /**
     854       * Constructor
     855       * @param moodle_url $url
     856       * @param string $label button text
     857       * @param string $method get or post submit method
     858       * @param array $attributes Attributes for the HTML button tag
     859       */
     860      public function __construct(moodle_url $url, $label, $method='post', $primary=false, $attributes = []) {
     861          $this->url    = clone($url);
     862          $this->label  = $label;
     863          $this->method = $method;
     864          $this->primary = $primary;
     865          $this->attributes = $attributes;
     866      }
     867  
     868      /**
     869       * Shortcut for adding a JS confirm dialog when the button is clicked.
     870       * The message must be a yes/no question.
     871       *
     872       * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
     873       */
     874      public function add_confirm_action($confirmmessage) {
     875          $this->add_action(new confirm_action($confirmmessage));
     876      }
     877  
     878      /**
     879       * Add action to the button.
     880       * @param component_action $action
     881       */
     882      public function add_action(component_action $action) {
     883          $this->actions[] = $action;
     884      }
     885  
     886      /**
     887       * Sets an attribute for the HTML button tag.
     888       *
     889       * @param  string $name  The attribute name
     890       * @param  mixed  $value The value
     891       * @return null
     892       */
     893      public function set_attribute($name, $value) {
     894          $this->attributes[$name] = $value;
     895      }
     896  
     897      /**
     898       * Export data.
     899       *
     900       * @param renderer_base $output Renderer.
     901       * @return stdClass
     902       */
     903      public function export_for_template(renderer_base $output) {
     904          $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
     905  
     906          $data = new stdClass();
     907          $data->id = html_writer::random_id('single_button');
     908          $data->formid = $this->formid;
     909          $data->method = $this->method;
     910          $data->url = $url === '' ? '#' : $url;
     911          $data->label = $this->label;
     912          $data->classes = $this->class;
     913          $data->disabled = $this->disabled;
     914          $data->tooltip = $this->tooltip;
     915          $data->primary = $this->primary;
     916  
     917          $data->attributes = [];
     918          foreach ($this->attributes as $key => $value) {
     919              $data->attributes[] = ['name' => $key, 'value' => $value];
     920          }
     921  
     922          // Form parameters.
     923          $params = $this->url->params();
     924          if ($this->method === 'post') {
     925              $params['sesskey'] = sesskey();
     926          }
     927          $data->params = array_map(function($key) use ($params) {
     928              return ['name' => $key, 'value' => $params[$key]];
     929          }, array_keys($params));
     930  
     931          // Button actions.
     932          $actions = $this->actions;
     933          $data->actions = array_map(function($action) use ($output) {
     934              return $action->export_for_template($output);
     935          }, $actions);
     936          $data->hasactions = !empty($data->actions);
     937  
     938          return $data;
     939      }
     940  }
     941  
     942  
     943  /**
     944   * Simple form with just one select field that gets submitted automatically.
     945   *
     946   * If JS not enabled small go button is printed too.
     947   *
     948   * @copyright 2009 Petr Skoda
     949   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     950   * @since Moodle 2.0
     951   * @package core
     952   * @category output
     953   */
     954  class single_select implements renderable, templatable {
     955  
     956      /**
     957       * @var moodle_url Target url - includes hidden fields
     958       */
     959      var $url;
     960  
     961      /**
     962       * @var string Name of the select element.
     963       */
     964      var $name;
     965  
     966      /**
     967       * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
     968       *     it is also possible to specify optgroup as complex label array ex.:
     969       *         array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
     970       *         array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
     971       */
     972      var $options;
     973  
     974      /**
     975       * @var string Selected option
     976       */
     977      var $selected;
     978  
     979      /**
     980       * @var array Nothing selected
     981       */
     982      var $nothing;
     983  
     984      /**
     985       * @var array Extra select field attributes
     986       */
     987      var $attributes = array();
     988  
     989      /**
     990       * @var string Button label
     991       */
     992      var $label = '';
     993  
     994      /**
     995       * @var array Button label's attributes
     996       */
     997      var $labelattributes = array();
     998  
     999      /**
    1000       * @var string Form submit method post or get
    1001       */
    1002      var $method = 'get';
    1003  
    1004      /**
    1005       * @var string Wrapping div class
    1006       */
    1007      var $class = 'singleselect';
    1008  
    1009      /**
    1010       * @var bool True if button disabled, false if normal
    1011       */
    1012      var $disabled = false;
    1013  
    1014      /**
    1015       * @var string Button tooltip
    1016       */
    1017      var $tooltip = null;
    1018  
    1019      /**
    1020       * @var string Form id
    1021       */
    1022      var $formid = null;
    1023  
    1024      /**
    1025       * @var help_icon The help icon for this element.
    1026       */
    1027      var $helpicon = null;
    1028  
    1029      /**
    1030       * Constructor
    1031       * @param moodle_url $url form action target, includes hidden fields
    1032       * @param string $name name of selection field - the changing parameter in url
    1033       * @param array $options list of options
    1034       * @param string $selected selected element
    1035       * @param array $nothing
    1036       * @param string $formid
    1037       */
    1038      public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
    1039          $this->url      = $url;
    1040          $this->name     = $name;
    1041          $this->options  = $options;
    1042          $this->selected = $selected;
    1043          $this->nothing  = $nothing;
    1044          $this->formid   = $formid;
    1045      }
    1046  
    1047      /**
    1048       * Shortcut for adding a JS confirm dialog when the button is clicked.
    1049       * The message must be a yes/no question.
    1050       *
    1051       * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
    1052       */
    1053      public function add_confirm_action($confirmmessage) {
    1054          $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
    1055      }
    1056  
    1057      /**
    1058       * Add action to the button.
    1059       *
    1060       * @param component_action $action
    1061       */
    1062      public function add_action(component_action $action) {
    1063          $this->actions[] = $action;
    1064      }
    1065  
    1066      /**
    1067       * Adds help icon.
    1068       *
    1069       * @deprecated since Moodle 2.0
    1070       */
    1071      public function set_old_help_icon($helppage, $title, $component = 'moodle') {
    1072          throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
    1073      }
    1074  
    1075      /**
    1076       * Adds help icon.
    1077       *
    1078       * @param string $identifier The keyword that defines a help page
    1079       * @param string $component
    1080       */
    1081      public function set_help_icon($identifier, $component = 'moodle') {
    1082          $this->helpicon = new help_icon($identifier, $component);
    1083      }
    1084  
    1085      /**
    1086       * Sets select's label
    1087       *
    1088       * @param string $label
    1089       * @param array $attributes (optional)
    1090       */
    1091      public function set_label($label, $attributes = array()) {
    1092          $this->label = $label;
    1093          $this->labelattributes = $attributes;
    1094  
    1095      }
    1096  
    1097      /**
    1098       * Export data.
    1099       *
    1100       * @param renderer_base $output Renderer.
    1101       * @return stdClass
    1102       */
    1103      public function export_for_template(renderer_base $output) {
    1104          $attributes = $this->attributes;
    1105  
    1106          $data = new stdClass();
    1107          $data->name = $this->name;
    1108          $data->method = $this->method;
    1109          $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
    1110          $data->classes = $this->class;
    1111          $data->label = $this->label;
    1112          $data->disabled = $this->disabled;
    1113          $data->title = $this->tooltip;
    1114          $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
    1115          $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
    1116  
    1117          // Select element attributes.
    1118          // Unset attributes that are already predefined in the template.
    1119          unset($attributes['id']);
    1120          unset($attributes['class']);
    1121          unset($attributes['name']);
    1122          unset($attributes['title']);
    1123          unset($attributes['disabled']);
    1124  
    1125          // Map the attributes.
    1126          $data->attributes = array_map(function($key) use ($attributes) {
    1127              return ['name' => $key, 'value' => $attributes[$key]];
    1128          }, array_keys($attributes));
    1129  
    1130          // Form parameters.
    1131          $params = $this->url->params();
    1132          if ($this->method === 'post') {
    1133              $params['sesskey'] = sesskey();
    1134          }
    1135          $data->params = array_map(function($key) use ($params) {
    1136              return ['name' => $key, 'value' => $params[$key]];
    1137          }, array_keys($params));
    1138  
    1139          // Select options.
    1140          $hasnothing = false;
    1141          if (is_string($this->nothing) && $this->nothing !== '') {
    1142              $nothing = ['' => $this->nothing];
    1143              $hasnothing = true;
    1144              $nothingkey = '';
    1145          } else if (is_array($this->nothing)) {
    1146              $nothingvalue = reset($this->nothing);
    1147              if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
    1148                  $nothing = [key($this->nothing) => get_string('choosedots')];
    1149              } else {
    1150                  $nothing = $this->nothing;
    1151              }
    1152              $hasnothing = true;
    1153              $nothingkey = key($this->nothing);
    1154          }
    1155          if ($hasnothing) {
    1156              $options = $nothing + $this->options;
    1157          } else {
    1158              $options = $this->options;
    1159          }
    1160  
    1161          foreach ($options as $value => $name) {
    1162              if (is_array($options[$value])) {
    1163                  foreach ($options[$value] as $optgroupname => $optgroupvalues) {
    1164                      $sublist = [];
    1165                      foreach ($optgroupvalues as $optvalue => $optname) {
    1166                          $option = [
    1167                              'value' => $optvalue,
    1168                              'name' => $optname,
    1169                              'selected' => strval($this->selected) === strval($optvalue),
    1170                          ];
    1171  
    1172                          if ($hasnothing && $nothingkey === $optvalue) {
    1173                              $option['ignore'] = 'data-ignore';
    1174                          }
    1175  
    1176                          $sublist[] = $option;
    1177                      }
    1178                      $data->options[] = [
    1179                          'name' => $optgroupname,
    1180                          'optgroup' => true,
    1181                          'options' => $sublist
    1182                      ];
    1183                  }
    1184              } else {
    1185                  $option = [
    1186                      'value' => $value,
    1187                      'name' => $options[$value],
    1188                      'selected' => strval($this->selected) === strval($value),
    1189                      'optgroup' => false
    1190                  ];
    1191  
    1192                  if ($hasnothing && $nothingkey === $value) {
    1193                      $option['ignore'] = 'data-ignore';
    1194                  }
    1195  
    1196                  $data->options[] = $option;
    1197              }
    1198          }
    1199  
    1200          // Label attributes.
    1201          $data->labelattributes = [];
    1202          // Unset label attributes that are already in the template.
    1203          unset($this->labelattributes['for']);
    1204          // Map the label attributes.
    1205          foreach ($this->labelattributes as $key => $value) {
    1206              $data->labelattributes[] = ['name' => $key, 'value' => $value];
    1207          }
    1208  
    1209          // Help icon.
    1210          $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
    1211  
    1212          return $data;
    1213      }
    1214  }
    1215  
    1216  /**
    1217   * Simple URL selection widget description.
    1218   *
    1219   * @copyright 2009 Petr Skoda
    1220   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1221   * @since Moodle 2.0
    1222   * @package core
    1223   * @category output
    1224   */
    1225  class url_select implements renderable, templatable {
    1226      /**
    1227       * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
    1228       *     it is also possible to specify optgroup as complex label array ex.:
    1229       *         array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
    1230       *         array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
    1231       */
    1232      var $urls;
    1233  
    1234      /**
    1235       * @var string Selected option
    1236       */
    1237      var $selected;
    1238  
    1239      /**
    1240       * @var array Nothing selected
    1241       */
    1242      var $nothing;
    1243  
    1244      /**
    1245       * @var array Extra select field attributes
    1246       */
    1247      var $attributes = array();
    1248  
    1249      /**
    1250       * @var string Button label
    1251       */
    1252      var $label = '';
    1253  
    1254      /**
    1255       * @var array Button label's attributes
    1256       */
    1257      var $labelattributes = array();
    1258  
    1259      /**
    1260       * @var string Wrapping div class
    1261       */
    1262      var $class = 'urlselect';
    1263  
    1264      /**
    1265       * @var bool True if button disabled, false if normal
    1266       */
    1267      var $disabled = false;
    1268  
    1269      /**
    1270       * @var string Button tooltip
    1271       */
    1272      var $tooltip = null;
    1273  
    1274      /**
    1275       * @var string Form id
    1276       */
    1277      var $formid = null;
    1278  
    1279      /**
    1280       * @var help_icon The help icon for this element.
    1281       */
    1282      var $helpicon = null;
    1283  
    1284      /**
    1285       * @var string If set, makes button visible with given name for button
    1286       */
    1287      var $showbutton = null;
    1288  
    1289      /**
    1290       * Constructor
    1291       * @param array $urls list of options
    1292       * @param string $selected selected element
    1293       * @param array $nothing
    1294       * @param string $formid
    1295       * @param string $showbutton Set to text of button if it should be visible
    1296       *   or null if it should be hidden (hidden version always has text 'go')
    1297       */
    1298      public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
    1299          $this->urls       = $urls;
    1300          $this->selected   = $selected;
    1301          $this->nothing    = $nothing;
    1302          $this->formid     = $formid;
    1303          $this->showbutton = $showbutton;
    1304      }
    1305  
    1306      /**
    1307       * Adds help icon.
    1308       *
    1309       * @deprecated since Moodle 2.0
    1310       */
    1311      public function set_old_help_icon($helppage, $title, $component = 'moodle') {
    1312          throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
    1313      }
    1314  
    1315      /**
    1316       * Adds help icon.
    1317       *
    1318       * @param string $identifier The keyword that defines a help page
    1319       * @param string $component
    1320       */
    1321      public function set_help_icon($identifier, $component = 'moodle') {
    1322          $this->helpicon = new help_icon($identifier, $component);
    1323      }
    1324  
    1325      /**
    1326       * Sets select's label
    1327       *
    1328       * @param string $label
    1329       * @param array $attributes (optional)
    1330       */
    1331      public function set_label($label, $attributes = array()) {
    1332          $this->label = $label;
    1333          $this->labelattributes = $attributes;
    1334      }
    1335  
    1336      /**
    1337       * Clean a URL.
    1338       *
    1339       * @param string $value The URL.
    1340       * @return The cleaned URL.
    1341       */
    1342      protected function clean_url($value) {
    1343          global $CFG;
    1344  
    1345          if (empty($value)) {
    1346              // Nothing.
    1347  
    1348          } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
    1349              $value = str_replace($CFG->wwwroot, '', $value);
    1350  
    1351          } else if (strpos($value, '/') !== 0) {
    1352              debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
    1353          }
    1354  
    1355          return $value;
    1356      }
    1357  
    1358      /**
    1359       * Flatten the options for Mustache.
    1360       *
    1361       * This also cleans the URLs.
    1362       *
    1363       * @param array $options The options.
    1364       * @param array $nothing The nothing option.
    1365       * @return array
    1366       */
    1367      protected function flatten_options($options, $nothing) {
    1368          $flattened = [];
    1369  
    1370          foreach ($options as $value => $option) {
    1371              if (is_array($option)) {
    1372                  foreach ($option as $groupname => $optoptions) {
    1373                      if (!isset($flattened[$groupname])) {
    1374                          $flattened[$groupname] = [
    1375                              'name' => $groupname,
    1376                              'isgroup' => true,
    1377                              'options' => []
    1378                          ];
    1379                      }
    1380                      foreach ($optoptions as $optvalue => $optoption) {
    1381                          $cleanedvalue = $this->clean_url($optvalue);
    1382                          $flattened[$groupname]['options'][$cleanedvalue] = [
    1383                              'name' => $optoption,
    1384                              'value' => $cleanedvalue,
    1385                              'selected' => $this->selected == $optvalue,
    1386                          ];
    1387                      }
    1388                  }
    1389  
    1390              } else {
    1391                  $cleanedvalue = $this->clean_url($value);
    1392                  $flattened[$cleanedvalue] = [
    1393                      'name' => $option,
    1394                      'value' => $cleanedvalue,
    1395                      'selected' => $this->selected == $value,
    1396                  ];
    1397              }
    1398          }
    1399  
    1400          if (!empty($nothing)) {
    1401              $value = key($nothing);
    1402              $name = reset($nothing);
    1403              $flattened = [
    1404                  $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
    1405              ] + $flattened;
    1406          }
    1407  
    1408          // Make non-associative array.
    1409          foreach ($flattened as $key => $value) {
    1410              if (!empty($value['options'])) {
    1411                  $flattened[$key]['options'] = array_values($value['options']);
    1412              }
    1413          }
    1414          $flattened = array_values($flattened);
    1415  
    1416          return $flattened;
    1417      }
    1418  
    1419      /**
    1420       * Export for template.
    1421       *
    1422       * @param renderer_base $output Renderer.
    1423       * @return stdClass
    1424       */
    1425      public function export_for_template(renderer_base $output) {
    1426          $attributes = $this->attributes;
    1427  
    1428          $data = new stdClass();
    1429          $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
    1430          $data->classes = $this->class;
    1431          $data->label = $this->label;
    1432          $data->disabled = $this->disabled;
    1433          $data->title = $this->tooltip;
    1434          $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
    1435          $data->sesskey = sesskey();
    1436          $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
    1437  
    1438          // Remove attributes passed as property directly.
    1439          unset($attributes['class']);
    1440          unset($attributes['id']);
    1441          unset($attributes['name']);
    1442          unset($attributes['title']);
    1443          unset($attributes['disabled']);
    1444  
    1445          $data->showbutton = $this->showbutton;
    1446  
    1447          // Select options.
    1448          $nothing = false;
    1449          if (is_string($this->nothing) && $this->nothing !== '') {
    1450              $nothing = ['' => $this->nothing];
    1451          } else if (is_array($this->nothing)) {
    1452              $nothingvalue = reset($this->nothing);
    1453              if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
    1454                  $nothing = [key($this->nothing) => get_string('choosedots')];
    1455              } else {
    1456                  $nothing = $this->nothing;
    1457              }
    1458          }
    1459          $data->options = $this->flatten_options($this->urls, $nothing);
    1460  
    1461          // Label attributes.
    1462          $data->labelattributes = [];
    1463          // Unset label attributes that are already in the template.
    1464          unset($this->labelattributes['for']);
    1465          // Map the label attributes.
    1466          foreach ($this->labelattributes as $key => $value) {
    1467              $data->labelattributes[] = ['name' => $key, 'value' => $value];
    1468          }
    1469  
    1470          // Help icon.
    1471          $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
    1472  
    1473          // Finally all the remaining attributes.
    1474          $data->attributes = [];
    1475          foreach ($attributes as $key => $value) {
    1476              $data->attributes[] = ['name' => $key, 'value' => $value];
    1477          }
    1478  
    1479          return $data;
    1480      }
    1481  }
    1482  
    1483  /**
    1484   * Data structure describing html link with special action attached.
    1485   *
    1486   * @copyright 2010 Petr Skoda
    1487   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1488   * @since Moodle 2.0
    1489   * @package core
    1490   * @category output
    1491   */
    1492  class action_link implements renderable {
    1493  
    1494      /**
    1495       * @var moodle_url Href url
    1496       */
    1497      public $url;
    1498  
    1499      /**
    1500       * @var string Link text HTML fragment
    1501       */
    1502      public $text;
    1503  
    1504      /**
    1505       * @var array HTML attributes
    1506       */
    1507      public $attributes;
    1508  
    1509      /**
    1510       * @var array List of actions attached to link
    1511       */
    1512      public $actions;
    1513  
    1514      /**
    1515       * @var pix_icon Optional pix icon to render with the link
    1516       */
    1517      public $icon;
    1518  
    1519      /**
    1520       * Constructor
    1521       * @param moodle_url $url
    1522       * @param string $text HTML fragment
    1523       * @param component_action $action
    1524       * @param array $attributes associative array of html link attributes + disabled
    1525       * @param pix_icon $icon optional pix_icon to render with the link text
    1526       */
    1527      public function __construct(moodle_url $url,
    1528                                  $text,
    1529                                  component_action $action=null,
    1530                                  array $attributes=null,
    1531                                  pix_icon $icon=null) {
    1532          $this->url = clone($url);
    1533          $this->text = $text;
    1534          $this->attributes = (array)$attributes;
    1535          if ($action) {
    1536              $this->add_action($action);
    1537          }
    1538          $this->icon = $icon;
    1539      }
    1540  
    1541      /**
    1542       * Add action to the link.
    1543       *
    1544       * @param component_action $action
    1545       */
    1546      public function add_action(component_action $action) {
    1547          $this->actions[] = $action;
    1548      }
    1549  
    1550      /**
    1551       * Adds a CSS class to this action link object
    1552       * @param string $class
    1553       */
    1554      public function add_class($class) {
    1555          if (empty($this->attributes['class'])) {
    1556              $this->attributes['class'] = $class;
    1557          } else {
    1558              $this->attributes['class'] .= ' ' . $class;
    1559          }
    1560      }
    1561  
    1562      /**
    1563       * Returns true if the specified class has been added to this link.
    1564       * @param string $class
    1565       * @return bool
    1566       */
    1567      public function has_class($class) {
    1568          return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
    1569      }
    1570  
    1571      /**
    1572       * Return the rendered HTML for the icon. Useful for rendering action links in a template.
    1573       * @return string
    1574       */
    1575      public function get_icon_html() {
    1576          global $OUTPUT;
    1577          if (!$this->icon) {
    1578              return '';
    1579          }
    1580          return $OUTPUT->render($this->icon);
    1581      }
    1582  
    1583      /**
    1584       * Export for template.
    1585       *
    1586       * @param renderer_base $output The renderer.
    1587       * @return stdClass
    1588       */
    1589      public function export_for_template(renderer_base $output) {
    1590          $data = new stdClass();
    1591          $attributes = $this->attributes;
    1592  
    1593          if (empty($attributes['id'])) {
    1594              $attributes['id'] = html_writer::random_id('action_link');
    1595          }
    1596          $data->id = $attributes['id'];
    1597          unset($attributes['id']);
    1598  
    1599          $data->disabled = !empty($attributes['disabled']);
    1600          unset($attributes['disabled']);
    1601  
    1602          $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
    1603          $data->url = $this->url ? $this->url->out(false) : '';
    1604          $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
    1605          $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
    1606          unset($attributes['class']);
    1607  
    1608          $data->attributes = array_map(function($key, $value) {
    1609              return [
    1610                  'name' => $key,
    1611                  'value' => $value
    1612              ];
    1613          }, array_keys($attributes), $attributes);
    1614  
    1615          $data->actions = array_map(function($action) use ($output) {
    1616              return $action->export_for_template($output);
    1617          }, !empty($this->actions) ? $this->actions : []);
    1618          $data->hasactions = !empty($this->actions);
    1619  
    1620          return $data;
    1621      }
    1622  }
    1623  
    1624  /**
    1625   * Simple html output class
    1626   *
    1627   * @copyright 2009 Tim Hunt, 2010 Petr Skoda
    1628   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1629   * @since Moodle 2.0
    1630   * @package core
    1631   * @category output
    1632   */
    1633  class html_writer {
    1634  
    1635      /**
    1636       * Outputs a tag with attributes and contents
    1637       *
    1638       * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
    1639       * @param string $contents What goes between the opening and closing tags
    1640       * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
    1641       * @return string HTML fragment
    1642       */
    1643      public static function tag($tagname, $contents, array $attributes = null) {
    1644          return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
    1645      }
    1646  
    1647      /**
    1648       * Outputs an opening tag with attributes
    1649       *
    1650       * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
    1651       * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
    1652       * @return string HTML fragment
    1653       */
    1654      public static function start_tag($tagname, array $attributes = null) {
    1655          return '<' . $tagname . self::attributes($attributes) . '>';
    1656      }
    1657  
    1658      /**
    1659       * Outputs a closing tag
    1660       *
    1661       * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
    1662       * @return string HTML fragment
    1663       */
    1664      public static function end_tag($tagname) {
    1665          return '</' . $tagname . '>';
    1666      }
    1667  
    1668      /**
    1669       * Outputs an empty tag with attributes
    1670       *
    1671       * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
    1672       * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
    1673       * @return string HTML fragment
    1674       */
    1675      public static function empty_tag($tagname, array $attributes = null) {
    1676          return '<' . $tagname . self::attributes($attributes) . ' />';
    1677      }
    1678  
    1679      /**
    1680       * Outputs a tag, but only if the contents are not empty
    1681       *
    1682       * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
    1683       * @param string $contents What goes between the opening and closing tags
    1684       * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
    1685       * @return string HTML fragment
    1686       */
    1687      public static function nonempty_tag($tagname, $contents, array $attributes = null) {
    1688          if ($contents === '' || is_null($contents)) {
    1689              return '';
    1690          }
    1691          return self::tag($tagname, $contents, $attributes);
    1692      }
    1693  
    1694      /**
    1695       * Outputs a HTML attribute and value
    1696       *
    1697       * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
    1698       * @param string $value The value of the attribute. The value will be escaped with {@link s()}
    1699       * @return string HTML fragment
    1700       */
    1701      public static function attribute($name, $value) {
    1702          if ($value instanceof moodle_url) {
    1703              return ' ' . $name . '="' . $value->out() . '"';
    1704          }
    1705  
    1706          // special case, we do not want these in output
    1707          if ($value === null) {
    1708              return '';
    1709          }
    1710  
    1711          // no sloppy trimming here!
    1712          return ' ' . $name . '="' . s($value) . '"';
    1713      }
    1714  
    1715      /**
    1716       * Outputs a list of HTML attributes and values
    1717       *
    1718       * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
    1719       *       The values will be escaped with {@link s()}
    1720       * @return string HTML fragment
    1721       */
    1722      public static function attributes(array $attributes = null) {
    1723          $attributes = (array)$attributes;
    1724          $output = '';
    1725          foreach ($attributes as $name => $value) {
    1726              $output .= self::attribute($name, $value);
    1727          }
    1728          return $output;
    1729      }
    1730  
    1731      /**
    1732       * Generates a simple image tag with attributes.
    1733       *
    1734       * @param string $src The source of image
    1735       * @param string $alt The alternate text for image
    1736       * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
    1737       * @return string HTML fragment
    1738       */
    1739      public static function img($src, $alt, array $attributes = null) {
    1740          $attributes = (array)$attributes;
    1741          $attributes['src'] = $src;
    1742          $attributes['alt'] = $alt;
    1743  
    1744          return self::empty_tag('img', $attributes);
    1745      }
    1746  
    1747      /**
    1748       * Generates random html element id.
    1749       *
    1750       * @staticvar int $counter
    1751       * @staticvar type $uniq
    1752       * @param string $base A string fragment that will be included in the random ID.
    1753       * @return string A unique ID
    1754       */
    1755      public static function random_id($base='random') {
    1756          static $counter = 0;
    1757          static $uniq;
    1758  
    1759          if (!isset($uniq)) {
    1760              $uniq = uniqid();
    1761          }
    1762  
    1763          $counter++;
    1764          return $base.$uniq.$counter;
    1765      }
    1766  
    1767      /**
    1768       * Generates a simple html link
    1769       *
    1770       * @param string|moodle_url $url The URL
    1771       * @param string $text The text
    1772       * @param array $attributes HTML attributes
    1773       * @return string HTML fragment
    1774       */
    1775      public static function link($url, $text, array $attributes = null) {
    1776          $attributes = (array)$attributes;
    1777          $attributes['href']  = $url;
    1778          return self::tag('a', $text, $attributes);
    1779      }
    1780  
    1781      /**
    1782       * Generates a simple checkbox with optional label
    1783       *
    1784       * @param string $name The name of the checkbox
    1785       * @param string $value The value of the checkbox
    1786       * @param bool $checked Whether the checkbox is checked
    1787       * @param string $label The label for the checkbox
    1788       * @param array $attributes Any attributes to apply to the checkbox
    1789       * @param array $labelattributes Any attributes to apply to the label, if present
    1790       * @return string html fragment
    1791       */
    1792      public static function checkbox($name, $value, $checked = true, $label = '',
    1793              array $attributes = null, array $labelattributes = null) {
    1794          $attributes = (array) $attributes;
    1795          $output = '';
    1796  
    1797          if ($label !== '' and !is_null($label)) {
    1798              if (empty($attributes['id'])) {
    1799                  $attributes['id'] = self::random_id('checkbox_');
    1800              }
    1801          }
    1802          $attributes['type']    = 'checkbox';
    1803          $attributes['value']   = $value;
    1804          $attributes['name']    = $name;
    1805          $attributes['checked'] = $checked ? 'checked' : null;
    1806  
    1807          $output .= self::empty_tag('input', $attributes);
    1808  
    1809          if ($label !== '' and !is_null($label)) {
    1810              $labelattributes = (array) $labelattributes;
    1811              $labelattributes['for'] = $attributes['id'];
    1812              $output .= self::tag('label', $label, $labelattributes);
    1813          }
    1814  
    1815          return $output;
    1816      }
    1817  
    1818      /**
    1819       * Generates a simple select yes/no form field
    1820       *
    1821       * @param string $name name of select element
    1822       * @param bool $selected
    1823       * @param array $attributes - html select element attributes
    1824       * @return string HTML fragment
    1825       */
    1826      public static function select_yes_no($name, $selected=true, array $attributes = null) {
    1827          $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
    1828          return self::select($options, $name, $selected, null, $attributes);
    1829      }
    1830  
    1831      /**
    1832       * Generates a simple select form field
    1833       *
    1834       * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
    1835       *
    1836       * @param array $options associative array value=>label ex.:
    1837       *                array(1=>'One, 2=>Two)
    1838       *              it is also possible to specify optgroup as complex label array ex.:
    1839       *                array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
    1840       *                array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
    1841       * @param string $name name of select element
    1842       * @param string|array $selected value or array of values depending on multiple attribute
    1843       * @param array|bool $nothing add nothing selected option, or false of not added
    1844       * @param array $attributes html select element attributes
    1845       * @return string HTML fragment
    1846       */
    1847      public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
    1848          $attributes = (array)$attributes;
    1849          if (is_array($nothing)) {
    1850              foreach ($nothing as $k=>$v) {
    1851                  if ($v === 'choose' or $v === 'choosedots') {
    1852                      $nothing[$k] = get_string('choosedots');
    1853                  }
    1854              }
    1855              $options = $nothing + $options; // keep keys, do not override
    1856  
    1857          } else if (is_string($nothing) and $nothing !== '') {
    1858              // BC
    1859              $options = array(''=>$nothing) + $options;
    1860          }
    1861  
    1862          // we may accept more values if multiple attribute specified
    1863          $selected = (array)$selected;
    1864          foreach ($selected as $k=>$v) {
    1865              $selected[$k] = (string)$v;
    1866          }
    1867  
    1868          if (!isset($attributes['id'])) {
    1869              $id = 'menu'.$name;
    1870              // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
    1871              $id = str_replace('[', '', $id);
    1872              $id = str_replace(']', '', $id);
    1873              $attributes['id'] = $id;
    1874          }
    1875  
    1876          if (!isset($attributes['class'])) {
    1877              $class = 'menu'.$name;
    1878              // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
    1879              $class = str_replace('[', '', $class);
    1880              $class = str_replace(']', '', $class);
    1881              $attributes['class'] = $class;
    1882          }
    1883          $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
    1884  
    1885          $attributes['name'] = $name;
    1886  
    1887          if (!empty($attributes['disabled'])) {
    1888              $attributes['disabled'] = 'disabled';
    1889          } else {
    1890              unset($attributes['disabled']);
    1891          }
    1892  
    1893          $output = '';
    1894          foreach ($options as $value=>$label) {
    1895              if (is_array($label)) {
    1896                  // ignore key, it just has to be unique
    1897                  $output .= self::select_optgroup(key($label), current($label), $selected);
    1898              } else {
    1899                  $output .= self::select_option($label, $value, $selected);
    1900              }
    1901          }
    1902          return self::tag('select', $output, $attributes);
    1903      }
    1904  
    1905      /**
    1906       * Returns HTML to display a select box option.
    1907       *
    1908       * @param string $label The label to display as the option.
    1909       * @param string|int $value The value the option represents
    1910       * @param array $selected An array of selected options
    1911       * @return string HTML fragment
    1912       */
    1913      private static function select_option($label, $value, array $selected) {
    1914          $attributes = array();
    1915          $value = (string)$value;
    1916          if (in_array($value, $selected, true)) {
    1917              $attributes['selected'] = 'selected';
    1918          }
    1919          $attributes['value'] = $value;
    1920          return self::tag('option', $label, $attributes);
    1921      }
    1922  
    1923      /**
    1924       * Returns HTML to display a select box option group.
    1925       *
    1926       * @param string $groupname The label to use for the group
    1927       * @param array $options The options in the group
    1928       * @param array $selected An array of selected values.
    1929       * @return string HTML fragment.
    1930       */
    1931      private static function select_optgroup($groupname, $options, array $selected) {
    1932          if (empty($options)) {
    1933              return '';
    1934          }
    1935          $attributes = array('label'=>$groupname);
    1936          $output = '';
    1937          foreach ($options as $value=>$label) {
    1938              $output .= self::select_option($label, $value, $selected);
    1939          }
    1940          return self::tag('optgroup', $output, $attributes);
    1941      }
    1942  
    1943      /**
    1944       * This is a shortcut for making an hour selector menu.
    1945       *
    1946       * @param string $type The type of selector (years, months, days, hours, minutes)
    1947       * @param string $name fieldname
    1948       * @param int $currenttime A default timestamp in GMT
    1949       * @param int $step minute spacing
    1950       * @param array $attributes - html select element attributes
    1951       * @return HTML fragment
    1952       */
    1953      public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
    1954          global $OUTPUT;
    1955  
    1956          if (!$currenttime) {
    1957              $currenttime = time();
    1958          }
    1959          $calendartype = \core_calendar\type_factory::get_calendar_instance();
    1960          $currentdate = $calendartype->timestamp_to_date_array($currenttime);
    1961          $userdatetype = $type;
    1962          $timeunits = array();
    1963  
    1964          switch ($type) {
    1965              case 'years':
    1966                  $timeunits = $calendartype->get_years();
    1967                  $userdatetype = 'year';
    1968                  break;
    1969              case 'months':
    1970                  $timeunits = $calendartype->get_months();
    1971                  $userdatetype = 'month';
    1972                  $currentdate['month'] = (int)$currentdate['mon'];
    1973                  break;
    1974              case 'days':
    1975                  $timeunits = $calendartype->get_days();
    1976                  $userdatetype = 'mday';
    1977                  break;
    1978              case 'hours':
    1979                  for ($i=0; $i<=23; $i++) {
    1980                      $timeunits[$i] = sprintf("%02d",$i);
    1981                  }
    1982                  break;
    1983              case 'minutes':
    1984                  if ($step != 1) {
    1985                      $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
    1986                  }
    1987  
    1988                  for ($i=0; $i<=59; $i+=$step) {
    1989                      $timeunits[$i] = sprintf("%02d",$i);
    1990                  }
    1991                  break;
    1992              default:
    1993                  throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
    1994          }
    1995  
    1996          $attributes = (array) $attributes;
    1997          $data = (object) [
    1998              'name' => $name,
    1999              'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
    2000              'label' => get_string(substr($type, 0, -1), 'form'),
    2001              'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
    2002                  return [
    2003                      'name' => $timeunits[$value],
    2004                      'value' => $value,
    2005                      'selected' => $currentdate[$userdatetype] == $value
    2006                  ];
    2007              }, array_keys($timeunits)),
    2008          ];
    2009  
    2010          unset($attributes['id']);
    2011          unset($attributes['name']);
    2012          $data->attributes = array_map(function($name) use ($attributes) {
    2013              return [
    2014                  'name' => $name,
    2015                  'value' => $attributes[$name]
    2016              ];
    2017          }, array_keys($attributes));
    2018  
    2019          return $OUTPUT->render_from_template('core/select_time', $data);
    2020      }
    2021  
    2022      /**
    2023       * Shortcut for quick making of lists
    2024       *
    2025       * Note: 'list' is a reserved keyword ;-)
    2026       *
    2027       * @param array $items
    2028       * @param array $attributes
    2029       * @param string $tag ul or ol
    2030       * @return string
    2031       */
    2032      public static function alist(array $items, array $attributes = null, $tag = 'ul') {
    2033          $output = html_writer::start_tag($tag, $attributes)."\n";
    2034          foreach ($items as $item) {
    2035              $output .= html_writer::tag('li', $item)."\n";
    2036          }
    2037          $output .= html_writer::end_tag($tag);
    2038          return $output;
    2039      }
    2040  
    2041      /**
    2042       * Returns hidden input fields created from url parameters.
    2043       *
    2044       * @param moodle_url $url
    2045       * @param array $exclude list of excluded parameters
    2046       * @return string HTML fragment
    2047       */
    2048      public static function input_hidden_params(moodle_url $url, array $exclude = null) {
    2049          $exclude = (array)$exclude;
    2050          $params = $url->params();
    2051          foreach ($exclude as $key) {
    2052              unset($params[$key]);
    2053          }
    2054  
    2055          $output = '';
    2056          foreach ($params as $key => $value) {
    2057              $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
    2058              $output .= self::empty_tag('input', $attributes)."\n";
    2059          }
    2060          return $output;
    2061      }
    2062  
    2063      /**
    2064       * Generate a script tag containing the the specified code.
    2065       *
    2066       * @param string $jscode the JavaScript code
    2067       * @param moodle_url|string $url optional url of the external script, $code ignored if specified
    2068       * @return string HTML, the code wrapped in <script> tags.
    2069       */
    2070      public static function script($jscode, $url=null) {
    2071          if ($jscode) {
    2072              return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
    2073  
    2074          } else if ($url) {
    2075              return self::tag('script', '', ['src' => $url]) . "\n";
    2076  
    2077          } else {
    2078              return '';
    2079          }
    2080      }
    2081  
    2082      /**
    2083       * Renders HTML table
    2084       *
    2085       * This method may modify the passed instance by adding some default properties if they are not set yet.
    2086       * If this is not what you want, you should make a full clone of your data before passing them to this
    2087       * method. In most cases this is not an issue at all so we do not clone by default for performance
    2088       * and memory consumption reasons.
    2089       *
    2090       * @param html_table $table data to be rendered
    2091       * @return string HTML code
    2092       */
    2093      public static function table(html_table $table) {
    2094          // prepare table data and populate missing properties with reasonable defaults
    2095          if (!empty($table->align)) {
    2096              foreach ($table->align as $key => $aa) {
    2097                  if ($aa) {
    2098                      $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';';  // Fix for RTL languages
    2099                  } else {
    2100                      $table->align[$key] = null;
    2101                  }
    2102              }
    2103          }
    2104          if (!empty($table->size)) {
    2105              foreach ($table->size as $key => $ss) {
    2106                  if ($ss) {
    2107                      $table->size[$key] = 'width:'. $ss .';';
    2108                  } else {
    2109                      $table->size[$key] = null;
    2110                  }
    2111              }
    2112          }
    2113          if (!empty($table->wrap)) {
    2114              foreach ($table->wrap as $key => $ww) {
    2115                  if ($ww) {
    2116                      $table->wrap[$key] = 'white-space:nowrap;';
    2117                  } else {
    2118                      $table->wrap[$key] = '';
    2119                  }
    2120              }
    2121          }
    2122          if (!empty($table->head)) {
    2123              foreach ($table->head as $key => $val) {
    2124                  if (!isset($table->align[$key])) {
    2125                      $table->align[$key] = null;
    2126                  }
    2127                  if (!isset($table->size[$key])) {
    2128                      $table->size[$key] = null;
    2129                  }
    2130                  if (!isset($table->wrap[$key])) {
    2131                      $table->wrap[$key] = null;
    2132                  }
    2133  
    2134              }
    2135          }
    2136          if (empty($table->attributes['class'])) {
    2137              $table->attributes['class'] = 'generaltable';
    2138          }
    2139          if (!empty($table->tablealign)) {
    2140              $table->attributes['class'] .= ' boxalign' . $table->tablealign;
    2141          }
    2142  
    2143          // explicitly assigned properties override those defined via $table->attributes
    2144          $table->attributes['class'] = trim($table->attributes['class']);
    2145          $attributes = array_merge($table->attributes, array(
    2146                  'id'            => $table->id,
    2147                  'width'         => $table->width,
    2148                  'summary'       => $table->summary,
    2149                  'cellpadding'   => $table->cellpadding,
    2150                  'cellspacing'   => $table->cellspacing,
    2151              ));
    2152          $output = html_writer::start_tag('table', $attributes) . "\n";
    2153  
    2154          $countcols = 0;
    2155  
    2156          // Output a caption if present.
    2157          if (!empty($table->caption)) {
    2158              $captionattributes = array();
    2159              if ($table->captionhide) {
    2160                  $captionattributes['class'] = 'accesshide';
    2161              }
    2162              $output .= html_writer::tag(
    2163                  'caption',
    2164                  $table->caption,
    2165                  $captionattributes
    2166              );
    2167          }
    2168  
    2169          if (!empty($table->head)) {
    2170              $countcols = count($table->head);
    2171  
    2172              $output .= html_writer::start_tag('thead', array()) . "\n";
    2173              $output .= html_writer::start_tag('tr', array()) . "\n";
    2174              $keys = array_keys($table->head);
    2175              $lastkey = end($keys);
    2176  
    2177              foreach ($table->head as $key => $heading) {
    2178                  // Convert plain string headings into html_table_cell objects
    2179                  if (!($heading instanceof html_table_cell)) {
    2180                      $headingtext = $heading;
    2181                      $heading = new html_table_cell();
    2182                      $heading->text = $headingtext;
    2183                      $heading->header = true;
    2184                  }
    2185  
    2186                  if ($heading->header !== false) {
    2187                      $heading->header = true;
    2188                  }
    2189  
    2190                  $tagtype = 'td';
    2191                  if ($heading->header && (string)$heading->text != '') {
    2192                      $tagtype = 'th';
    2193                  }
    2194  
    2195                  $heading->attributes['class'] .= ' header c' . $key;
    2196                  if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
    2197                      $heading->colspan = $table->headspan[$key];
    2198                      $countcols += $table->headspan[$key] - 1;
    2199                  }
    2200  
    2201                  if ($key == $lastkey) {
    2202                      $heading->attributes['class'] .= ' lastcol';
    2203                  }
    2204                  if (isset($table->colclasses[$key])) {
    2205                      $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
    2206                  }
    2207                  $heading->attributes['class'] = trim($heading->attributes['class']);
    2208                  $attributes = array_merge($heading->attributes, [
    2209                      'style'     => $table->align[$key] . $table->size[$key] . $heading->style,
    2210                      'colspan'   => $heading->colspan,
    2211                  ]);
    2212  
    2213                  if ($tagtype == 'th') {
    2214                      $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
    2215                  }
    2216  
    2217                  $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
    2218              }
    2219              $output .= html_writer::end_tag('tr') . "\n";
    2220              $output .= html_writer::end_tag('thead') . "\n";
    2221  
    2222              if (empty($table->data)) {
    2223                  // For valid XHTML strict every table must contain either a valid tr
    2224                  // or a valid tbody... both of which must contain a valid td
    2225                  $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
    2226                  $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
    2227                  $output .= html_writer::end_tag('tbody');
    2228              }
    2229          }
    2230  
    2231          if (!empty($table->data)) {
    2232              $keys       = array_keys($table->data);
    2233              $lastrowkey = end($keys);
    2234              $output .= html_writer::start_tag('tbody', array());
    2235  
    2236              foreach ($table->data as $key => $row) {
    2237                  if (($row === 'hr') && ($countcols)) {
    2238                      $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
    2239                  } else {
    2240                      // Convert array rows to html_table_rows and cell strings to html_table_cell objects
    2241                      if (!($row instanceof html_table_row)) {
    2242                          $newrow = new html_table_row();
    2243  
    2244                          foreach ($row as $cell) {
    2245                              if (!($cell instanceof html_table_cell)) {
    2246                                  $cell = new html_table_cell($cell);
    2247                              }
    2248                              $newrow->cells[] = $cell;
    2249                          }
    2250                          $row = $newrow;
    2251                      }
    2252  
    2253                      if (isset($table->rowclasses[$key])) {
    2254                          $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
    2255                      }
    2256  
    2257                      if ($key == $lastrowkey) {
    2258                          $row->attributes['class'] .= ' lastrow';
    2259                      }
    2260  
    2261                      // Explicitly assigned properties should override those defined in the attributes.
    2262                      $row->attributes['class'] = trim($row->attributes['class']);
    2263                      $trattributes = array_merge($row->attributes, array(
    2264                              'id'            => $row->id,
    2265                              'style'         => $row->style,
    2266                          ));
    2267                      $output .= html_writer::start_tag('tr', $trattributes) . "\n";
    2268                      $keys2 = array_keys($row->cells);
    2269                      $lastkey = end($keys2);
    2270  
    2271                      $gotlastkey = false; //flag for sanity checking
    2272                      foreach ($row->cells as $key => $cell) {
    2273                          if ($gotlastkey) {
    2274                              //This should never happen. Why do we have a cell after the last cell?
    2275                              mtrace("A cell with key ($key) was found after the last key ($lastkey)");
    2276                          }
    2277  
    2278                          if (!($cell instanceof html_table_cell)) {
    2279                              $mycell = new html_table_cell();
    2280                              $mycell->text = $cell;
    2281                              $cell = $mycell;
    2282                          }
    2283  
    2284                          if (($cell->header === true) && empty($cell->scope)) {
    2285                              $cell->scope = 'row';
    2286                          }
    2287  
    2288                          if (isset($table->colclasses[$key])) {
    2289                              $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
    2290                          }
    2291  
    2292                          $cell->attributes['class'] .= ' cell c' . $key;
    2293                          if ($key == $lastkey) {
    2294                              $cell->attributes['class'] .= ' lastcol';
    2295                              $gotlastkey = true;
    2296                          }
    2297                          $tdstyle = '';
    2298                          $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
    2299                          $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
    2300                          $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
    2301                          $cell->attributes['class'] = trim($cell->attributes['class']);
    2302                          $tdattributes = array_merge($cell->attributes, array(
    2303                                  'style' => $tdstyle . $cell->style,
    2304                                  'colspan' => $cell->colspan,
    2305                                  'rowspan' => $cell->rowspan,
    2306                                  'id' => $cell->id,
    2307                                  'abbr' => $cell->abbr,
    2308                                  'scope' => $cell->scope,
    2309                              ));
    2310                          $tagtype = 'td';
    2311                          if ($cell->header === true) {
    2312                              $tagtype = 'th';
    2313                          }
    2314                          $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
    2315                      }
    2316                  }
    2317                  $output .= html_writer::end_tag('tr') . "\n";
    2318              }
    2319              $output .= html_writer::end_tag('tbody') . "\n";
    2320          }
    2321          $output .= html_writer::end_tag('table') . "\n";
    2322  
    2323          return $output;
    2324      }
    2325  
    2326      /**
    2327       * Renders form element label
    2328       *
    2329       * By default, the label is suffixed with a label separator defined in the
    2330       * current language pack (colon by default in the English lang pack).
    2331       * Adding the colon can be explicitly disabled if needed. Label separators
    2332       * are put outside the label tag itself so they are not read by
    2333       * screenreaders (accessibility).
    2334       *
    2335       * Parameter $for explicitly associates the label with a form control. When
    2336       * set, the value of this attribute must be the same as the value of
    2337       * the id attribute of the form control in the same document. When null,
    2338       * the label being defined is associated with the control inside the label
    2339       * element.
    2340       *
    2341       * @param string $text content of the label tag
    2342       * @param string|null $for id of the element this label is associated with, null for no association
    2343       * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
    2344       * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
    2345       * @return string HTML of the label element
    2346       */
    2347      public static function label($text, $for, $colonize = true, array $attributes=array()) {
    2348          if (!is_null($for)) {
    2349              $attributes = array_merge($attributes, array('for' => $for));
    2350          }
    2351          $text = trim($text);
    2352          $label = self::tag('label', $text, $attributes);
    2353  
    2354          // TODO MDL-12192 $colonize disabled for now yet
    2355          // if (!empty($text) and $colonize) {
    2356          //     // the $text may end with the colon already, though it is bad string definition style
    2357          //     $colon = get_string('labelsep', 'langconfig');
    2358          //     if (!empty($colon)) {
    2359          //         $trimmed = trim($colon);
    2360          //         if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
    2361          //             //debugging('The label text should not end with colon or other label separator,
    2362          //             //           please fix the string definition.', DEBUG_DEVELOPER);
    2363          //         } else {
    2364          //             $label .= $colon;
    2365          //         }
    2366          //     }
    2367          // }
    2368  
    2369          return $label;
    2370      }
    2371  
    2372      /**
    2373       * Combines a class parameter with other attributes. Aids in code reduction
    2374       * because the class parameter is very frequently used.
    2375       *
    2376       * If the class attribute is specified both in the attributes and in the
    2377       * class parameter, the two values are combined with a space between.
    2378       *
    2379       * @param string $class Optional CSS class (or classes as space-separated list)
    2380       * @param array $attributes Optional other attributes as array
    2381       * @return array Attributes (or null if still none)
    2382       */
    2383      private static function add_class($class = '', array $attributes = null) {
    2384          if ($class !== '') {
    2385              $classattribute = array('class' => $class);
    2386              if ($attributes) {
    2387                  if (array_key_exists('class', $attributes)) {
    2388                      $attributes['class'] = trim($attributes['class'] . ' ' . $class);
    2389                  } else {
    2390                      $attributes = $classattribute + $attributes;
    2391                  }
    2392              } else {
    2393                  $attributes = $classattribute;
    2394              }
    2395          }
    2396          return $attributes;
    2397      }
    2398  
    2399      /**
    2400       * Creates a <div> tag. (Shortcut function.)
    2401       *
    2402       * @param string $content HTML content of tag
    2403       * @param string $class Optional CSS class (or classes as space-separated list)
    2404       * @param array $attributes Optional other attributes as array
    2405       * @return string HTML code for div
    2406       */
    2407      public static function div($content, $class = '', array $attributes = null) {
    2408          return self::tag('div', $content, self::add_class($class, $attributes));
    2409      }
    2410  
    2411      /**
    2412       * Starts a <div> tag. (Shortcut function.)
    2413       *
    2414       * @param string $class Optional CSS class (or classes as space-separated list)
    2415       * @param array $attributes Optional other attributes as array
    2416       * @return string HTML code for open div tag
    2417       */
    2418      public static function start_div($class = '', array $attributes = null) {
    2419          return self::start_tag('div', self::add_class($class, $attributes));
    2420      }
    2421  
    2422      /**
    2423       * Ends a <div> tag. (Shortcut function.)
    2424       *
    2425       * @return string HTML code for close div tag
    2426       */
    2427      public static function end_div() {
    2428          return self::end_tag('div');
    2429      }
    2430  
    2431      /**
    2432       * Creates a <span> tag. (Shortcut function.)
    2433       *
    2434       * @param string $content HTML content of tag
    2435       * @param string $class Optional CSS class (or classes as space-separated list)
    2436       * @param array $attributes Optional other attributes as array
    2437       * @return string HTML code for span
    2438       */
    2439      public static function span($content, $class = '', array $attributes = null) {
    2440          return self::tag('span', $content, self::add_class($class, $attributes));
    2441      }
    2442  
    2443      /**
    2444       * Starts a <span> tag. (Shortcut function.)
    2445       *
    2446       * @param string $class Optional CSS class (or classes as space-separated list)
    2447       * @param array $attributes Optional other attributes as array
    2448       * @return string HTML code for open span tag
    2449       */
    2450      public static function start_span($class = '', array $attributes = null) {
    2451          return self::start_tag('span', self::add_class($class, $attributes));
    2452      }
    2453  
    2454      /**
    2455       * Ends a <span> tag. (Shortcut function.)
    2456       *
    2457       * @return string HTML code for close span tag
    2458       */
    2459      public static function end_span() {
    2460          return self::end_tag('span');
    2461      }
    2462  }
    2463  
    2464  /**
    2465   * Simple javascript output class
    2466   *
    2467   * @copyright 2010 Petr Skoda
    2468   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2469   * @since Moodle 2.0
    2470   * @package core
    2471   * @category output
    2472   */
    2473  class js_writer {
    2474  
    2475      /**
    2476       * Returns javascript code calling the function
    2477       *
    2478       * @param string $function function name, can be complex like Y.Event.purgeElement
    2479       * @param array $arguments parameters
    2480       * @param int $delay execution delay in seconds
    2481       * @return string JS code fragment
    2482       */
    2483      public static function function_call($function, array $arguments = null, $delay=0) {
    2484          if ($arguments) {
    2485              $arguments = array_map('json_encode', convert_to_array($arguments));
    2486              $arguments = implode(', ', $arguments);
    2487          } else {
    2488              $arguments = '';
    2489          }
    2490          $js = "$function($arguments);";
    2491  
    2492          if ($delay) {
    2493              $delay = $delay * 1000; // in miliseconds
    2494              $js = "setTimeout(function() { $js }, $delay);";
    2495          }
    2496          return $js . "\n";
    2497      }
    2498  
    2499      /**
    2500       * Special function which adds Y as first argument of function call.
    2501       *
    2502       * @param string $function The function to call
    2503       * @param array $extraarguments Any arguments to pass to it
    2504       * @return string Some JS code
    2505       */
    2506      public static function function_call_with_Y($function, array $extraarguments = null) {
    2507          if ($extraarguments) {
    2508              $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
    2509              $arguments = 'Y, ' . implode(', ', $extraarguments);
    2510          } else {
    2511              $arguments = 'Y';
    2512          }
    2513          return "$function($arguments);\n";
    2514      }
    2515  
    2516      /**
    2517       * Returns JavaScript code to initialise a new object
    2518       *
    2519       * @param string $var If it is null then no var is assigned the new object.
    2520       * @param string $class The class to initialise an object for.
    2521       * @param array $arguments An array of args to pass to the init method.
    2522       * @param array $requirements Any modules required for this class.
    2523       * @param int $delay The delay before initialisation. 0 = no delay.
    2524       * @return string Some JS code
    2525       */
    2526      public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
    2527          if (is_array($arguments)) {
    2528              $arguments = array_map('json_encode', convert_to_array($arguments));
    2529              $arguments = implode(', ', $arguments);
    2530          }
    2531  
    2532          if ($var === null) {
    2533              $js = "new $class(Y, $arguments);";
    2534          } else if (strpos($var, '.')!==false) {
    2535              $js = "$var = new $class(Y, $arguments);";
    2536          } else {
    2537              $js = "var $var = new $class(Y, $arguments);";
    2538          }
    2539  
    2540          if ($delay) {
    2541              $delay = $delay * 1000; // in miliseconds
    2542              $js = "setTimeout(function() { $js }, $delay);";
    2543          }
    2544  
    2545          if (count($requirements) > 0) {
    2546              $requirements = implode("', '", $requirements);
    2547              $js = "Y.use('$requirements', function(Y){ $js });";
    2548          }
    2549          return $js."\n";
    2550      }
    2551  
    2552      /**
    2553       * Returns code setting value to variable
    2554       *
    2555       * @param string $name
    2556       * @param mixed $value json serialised value
    2557       * @param bool $usevar add var definition, ignored for nested properties
    2558       * @return string JS code fragment
    2559       */
    2560      public static function set_variable($name, $value, $usevar = true) {
    2561          $output = '';
    2562  
    2563          if ($usevar) {
    2564              if (strpos($name, '.')) {
    2565                  $output .= '';
    2566              } else {
    2567                  $output .= 'var ';
    2568              }
    2569          }
    2570  
    2571          $output .= "$name = ".json_encode($value).";";
    2572  
    2573          return $output;
    2574      }
    2575  
    2576      /**
    2577       * Writes event handler attaching code
    2578       *
    2579       * @param array|string $selector standard YUI selector for elements, may be
    2580       *     array or string, element id is in the form "#idvalue"
    2581       * @param string $event A valid DOM event (click, mousedown, change etc.)
    2582       * @param string $function The name of the function to call
    2583       * @param array $arguments An optional array of argument parameters to pass to the function
    2584       * @return string JS code fragment
    2585       */
    2586      public static function event_handler($selector, $event, $function, array $arguments = null) {
    2587          $selector = json_encode($selector);
    2588          $output = "Y.on('$event', $function, $selector, null";
    2589          if (!empty($arguments)) {
    2590              $output .= ', ' . json_encode($arguments);
    2591          }
    2592          return $output . ");\n";
    2593      }
    2594  }
    2595  
    2596  /**
    2597   * Holds all the information required to render a <table> by {@link core_renderer::table()}
    2598   *
    2599   * Example of usage:
    2600   * $t = new html_table();
    2601   * ... // set various properties of the object $t as described below
    2602   * echo html_writer::table($t);
    2603   *
    2604   * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
    2605   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2606   * @since Moodle 2.0
    2607   * @package core
    2608   * @category output
    2609   */
    2610  class html_table {
    2611  
    2612      /**
    2613       * @var string Value to use for the id attribute of the table
    2614       */
    2615      public $id = null;
    2616  
    2617      /**
    2618       * @var array Attributes of HTML attributes for the <table> element
    2619       */
    2620      public $attributes = array();
    2621  
    2622      /**
    2623       * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
    2624       * For more control over the rendering of the headers, an array of html_table_cell objects
    2625       * can be passed instead of an array of strings.
    2626       *
    2627       * Example of usage:
    2628       * $t->head = array('Student', 'Grade');
    2629       */
    2630      public $head;
    2631  
    2632      /**
    2633       * @var array An array that can be used to make a heading span multiple columns.
    2634       * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
    2635       * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
    2636       *
    2637       * Example of usage:
    2638       * $t->headspan = array(2,1);
    2639       */
    2640      public $headspan;
    2641  
    2642      /**
    2643       * @var array An array of column alignments.
    2644       * The value is used as CSS 'text-align' property. Therefore, possible
    2645       * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
    2646       * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
    2647       *
    2648       * Examples of usage:
    2649       * $t->align = array(null, 'right');
    2650       * or
    2651       * $t->align[1] = 'right';
    2652       */
    2653      public $align;
    2654  
    2655      /**
    2656       * @var array The value is used as CSS 'size' property.
    2657       *
    2658       * Examples of usage:
    2659       * $t->size = array('50%', '50%');
    2660       * or
    2661       * $t->size[1] = '120px';
    2662       */
    2663      public $size;
    2664  
    2665      /**
    2666       * @var array An array of wrapping information.
    2667       * The only possible value is 'nowrap' that sets the
    2668       * CSS property 'white-space' to the value 'nowrap' in the given column.
    2669       *
    2670       * Example of usage:
    2671       * $t->wrap = array(null, 'nowrap');
    2672       */
    2673      public $wrap;
    2674  
    2675      /**
    2676       * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
    2677       * $head specified, the string 'hr' (for horizontal ruler) can be used
    2678       * instead of an array of cells data resulting in a divider rendered.
    2679       *
    2680       * Example of usage with array of arrays:
    2681       * $row1 = array('Harry Potter', '76 %');
    2682       * $row2 = array('Hermione Granger', '100 %');
    2683       * $t->data = array($row1, $row2);
    2684       *
    2685       * Example with array of html_table_row objects: (used for more fine-grained control)
    2686       * $cell1 = new html_table_cell();
    2687       * $cell1->text = 'Harry Potter';
    2688       * $cell1->colspan = 2;
    2689       * $row1 = new html_table_row();
    2690       * $row1->cells[] = $cell1;
    2691       * $cell2 = new html_table_cell();
    2692       * $cell2->text = 'Hermione Granger';
    2693       * $cell3 = new html_table_cell();
    2694       * $cell3->text = '100 %';
    2695       * $row2 = new html_table_row();
    2696       * $row2->cells = array($cell2, $cell3);
    2697       * $t->data = array($row1, $row2);
    2698       */
    2699      public $data = [];
    2700  
    2701      /**
    2702       * @deprecated since Moodle 2.0. Styling should be in the CSS.
    2703       * @var string Width of the table, percentage of the page preferred.
    2704       */
    2705      public $width = null;
    2706  
    2707      /**
    2708       * @deprecated since Moodle 2.0. Styling should be in the CSS.
    2709       * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
    2710       */
    2711      public $tablealign = null;
    2712  
    2713      /**
    2714       * @deprecated since Moodle 2.0. Styling should be in the CSS.
    2715       * @var int Padding on each cell, in pixels
    2716       */
    2717      public $cellpadding = null;
    2718  
    2719      /**
    2720       * @var int Spacing between cells, in pixels
    2721       * @deprecated since Moodle 2.0. Styling should be in the CSS.
    2722       */
    2723      public $cellspacing = null;
    2724  
    2725      /**
    2726       * @var array Array of classes to add to particular rows, space-separated string.
    2727       * Class 'lastrow' is added automatically for the last row in the table.
    2728       *
    2729       * Example of usage:
    2730       * $t->rowclasses[9] = 'tenth'
    2731       */
    2732      public $rowclasses;
    2733  
    2734      /**
    2735       * @var array An array of classes to add to every cell in a particular column,
    2736       * space-separated string. Class 'cell' is added automatically by the renderer.
    2737       * Classes 'c0' or 'c1' are added automatically for every odd or even column,
    2738       * respectively. Class 'lastcol' is added automatically for all last cells
    2739       * in a row.
    2740       *
    2741       * Example of usage:
    2742       * $t->colclasses = array(null, 'grade');
    2743       */
    2744      public $colclasses;
    2745  
    2746      /**
    2747       * @var string Description of the contents for screen readers.
    2748       *
    2749       * The "summary" attribute on the "table" element is not supported in HTML5.
    2750       * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
    2751       * or, simplify the structure of the table so that no description is needed.
    2752       *
    2753       * @deprecated since Moodle 3.9.
    2754       */
    2755      public $summary;
    2756  
    2757      /**
    2758       * @var string Caption for the table, typically a title.
    2759       *
    2760       * Example of usage:
    2761       * $t->caption = "TV Guide";
    2762       */
    2763      public $caption;
    2764  
    2765      /**
    2766       * @var bool Whether to hide the table's caption from sighted users.
    2767       *
    2768       * Example of usage:
    2769       * $t->caption = "TV Guide";
    2770       * $t->captionhide = true;
    2771       */
    2772      public $captionhide = false;
    2773  
    2774      /**
    2775       * Constructor
    2776       */
    2777      public function __construct() {
    2778          $this->attributes['class'] = '';
    2779      }
    2780  }
    2781  
    2782  /**
    2783   * Component representing a table row.
    2784   *
    2785   * @copyright 2009 Nicolas Connault
    2786   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2787   * @since Moodle 2.0
    2788   * @package core
    2789   * @category output
    2790   */
    2791  class html_table_row {
    2792  
    2793      /**
    2794       * @var string Value to use for the id attribute of the row.
    2795       */
    2796      public $id = null;
    2797  
    2798      /**
    2799       * @var array Array of html_table_cell objects
    2800       */
    2801      public $cells = array();
    2802  
    2803      /**
    2804       * @var string Value to use for the style attribute of the table row
    2805       */
    2806      public $style = null;
    2807  
    2808      /**
    2809       * @var array Attributes of additional HTML attributes for the <tr> element
    2810       */
    2811      public $attributes = array();
    2812  
    2813      /**
    2814       * Constructor
    2815       * @param array $cells
    2816       */
    2817      public function __construct(array $cells=null) {
    2818          $this->attributes['class'] = '';
    2819          $cells = (array)$cells;
    2820          foreach ($cells as $cell) {
    2821              if ($cell instanceof html_table_cell) {
    2822                  $this->cells[] = $cell;
    2823              } else {
    2824                  $this->cells[] = new html_table_cell($cell);
    2825              }
    2826          }
    2827      }
    2828  }
    2829  
    2830  /**
    2831   * Component representing a table cell.
    2832   *
    2833   * @copyright 2009 Nicolas Connault
    2834   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2835   * @since Moodle 2.0
    2836   * @package core
    2837   * @category output
    2838   */
    2839  class html_table_cell {
    2840  
    2841      /**
    2842       * @var string Value to use for the id attribute of the cell.
    2843       */
    2844      public $id = null;
    2845  
    2846      /**
    2847       * @var string The contents of the cell.
    2848       */
    2849      public $text;
    2850  
    2851      /**
    2852       * @var string Abbreviated version of the contents of the cell.
    2853       */
    2854      public $abbr = null;
    2855  
    2856      /**
    2857       * @var int Number of columns this cell should span.
    2858       */
    2859      public $colspan = null;
    2860  
    2861      /**
    2862       * @var int Number of rows this cell should span.
    2863       */
    2864      public $rowspan = null;
    2865  
    2866      /**
    2867       * @var string Defines a way to associate header cells and data cells in a table.
    2868       */
    2869      public $scope = null;
    2870  
    2871      /**
    2872       * @var bool Whether or not this cell is a header cell.
    2873       */
    2874      public $header = null;
    2875  
    2876      /**
    2877       * @var string Value to use for the style attribute of the table cell
    2878       */
    2879      public $style = null;
    2880  
    2881      /**
    2882       * @var array Attributes of additional HTML attributes for the <td> element
    2883       */
    2884      public $attributes = array();
    2885  
    2886      /**
    2887       * Constructs a table cell
    2888       *
    2889       * @param string $text
    2890       */
    2891      public function __construct($text = null) {
    2892          $this->text = $text;
    2893          $this->attributes['class'] = '';
    2894      }
    2895  }
    2896  
    2897  /**
    2898   * Component representing a paging bar.
    2899   *
    2900   * @copyright 2009 Nicolas Connault
    2901   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2902   * @since Moodle 2.0
    2903   * @package core
    2904   * @category output
    2905   */
    2906  class paging_bar implements renderable, templatable {
    2907  
    2908      /**
    2909       * @var int The maximum number of pagelinks to display.
    2910       */
    2911      public $maxdisplay = 18;
    2912  
    2913      /**
    2914       * @var int The total number of entries to be pages through..
    2915       */
    2916      public $totalcount;
    2917  
    2918      /**
    2919       * @var int The page you are currently viewing.
    2920       */
    2921      public $page;
    2922  
    2923      /**
    2924       * @var int The number of entries that should be shown per page.
    2925       */
    2926      public $perpage;
    2927  
    2928      /**
    2929       * @var string|moodle_url If this  is a string then it is the url which will be appended with $pagevar,
    2930       * an equals sign and the page number.
    2931       * If this is a moodle_url object then the pagevar param will be replaced by
    2932       * the page no, for each page.
    2933       */
    2934      public $baseurl;
    2935  
    2936      /**
    2937       * @var string This is the variable name that you use for the pagenumber in your
    2938       * code (ie. 'tablepage', 'blogpage', etc)
    2939       */
    2940      public $pagevar;
    2941  
    2942      /**
    2943       * @var string A HTML link representing the "previous" page.
    2944       */
    2945      public $previouslink = null;
    2946  
    2947      /**
    2948       * @var string A HTML link representing the "next" page.
    2949       */
    2950      public $nextlink = null;
    2951  
    2952      /**
    2953       * @var string A HTML link representing the first page.
    2954       */
    2955      public $firstlink = null;
    2956  
    2957      /**
    2958       * @var string A HTML link representing the last page.
    2959       */
    2960      public $lastlink = null;
    2961  
    2962      /**
    2963       * @var array An array of strings. One of them is just a string: the current page
    2964       */
    2965      public $pagelinks = array();
    2966  
    2967      /**
    2968       * Constructor paging_bar with only the required params.
    2969       *
    2970       * @param int $totalcount The total number of entries available to be paged through
    2971       * @param int $page The page you are currently viewing
    2972       * @param int $perpage The number of entries that should be shown per page
    2973       * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
    2974       * @param string $pagevar name of page parameter that holds the page number
    2975       */
    2976      public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
    2977          $this->totalcount = $totalcount;
    2978          $this->page       = $page;
    2979          $this->perpage    = $perpage;
    2980          $this->baseurl    = $baseurl;
    2981          $this->pagevar    = $pagevar;
    2982      }
    2983  
    2984      /**
    2985       * Prepares the paging bar for output.
    2986       *
    2987       * This method validates the arguments set up for the paging bar and then
    2988       * produces fragments of HTML to assist display later on.
    2989       *
    2990       * @param renderer_base $output
    2991       * @param moodle_page $page
    2992       * @param string $target
    2993       * @throws coding_exception
    2994       */
    2995      public function prepare(renderer_base $output, moodle_page $page, $target) {
    2996          if (!isset($this->totalcount) || is_null($this->totalcount)) {
    2997              throw new coding_exception('paging_bar requires a totalcount value.');
    2998          }
    2999          if (!isset($this->page) || is_null($this->page)) {
    3000              throw new coding_exception('paging_bar requires a page value.');
    3001          }
    3002          if (empty($this->perpage)) {
    3003              throw new coding_exception('paging_bar requires a perpage value.');
    3004          }
    3005          if (empty($this->baseurl)) {
    3006              throw new coding_exception('paging_bar requires a baseurl value.');
    3007          }
    3008  
    3009          if ($this->totalcount > $this->perpage) {
    3010              $pagenum = $this->page - 1;
    3011  
    3012              if ($this->page > 0) {
    3013                  $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
    3014              }
    3015  
    3016              if ($this->perpage > 0) {
    3017                  $lastpage = ceil($this->totalcount / $this->perpage);
    3018              } else {
    3019                  $lastpage = 1;
    3020              }
    3021  
    3022              if ($this->page > round(($this->maxdisplay/3)*2)) {
    3023                  $currpage = $this->page - round($this->maxdisplay/3);
    3024  
    3025                  $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
    3026              } else {
    3027                  $currpage = 0;
    3028              }
    3029  
    3030              $displaycount = $displaypage = 0;
    3031  
    3032              while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
    3033                  $displaypage = $currpage + 1;
    3034  
    3035                  if ($this->page == $currpage) {
    3036                      $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
    3037                  } else {
    3038                      $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
    3039                      $this->pagelinks[] = $pagelink;
    3040                  }
    3041  
    3042                  $displaycount++;
    3043                  $currpage++;
    3044              }
    3045  
    3046              if ($currpage < $lastpage) {
    3047                  $lastpageactual = $lastpage - 1;
    3048                  $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
    3049              }
    3050  
    3051              $pagenum = $this->page + 1;
    3052  
    3053              if ($pagenum != $lastpage) {
    3054                  $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
    3055              }
    3056          }
    3057      }
    3058  
    3059      /**
    3060       * Export for template.
    3061       *
    3062       * @param renderer_base $output The renderer.
    3063       * @return stdClass
    3064       */
    3065      public function export_for_template(renderer_base $output) {
    3066          $data = new stdClass();
    3067          $data->previous = null;
    3068          $data->next = null;
    3069          $data->first = null;
    3070          $data->last = null;
    3071          $data->label = get_string('page');
    3072          $data->pages = [];
    3073          $data->haspages = $this->totalcount > $this->perpage;
    3074          $data->pagesize = $this->perpage;
    3075  
    3076          if (!$data->haspages) {
    3077              return $data;
    3078          }
    3079  
    3080          if ($this->page > 0) {
    3081              $data->previous = [
    3082                  'page' => $this->page,
    3083                  'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
    3084              ];
    3085          }
    3086  
    3087          $currpage = 0;
    3088          if ($this->page > round(($this->maxdisplay / 3) * 2)) {
    3089              $currpage = $this->page - round($this->maxdisplay / 3);
    3090              $data->first = [
    3091                  'page' => 1,
    3092                  'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
    3093              ];
    3094          }
    3095  
    3096          $lastpage = 1;
    3097          if ($this->perpage > 0) {
    3098              $lastpage = ceil($this->totalcount / $this->perpage);
    3099          }
    3100  
    3101          $displaycount = 0;
    3102          $displaypage = 0;
    3103          while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
    3104              $displaypage = $currpage + 1;
    3105  
    3106              $iscurrent = $this->page == $currpage;
    3107              $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
    3108  
    3109              $data->pages[] = [
    3110                  'page' => $displaypage,
    3111                  'active' => $iscurrent,
    3112                  'url' => $iscurrent ? null : $link->out(false)
    3113              ];
    3114  
    3115              $displaycount++;
    3116              $currpage++;
    3117          }
    3118  
    3119          if ($currpage < $lastpage) {
    3120              $data->last = [
    3121                  'page' => $lastpage,
    3122                  'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
    3123              ];
    3124          }
    3125  
    3126          if ($this->page + 1 != $lastpage) {
    3127              $data->next = [
    3128                  'page' => $this->page + 2,
    3129                  'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
    3130              ];
    3131          }
    3132  
    3133          return $data;
    3134      }
    3135  }
    3136  
    3137  /**
    3138   * Component representing initials bar.
    3139   *
    3140   * @copyright 2017 Ilya Tregubov
    3141   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3142   * @since Moodle 3.3
    3143   * @package core
    3144   * @category output
    3145   */
    3146  class initials_bar implements renderable, templatable {
    3147  
    3148      /**
    3149       * @var string Currently selected letter.
    3150       */
    3151      public $current;
    3152  
    3153      /**
    3154       * @var string Class name to add to this initial bar.
    3155       */
    3156      public $class;
    3157  
    3158      /**
    3159       * @var string The name to put in front of this initial bar.
    3160       */
    3161      public $title;
    3162  
    3163      /**
    3164       * @var string URL parameter name for this initial.
    3165       */
    3166      public $urlvar;
    3167  
    3168      /**
    3169       * @var string URL object.
    3170       */
    3171      public $url;
    3172  
    3173      /**
    3174       * @var array An array of letters in the alphabet.
    3175       */
    3176      public $alpha;
    3177  
    3178      /**
    3179       * Constructor initials_bar with only the required params.
    3180       *
    3181       * @param string $current the currently selected letter.
    3182       * @param string $class class name to add to this initial bar.
    3183       * @param string $title the name to put in front of this initial bar.
    3184       * @param string $urlvar URL parameter name for this initial.
    3185       * @param string $url URL object.
    3186       * @param array $alpha of letters in the alphabet.
    3187       */
    3188      public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
    3189          $this->current       = $current;
    3190          $this->class    = $class;
    3191          $this->title    = $title;
    3192          $this->urlvar    = $urlvar;
    3193          $this->url    = $url;
    3194          $this->alpha    = $alpha;
    3195      }
    3196  
    3197      /**
    3198       * Export for template.
    3199       *
    3200       * @param renderer_base $output The renderer.
    3201       * @return stdClass
    3202       */
    3203      public function export_for_template(renderer_base $output) {
    3204          $data = new stdClass();
    3205  
    3206          if ($this->alpha == null) {
    3207              $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
    3208          }
    3209  
    3210          if ($this->current == 'all') {
    3211              $this->current = '';
    3212          }
    3213  
    3214          // We want to find a letter grouping size which suits the language so
    3215          // find the largest group size which is less than 15 chars.
    3216          // The choice of 15 chars is the largest number of chars that reasonably
    3217          // fits on the smallest supported screen size. By always using a max number
    3218          // of groups which is a factor of 2, we always get nice wrapping, and the
    3219          // last row is always the shortest.
    3220          $groupsize = count($this->alpha);
    3221          $groups = 1;
    3222          while ($groupsize > 15) {
    3223              $groups *= 2;
    3224              $groupsize = ceil(count($this->alpha) / $groups);
    3225          }
    3226  
    3227          $groupsizelimit = 0;
    3228          $groupnumber = 0;
    3229          foreach ($this->alpha as $letter) {
    3230              if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
    3231                  $groupnumber++;
    3232              }
    3233              $groupletter = new stdClass();
    3234              $groupletter->name = $letter;
    3235              $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
    3236              if ($letter == $this->current) {
    3237                  $groupletter->selected = $this->current;
    3238              }
    3239              if (!isset($data->group[$groupnumber])) {
    3240                  $data->group[$groupnumber] = new stdClass();
    3241              }
    3242              $data->group[$groupnumber]->letter[] = $groupletter;
    3243          }
    3244  
    3245          $data->class = $this->class;
    3246          $data->title = $this->title;
    3247          $data->url = $this->url->out(false, array($this->urlvar => ''));
    3248          $data->current = $this->current;
    3249          $data->all = get_string('all');
    3250  
    3251          return $data;
    3252      }
    3253  }
    3254  
    3255  /**
    3256   * This class represents how a block appears on a page.
    3257   *
    3258   * During output, each block instance is asked to return a block_contents object,
    3259   * those are then passed to the $OUTPUT->block function for display.
    3260   *
    3261   * contents should probably be generated using a moodle_block_..._renderer.
    3262   *
    3263   * Other block-like things that need to appear on the page, for example the
    3264   * add new block UI, are also represented as block_contents objects.
    3265   *
    3266   * @copyright 2009 Tim Hunt
    3267   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3268   * @since Moodle 2.0
    3269   * @package core
    3270   * @category output
    3271   */
    3272  class block_contents {
    3273  
    3274      /** Used when the block cannot be collapsed **/
    3275      const NOT_HIDEABLE = 0;
    3276  
    3277      /** Used when the block can be collapsed but currently is not **/
    3278      const VISIBLE = 1;
    3279  
    3280      /** Used when the block has been collapsed **/
    3281      const HIDDEN = 2;
    3282  
    3283      /**
    3284       * @var int Used to set $skipid.
    3285       */
    3286      protected static $idcounter = 1;
    3287  
    3288      /**
    3289       * @var int All the blocks (or things that look like blocks) printed on
    3290       * a page are given a unique number that can be used to construct id="" attributes.
    3291       * This is set automatically be the {@link prepare()} method.
    3292       * Do not try to set it manually.
    3293       */
    3294      public $skipid;
    3295  
    3296      /**
    3297       * @var int If this is the contents of a real block, this should be set
    3298       * to the block_instance.id. Otherwise this should be set to 0.
    3299       */
    3300      public $blockinstanceid = 0;
    3301  
    3302      /**
    3303       * @var int If this is a real block instance, and there is a corresponding
    3304       * block_position.id for the block on this page, this should be set to that id.
    3305       * Otherwise it should be 0.
    3306       */
    3307      public $blockpositionid = 0;
    3308  
    3309      /**
    3310       * @var array An array of attribute => value pairs that are put on the outer div of this
    3311       * block. {@link $id} and {@link $classes} attributes should be set separately.
    3312       */
    3313      public $attributes;
    3314  
    3315      /**
    3316       * @var string The title of this block. If this came from user input, it should already
    3317       * have had format_string() processing done on it. This will be output inside
    3318       * <h2> tags. Please do not cause invalid XHTML.
    3319       */
    3320      public $title = '';
    3321  
    3322      /**
    3323       * @var string The label to use when the block does not, or will not have a visible title.
    3324       * You should never set this as well as title... it will just be ignored.
    3325       */
    3326      public $arialabel = '';
    3327  
    3328      /**
    3329       * @var string HTML for the content
    3330       */
    3331      public $content = '';
    3332  
    3333      /**
    3334       * @var array An alternative to $content, it you want a list of things with optional icons.
    3335       */
    3336      public $footer = '';
    3337  
    3338      /**
    3339       * @var string Any small print that should appear under the block to explain
    3340       * to the teacher about the block, for example 'This is a sticky block that was
    3341       * added in the system context.'
    3342       */
    3343      public $annotation = '';
    3344  
    3345      /**
    3346       * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
    3347       * the user can toggle whether this block is visible.
    3348       */
    3349      public $collapsible = self::NOT_HIDEABLE;
    3350  
    3351      /**
    3352       * Set this to true if the block is dockable.
    3353       * @var bool
    3354       */
    3355      public $dockable = false;
    3356  
    3357      /**
    3358       * @var array A (possibly empty) array of editing controls. Each element of
    3359       * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
    3360       * $icon is the icon name. Fed to $OUTPUT->image_url.
    3361       */
    3362      public $controls = array();
    3363  
    3364  
    3365      /**
    3366       * Create new instance of block content
    3367       * @param array $attributes
    3368       */
    3369      public function __construct(array $attributes = null) {
    3370          $this->skipid = self::$idcounter;
    3371          self::$idcounter += 1;
    3372  
    3373          if ($attributes) {
    3374              // standard block
    3375              $this->attributes = $attributes;
    3376          } else {
    3377              // simple "fake" blocks used in some modules and "Add new block" block
    3378              $this->attributes = array('class'=>'block');
    3379          }
    3380      }
    3381  
    3382      /**
    3383       * Add html class to block
    3384       *
    3385       * @param string $class
    3386       */
    3387      public function add_class($class) {
    3388          $this->attributes['class'] .= ' '.$class;
    3389      }
    3390  
    3391      /**
    3392       * Check if the block is a fake block.
    3393       *
    3394       * @return boolean
    3395       */
    3396      public function is_fake() {
    3397          return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
    3398      }
    3399  }
    3400  
    3401  
    3402  /**
    3403   * This class represents a target for where a block can go when it is being moved.
    3404   *
    3405   * This needs to be rendered as a form with the given hidden from fields, and
    3406   * clicking anywhere in the form should submit it. The form action should be
    3407   * $PAGE->url.
    3408   *
    3409   * @copyright 2009 Tim Hunt
    3410   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3411   * @since Moodle 2.0
    3412   * @package core
    3413   * @category output
    3414   */
    3415  class block_move_target {
    3416  
    3417      /**
    3418       * @var moodle_url Move url
    3419       */
    3420      public $url;
    3421  
    3422      /**
    3423       * Constructor
    3424       * @param moodle_url $url
    3425       */
    3426      public function __construct(moodle_url $url) {
    3427          $this->url  = $url;
    3428      }
    3429  }
    3430  
    3431  /**
    3432   * Custom menu item
    3433   *
    3434   * This class is used to represent one item within a custom menu that may or may
    3435   * not have children.
    3436   *
    3437   * @copyright 2010 Sam Hemelryk
    3438   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3439   * @since Moodle 2.0
    3440   * @package core
    3441   * @category output
    3442   */
    3443  class custom_menu_item implements renderable, templatable {
    3444  
    3445      /**
    3446       * @var string The text to show for the item
    3447       */
    3448      protected $text;
    3449  
    3450      /**
    3451       * @var moodle_url The link to give the icon if it has no children
    3452       */
    3453      protected $url;
    3454  
    3455      /**
    3456       * @var string A title to apply to the item. By default the text
    3457       */
    3458      protected $title;
    3459  
    3460      /**
    3461       * @var int A sort order for the item, not necessary if you order things in
    3462       * the CFG var.
    3463       */
    3464      protected $sort;
    3465  
    3466      /**
    3467       * @var custom_menu_item A reference to the parent for this item or NULL if
    3468       * it is a top level item
    3469       */
    3470      protected $parent;
    3471  
    3472      /**
    3473       * @var array A array in which to store children this item has.
    3474       */
    3475      protected $children = array();
    3476  
    3477      /**
    3478       * @var int A reference to the sort var of the last child that was added
    3479       */
    3480      protected $lastsort = 0;
    3481  
    3482      /**
    3483       * Constructs the new custom menu item
    3484       *
    3485       * @param string $text
    3486       * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
    3487       * @param string $title A title to apply to this item [Optional]
    3488       * @param int $sort A sort or to use if we need to sort differently [Optional]
    3489       * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
    3490       *        belongs to, only if the child has a parent. [Optional]
    3491       */
    3492      public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
    3493          $this->text = $text;
    3494          $this->url = $url;
    3495          $this->title = $title;
    3496          $this->sort = (int)$sort;
    3497          $this->parent = $parent;
    3498      }
    3499  
    3500      /**
    3501       * Adds a custom menu item as a child of this node given its properties.
    3502       *
    3503       * @param string $text
    3504       * @param moodle_url $url
    3505       * @param string $title
    3506       * @param int $sort
    3507       * @return custom_menu_item
    3508       */
    3509      public function add($text, moodle_url $url = null, $title = null, $sort = null) {
    3510          $key = count($this->children);
    3511          if (empty($sort)) {
    3512              $sort = $this->lastsort + 1;
    3513          }
    3514          $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
    3515          $this->lastsort = (int)$sort;
    3516          return $this->children[$key];
    3517      }
    3518  
    3519      /**
    3520       * Removes a custom menu item that is a child or descendant to the current menu.
    3521       *
    3522       * Returns true if child was found and removed.
    3523       *
    3524       * @param custom_menu_item $menuitem
    3525       * @return bool
    3526       */
    3527      public function remove_child(custom_menu_item $menuitem) {
    3528          $removed = false;
    3529          if (($key = array_search($menuitem, $this->children)) !== false) {
    3530              unset($this->children[$key]);
    3531              $this->children = array_values($this->children);
    3532              $removed = true;
    3533          } else {
    3534              foreach ($this->children as $child) {
    3535                  if ($removed = $child->remove_child($menuitem)) {
    3536                      break;
    3537                  }
    3538              }
    3539          }
    3540          return $removed;
    3541      }
    3542  
    3543      /**
    3544       * Returns the text for this item
    3545       * @return string
    3546       */
    3547      public function get_text() {
    3548          return $this->text;
    3549      }
    3550  
    3551      /**
    3552       * Returns the url for this item
    3553       * @return moodle_url
    3554       */
    3555      public function get_url() {
    3556          return $this->url;
    3557      }
    3558  
    3559      /**
    3560       * Returns the title for this item
    3561       * @return string
    3562       */
    3563      public function get_title() {
    3564          return $this->title;
    3565      }
    3566  
    3567      /**
    3568       * Sorts and returns the children for this item
    3569       * @return array
    3570       */
    3571      public function get_children() {
    3572          $this->sort();
    3573          return $this->children;
    3574      }
    3575  
    3576      /**
    3577       * Gets the sort order for this child
    3578       * @return int
    3579       */
    3580      public function get_sort_order() {
    3581          return $this->sort;
    3582      }
    3583  
    3584      /**
    3585       * Gets the parent this child belong to
    3586       * @return custom_menu_item
    3587       */
    3588      public function get_parent() {
    3589          return $this->parent;
    3590      }
    3591  
    3592      /**
    3593       * Sorts the children this item has
    3594       */
    3595      public function sort() {
    3596          usort($this->children, array('custom_menu','sort_custom_menu_items'));
    3597      }
    3598  
    3599      /**
    3600       * Returns true if this item has any children
    3601       * @return bool
    3602       */
    3603      public function has_children() {
    3604          return (count($this->children) > 0);
    3605      }
    3606  
    3607      /**
    3608       * Sets the text for the node
    3609       * @param string $text
    3610       */
    3611      public function set_text($text) {
    3612          $this->text = (string)$text;
    3613      }
    3614  
    3615      /**
    3616       * Sets the title for the node
    3617       * @param string $title
    3618       */
    3619      public function set_title($title) {
    3620          $this->title = (string)$title;
    3621      }
    3622  
    3623      /**
    3624       * Sets the url for the node
    3625       * @param moodle_url $url
    3626       */
    3627      public function set_url(moodle_url $url) {
    3628          $this->url = $url;
    3629      }
    3630  
    3631      /**
    3632       * Export this data so it can be used as the context for a mustache template.
    3633       *
    3634       * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
    3635       * @return array
    3636       */
    3637      public function export_for_template(renderer_base $output) {
    3638          global $CFG;
    3639  
    3640          require_once($CFG->libdir . '/externallib.php');
    3641  
    3642          $syscontext = context_system::instance();
    3643  
    3644          $context = new stdClass();
    3645          $context->text = external_format_string($this->text, $syscontext->id);
    3646          $context->url = $this->url ? $this->url->out() : null;
    3647          $context->title = external_format_string($this->title, $syscontext->id);
    3648          $context->sort = $this->sort;
    3649          $context->children = array();
    3650          if (preg_match("/^#+$/", $this->text)) {
    3651              $context->divider = true;
    3652          }
    3653          $context->haschildren = !empty($this->children) && (count($this->children) > 0);
    3654          foreach ($this->children as $child) {
    3655              $child = $child->export_for_template($output);
    3656              array_push($context->children, $child);
    3657          }
    3658  
    3659          return $context;
    3660      }
    3661  }
    3662  
    3663  /**
    3664   * Custom menu class
    3665   *
    3666   * This class is used to operate a custom menu that can be rendered for the page.
    3667   * The custom menu is built using $CFG->custommenuitems and is a structured collection
    3668   * of custom_menu_item nodes that can be rendered by the core renderer.
    3669   *
    3670   * To configure the custom menu:
    3671   *     Settings: Administration > Appearance > Themes > Theme settings
    3672   *
    3673   * @copyright 2010 Sam Hemelryk
    3674   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3675   * @since Moodle 2.0
    3676   * @package core
    3677   * @category output
    3678   */
    3679  class custom_menu extends custom_menu_item {
    3680  
    3681      /**
    3682       * @var string The language we should render for, null disables multilang support.
    3683       */
    3684      protected $currentlanguage = null;
    3685  
    3686      /**
    3687       * Creates the custom menu
    3688       *
    3689       * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
    3690       * @param string $currentlanguage the current language code, null disables multilang support
    3691       */
    3692      public function __construct($definition = '', $currentlanguage = null) {
    3693          $this->currentlanguage = $currentlanguage;
    3694          parent::__construct('root'); // create virtual root element of the menu
    3695          if (!empty($definition)) {
    3696              $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
    3697          }
    3698      }
    3699  
    3700      /**
    3701       * Overrides the children of this custom menu. Useful when getting children
    3702       * from $CFG->custommenuitems
    3703       *
    3704       * @param array $children
    3705       */
    3706      public function override_children(array $children) {
    3707          $this->children = array();
    3708          foreach ($children as $child) {
    3709              if ($child instanceof custom_menu_item) {
    3710                  $this->children[] = $child;
    3711              }
    3712          }
    3713      }
    3714  
    3715      /**
    3716       * Converts a string into a structured array of custom_menu_items which can
    3717       * then be added to a custom menu.
    3718       *
    3719       * Structure:
    3720       *     text|url|title|langs
    3721       * The number of hyphens at the start determines the depth of the item. The
    3722       * languages are optional, comma separated list of languages the line is for.
    3723       *
    3724       * Example structure:
    3725       *     First level first item|http://www.moodle.com/
    3726       *     -Second level first item|http://www.moodle.com/partners/
    3727       *     -Second level second item|http://www.moodle.com/hq/
    3728       *     --Third level first item|http://www.moodle.com/jobs/
    3729       *     -Second level third item|http://www.moodle.com/development/
    3730       *     First level second item|http://www.moodle.com/feedback/
    3731       *     First level third item
    3732       *     English only|http://moodle.com|English only item|en
    3733       *     German only|http://moodle.de|Deutsch|de,de_du,de_kids
    3734       *
    3735       *
    3736       * @static
    3737       * @param string $text the menu items definition
    3738       * @param string $language the language code, null disables multilang support
    3739       * @return array
    3740       */
    3741      public static function convert_text_to_menu_nodes($text, $language = null) {
    3742          $root = new custom_menu();
    3743          $lastitem = $root;
    3744          $lastdepth = 0;
    3745          $hiddenitems = array();
    3746          $lines = explode("\n", $text);
    3747          foreach ($lines as $linenumber => $line) {
    3748              $line = trim($line);
    3749              if (strlen($line) == 0) {
    3750                  continue;
    3751              }
    3752              // Parse item settings.
    3753              $itemtext = null;
    3754              $itemurl = null;
    3755              $itemtitle = null;
    3756              $itemvisible = true;
    3757              $settings = explode('|', $line);
    3758              foreach ($settings as $i => $setting) {
    3759                  $setting = trim($setting);
    3760                  if (!empty($setting)) {
    3761                      switch ($i) {
    3762                          case 0: // Menu text.
    3763                              $itemtext = ltrim($setting, '-');
    3764                              break;
    3765                          case 1: // URL.
    3766                              try {
    3767                                  $itemurl = new moodle_url($setting);
    3768                              } catch (moodle_exception $exception) {
    3769                                  // We're not actually worried about this, we don't want to mess up the display
    3770                                  // just for a wrongly entered URL.
    3771                                  $itemurl = null;
    3772                              }
    3773                              break;
    3774                          case 2: // Title attribute.
    3775                              $itemtitle = $setting;
    3776                              break;
    3777                          case 3: // Language.
    3778                              if (!empty($language)) {
    3779                                  $itemlanguages = array_map('trim', explode(',', $setting));
    3780                                  $itemvisible &= in_array($language, $itemlanguages);
    3781                              }
    3782                              break;
    3783                      }
    3784                  }
    3785              }
    3786              // Get depth of new item.
    3787              preg_match('/^(\-*)/', $line, $match);
    3788              $itemdepth = strlen($match[1]) + 1;
    3789              // Find parent item for new item.
    3790              while (($lastdepth - $itemdepth) >= 0) {
    3791                  $lastitem = $lastitem->get_parent();
    3792                  $lastdepth--;
    3793              }
    3794              $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
    3795              $lastdepth++;
    3796              if (!$itemvisible) {
    3797                  $hiddenitems[] = $lastitem;
    3798              }
    3799          }
    3800          foreach ($hiddenitems as $item) {
    3801              $item->parent->remove_child($item);
    3802          }
    3803          return $root->get_children();
    3804      }
    3805  
    3806      /**
    3807       * Sorts two custom menu items
    3808       *
    3809       * This function is designed to be used with the usort method
    3810       *     usort($this->children, array('custom_menu','sort_custom_menu_items'));
    3811       *
    3812       * @static
    3813       * @param custom_menu_item $itema
    3814       * @param custom_menu_item $itemb
    3815       * @return int
    3816       */
    3817      public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
    3818          $itema = $itema->get_sort_order();
    3819          $itemb = $itemb->get_sort_order();
    3820          if ($itema == $itemb) {
    3821              return 0;
    3822          }
    3823          return ($itema > $itemb) ? +1 : -1;
    3824      }
    3825  }
    3826  
    3827  /**
    3828   * Stores one tab
    3829   *
    3830   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3831   * @package core
    3832   */
    3833  class tabobject implements renderable, templatable {
    3834      /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
    3835      var $id;
    3836      /** @var moodle_url|string link */
    3837      var $link;
    3838      /** @var string text on the tab */
    3839      var $text;
    3840      /** @var string title under the link, by defaul equals to text */
    3841      var $title;
    3842      /** @var bool whether to display a link under the tab name when it's selected */
    3843      var $linkedwhenselected = false;
    3844      /** @var bool whether the tab is inactive */
    3845      var $inactive = false;
    3846      /** @var bool indicates that this tab's child is selected */
    3847      var $activated = false;
    3848      /** @var bool indicates that this tab is selected */
    3849      var $selected = false;
    3850      /** @var array stores children tabobjects */
    3851      var $subtree = array();
    3852      /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
    3853      var $level = 1;
    3854  
    3855      /**
    3856       * Constructor
    3857       *
    3858       * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
    3859       * @param string|moodle_url $link
    3860       * @param string $text text on the tab
    3861       * @param string $title title under the link, by defaul equals to text
    3862       * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
    3863       */
    3864      public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
    3865          $this->id = $id;
    3866          $this->link = $link;
    3867          $this->text = $text;
    3868          $this->title = $title ? $title : $text;
    3869          $this->linkedwhenselected = $linkedwhenselected;
    3870      }
    3871  
    3872      /**
    3873       * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
    3874       *
    3875       * @param string $selected the id of the selected tab (whatever row it's on),
    3876       *    if null marks all tabs as unselected
    3877       * @return bool whether this tab is selected or contains selected tab in its subtree
    3878       */
    3879      protected function set_selected($selected) {
    3880          if ((string)$selected === (string)$this->id) {
    3881              $this->selected = true;
    3882              // This tab is selected. No need to travel through subtree.
    3883              return true;
    3884          }
    3885          foreach ($this->subtree as $subitem) {
    3886              if ($subitem->set_selected($selected)) {
    3887                  // This tab has child that is selected. Mark it as activated. No need to check other children.
    3888                  $this->activated = true;
    3889                  return true;
    3890              }
    3891          }
    3892          return false;
    3893      }
    3894  
    3895      /**
    3896       * Travels through tree and finds a tab with specified id
    3897       *
    3898       * @param string $id
    3899       * @return tabtree|null
    3900       */
    3901      public function find($id) {
    3902          if ((string)$this->id === (string)$id) {
    3903              return $this;
    3904          }
    3905          foreach ($this->subtree as $tab) {
    3906              if ($obj = $tab->find($id)) {
    3907                  return $obj;
    3908              }
    3909          }
    3910          return null;
    3911      }
    3912  
    3913      /**
    3914       * Allows to mark each tab's level in the tree before rendering.
    3915       *
    3916       * @param int $level
    3917       */
    3918      protected function set_level($level) {
    3919          $this->level = $level;
    3920          foreach ($this->subtree as $tab) {
    3921              $tab->set_level($level + 1);
    3922          }
    3923      }
    3924  
    3925      /**
    3926       * Export for template.
    3927       *
    3928       * @param renderer_base $output Renderer.
    3929       * @return object
    3930       */
    3931      public function export_for_template(renderer_base $output) {
    3932          if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
    3933              $link = null;
    3934          } else {
    3935              $link = $this->link;
    3936          }
    3937          $active = $this->activated || $this->selected;
    3938  
    3939          return (object) [
    3940              'id' => $this->id,
    3941              'link' => is_object($link) ? $link->out(false) : $link,
    3942              'text' => $this->text,
    3943              'title' => $this->title,
    3944              'inactive' => !$active && $this->inactive,
    3945              'active' => $active,
    3946              'level' => $this->level,
    3947          ];
    3948      }
    3949  
    3950  }
    3951  
    3952  /**
    3953   * Renderable for the main page header.
    3954   *
    3955   * @package core
    3956   * @category output
    3957   * @since 2.9
    3958   * @copyright 2015 Adrian Greeve <adrian@moodle.com>
    3959   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    3960   */
    3961  class context_header implements renderable {
    3962  
    3963      /**
    3964       * @var string $heading Main heading.
    3965       */
    3966      public $heading;
    3967      /**
    3968       * @var int $headinglevel Main heading 'h' tag level.
    3969       */
    3970      public $headinglevel;
    3971      /**
    3972       * @var string|null $imagedata HTML code for the picture in the page header.
    3973       */
    3974      public $imagedata;
    3975      /**
    3976       * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
    3977       *      array elements - title => alternate text for the image, or if no image is available the button text.
    3978       *                       url => Link for the button to head to. Should be a moodle_url.
    3979       *                       image => location to the image, or name of the image in /pix/t/{image name}.
    3980       *                       linkattributes => additional attributes for the <a href> element.
    3981       *                       page => page object. Don't include if the image is an external image.
    3982       */
    3983      public $additionalbuttons;
    3984  
    3985      /**
    3986       * Constructor.
    3987       *
    3988       * @param string $heading Main heading data.
    3989       * @param int $headinglevel Main heading 'h' tag level.
    3990       * @param string|null $imagedata HTML code for the picture in the page header.
    3991       * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
    3992       */
    3993      public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
    3994  
    3995          $this->heading = $heading;
    3996          $this->headinglevel = $headinglevel;
    3997          $this->imagedata = $imagedata;
    3998          $this->additionalbuttons = $additionalbuttons;
    3999          // If we have buttons then format them.
    4000          if (isset($this->additionalbuttons)) {
    4001              $this->format_button_images();
    4002          }
    4003      }
    4004  
    4005      /**
    4006       * Adds an array element for a formatted image.
    4007       */
    4008      protected function format_button_images() {
    4009  
    4010          foreach ($this->additionalbuttons as $buttontype => $button) {
    4011              $page = $button['page'];
    4012              // If no image is provided then just use the title.
    4013              if (!isset($button['image'])) {
    4014                  $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
    4015              } else {
    4016                  // Check to see if this is an internal Moodle icon.
    4017                  $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
    4018                  if ($internalimage) {
    4019                      $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
    4020                  } else {
    4021                      // Treat as an external image.
    4022                      $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
    4023                  }
    4024              }
    4025  
    4026              if (isset($button['linkattributes']['class'])) {
    4027                  $class = $button['linkattributes']['class'] . ' btn';
    4028              } else {
    4029                  $class = 'btn';
    4030              }
    4031              // Add the bootstrap 'btn' class for formatting.
    4032              $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
    4033                      array('class' => $class));
    4034          }
    4035      }
    4036  }
    4037  
    4038  /**
    4039   * Stores tabs list
    4040   *
    4041   * Example how to print a single line tabs:
    4042   * $rows = array(
    4043   *    new tabobject(...),
    4044   *    new tabobject(...)
    4045   * );
    4046   * echo $OUTPUT->tabtree($rows, $selectedid);
    4047   *
    4048   * Multiple row tabs may not look good on some devices but if you want to use them
    4049   * you can specify ->subtree for the active tabobject.
    4050   *
    4051   * @copyright 2013 Marina Glancy
    4052   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    4053   * @since Moodle 2.5
    4054   * @package core
    4055   * @category output
    4056   */
    4057  class tabtree extends tabobject {
    4058      /**
    4059       * Constuctor
    4060       *
    4061       * It is highly recommended to call constructor when list of tabs is already
    4062       * populated, this way you ensure that selected and inactive tabs are located
    4063       * and attribute level is set correctly.
    4064       *
    4065       * @param array $tabs array of tabs, each of them may have it's own ->subtree
    4066       * @param string|null $selected which tab to mark as selected, all parent tabs will
    4067       *     automatically be marked as activated
    4068       * @param array|string|null $inactive list of ids of inactive tabs, regardless of
    4069       *     their level. Note that you can as weel specify tabobject::$inactive for separate instances
    4070       */
    4071      public function __construct($tabs, $selected = null, $inactive = null) {
    4072          $this->subtree = $tabs;
    4073          if ($selected !== null) {
    4074              $this->set_selected($selected);
    4075          }
    4076          if ($inactive !== null) {
    4077              if (is_array($inactive)) {
    4078                  foreach ($inactive as $id) {
    4079                      if ($tab = $this->find($id)) {
    4080                          $tab->inactive = true;
    4081                      }
    4082                  }
    4083              } else if ($tab = $this->find($inactive)) {
    4084                  $tab->inactive = true;
    4085              }
    4086          }
    4087          $this->set_level(0);
    4088      }
    4089  
    4090      /**
    4091       * Export for template.
    4092       *
    4093       * @param renderer_base $output Renderer.
    4094       * @return object
    4095       */
    4096      public function export_for_template(renderer_base $output) {
    4097          $tabs = [];
    4098          $secondrow = false;
    4099  
    4100          foreach ($this->subtree as $tab) {
    4101              $tabs[] = $tab->export_for_template($output);
    4102              if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
    4103                  $secondrow = new tabtree($tab->subtree);
    4104              }
    4105          }
    4106  
    4107          return (object) [
    4108              'tabs' => $tabs,
    4109              'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
    4110          ];
    4111      }
    4112  }
    4113  
    4114  /**
    4115   * An action menu.
    4116   *
    4117   * This action menu component takes a series of primary and secondary actions.
    4118   * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
    4119   * down menu.
    4120   *
    4121   * @package core
    4122   * @category output
    4123   * @copyright 2013 Sam Hemelryk
    4124   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    4125   */
    4126  class action_menu implements renderable, templatable {
    4127  
    4128      /**
    4129       * Top right alignment.
    4130       */
    4131      const TL = 1;
    4132  
    4133      /**
    4134       * Top right alignment.
    4135       */
    4136      const TR = 2;
    4137  
    4138      /**
    4139       * Top right alignment.
    4140       */
    4141      const BL = 3;
    4142  
    4143      /**
    4144       * Top right alignment.
    4145       */
    4146      const BR = 4;
    4147  
    4148      /**
    4149       * The instance number. This is unique to this instance of the action menu.
    4150       * @var int
    4151       */
    4152      protected $instance = 0;
    4153  
    4154      /**
    4155       * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
    4156       * @var array
    4157       */
    4158      protected $primaryactions = array();
    4159  
    4160      /**
    4161       * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
    4162       * @var array
    4163       */
    4164      protected $secondaryactions = array();
    4165  
    4166      /**
    4167       * An array of attributes added to the container of the action menu.
    4168       * Initialised with defaults during construction.
    4169       * @var array
    4170       */
    4171      public $attributes = array();
    4172      /**
    4173       * An array of attributes added to the container of the primary actions.
    4174       * Initialised with defaults during construction.
    4175       * @var array
    4176       */
    4177      public $attributesprimary = array();
    4178      /**
    4179       * An array of attributes added to the container of the secondary actions.
    4180       * Initialised with defaults during construction.
    4181       * @var array
    4182       */
    4183      public $attributessecondary = array();
    4184  
    4185      /**
    4186       * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
    4187       * @var array
    4188       */
    4189      public $actiontext = null;
    4190  
    4191      /**
    4192       * The string to use for the accessible label for the menu.
    4193       * @var array
    4194       */
    4195      public $actionlabel = null;
    4196  
    4197      /**
    4198       * An icon to use for the toggling the secondary menu (dropdown).
    4199       * @var pix_icon
    4200       */
    4201      public $actionicon;
    4202  
    4203      /**
    4204       * Any text to use for the toggling the secondary menu (dropdown).
    4205       * @var string
    4206       */
    4207      public $menutrigger = '';
    4208  
    4209      /**
    4210       * Any extra classes for toggling to the secondary menu.
    4211       * @var string
    4212       */
    4213      public $triggerextraclasses = '';
    4214  
    4215      /**
    4216       * Place the action menu before all other actions.
    4217       * @var bool
    4218       */
    4219      public $prioritise = false;
    4220  
    4221      /**
    4222       * Constructs the action menu with the given items.
    4223       *
    4224       * @param array $actions An array of actions (action_menu_link|pix_icon|string).
    4225       */
    4226      public function __construct(array $actions = array()) {
    4227          static $initialised = 0;
    4228          $this->instance = $initialised;
    4229          $initialised++;
    4230  
    4231          $this->attributes = array(
    4232              'id' => 'action-menu-'.$this->instance,
    4233              'class' => 'moodle-actionmenu',
    4234              'data-enhance' => 'moodle-core-actionmenu'
    4235          );
    4236          $this->attributesprimary = array(
    4237              'id' => 'action-menu-'.$this->instance.'-menubar',
    4238              'class' => 'menubar',
    4239              'role' => 'menubar'
    4240          );
    4241          $this->attributessecondary = array(
    4242              'id' => 'action-menu-'.$this->instance.'-menu',
    4243              'class' => 'menu',
    4244              'data-rel' => 'menu-content',
    4245              'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
    4246              'role' => 'menu'
    4247          );
    4248          $this->set_alignment(self::TR, self::BR);
    4249          foreach ($actions as $action) {
    4250              $this->add($action);
    4251          }
    4252      }
    4253  
    4254      /**
    4255       * Sets the label for the menu trigger.
    4256       *
    4257       * @param string $label The text
    4258       */
    4259      public function set_action_label($label) {
    4260          $this->actionlabel = $label;
    4261      }
    4262  
    4263      /**
    4264       * Sets the menu trigger text.
    4265       *
    4266       * @param string $trigger The text
    4267       * @param string $extraclasses Extra classes to style the secondary menu toggle.
    4268       */
    4269      public function set_menu_trigger($trigger, $extraclasses = '') {
    4270          $this->menutrigger = $trigger;
    4271          $this->triggerextraclasses = $extraclasses;
    4272      }
    4273  
    4274      /**
    4275       * Return true if there is at least one visible link in the menu.
    4276       *
    4277       * @return bool
    4278       */
    4279      public function is_empty() {
    4280          return !count($this->primaryactions) && !count($this->secondaryactions);
    4281      }
    4282  
    4283      /**
    4284       * Initialises JS required fore the action menu.
    4285       * The JS is only required once as it manages all action menu's on the page.
    4286       *
    4287       * @param moodle_page $page
    4288       */
    4289      public function initialise_js(moodle_page $page) {
    4290          static $initialised = false;
    4291          if (!$initialised) {
    4292              $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
    4293              $initialised = true;
    4294          }
    4295      }
    4296  
    4297      /**
    4298       * Adds an action to this action menu.
    4299       *
    4300       * @param action_menu_link|pix_icon|string $action
    4301       */
    4302      public function add($action) {
    4303          if ($action instanceof action_link) {
    4304              if ($action->primary) {
    4305                  $this->add_primary_action($action);
    4306              } else {
    4307                  $this->add_secondary_action($action);
    4308              }
    4309          } else if ($action instanceof pix_icon) {
    4310              $this->add_primary_action($action);
    4311          } else {
    4312              $this->add_secondary_action($action);
    4313          }
    4314      }
    4315  
    4316      /**
    4317       * Adds a primary action to the action menu.
    4318       *
    4319       * @param action_menu_link|action_link|pix_icon|string $action
    4320       */
    4321      public function add_primary_action($action) {
    4322          if ($action instanceof action_link || $action instanceof pix_icon) {
    4323              $action->attributes['role'] = 'menuitem';
    4324              if ($action instanceof action_menu_link) {
    4325                  $action->actionmenu = $this;
    4326              }
    4327          }
    4328          $this->primaryactions[] = $action;
    4329      }
    4330  
    4331      /**
    4332       * Adds a secondary action to the action menu.
    4333       *
    4334       * @param action_link|pix_icon|string $action
    4335       */
    4336      public function add_secondary_action($action) {
    4337          if ($action instanceof action_link || $action instanceof pix_icon) {
    4338              $action->attributes['role'] = 'menuitem';
    4339              if ($action instanceof action_menu_link) {
    4340                  $action->actionmenu = $this;
    4341              }
    4342          }
    4343          $this->secondaryactions[] = $action;
    4344      }
    4345  
    4346      /**
    4347       * Returns the primary actions ready to be rendered.
    4348       *
    4349       * @param core_renderer $output The renderer to use for getting icons.
    4350       * @return array
    4351       */
    4352      public function get_primary_actions(core_renderer $output = null) {
    4353          global $OUTPUT;
    4354          if ($output === null) {
    4355              $output = $OUTPUT;
    4356          }
    4357          $pixicon = $this->actionicon;
    4358          $linkclasses = array('toggle-display');
    4359  
    4360          $title = '';
    4361          if (!empty($this->menutrigger)) {
    4362              $pixicon = '<b class="caret"></b>';
    4363              $linkclasses[] = 'textmenu';
    4364          } else {
    4365              $title = new lang_string('actionsmenu', 'moodle');
    4366              $this->actionicon = new pix_icon(
    4367                  't/edit_menu',
    4368                  '',
    4369                  'moodle',
    4370                  array('class' => 'iconsmall actionmenu', 'title' => '')
    4371              );
    4372              $pixicon = $this->actionicon;
    4373          }
    4374          if ($pixicon instanceof renderable) {
    4375              $pixicon = $output->render($pixicon);
    4376              if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
    4377                  $title = $pixicon->attributes['alt'];
    4378              }
    4379          }
    4380          $string = '';
    4381          if ($this->actiontext) {
    4382              $string = $this->actiontext;
    4383          }
    4384          $label = '';
    4385          if ($this->actionlabel) {
    4386              $label = $this->actionlabel;
    4387          } else {
    4388              $label = $title;
    4389          }
    4390          $actions = $this->primaryactions;
    4391          $attributes = array(
    4392              'class' => implode(' ', $linkclasses),
    4393              'title' => $title,
    4394              'aria-label' => $label,
    4395              'id' => 'action-menu-toggle-'.$this->instance,
    4396              'role' => 'menuitem'
    4397          );
    4398          $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
    4399          if ($this->prioritise) {
    4400              array_unshift($actions, $link);
    4401          } else {
    4402              $actions[] = $link;
    4403          }
    4404          return $actions;
    4405      }
    4406  
    4407      /**
    4408       * Returns the secondary actions ready to be rendered.
    4409       * @return array
    4410       */
    4411      public function get_secondary_actions() {
    4412          return $this->secondaryactions;
    4413      }
    4414  
    4415      /**
    4416       * Sets the selector that should be used to find the owning node of this menu.
    4417       * @param string $selector A CSS/YUI selector to identify the owner of the menu.
    4418       */
    4419      public function set_owner_selector($selector) {
    4420          $this->attributes['data-owner'] = $selector;
    4421      }
    4422  
    4423      /**
    4424       * Sets the alignment of the dialogue in relation to button used to toggle it.
    4425       *
    4426       * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
    4427       * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
    4428       */
    4429      public function set_alignment($dialogue, $button) {
    4430          if (isset($this->attributessecondary['data-align'])) {
    4431              // We've already got one set, lets remove the old class so as to avoid troubles.
    4432              $class = $this->attributessecondary['class'];
    4433              $search = 'align-'.$this->attributessecondary['data-align'];
    4434              $this->attributessecondary['class'] = str_replace($search, '', $class);
    4435          }
    4436          $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
    4437          $this->attributessecondary['data-align'] = $align;
    4438          $this->attributessecondary['class'] .= ' align-'.$align;
    4439      }
    4440  
    4441      /**
    4442       * Returns a string to describe the alignment.
    4443       *
    4444       * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
    4445       * @return string
    4446       */
    4447      protected function get_align_string($align) {
    4448          switch ($align) {
    4449              case self::TL :
    4450                  return 'tl';
    4451              case self::TR :
    4452                  return 'tr';
    4453              case self::BL :
    4454                  return 'bl';
    4455              case self::BR :
    4456                  return 'br';
    4457              default :
    4458                  return 'tl';
    4459          }
    4460      }
    4461  
    4462      /**
    4463       * Sets a constraint for the dialogue.
    4464       *
    4465       * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
    4466       * element the constraint identifies.
    4467       *
    4468       * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
    4469       * (flexible_table and any of it's child classes are a likely candidate).
    4470       *
    4471       * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
    4472       */
    4473      public function set_constraint($ancestorselector) {
    4474          $this->attributessecondary['data-constraint'] = $ancestorselector;
    4475      }
    4476  
    4477      /**
    4478       * If you call this method the action menu will be displayed but will not be enhanced.
    4479       *
    4480       * By not displaying the menu enhanced all items will be displayed in a single row.
    4481       *
    4482       * @deprecated since Moodle 3.2
    4483       */
    4484      public function do_not_enhance() {
    4485          debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
    4486      }
    4487  
    4488      /**
    4489       * Returns true if this action menu will be enhanced.
    4490       *
    4491       * @return bool
    4492       */
    4493      public function will_be_enhanced() {
    4494          return isset($this->attributes['data-enhance']);
    4495      }
    4496  
    4497      /**
    4498       * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
    4499       *
    4500       * This property can be useful when the action menu is displayed within a parent element that is either floated
    4501       * or relatively positioned.
    4502       * In that situation the width of the menu is determined by the width of the parent element which may not be large
    4503       * enough for the menu items without them wrapping.
    4504       * This disables the wrapping so that the menu takes on the width of the longest item.
    4505       *
    4506       * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
    4507       */
    4508      public function set_nowrap_on_items($value = true) {
    4509          $class = 'nowrap-items';
    4510          if (!empty($this->attributes['class'])) {
    4511              $pos = strpos($this->attributes['class'], $class);
    4512              if ($value === true && $pos === false) {
    4513                  // The value is true and the class has not been set yet. Add it.
    4514                  $this->attributes['class'] .= ' '.$class;
    4515              } else if ($value === false && $pos !== false) {
    4516                  // The value is false and the class has been set. Remove it.
    4517                  $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
    4518              }
    4519          } else if ($value) {
    4520              // The value is true and the class has not been set yet. Add it.
    4521              $this->attributes['class'] = $class;
    4522          }
    4523      }
    4524  
    4525      /**
    4526       * Export for template.
    4527       *
    4528       * @param renderer_base $output The renderer.
    4529       * @return stdClass
    4530       */
    4531      public function export_for_template(renderer_base $output) {
    4532          $data = new stdClass();
    4533          $attributes = $this->attributes;
    4534          $attributesprimary = $this->attributesprimary;
    4535          $attributessecondary = $this->attributessecondary;
    4536  
    4537          $data->instance = $this->instance;
    4538  
    4539          $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
    4540          unset($attributes['class']);
    4541  
    4542          $data->attributes = array_map(function($key, $value) {
    4543              return [ 'name' => $key, 'value' => $value ];
    4544          }, array_keys($attributes), $attributes);
    4545  
    4546          $primary = new stdClass();
    4547          $primary->title = '';
    4548          $primary->prioritise = $this->prioritise;
    4549  
    4550          $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
    4551          unset($attributesprimary['class']);
    4552          $primary->attributes = array_map(function($key, $value) {
    4553              return [ 'name' => $key, 'value' => $value ];
    4554          }, array_keys($attributesprimary), $attributesprimary);
    4555  
    4556          $actionicon = $this->actionicon;
    4557          if (!empty($this->menutrigger)) {
    4558              $primary->menutrigger = $this->menutrigger;
    4559              $primary->triggerextraclasses = $this->triggerextraclasses;
    4560              if ($this->actionlabel) {
    4561                  $primary->title = $this->actionlabel;
    4562              } else if ($this->actiontext) {
    4563                  $primary->title = $this->actiontext;
    4564              } else {
    4565                  $primary->title = strip_tags($this->menutrigger);
    4566              }
    4567          } else {
    4568              $primary->title = get_string('actionsmenu');
    4569              $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
    4570              $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
    4571          }
    4572  
    4573          if ($actionicon instanceof pix_icon) {
    4574              $primary->icon = $actionicon->export_for_pix();
    4575              if (!empty($actionicon->attributes['alt'])) {
    4576                  $primary->title = $actionicon->attributes['alt'];
    4577              }
    4578          } else {
    4579              $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
    4580          }
    4581  
    4582          $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
    4583          $primary->items = array_map(function($item) use ($output) {
    4584              $data = (object) [];
    4585              if ($item instanceof action_menu_link) {
    4586                  $data->actionmenulink = $item->export_for_template($output);
    4587              } else if ($item instanceof action_menu_filler) {
    4588                  $data->actionmenufiller = $item->export_for_template($output);
    4589              } else if ($item instanceof action_link) {
    4590                  $data->actionlink = $item->export_for_template($output);
    4591              } else if ($item instanceof pix_icon) {
    4592                  $data->pixicon = $item->export_for_template($output);
    4593              } else {
    4594                  $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
    4595              }
    4596              return $data;
    4597          }, $this->primaryactions);
    4598  
    4599          $secondary = new stdClass();
    4600          $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
    4601          unset($attributessecondary['class']);
    4602          $secondary->attributes = array_map(function($key, $value) {
    4603              return [ 'name' => $key, 'value' => $value ];
    4604          }, array_keys($attributessecondary), $attributessecondary);
    4605          $secondary->items = array_map(function($item) use ($output) {
    4606              $data = (object) [];
    4607              if ($item instanceof action_menu_link) {
    4608                  $data->actionmenulink = $item->export_for_template($output);
    4609              } else if ($item instanceof action_menu_filler) {
    4610                  $data->actionmenufiller = $item->export_for_template($output);
    4611              } else if ($item instanceof action_link) {
    4612                  $data->actionlink = $item->export_for_template($output);
    4613              } else if ($item instanceof pix_icon) {
    4614                  $data->pixicon = $item->export_for_template($output);
    4615              } else {
    4616                  $data->