PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/outputcomponents.php

https://github.com/mylescarrick/moodle
PHP | 2454 lines | 1088 code | 191 blank | 1175 comment | 185 complexity | c11fb7d643c0d9f48fa536e059de8955 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. * @subpackage lib
  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. * @author 2010 Petr Skoda (skodak) info@skodak.org
  31. */
  32. interface renderable {
  33. // intentionally empty
  34. }
  35. /**
  36. * Data structure representing a file picker.
  37. *
  38. * @copyright 2010 Dongsheng Cai
  39. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40. * @since Moodle 2.0
  41. */
  42. class file_picker implements renderable {
  43. public $options;
  44. public function __construct(stdClass $options) {
  45. global $CFG, $USER, $PAGE;
  46. require_once($CFG->dirroot. '/repository/lib.php');
  47. $defaults = array(
  48. 'accepted_types'=>'*',
  49. 'return_types'=>FILE_INTERNAL,
  50. 'env' => 'filepicker',
  51. 'client_id' => uniqid(),
  52. 'itemid' => 0,
  53. 'maxbytes'=>-1,
  54. 'maxfiles'=>1,
  55. );
  56. foreach ($defaults as $key=>$value) {
  57. if (empty($options->$key)) {
  58. $options->$key = $value;
  59. }
  60. }
  61. $options->currentfile = '';
  62. if (!empty($options->itemid)) {
  63. $fs = get_file_storage();
  64. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  65. if (empty($options->filename)) {
  66. if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
  67. $file = reset($files);
  68. }
  69. } else {
  70. $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
  71. }
  72. if (!empty($file)) {
  73. $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
  74. }
  75. }
  76. // initilise options, getting files in root path
  77. $this->options = initialise_filepicker($options);
  78. // copying other options
  79. foreach ($options as $name=>$value) {
  80. if (!isset($this->options->$name)) {
  81. $this->options->$name = $value;
  82. }
  83. }
  84. }
  85. }
  86. /**
  87. * Data structure representing a user picture.
  88. *
  89. * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
  90. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  91. * @since Moodle 2.0
  92. */
  93. class user_picture implements renderable {
  94. /**
  95. * @var array List of mandatory fields in user record here. (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
  96. */
  97. protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
  98. /**
  99. * @var object $user A user object with at least fields all columns specified in $fields array constant set.
  100. */
  101. public $user;
  102. /**
  103. * @var int $courseid The course id. Used when constructing the link to the user's profile,
  104. * page course id used if not specified.
  105. */
  106. public $courseid;
  107. /**
  108. * @var bool $link add course profile link to image
  109. */
  110. public $link = true;
  111. /**
  112. * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
  113. */
  114. public $size = 35;
  115. /**
  116. * @var boolean $alttext add non-blank alt-text to the image.
  117. * Default true, set to false when image alt just duplicates text in screenreaders.
  118. */
  119. public $alttext = true;
  120. /**
  121. * @var boolean $popup Whether or not to open the link in a popup window.
  122. */
  123. public $popup = false;
  124. /**
  125. * @var string Image class attribute
  126. */
  127. public $class = 'userpicture';
  128. /**
  129. * User picture constructor.
  130. *
  131. * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
  132. * @param array $options such as link, size, link, ...
  133. */
  134. public function __construct(stdClass $user) {
  135. global $DB;
  136. if (empty($user->id)) {
  137. throw new coding_exception('User id is required when printing user avatar image.');
  138. }
  139. // only touch the DB if we are missing data and complain loudly...
  140. $needrec = false;
  141. foreach (self::$fields as $field) {
  142. if (!array_key_exists($field, $user)) {
  143. $needrec = true;
  144. debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
  145. .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
  146. break;
  147. }
  148. }
  149. if ($needrec) {
  150. $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
  151. } else {
  152. $this->user = clone($user);
  153. }
  154. }
  155. /**
  156. * Returns a list of required user fields, useful when fetching required user info from db.
  157. *
  158. * In some cases we have to fetch the user data together with some other information,
  159. * the idalias is useful there because the id would otherwise override the main
  160. * id of the result record. Please note it has to be converted back to id before rendering.
  161. *
  162. * @param string $tableprefix name of database table prefix in query
  163. * @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)
  164. * @param string $idalias alias of id field
  165. * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
  166. * @return string
  167. */
  168. public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
  169. if (!$tableprefix and !$extrafields and !$idalias) {
  170. return implode(',', self::$fields);
  171. }
  172. if ($tableprefix) {
  173. $tableprefix .= '.';
  174. }
  175. $fields = array();
  176. foreach (self::$fields as $field) {
  177. if ($field === 'id' and $idalias and $idalias !== 'id') {
  178. $fields[$field] = "$tableprefix$field AS $idalias";
  179. } else {
  180. if ($fieldprefix and $field !== 'id') {
  181. $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
  182. } else {
  183. $fields[$field] = "$tableprefix$field";
  184. }
  185. }
  186. }
  187. // add extra fields if not already there
  188. if ($extrafields) {
  189. foreach ($extrafields as $e) {
  190. if ($e === 'id' or isset($fields[$e])) {
  191. continue;
  192. }
  193. if ($fieldprefix) {
  194. $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
  195. } else {
  196. $fields[$e] = "$tableprefix$e";
  197. }
  198. }
  199. }
  200. return implode(',', $fields);
  201. }
  202. /**
  203. * Extract the aliased user fields from a given record
  204. *
  205. * Given a record that was previously obtained using {@link self::fields()} with aliases,
  206. * this method extracts user related unaliased fields.
  207. *
  208. * @param stdClass $record containing user picture fields
  209. * @param array $extrafields extra fields included in the $record
  210. * @param string $idalias alias of the id field
  211. * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
  212. * @return stdClass object with unaliased user fields
  213. */
  214. public static function unalias(stdClass $record, array $extrafields=null, $idalias='id', $fieldprefix='') {
  215. if (empty($idalias)) {
  216. $idalias = 'id';
  217. }
  218. $return = new stdClass();
  219. foreach (self::$fields as $field) {
  220. if ($field === 'id') {
  221. if (property_exists($record, $idalias)) {
  222. $return->id = $record->{$idalias};
  223. }
  224. } else {
  225. if (property_exists($record, $fieldprefix.$field)) {
  226. $return->{$field} = $record->{$fieldprefix.$field};
  227. }
  228. }
  229. }
  230. // add extra fields if not already there
  231. if ($extrafields) {
  232. foreach ($extrafields as $e) {
  233. if ($e === 'id' or property_exists($return, $e)) {
  234. continue;
  235. }
  236. $return->{$e} = $record->{$fieldprefix.$e};
  237. }
  238. }
  239. return $return;
  240. }
  241. }
  242. /**
  243. * Data structure representing a help icon.
  244. *
  245. * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
  246. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  247. * @since Moodle 2.0
  248. */
  249. class old_help_icon implements renderable {
  250. /**
  251. * @var string $helpidentifier lang pack identifier
  252. */
  253. public $helpidentifier;
  254. /**
  255. * @var string $title A descriptive text for title tooltip
  256. */
  257. public $title = null;
  258. /**
  259. * @var string $component Component name, the same as in get_string()
  260. */
  261. public $component = 'moodle';
  262. /**
  263. * @var string $linktext Extra descriptive text next to the icon
  264. */
  265. public $linktext = null;
  266. /**
  267. * Constructor: sets up the other components in case they are needed
  268. * @param string $helpidentifier The keyword that defines a help page
  269. * @param string $title A descriptive text for accessibility only
  270. * @param string $component
  271. * @param bool $linktext add extra text to icon
  272. * @return void
  273. */
  274. public function __construct($helpidentifier, $title, $component = 'moodle') {
  275. if (empty($title)) {
  276. throw new coding_exception('A help_icon object requires a $text parameter');
  277. }
  278. if (empty($helpidentifier)) {
  279. throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
  280. }
  281. $this->helpidentifier = $helpidentifier;
  282. $this->title = $title;
  283. $this->component = $component;
  284. }
  285. }
  286. /**
  287. * Data structure representing a help icon.
  288. *
  289. * @copyright 2010 Petr Skoda (info@skodak.org)
  290. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  291. * @since Moodle 2.0
  292. */
  293. class help_icon implements renderable {
  294. /**
  295. * @var string $identifier lang pack identifier (without the "_help" suffix),
  296. * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
  297. * must exist.
  298. */
  299. public $identifier;
  300. /**
  301. * @var string $component Component name, the same as in get_string()
  302. */
  303. public $component;
  304. /**
  305. * @var string $linktext Extra descriptive text next to the icon
  306. */
  307. public $linktext = null;
  308. /**
  309. * Constructor
  310. * @param string $identifier string for help page title,
  311. * string with _help suffix is used for the actual help text.
  312. * string with _link suffix is used to create a link to further info (if it exists)
  313. * @param string $component
  314. */
  315. public function __construct($identifier, $component) {
  316. $this->identifier = $identifier;
  317. $this->component = $component;
  318. }
  319. /**
  320. * Verifies that both help strings exists, shows debug warnings if not
  321. */
  322. public function diag_strings() {
  323. $sm = get_string_manager();
  324. if (!$sm->string_exists($this->identifier, $this->component)) {
  325. debugging("Help title string does not exist: [$this->identifier, $this->component]");
  326. }
  327. if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
  328. debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
  329. }
  330. }
  331. }
  332. /**
  333. * Data structure representing an icon.
  334. *
  335. * @copyright 2010 Petr Skoda
  336. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  337. * @since Moodle 2.0
  338. */
  339. class pix_icon implements renderable {
  340. var $pix;
  341. var $component;
  342. var $attributes = array();
  343. /**
  344. * Constructor
  345. * @param string $pix short icon name
  346. * @param string $component component name
  347. * @param array $attributes html attributes
  348. */
  349. public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
  350. $this->pix = $pix;
  351. $this->component = $component;
  352. $this->attributes = (array)$attributes;
  353. $this->attributes['alt'] = $alt;
  354. if (empty($this->attributes['class'])) {
  355. $this->attributes['class'] = 'smallicon';
  356. }
  357. if (!isset($this->attributes['title'])) {
  358. $this->attributes['title'] = $this->attributes['alt'];
  359. }
  360. }
  361. }
  362. /**
  363. * Data structure representing an emoticon image
  364. *
  365. * @since Moodle 2.0
  366. */
  367. class pix_emoticon extends pix_icon implements renderable {
  368. /**
  369. * Constructor
  370. * @param string $pix short icon name
  371. * @param string $alt alternative text
  372. * @param string $component emoticon image provider
  373. * @param array $attributes explicit HTML attributes
  374. */
  375. public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
  376. if (empty($attributes['class'])) {
  377. $attributes['class'] = 'emoticon';
  378. }
  379. parent::__construct($pix, $alt, $component, $attributes);
  380. }
  381. }
  382. /**
  383. * Data structure representing a simple form with only one button.
  384. *
  385. * @copyright 2009 Petr Skoda
  386. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  387. * @since Moodle 2.0
  388. */
  389. class single_button implements renderable {
  390. /**
  391. * Target url
  392. * @var moodle_url
  393. */
  394. var $url;
  395. /**
  396. * Button label
  397. * @var string
  398. */
  399. var $label;
  400. /**
  401. * Form submit method
  402. * @var string post or get
  403. */
  404. var $method = 'post';
  405. /**
  406. * Wrapping div class
  407. * @var string
  408. * */
  409. var $class = 'singlebutton';
  410. /**
  411. * True if button disabled, false if normal
  412. * @var boolean
  413. */
  414. var $disabled = false;
  415. /**
  416. * Button tooltip
  417. * @var string
  418. */
  419. var $tooltip = null;
  420. /**
  421. * Form id
  422. * @var string
  423. */
  424. var $formid;
  425. /**
  426. * List of attached actions
  427. * @var array of component_action
  428. */
  429. var $actions = array();
  430. /**
  431. * Constructor
  432. * @param string|moodle_url $url
  433. * @param string $label button text
  434. * @param string $method get or post submit method
  435. */
  436. public function __construct(moodle_url $url, $label, $method='post') {
  437. $this->url = clone($url);
  438. $this->label = $label;
  439. $this->method = $method;
  440. }
  441. /**
  442. * Shortcut for adding a JS confirm dialog when the button is clicked.
  443. * The message must be a yes/no question.
  444. * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
  445. * @return void
  446. */
  447. public function add_confirm_action($confirmmessage) {
  448. $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
  449. }
  450. /**
  451. * Add action to the button.
  452. * @param component_action $action
  453. * @return void
  454. */
  455. public function add_action(component_action $action) {
  456. $this->actions[] = $action;
  457. }
  458. }
  459. /**
  460. * Simple form with just one select field that gets submitted automatically.
  461. * If JS not enabled small go button is printed too.
  462. *
  463. * @copyright 2009 Petr Skoda
  464. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  465. * @since Moodle 2.0
  466. */
  467. class single_select implements renderable {
  468. /**
  469. * Target url - includes hidden fields
  470. * @var moodle_url
  471. */
  472. var $url;
  473. /**
  474. * Name of the select element.
  475. * @var string
  476. */
  477. var $name;
  478. /**
  479. * @var array $options associative array value=>label ex.:
  480. * array(1=>'One, 2=>Two)
  481. * it is also possible to specify optgroup as complex label array ex.:
  482. * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
  483. * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
  484. */
  485. var $options;
  486. /**
  487. * Selected option
  488. * @var string
  489. */
  490. var $selected;
  491. /**
  492. * Nothing selected
  493. * @var array
  494. */
  495. var $nothing;
  496. /**
  497. * Extra select field attributes
  498. * @var array
  499. */
  500. var $attributes = array();
  501. /**
  502. * Button label
  503. * @var string
  504. */
  505. var $label = '';
  506. /**
  507. * Form submit method
  508. * @var string post or get
  509. */
  510. var $method = 'get';
  511. /**
  512. * Wrapping div class
  513. * @var string
  514. * */
  515. var $class = 'singleselect';
  516. /**
  517. * True if button disabled, false if normal
  518. * @var boolean
  519. */
  520. var $disabled = false;
  521. /**
  522. * Button tooltip
  523. * @var string
  524. */
  525. var $tooltip = null;
  526. /**
  527. * Form id
  528. * @var string
  529. */
  530. var $formid = null;
  531. /**
  532. * List of attached actions
  533. * @var array of component_action
  534. */
  535. var $helpicon = null;
  536. /**
  537. * Constructor
  538. * @param moodle_url $url form action target, includes hidden fields
  539. * @param string $name name of selection field - the changing parameter in url
  540. * @param array $options list of options
  541. * @param string $selected selected element
  542. * @param array $nothing
  543. * @param string $formid
  544. */
  545. public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
  546. $this->url = $url;
  547. $this->name = $name;
  548. $this->options = $options;
  549. $this->selected = $selected;
  550. $this->nothing = $nothing;
  551. $this->formid = $formid;
  552. }
  553. /**
  554. * Shortcut for adding a JS confirm dialog when the button is clicked.
  555. * The message must be a yes/no question.
  556. * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
  557. * @return void
  558. */
  559. public function add_confirm_action($confirmmessage) {
  560. $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
  561. }
  562. /**
  563. * Add action to the button.
  564. * @param component_action $action
  565. * @return void
  566. */
  567. public function add_action(component_action $action) {
  568. $this->actions[] = $action;
  569. }
  570. /**
  571. * Adds help icon.
  572. * @param string $page The keyword that defines a help page
  573. * @param string $title A descriptive text for accessibility only
  574. * @param string $component
  575. * @param bool $linktext add extra text to icon
  576. * @return void
  577. */
  578. public function set_old_help_icon($helppage, $title, $component = 'moodle') {
  579. $this->helpicon = new old_help_icon($helppage, $title, $component);
  580. }
  581. /**
  582. * Adds help icon.
  583. * @param string $identifier The keyword that defines a help page
  584. * @param string $component
  585. * @param bool $linktext add extra text to icon
  586. * @return void
  587. */
  588. public function set_help_icon($identifier, $component = 'moodle') {
  589. $this->helpicon = new help_icon($identifier, $component);
  590. }
  591. /**
  592. * Sets select's label
  593. * @param string $label
  594. * @return void
  595. */
  596. public function set_label($label) {
  597. $this->label = $label;
  598. }
  599. }
  600. /**
  601. * Simple URL selection widget description.
  602. * @copyright 2009 Petr Skoda
  603. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  604. * @since Moodle 2.0
  605. */
  606. class url_select implements renderable {
  607. /**
  608. * @var array $urls associative array value=>label ex.:
  609. * array(1=>'One, 2=>Two)
  610. * it is also possible to specify optgroup as complex label array ex.:
  611. * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
  612. * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
  613. */
  614. var $urls;
  615. /**
  616. * Selected option
  617. * @var string
  618. */
  619. var $selected;
  620. /**
  621. * Nothing selected
  622. * @var array
  623. */
  624. var $nothing;
  625. /**
  626. * Extra select field attributes
  627. * @var array
  628. */
  629. var $attributes = array();
  630. /**
  631. * Button label
  632. * @var string
  633. */
  634. var $label = '';
  635. /**
  636. * Wrapping div class
  637. * @var string
  638. * */
  639. var $class = 'urlselect';
  640. /**
  641. * True if button disabled, false if normal
  642. * @var boolean
  643. */
  644. var $disabled = false;
  645. /**
  646. * Button tooltip
  647. * @var string
  648. */
  649. var $tooltip = null;
  650. /**
  651. * Form id
  652. * @var string
  653. */
  654. var $formid = null;
  655. /**
  656. * List of attached actions
  657. * @var array of component_action
  658. */
  659. var $helpicon = null;
  660. /**
  661. * @var string If set, makes button visible with given name for button
  662. */
  663. var $showbutton = null;
  664. /**
  665. * Constructor
  666. * @param array $urls list of options
  667. * @param string $selected selected element
  668. * @param array $nothing
  669. * @param string $formid
  670. * @param string $showbutton Set to text of button if it should be visible
  671. * or null if it should be hidden (hidden version always has text 'go')
  672. */
  673. public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
  674. $formid=null, $showbutton=null) {
  675. $this->urls = $urls;
  676. $this->selected = $selected;
  677. $this->nothing = $nothing;
  678. $this->formid = $formid;
  679. $this->showbutton = $showbutton;
  680. }
  681. /**
  682. * Adds help icon.
  683. * @param string $page The keyword that defines a help page
  684. * @param string $title A descriptive text for accessibility only
  685. * @param string $component
  686. * @param bool $linktext add extra text to icon
  687. * @return void
  688. */
  689. public function set_old_help_icon($helppage, $title, $component = 'moodle') {
  690. $this->helpicon = new old_help_icon($helppage, $title, $component);
  691. }
  692. /**
  693. * Adds help icon.
  694. * @param string $identifier The keyword that defines a help page
  695. * @param string $component
  696. * @param bool $linktext add extra text to icon
  697. * @return void
  698. */
  699. public function set_help_icon($identifier, $component = 'moodle') {
  700. $this->helpicon = new help_icon($identifier, $component);
  701. }
  702. /**
  703. * Sets select's label
  704. * @param string $label
  705. * @return void
  706. */
  707. public function set_label($label) {
  708. $this->label = $label;
  709. }
  710. }
  711. /**
  712. * Data structure describing html link with special action attached.
  713. * @copyright 2010 Petr Skoda
  714. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  715. * @since Moodle 2.0
  716. */
  717. class action_link implements renderable {
  718. /**
  719. * Href url
  720. * @var moodle_url
  721. */
  722. var $url;
  723. /**
  724. * Link text
  725. * @var string HTML fragment
  726. */
  727. var $text;
  728. /**
  729. * HTML attributes
  730. * @var array
  731. */
  732. var $attributes;
  733. /**
  734. * List of actions attached to link
  735. * @var array of component_action
  736. */
  737. var $actions;
  738. /**
  739. * Constructor
  740. * @param string|moodle_url $url
  741. * @param string $text HTML fragment
  742. * @param component_action $action
  743. * @param array $attributes associative array of html link attributes + disabled
  744. */
  745. public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
  746. $this->url = clone($url);
  747. $this->text = $text;
  748. $this->attributes = (array)$attributes;
  749. if ($action) {
  750. $this->add_action($action);
  751. }
  752. }
  753. /**
  754. * Add action to the link.
  755. * @param component_action $action
  756. * @return void
  757. */
  758. public function add_action(component_action $action) {
  759. $this->actions[] = $action;
  760. }
  761. public function add_class($class) {
  762. if (empty($this->attributes['class'])) {
  763. $this->attributes['class'] = $class;
  764. } else {
  765. $this->attributes['class'] .= ' ' . $class;
  766. }
  767. }
  768. }
  769. // ==== HTML writer and helper classes, will be probably moved elsewhere ======
  770. /**
  771. * Simple html output class
  772. * @copyright 2009 Tim Hunt, 2010 Petr Skoda
  773. */
  774. class html_writer {
  775. /**
  776. * Outputs a tag with attributes and contents
  777. * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
  778. * @param string $contents What goes between the opening and closing tags
  779. * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
  780. * @return string HTML fragment
  781. */
  782. public static function tag($tagname, $contents, array $attributes = null) {
  783. return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
  784. }
  785. /**
  786. * Outputs an opening tag with attributes
  787. * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
  788. * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
  789. * @return string HTML fragment
  790. */
  791. public static function start_tag($tagname, array $attributes = null) {
  792. return '<' . $tagname . self::attributes($attributes) . '>';
  793. }
  794. /**
  795. * Outputs a closing tag
  796. * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
  797. * @return string HTML fragment
  798. */
  799. public static function end_tag($tagname) {
  800. return '</' . $tagname . '>';
  801. }
  802. /**
  803. * Outputs an empty tag with attributes
  804. * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
  805. * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
  806. * @return string HTML fragment
  807. */
  808. public static function empty_tag($tagname, array $attributes = null) {
  809. return '<' . $tagname . self::attributes($attributes) . ' />';
  810. }
  811. /**
  812. * Outputs a tag, but only if the contents are not empty
  813. * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
  814. * @param string $contents What goes between the opening and closing tags
  815. * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
  816. * @return string HTML fragment
  817. */
  818. public static function nonempty_tag($tagname, $contents, array $attributes = null) {
  819. if ($contents === '' || is_null($contents)) {
  820. return '';
  821. }
  822. return self::tag($tagname, $contents, $attributes);
  823. }
  824. /**
  825. * Outputs a HTML attribute and value
  826. * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
  827. * @param string $value The value of the attribute. The value will be escaped with {@link s()}
  828. * @return string HTML fragment
  829. */
  830. public static function attribute($name, $value) {
  831. if (is_array($value)) {
  832. debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
  833. }
  834. if ($value instanceof moodle_url) {
  835. return ' ' . $name . '="' . $value->out() . '"';
  836. }
  837. // special case, we do not want these in output
  838. if ($value === null) {
  839. return '';
  840. }
  841. // no sloppy trimming here!
  842. return ' ' . $name . '="' . s($value) . '"';
  843. }
  844. /**
  845. * Outputs a list of HTML attributes and values
  846. * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
  847. * The values will be escaped with {@link s()}
  848. * @return string HTML fragment
  849. */
  850. public static function attributes(array $attributes = null) {
  851. $attributes = (array)$attributes;
  852. $output = '';
  853. foreach ($attributes as $name => $value) {
  854. $output .= self::attribute($name, $value);
  855. }
  856. return $output;
  857. }
  858. /**
  859. * Generates random html element id.
  860. * @param string $base
  861. * @return string
  862. */
  863. public static function random_id($base='random') {
  864. return uniqid($base);
  865. }
  866. /**
  867. * Generates a simple html link
  868. * @param string|moodle_url $url
  869. * @param string $text link txt
  870. * @param array $attributes extra html attributes
  871. * @return string HTML fragment
  872. */
  873. public static function link($url, $text, array $attributes = null) {
  874. $attributes = (array)$attributes;
  875. $attributes['href'] = $url;
  876. return self::tag('a', $text, $attributes);
  877. }
  878. /**
  879. * generates a simple checkbox with optional label
  880. * @param string $name
  881. * @param string $value
  882. * @param bool $checked
  883. * @param string $label
  884. * @param array $attributes
  885. * @return string html fragment
  886. */
  887. public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
  888. $attributes = (array)$attributes;
  889. $output = '';
  890. if ($label !== '' and !is_null($label)) {
  891. if (empty($attributes['id'])) {
  892. $attributes['id'] = self::random_id('checkbox_');
  893. }
  894. }
  895. $attributes['type'] = 'checkbox';
  896. $attributes['value'] = $value;
  897. $attributes['name'] = $name;
  898. $attributes['checked'] = $checked ? 'checked' : null;
  899. $output .= self::empty_tag('input', $attributes);
  900. if ($label !== '' and !is_null($label)) {
  901. $output .= self::tag('label', $label, array('for'=>$attributes['id']));
  902. }
  903. return $output;
  904. }
  905. /**
  906. * Generates a simple select yes/no form field
  907. * @param string $name name of select element
  908. * @param bool $selected
  909. * @param array $attributes - html select element attributes
  910. * @return string HRML fragment
  911. */
  912. public static function select_yes_no($name, $selected=true, array $attributes = null) {
  913. $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
  914. return self::select($options, $name, $selected, null, $attributes);
  915. }
  916. /**
  917. * Generates a simple select form field
  918. * @param array $options associative array value=>label ex.:
  919. * array(1=>'One, 2=>Two)
  920. * it is also possible to specify optgroup as complex label array ex.:
  921. * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
  922. * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
  923. * @param string $name name of select element
  924. * @param string|array $selected value or array of values depending on multiple attribute
  925. * @param array|bool $nothing, add nothing selected option, or false of not added
  926. * @param array $attributes - html select element attributes
  927. * @return string HTML fragment
  928. */
  929. public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
  930. $attributes = (array)$attributes;
  931. if (is_array($nothing)) {
  932. foreach ($nothing as $k=>$v) {
  933. if ($v === 'choose' or $v === 'choosedots') {
  934. $nothing[$k] = get_string('choosedots');
  935. }
  936. }
  937. $options = $nothing + $options; // keep keys, do not override
  938. } else if (is_string($nothing) and $nothing !== '') {
  939. // BC
  940. $options = array(''=>$nothing) + $options;
  941. }
  942. // we may accept more values if multiple attribute specified
  943. $selected = (array)$selected;
  944. foreach ($selected as $k=>$v) {
  945. $selected[$k] = (string)$v;
  946. }
  947. if (!isset($attributes['id'])) {
  948. $id = 'menu'.$name;
  949. // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
  950. $id = str_replace('[', '', $id);
  951. $id = str_replace(']', '', $id);
  952. $attributes['id'] = $id;
  953. }
  954. if (!isset($attributes['class'])) {
  955. $class = 'menu'.$name;
  956. // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
  957. $class = str_replace('[', '', $class);
  958. $class = str_replace(']', '', $class);
  959. $attributes['class'] = $class;
  960. }
  961. $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
  962. $attributes['name'] = $name;
  963. if (!empty($attributes['disabled'])) {
  964. $attributes['disabled'] = 'disabled';
  965. } else {
  966. unset($attributes['disabled']);
  967. }
  968. $output = '';
  969. foreach ($options as $value=>$label) {
  970. if (is_array($label)) {
  971. // ignore key, it just has to be unique
  972. $output .= self::select_optgroup(key($label), current($label), $selected);
  973. } else {
  974. $output .= self::select_option($label, $value, $selected);
  975. }
  976. }
  977. return self::tag('select', $output, $attributes);
  978. }
  979. private static function select_option($label, $value, array $selected) {
  980. $attributes = array();
  981. $value = (string)$value;
  982. if (in_array($value, $selected, true)) {
  983. $attributes['selected'] = 'selected';
  984. }
  985. $attributes['value'] = $value;
  986. return self::tag('option', $label, $attributes);
  987. }
  988. private static function select_optgroup($groupname, $options, array $selected) {
  989. if (empty($options)) {
  990. return '';
  991. }
  992. $attributes = array('label'=>$groupname);
  993. $output = '';
  994. foreach ($options as $value=>$label) {
  995. $output .= self::select_option($label, $value, $selected);
  996. }
  997. return self::tag('optgroup', $output, $attributes);
  998. }
  999. /**
  1000. * This is a shortcut for making an hour selector menu.
  1001. * @param string $type The type of selector (years, months, days, hours, minutes)
  1002. * @param string $name fieldname
  1003. * @param int $currenttime A default timestamp in GMT
  1004. * @param int $step minute spacing
  1005. * @param array $attributes - html select element attributes
  1006. * @return HTML fragment
  1007. */
  1008. public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
  1009. if (!$currenttime) {
  1010. $currenttime = time();
  1011. }
  1012. $currentdate = usergetdate($currenttime);
  1013. $userdatetype = $type;
  1014. $timeunits = array();
  1015. switch ($type) {
  1016. case 'years':
  1017. for ($i=1970; $i<=2020; $i++) {
  1018. $timeunits[$i] = $i;
  1019. }
  1020. $userdatetype = 'year';
  1021. break;
  1022. case 'months':
  1023. for ($i=1; $i<=12; $i++) {
  1024. $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
  1025. }
  1026. $userdatetype = 'month';
  1027. $currentdate['month'] = $currentdate['mon'];
  1028. break;
  1029. case 'days':
  1030. for ($i=1; $i<=31; $i++) {
  1031. $timeunits[$i] = $i;
  1032. }
  1033. $userdatetype = 'mday';
  1034. break;
  1035. case 'hours':
  1036. for ($i=0; $i<=23; $i++) {
  1037. $timeunits[$i] = sprintf("%02d",$i);
  1038. }
  1039. break;
  1040. case 'minutes':
  1041. if ($step != 1) {
  1042. $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
  1043. }
  1044. for ($i=0; $i<=59; $i+=$step) {
  1045. $timeunits[$i] = sprintf("%02d",$i);
  1046. }
  1047. break;
  1048. default:
  1049. throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
  1050. }
  1051. if (empty($attributes['id'])) {
  1052. $attributes['id'] = self::random_id('ts_');
  1053. }
  1054. $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
  1055. $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
  1056. return $label.$timerselector;
  1057. }
  1058. /**
  1059. * Shortcut for quick making of lists
  1060. * @param array $items
  1061. * @param string $tag ul or ol
  1062. * @param array $attributes
  1063. * @return string
  1064. */
  1065. public static function alist(array $items, array $attributes = null, $tag = 'ul') {
  1066. //note: 'list' is a reserved keyword ;-)
  1067. $output = '';
  1068. foreach ($items as $item) {
  1069. $output .= html_writer::start_tag('li') . "\n";
  1070. $output .= $item . "\n";
  1071. $output .= html_writer::end_tag('li') . "\n";
  1072. }
  1073. return html_writer::tag($tag, $output, $attributes);
  1074. }
  1075. /**
  1076. * Returns hidden input fields created from url parameters.
  1077. * @param moodle_url $url
  1078. * @param array $exclude list of excluded parameters
  1079. * @return string HTML fragment
  1080. */
  1081. public static function input_hidden_params(moodle_url $url, array $exclude = null) {
  1082. $exclude = (array)$exclude;
  1083. $params = $url->params();
  1084. foreach ($exclude as $key) {
  1085. unset($params[$key]);
  1086. }
  1087. $output = '';
  1088. foreach ($params as $key => $value) {
  1089. $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
  1090. $output .= self::empty_tag('input', $attributes)."\n";
  1091. }
  1092. return $output;
  1093. }
  1094. /**
  1095. * Generate a script tag containing the the specified code.
  1096. *
  1097. * @param string $js the JavaScript code
  1098. * @param moodle_url|string optional url of the external script, $code ignored if specified
  1099. * @return string HTML, the code wrapped in <script> tags.
  1100. */
  1101. public static function script($jscode, $url=null) {
  1102. if ($jscode) {
  1103. $attributes = array('type'=>'text/javascript');
  1104. return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
  1105. } else if ($url) {
  1106. $attributes = array('type'=>'text/javascript', 'src'=>$url);
  1107. return self::tag('script', '', $attributes) . "\n";
  1108. } else {
  1109. return '';
  1110. }
  1111. }
  1112. /**
  1113. * Renders HTML table
  1114. *
  1115. * This method may modify the passed instance by adding some default properties if they are not set yet.
  1116. * If this is not what you want, you should make a full clone of your data before passing them to this
  1117. * method. In most cases this is not an issue at all so we do not clone by default for performance
  1118. * and memory consumption reasons.
  1119. *
  1120. * @param html_table $table data to be rendered
  1121. * @return string HTML code
  1122. */
  1123. public static function table(html_table $table) {
  1124. // prepare table data and populate missing properties with reasonable defaults
  1125. if (!empty($table->align)) {
  1126. foreach ($table->align as $key => $aa) {
  1127. if ($aa) {
  1128. $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
  1129. } else {
  1130. $table->align[$key] = null;
  1131. }
  1132. }
  1133. }
  1134. if (!empty($table->size)) {
  1135. foreach ($table->size as $key => $ss) {
  1136. if ($ss) {
  1137. $table->size[$key] = 'width:'. $ss .';';
  1138. } else {
  1139. $table->size[$key] = null;
  1140. }
  1141. }
  1142. }
  1143. if (!empty($table->wrap)) {
  1144. foreach ($table->wrap as $key => $ww) {
  1145. if ($ww) {
  1146. $table->wrap[$key] = 'white-space:nowrap;';
  1147. } else {
  1148. $table->wrap[$key] = '';
  1149. }
  1150. }
  1151. }
  1152. if (!empty($table->head)) {
  1153. foreach ($table->head as $key => $val) {
  1154. if (!isset($table->align[$key])) {
  1155. $table->align[$key] = null;
  1156. }
  1157. if (!isset($table->size[$key])) {
  1158. $table->size[$key] = null;
  1159. }
  1160. if (!isset($table->wrap[$key])) {
  1161. $table->wrap[$key] = null;
  1162. }
  1163. }
  1164. }
  1165. if (empty($table->attributes['class'])) {
  1166. $table->attributes['class'] = 'generaltable';
  1167. }
  1168. if (!empty($table->tablealign)) {
  1169. $table->attributes['class'] .= ' boxalign' . $table->tablealign;
  1170. }
  1171. // explicitly assigned properties override those defined via $table->attributes
  1172. $table->attributes['class'] = trim($table->attributes['class']);
  1173. $attributes = array_merge($table->attributes, array(
  1174. 'id' => $table->id,
  1175. 'width' => $table->width,
  1176. 'summary' => $table->summary,
  1177. 'cellpadding' => $table->cellpadding,
  1178. 'cellspacing' => $table->cellspacing,
  1179. ));
  1180. $output = html_writer::start_tag('table', $attributes) . "\n";
  1181. $countcols = 0;
  1182. if (!empty($table->head)) {
  1183. $countcols = count($table->head);
  1184. $output .= html_writer::start_tag('thead', array()) . "\n";
  1185. $output .= html_writer::start_tag('tr', array()) . "\n";
  1186. $keys = array_keys($table->head);
  1187. $lastkey = end($keys);
  1188. foreach ($table->head as $key => $heading) {
  1189. // Convert plain string headings into html_table_cell objects
  1190. if (!($heading instanceof html_table_cell)) {
  1191. $headingtext = $heading;
  1192. $heading = new html_table_cell();
  1193. $heading->text = $headingtext;
  1194. $heading->header = true;
  1195. }
  1196. if ($heading->header !== false) {
  1197. $heading->header = true;
  1198. }
  1199. if ($heading->header && empty($heading->scope)) {
  1200. $heading->scope = 'col';
  1201. }
  1202. $heading->attributes['class'] .= ' header c' . $key;
  1203. if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
  1204. $heading->colspan = $table->headspan[$key];
  1205. $countcols += $table->headspan[$key] - 1;
  1206. }
  1207. if ($key == $lastkey) {
  1208. $heading->attributes['class'] .= ' lastcol';
  1209. }
  1210. if (isset($table->colclasses[$key])) {
  1211. $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
  1212. }
  1213. $heading->attributes['class'] = trim($heading->attributes['class']);
  1214. $attributes = array_merge($heading->attributes, array(
  1215. 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
  1216. 'scope' => $heading->scope,
  1217. 'colspan' => $heading->colspan,
  1218. ));
  1219. $tagtype = 'td';
  1220. if ($heading->header === true) {
  1221. $tagtype = 'th';
  1222. }
  1223. $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
  1224. }
  1225. $output .= html_writer::end_tag('tr') . "\n";
  1226. $output .= html_writer::end_tag('thead') . "\n";
  1227. if (empty($table->data)) {
  1228. // For valid XHTML strict every table must contain either a valid tr
  1229. // or a valid tbody... both of which must contain a valid td
  1230. $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
  1231. $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
  1232. $output .= html_writer::end_tag('tbody');
  1233. }
  1234. }
  1235. if (!empty($table->data)) {
  1236. $oddeven = 1;
  1237. $keys = array_keys($table->data);
  1238. $lastrowkey = end($keys);
  1239. $output .= html_writer::start_tag('tbody', array());
  1240. foreach ($table->data as $key => $row) {
  1241. if (($row === 'hr') && ($countcols)) {
  1242. $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
  1243. } else {
  1244. // Convert array rows to html_table_rows and cell strings to html_table_cell objects
  1245. if (!($row instanceof html_table_row)) {
  1246. $newrow = new html_table_row();
  1247. foreach ($row as $item) {
  1248. $cell = new html_table_cell();
  1249. $cell->text = $item;
  1250. $newrow->cells[] = $cell;
  1251. }
  1252. $row = $newrow;
  1253. }
  1254. $oddeven = $oddeven ? 0 : 1;
  1255. if (isset($table->rowclasses[$key])) {
  1256. $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
  1257. }
  1258. $row->attributes['class'] .= ' r' . $oddeven;
  1259. if ($key == $lastrowkey) {
  1260. $row->attributes['class'] .= ' lastrow';
  1261. }
  1262. $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
  1263. $keys2 = array_keys($row->cells);
  1264. $lastkey = end($keys2);
  1265. $gotlastkey = false; //flag for sanity checking
  1266. foreach ($row->cells as $key => $cell) {
  1267. if ($gotlastkey) {
  1268. //This should never happen. Why do we have a cell after the last cell?
  1269. mtrace("A cell with key ($key) was found after the last key ($lastkey)");
  1270. }
  1271. if (!($cell instanceof html_table_cell)) {
  1272. $mycell = new html_table_cell();
  1273. $mycell->text = $cell;
  1274. $cell = $mycell;
  1275. }
  1276. if (($cell->header === true) && empty($cell->scope)) {
  1277. $cell->scope = 'row';
  1278. }
  1279. if (isset($table->colclasses[$key])) {
  1280. $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
  1281. }
  1282. $cell->attributes['class'] .= ' cell c' . $key;
  1283. if ($key == $lastkey) {
  1284. $cell->attributes['class'] .= ' lastcol';
  1285. $gotlastkey = true;
  1286. }
  1287. $tdstyle = '';
  1288. $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
  1289. $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
  1290. $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
  1291. $cell->attributes['class'] = trim($cell->attributes['class']);
  1292. $tdattributes = array_merge($cell->attributes, array(
  1293. 'style' => $tdstyle . $cell->style,
  1294. 'colspan' => $cell->colspan,
  1295. 'rowspan' => $cell->rowspan,
  1296. 'id' => $cell->id,
  1297. 'abbr' => $cell->abbr,
  1298. 'scope' => $cell->scope,
  1299. ));
  1300. $tagtype = 'td';
  1301. if ($cell->header === true) {
  1302. $tagtype = 'th';
  1303. }
  1304. $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
  1305. }
  1306. }
  1307. $output .= html_writer::end_tag('tr') . "\n";
  1308. }
  1309. $output .= html_writer::end_tag('tbody') . "\n";
  1310. }
  1311. $output .= html_writer::end_tag('table') . "\n";
  1312. return $output;
  1313. }
  1314. /**
  1315. * Renders form element label
  1316. *
  1317. * By default, the label is suffixed with a label separator defined in the
  1318. * current language pack (colon by default in the English lang pack).
  1319. * Adding the colon can be explicitly disabled if needed. Label separators
  1320. * are put outside the label tag itself so they are not read by
  1321. * screenreaders (accessibility).
  1322. *
  1323. * Parameter $for explicitly associates …

Large files files are truncated, but you can click here to view the full file