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

/lib/outputcomponents.php

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