PageRenderTime 58ms CodeModel.GetById 13ms RepoModel.GetById 1ms 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
  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 the label with a form control. When
  1324. * set, the value of this attribute must be the same as the value of
  1325. * the id attribute of the form control in the same document. When null,
  1326. * the label being defined is associated with the control inside the label
  1327. * element.
  1328. *
  1329. * @param string $text content of the label tag
  1330. * @param string|null $for id of the element this label is associated with, null for no association
  1331. * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
  1332. * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
  1333. * @return string HTML of the label element
  1334. */
  1335. public static function label($text, $for, $colonize=true, array $attributes=array()) {
  1336. if (!is_null($for)) {
  1337. $attributes = array_merge($attributes, array('for' => $for));
  1338. }
  1339. $text = trim($text);
  1340. $label = self::tag('label', $text, $attributes);
  1341. /*
  1342. // TODO $colonize disabled for now yet - see MDL-12192 for details
  1343. if (!empty($text) and $colonize) {
  1344. // the $text may end with the colon already, though it is bad string definition style
  1345. $colon = get_string('labelsep', 'langconfig');
  1346. if (!empty($colon)) {
  1347. $trimmed = trim($colon);
  1348. if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
  1349. //debugging('The label text should not end with colon or other label separator,
  1350. // please fix the string definition.', DEBUG_DEVELOPER);
  1351. } else {
  1352. $label .= $colon;
  1353. }
  1354. }
  1355. }
  1356. */
  1357. return $label;
  1358. }
  1359. }
  1360. // ==== JS writer and helper classes, will be probably moved elsewhere ======
  1361. /**
  1362. * Simple javascript output class
  1363. * @copyright 2010 Petr Skoda
  1364. */
  1365. class js_writer {
  1366. /**
  1367. * Returns javascript code calling the function
  1368. * @param string $function function name, can be complex like Y.Event.purgeElement
  1369. * @param array $arguments parameters
  1370. * @param int $delay execution delay in seconds
  1371. * @return string JS code fragment
  1372. */
  1373. public static function function_call($function, array $arguments = null, $delay=0) {
  1374. if ($arguments) {
  1375. $arguments = array_map('json_encode', $arguments);
  1376. $arguments = implode(', ', $arguments);
  1377. } else {
  1378. $arguments = '';
  1379. }
  1380. $js = "$function($arguments);";
  1381. if ($delay) {
  1382. $delay = $delay * 1000; // in miliseconds
  1383. $js = "setTimeout(function() { $js }, $delay);";
  1384. }
  1385. return $js . "\n";
  1386. }
  1387. /**
  1388. * Special function which adds Y as first argument of fucntion call.
  1389. * @param string $function
  1390. * @param array $extraarguments
  1391. * @return string
  1392. */
  1393. public static function function_call_with_Y($function, array $extraarguments = null) {
  1394. if ($extraarguments) {
  1395. $extraarguments = array_map('json_encode', $extraarguments);
  1396. $arguments = 'Y, ' . implode(', ', $extraarguments);
  1397. } else {
  1398. $arguments = 'Y';
  1399. }
  1400. return "$function($arguments);\n";
  1401. }
  1402. /**
  1403. * Returns JavaScript code to initialise a new object
  1404. * @param string|null $var If it is null then no var is assigned the new object
  1405. * @param string $class
  1406. * @param array $arguments
  1407. * @param array $requirements
  1408. * @param int $delay
  1409. * @return string
  1410. */
  1411. public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
  1412. if (is_array($arguments)) {
  1413. $arguments = array_map('json_encode', $arguments);
  1414. $arguments = implode(', ', $arguments);
  1415. }
  1416. if ($var === null) {
  1417. $js = "new $class(Y, $arguments);";
  1418. } else if (strpos($var, '.')!==false) {
  1419. $js = "$var = new $class(Y, $arguments);";
  1420. } else {
  1421. $js = "var $var = new $class(Y, $arguments);";
  1422. }
  1423. if ($delay) {
  1424. $delay = $delay * 1000; // in miliseconds
  1425. $js = "setTimeout(function() { $js }, $delay);";
  1426. }
  1427. if (count($requirements) > 0) {
  1428. $requirements = implode("', '", $requirements);
  1429. $js = "Y.use('$requirements', function(Y){ $js });";
  1430. }
  1431. return $js."\n";
  1432. }
  1433. /**
  1434. * Returns code setting value to variable
  1435. * @param string $name
  1436. * @param mixed $value json serialised value
  1437. * @param bool $usevar add var definition, ignored for nested properties
  1438. * @return string JS code fragment
  1439. */
  1440. public static function set_variable($name, $value, $usevar=true) {
  1441. $output = '';
  1442. if ($usevar) {
  1443. if (strpos($name, '.')) {
  1444. $output .= '';
  1445. } else {
  1446. $output .= 'var ';
  1447. }
  1448. }
  1449. $output .= "$name = ".json_encode($value).";";
  1450. return $output;
  1451. }
  1452. /**
  1453. * Writes event handler attaching code
  1454. * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
  1455. * @param string $event A valid DOM event (click, mousedown, change etc.)
  1456. * @param string $function The name of the function to call
  1457. * @param array $arguments An optional array of argument parameters to pass to the function
  1458. * @return string JS code fragment
  1459. */
  1460. public static function event_handler($selector, $event, $function, array $arguments = null) {
  1461. $selector = json_encode($selector);
  1462. $output = "Y.on('$event', $function, $selector, null";
  1463. if (!empty($arguments)) {
  1464. $output .= ', ' . json_encode($arguments);
  1465. }
  1466. return $output . ");\n";
  1467. }
  1468. }
  1469. /**
  1470. * Holds all the information required to render a <table> by {@see core_renderer::table()}
  1471. *
  1472. * Example of usage:
  1473. * $t = new html_table();
  1474. * ... // set various properties of the object $t as described below
  1475. * echo html_writer::table($t);
  1476. *
  1477. * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
  1478. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1479. * @since Moodle 2.0
  1480. */
  1481. class html_table {
  1482. /**
  1483. * @var string value to use for the id attribute of the table
  1484. */
  1485. public $id = null;
  1486. /**
  1487. * @var array attributes of HTML attributes for the <table> element
  1488. */
  1489. public $attributes = array();
  1490. /**
  1491. * For more control over the rendering of the headers, an array of html_table_cell objects
  1492. * can be passed instead of an array of strings.
  1493. * @var array of headings. The n-th array item is used as a heading of the n-th column.
  1494. *
  1495. * Example of usage:
  1496. * $t->head = array('Student', 'Grade');
  1497. */
  1498. public $head;
  1499. /**
  1500. * @var array can be used to make a heading span multiple columns
  1501. *
  1502. * Example of usage:
  1503. * $t->headspan = array(2,1);
  1504. *
  1505. * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
  1506. * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
  1507. */
  1508. public $headspan;
  1509. /**
  1510. * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
  1511. * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
  1512. * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
  1513. *
  1514. * Examples of usage:
  1515. * $t->align = array(null, 'right');
  1516. * or
  1517. * $t->align[1] = 'right';
  1518. *
  1519. */
  1520. public $align;
  1521. /**
  1522. * @var array of column sizes. The value is used as CSS 'size' property.
  1523. *
  1524. * Examples of usage:
  1525. * $t->size = array('50%', '50%');
  1526. * or
  1527. * $t->size[1] = '120px';
  1528. */
  1529. public $size;
  1530. /**
  1531. * @var array of wrapping information. The only possible value is 'nowrap' that sets the
  1532. * CSS property 'white-space' to the value 'nowrap' in the given column.
  1533. *
  1534. * Example of usage:
  1535. * $t->wrap = array(null, 'nowrap');
  1536. */
  1537. public $wrap;
  1538. /**
  1539. * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
  1540. * $head specified, the string 'hr' (for horizontal ruler) can be used
  1541. * instead of an array of cells data resulting in a divider rendered.
  1542. *
  1543. * Example of usage with array of arrays:
  1544. * $row1 = array('Harry Potter', '76 %');
  1545. * $row2 = array('Hermione Granger', '100 %');
  1546. * $t->data = array($row1, $row2);
  1547. *
  1548. * Example with array of html_table_row objects: (used for more fine-grained control)
  1549. * $cell1 = new html_table_cell();
  1550. * $cell1->text = 'Harry Potter';
  1551. * $cell1->colspan = 2;
  1552. * $row1 = new html_table_row();
  1553. * $row1->cells[] = $cell1;
  1554. * $cell2 = new html_table_cell();
  1555. * $cell2->text = 'Hermione Granger';
  1556. * $cell3 = new html_table_cell();
  1557. * $cell3->text = '100 %';
  1558. * $row2 = new html_table_row();
  1559. * $row2->cells = array($cell2, $cell3);
  1560. * $t->data = array($row1, $row2);
  1561. */
  1562. public $data;
  1563. /**
  1564. * @var string width of the table, percentage of the page preferred. Defaults to 80%
  1565. * @deprecated since Moodle 2.0. Styling should be in the CSS.
  1566. */
  1567. public $width = null;
  1568. /**
  1569. * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
  1570. * @deprecated since Moodle 2.0. Styling should be in the CSS.
  1571. */
  1572. public $tablealign = null;
  1573. /**
  1574. * @var int padding on each cell, in pixels
  1575. * @deprecated since Moodle 2.0. Styling should be in the CSS.
  1576. */
  1577. public $cellpadding = null;
  1578. /**
  1579. * @var int spacing between cells, in pixels
  1580. * @deprecated since Moodle 2.0. Styling should be in the CSS.
  1581. */
  1582. public $cellspacing = null;
  1583. /**
  1584. * @var array classes to add to particular rows, space-separated string.
  1585. * Classes 'r0' or 'r1' are added automatically for every odd or even row,
  1586. * respectively. Class 'lastrow' is added automatically for the last row
  1587. * in the table.
  1588. *
  1589. * Example of usage:
  1590. * $t->rowclasses[9] = 'tenth'
  1591. */
  1592. public $rowclasses;
  1593. /**
  1594. * @var array classes to add to every cell in a particular column,
  1595. * space-separated string. Class 'cell' is added automatically by the renderer.
  1596. * Classes 'c0' or 'c1' are added automatically for every odd or even column,
  1597. * respectively. Class 'lastcol' is added automatically for all last cells
  1598. * in a row.
  1599. *
  1600. * Example of usage:
  1601. * $t->colclasses = array(null, 'grade');
  1602. */
  1603. public $colclasses;
  1604. /**
  1605. * @var string description of the contents for screen readers.
  1606. */
  1607. public $summary;
  1608. /**
  1609. * Constructor
  1610. */
  1611. public function __construct() {
  1612. $this->attributes['class'] = '';
  1613. }
  1614. }
  1615. /**
  1616. * Component representing a table row.
  1617. *
  1618. * @copyright 2009 Nicolas Connault
  1619. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1620. * @since Moodle 2.0
  1621. */
  1622. class html_table_row {
  1623. /**
  1624. * @var string value to use for the id attribute of the row
  1625. */
  1626. public $id = null;
  1627. /**
  1628. * @var array $cells Array of html_table_cell objects
  1629. */
  1630. public $cells = array();
  1631. /**
  1632. * @var string $style value to use for the style attribute of the table row
  1633. */
  1634. public $style = null;
  1635. /**
  1636. * @var array attributes of additional HTML attributes for the <tr> element
  1637. */
  1638. public $attributes = array();
  1639. /**
  1640. * Constructor
  1641. * @param array $cells
  1642. */
  1643. public function __construct(array $cells=null) {
  1644. $this->attributes['class'] = '';
  1645. $cells = (array)$cells;
  1646. foreach ($cells as $cell) {
  1647. if ($cell instanceof html_table_cell) {
  1648. $this->cells[] = $cell;
  1649. } else {
  1650. $this->cells[] = new html_table_cell($cell);
  1651. }
  1652. }
  1653. }
  1654. }
  1655. /**
  1656. * Component representing a table cell.
  1657. *
  1658. * @copyright 2009 Nicolas Connault
  1659. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1660. * @since Moodle 2.0
  1661. */
  1662. class html_table_cell {
  1663. /**
  1664. * @var string value to use for the id attribute of the cell
  1665. */
  1666. public $id = null;
  1667. /**
  1668. * @var string $text The contents of the cell
  1669. */
  1670. public $text;
  1671. /**
  1672. * @var string $abbr Abbreviated version of the contents of the cell
  1673. */
  1674. public $abbr = null;
  1675. /**
  1676. * @var int $colspan Number of columns this cell should span
  1677. */
  1678. public $colspan = null;
  1679. /**
  1680. * @var int $rowspan Number of rows this cell should span
  1681. */
  1682. public $rowspan = null;
  1683. /**
  1684. * @var string $scope Defines a way to associate header cells and data cells in a table
  1685. */
  1686. public $scope = null;
  1687. /**
  1688. * @var boolean $header Whether or not this cell is a header cell
  1689. */
  1690. public $header = null;
  1691. /**
  1692. * @var string $style value to use for the style attribute of the table cell
  1693. */
  1694. public $style = null;
  1695. /**
  1696. * @var array attributes of additional HTML attributes for the <td> element
  1697. */
  1698. public $attributes = array();
  1699. public function __construct($text = null) {
  1700. $this->text = $text;
  1701. $this->attributes['class'] = '';
  1702. }
  1703. }
  1704. /// Complex components aggregating simpler components
  1705. /**
  1706. * Component representing a paging bar.
  1707. *
  1708. * @copyright 2009 Nicolas Connault
  1709. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1710. * @since Moodle 2.0
  1711. */
  1712. class paging_bar implements renderable {
  1713. /**
  1714. * @var int $maxdisplay The maximum number of pagelinks to display
  1715. */
  1716. public $maxdisplay = 18;
  1717. /**
  1718. * @var int $totalcount post or get
  1719. */
  1720. public $totalcount;
  1721. /**
  1722. * @var int $page The page you are currently viewing
  1723. */
  1724. public $page;
  1725. /**
  1726. * @var int $perpage The number of entries that should be shown per page
  1727. */
  1728. public $perpage;
  1729. /**
  1730. * @var string $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
  1731. * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
  1732. */
  1733. public $baseurl;
  1734. /**
  1735. * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
  1736. */
  1737. public $pagevar;
  1738. /**
  1739. * @var string $previouslink A HTML link representing the "previous" page
  1740. */
  1741. public $previouslink = null;
  1742. /**
  1743. * @var tring $nextlink A HTML link representing the "next" page
  1744. */
  1745. public $nextlink = null;
  1746. /**
  1747. * @var tring $firstlink A HTML link representing the first page
  1748. */
  1749. public $firstlink = null;
  1750. /**
  1751. * @var tring $lastlink A HTML link representing the last page
  1752. */
  1753. public $lastlink = null;
  1754. /**
  1755. * @var array $pagelinks An array of strings. One of them is just a string: the current page
  1756. */
  1757. public $pagelinks = array();
  1758. /**
  1759. * Constructor paging_bar with only the required params.
  1760. *
  1761. * @param int $totalcount The total number of entries available to be paged through
  1762. * @param int $page The page you are currently viewing
  1763. * @param int $perpage The number of entries that should be shown per page
  1764. * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
  1765. * @param string $pagevar name of page parameter that holds the page number
  1766. */
  1767. public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
  1768. $this->totalcount = $totalcount;
  1769. $this->page = $page;
  1770. $this->perpage = $perpage;
  1771. $this->baseurl = $baseurl;
  1772. $this->pagevar = $pagevar;
  1773. }
  1774. /**
  1775. * @return void
  1776. */
  1777. public function prepare(renderer_base $output, moodle_page $page, $target) {
  1778. if (!isset($this->totalcount) || is_null($this->totalcount)) {
  1779. throw new coding_exception('paging_bar requires a totalcount value.');
  1780. }
  1781. if (!isset($this->page) || is_null($this->page)) {
  1782. throw new coding_exception('paging_bar requires a page value.');
  1783. }
  1784. if (empty($this->perpage)) {
  1785. throw new coding_exception('paging_bar requires a perpage value.');
  1786. }
  1787. if (empty($this->baseurl)) {
  1788. throw new coding_exception('paging_bar requires a baseurl value.');
  1789. }
  1790. if ($this->totalcount > $this->perpage) {
  1791. $pagenum = $this->page - 1;
  1792. if ($this->page > 0) {
  1793. $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
  1794. }
  1795. if ($this->perpage > 0) {
  1796. $lastpage = ceil($this->totalcount / $this->perpage);
  1797. } else {
  1798. $lastpage = 1;
  1799. }
  1800. if ($this->page > 15) {
  1801. $startpage = $this->page - 10;
  1802. $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
  1803. } else {
  1804. $startpage = 0;
  1805. }
  1806. $currpage = $startpage;
  1807. $displaycount = $displaypage = 0;
  1808. while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
  1809. $displaypage = $currpage + 1;
  1810. if ($this->page == $currpage) {
  1811. $this->pagelinks[] = $displaypage;
  1812. } else {
  1813. $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
  1814. $this->pagelinks[] = $pagelink;
  1815. }
  1816. $displaycount++;
  1817. $currpage++;
  1818. }
  1819. if ($currpage < $lastpage) {
  1820. $lastpageactual = $lastpage - 1;
  1821. $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
  1822. }
  1823. $pagenum = $this->page + 1;
  1824. if ($pagenum != $displaypage) {
  1825. $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
  1826. }
  1827. }
  1828. }
  1829. }
  1830. /**
  1831. * This class represents how a block appears on a page.
  1832. *
  1833. * During output, each block instance is asked to return a block_contents object,
  1834. * those are then passed to the $OUTPUT->block function for display.
  1835. *
  1836. * {@link $contents} should probably be generated using a moodle_block_..._renderer.
  1837. *
  1838. * Other block-like things that need to appear on the page, for example the
  1839. * add new block UI, are also represented as block_contents objects.
  1840. *
  1841. * @copyright 2009 Tim Hunt
  1842. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1843. * @since Moodle 2.0
  1844. */
  1845. class block_contents {
  1846. /** @var int used to set $skipid. */
  1847. protected static $idcounter = 1;
  1848. const NOT_HIDEABLE = 0;
  1849. const VISIBLE = 1;
  1850. const HIDDEN = 2;
  1851. /**
  1852. * @var integer $skipid All the blocks (or things that look like blocks)
  1853. * printed on a page are given a unique number that can be used to construct
  1854. * id="" attributes. This is set automatically be the {@link prepare()} method.
  1855. * Do not try to set it manually.
  1856. */
  1857. public $skipid;
  1858. /**
  1859. * @var integer If this is the contents of a real block, this should be set to
  1860. * the block_instance.id. Otherwise this should be set to 0.
  1861. */
  1862. public $blockinstanceid = 0;
  1863. /**
  1864. * @var integer if this is a real block instance, and there is a corresponding
  1865. * block_position.id for the block on this page, this should be set to that id.
  1866. * Otherwise it should be 0.
  1867. */
  1868. public $blockpositionid = 0;
  1869. /**
  1870. * @param array $attributes an array of attribute => value pairs that are put on the
  1871. * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
  1872. */
  1873. public $attributes;
  1874. /**
  1875. * @param string $title The title of this block. If this came from user input,
  1876. * it should already have had format_string() processing done on it. This will
  1877. * be output inside <h2> tags. Please do not cause invalid XHTML.
  1878. */
  1879. public $title = '';
  1880. /**
  1881. * @param string $content HTML for the content
  1882. */
  1883. public $content = '';
  1884. /**
  1885. * @param array $list an alternative to $content, it you want a list of things with optional icons.
  1886. */
  1887. public $footer = '';
  1888. /**
  1889. * Any small print that should appear under the block to explain to the
  1890. * teacher about the block, for example 'This is a sticky block that was
  1891. * added in the system context.'
  1892. * @var string
  1893. */
  1894. public $annotation = '';
  1895. /**
  1896. * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
  1897. * the user can toggle whether this block is visible.
  1898. */
  1899. public $collapsible = self::NOT_HIDEABLE;
  1900. /**
  1901. * A (possibly empty) array of editing controls. Each element of this array
  1902. * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
  1903. * $icon is the icon name. Fed to $OUTPUT->pix_url.
  1904. * @var array
  1905. */
  1906. public $controls = array();
  1907. /**
  1908. * Create new instance of block content
  1909. * @param array $attributes
  1910. */
  1911. public function __construct(array $attributes=null) {
  1912. $this->skipid = self::$idcounter;
  1913. self::$idcounter += 1;
  1914. if ($attributes) {
  1915. // standard block
  1916. $this->attributes = $attributes;
  1917. } else {
  1918. // simple "fake" blocks used in some modules and "Add new block" block
  1919. $this->attributes = array('class'=>'block');
  1920. }
  1921. }
  1922. /**
  1923. * Add html class to block
  1924. * @param string $class
  1925. * @return void
  1926. */
  1927. public function add_class($class) {
  1928. $this->attributes['class'] .= ' '.$class;
  1929. }
  1930. }
  1931. /**
  1932. * This class represents a target for where a block can go when it is being moved.
  1933. *
  1934. * This needs to be rendered as a form with the given hidden from fields, and
  1935. * clicking anywhere in the form should submit it. The form action should be
  1936. * $PAGE->url.
  1937. *
  1938. * @copyright 2009 Tim Hunt
  1939. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1940. * @since Moodle 2.0
  1941. */
  1942. class block_move_target {
  1943. /**
  1944. * Move url
  1945. * @var moodle_url
  1946. */
  1947. public $url;
  1948. /**
  1949. * label
  1950. * @var string
  1951. */
  1952. public $text;
  1953. /**
  1954. * Constructor
  1955. * @param string $text
  1956. * @param moodle_url $url
  1957. */
  1958. public function __construct($text, moodle_url $url) {
  1959. $this->text = $text;
  1960. $this->url = $url;
  1961. }
  1962. }
  1963. /**
  1964. * Custom menu item
  1965. *
  1966. * This class is used to represent one item within a custom menu that may or may
  1967. * not have children.
  1968. *
  1969. * @copyright 2010 Sam Hemelryk
  1970. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1971. * @since Moodle 2.0
  1972. */
  1973. class custom_menu_item implements renderable {
  1974. /**
  1975. * The text to show for the item
  1976. * @var string
  1977. */
  1978. protected $text;
  1979. /**
  1980. * The link to give the icon if it has no children
  1981. * @var moodle_url
  1982. */
  1983. protected $url;
  1984. /**
  1985. * A title to apply to the item. By default the text
  1986. * @var string
  1987. */
  1988. protected $title;
  1989. /**
  1990. * A sort order for the item, not necessary if you order things in the CFG var
  1991. * @var int
  1992. */
  1993. protected $sort;
  1994. /**
  1995. * A reference to the parent for this item or NULL if it is a top level item
  1996. * @var custom_menu_item
  1997. */
  1998. protected $parent;
  1999. /**
  2000. * A array in which to store children this item has.
  2001. * @var array
  2002. */
  2003. protected $children = array();
  2004. /**
  2005. * A reference to the sort var of the last child that was added
  2006. * @var int
  2007. */
  2008. protected $lastsort = 0;
  2009. /**
  2010. * Constructs the new custom menu item
  2011. *
  2012. * @param string $text
  2013. * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
  2014. * @param string $title A title to apply to this item [Optional]
  2015. * @param int $sort A sort or to use if we need to sort differently [Optional]
  2016. * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
  2017. * belongs to, only if the child has a parent. [Optional]
  2018. */
  2019. public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
  2020. $this->text = $text;
  2021. $this->url = $url;
  2022. $this->title = $title;
  2023. $this->sort = (int)$sort;
  2024. $this->parent = $parent;
  2025. }
  2026. /**
  2027. * Adds a custom menu item as a child of this node given its properties.
  2028. *
  2029. * @param string $text
  2030. * @param moodle_url $url
  2031. * @param string $title
  2032. * @param int $sort
  2033. * @return custom_menu_item
  2034. */
  2035. public function add($text, moodle_url $url=null, $title=null, $sort = null) {
  2036. $key = count($this->children);
  2037. if (empty($sort)) {
  2038. $sort = $this->lastsort + 1;
  2039. }
  2040. $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
  2041. $this->lastsort = (int)$sort;
  2042. return $this->children[$key];
  2043. }
  2044. /**
  2045. * Returns the text for this item
  2046. * @return string
  2047. */
  2048. public function get_text() {
  2049. return $this->text;
  2050. }
  2051. /**
  2052. * Returns the url for this item
  2053. * @return moodle_url
  2054. */
  2055. public function get_url() {
  2056. return $this->url;
  2057. }
  2058. /**
  2059. * Returns the title for this item
  2060. * @return string
  2061. */
  2062. public function get_title() {
  2063. return $this->title;
  2064. }
  2065. /**
  2066. * Sorts and returns the children for this item
  2067. * @return array
  2068. */
  2069. public function get_children() {
  2070. $this->sort();
  2071. return $this->children;
  2072. }
  2073. /**
  2074. * Gets the sort order for this child
  2075. * @return int
  2076. */
  2077. public function get_sort_order() {
  2078. return $this->sort;
  2079. }
  2080. /**
  2081. * Gets the parent this child belong to
  2082. * @return custom_menu_item
  2083. */
  2084. public function get_parent() {
  2085. return $this->parent;
  2086. }
  2087. /**
  2088. * Sorts the children this item has
  2089. */
  2090. public function sort() {
  2091. usort($this->children, array('custom_menu','sort_custom_menu_items'));
  2092. }
  2093. /**
  2094. * Returns true if this item has any children
  2095. * @return bool
  2096. */
  2097. public function has_children() {
  2098. return (count($this->children) > 0);
  2099. }
  2100. /**
  2101. * Sets the text for the node
  2102. * @param string $text
  2103. */
  2104. public function set_text($text) {
  2105. $this->text = (string)$text;
  2106. }
  2107. /**
  2108. * Sets the title for the node
  2109. * @param string $title
  2110. */
  2111. public function set_title($title) {
  2112. $this->title = (string)$title;
  2113. }
  2114. /**
  2115. * Sets the url for the node
  2116. * @param moodle_url $url
  2117. */
  2118. public function set_url(moodle_url $url) {
  2119. $this->url = $url;
  2120. }
  2121. }
  2122. /**
  2123. * Custom menu class
  2124. *
  2125. * This class is used to operate a custom menu that can be rendered for the page.
  2126. * The custom menu is built using $CFG->custommenuitems and is a structured collection
  2127. * of custom_menu_item nodes that can be rendered by the core renderer.
  2128. *
  2129. * To configure the custom menu:
  2130. * Settings: Administration > Appearance > Themes > Theme settings
  2131. *
  2132. * @copyright 2010 Sam Hemelryk
  2133. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2134. * @since Moodle 2.0
  2135. */
  2136. class custom_menu extends custom_menu_item {
  2137. /**
  2138. * Creates the custom menu
  2139. * @param string $text Sets the text for this custom menu, never gets used and is optional
  2140. */
  2141. public function __construct($text='base') {
  2142. global $CFG;
  2143. parent::__construct($text);
  2144. if (!empty($CFG->custommenuitems)) {
  2145. $this->override_children(self::convert_text_to_menu_nodes($CFG->custommenuitems));
  2146. }
  2147. }
  2148. /**
  2149. * Overrides the children of this custom menu. Useful when getting children
  2150. * from $CFG->custommenuitems
  2151. */
  2152. public function override_children(array $children) {
  2153. $this->children = array();
  2154. foreach ($children as $child) {
  2155. if ($child instanceof custom_menu_item) {
  2156. $this->children[] = $child;
  2157. }
  2158. }
  2159. }
  2160. /**
  2161. * Converts a string into a structured array of custom_menu_items which can
  2162. * then be added to a custom menu.
  2163. *
  2164. * Structure:
  2165. * text|url|title
  2166. * The number of hyphens at the start determines the depth of the item
  2167. *
  2168. * Example structure:
  2169. * First level first item|http://www.moodle.com/
  2170. * -Second level first item|http://www.moodle.com/partners/
  2171. * -Second level second item|http://www.moodle.com/hq/
  2172. * --Third level first item|http://www.moodle.com/jobs/
  2173. * -Second level third item|http://www.moodle.com/development/
  2174. * First level second item|http://www.moodle.com/feedback/
  2175. * First level third item
  2176. *
  2177. * @static
  2178. * @param string $text
  2179. * @return array
  2180. */
  2181. public static function convert_text_to_menu_nodes($text) {
  2182. $lines = explode("\n", $text);
  2183. $children = array();
  2184. $lastchild = null;
  2185. $lastdepth = null;
  2186. $lastsort = 0;
  2187. foreach ($lines as $line) {
  2188. $line = trim($line);
  2189. $bits = explode('|', $line ,4); // name|url|title|sort
  2190. if (!array_key_exists(0, $bits) || empty($bits[0])) {
  2191. // Every item must have a name to be valid
  2192. continue;
  2193. } else {
  2194. $bits[0] = ltrim($bits[0],'-');
  2195. }
  2196. if (!array_key_exists(1, $bits)) {
  2197. // Set the url to null
  2198. $bits[1] = null;
  2199. } else {
  2200. // Make sure the url is a moodle url
  2201. $bits[1] = new moodle_url(trim($bits[1]));
  2202. }
  2203. if (!array_key_exists(2, $bits)) {
  2204. // Set the title to null seeing as there isn't one
  2205. $bits[2] = $bits[0];
  2206. }
  2207. // Set an incremental sort order to keep it simple.
  2208. $bits[3] = $lastsort;
  2209. $lastsort = $bits[3]+1;
  2210. if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
  2211. $depth = strlen($match[1]);
  2212. if ($depth < $lastdepth) {
  2213. $difference = $lastdepth - $depth;
  2214. if ($lastdepth > 1 && $lastdepth != $difference) {
  2215. $tempchild = $lastchild->get_parent();
  2216. for ($i =0; $i < $difference; $i++) {
  2217. $tempchild = $tempchild->get_parent();
  2218. }
  2219. $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $bits[3]);
  2220. } else {
  2221. $depth = 0;
  2222. $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
  2223. $children[] = $lastchild;
  2224. }
  2225. } else if ($depth > $lastdepth) {
  2226. $depth = $lastdepth + 1;
  2227. $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $bits[3]);
  2228. } else {
  2229. if ($depth == 0) {
  2230. $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
  2231. $children[] = $lastchild;
  2232. } else {
  2233. $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
  2234. }
  2235. }
  2236. } else {
  2237. $depth = 0;
  2238. $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
  2239. $children[] = $lastchild;
  2240. }
  2241. $lastdepth = $depth;
  2242. }
  2243. return $children;
  2244. }
  2245. /**
  2246. * Sorts two custom menu items
  2247. *
  2248. * This function is designed to be used with the usort method
  2249. * usort($this->children, array('custom_menu','sort_custom_menu_items'));
  2250. *
  2251. * @param custom_menu_item $itema
  2252. * @param custom_menu_item $itemb
  2253. * @return int
  2254. */
  2255. public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
  2256. $itema = $itema->get_sort_order();
  2257. $itemb = $itemb->get_sort_order();
  2258. if ($itema == $itemb) {
  2259. return 0;
  2260. }
  2261. return ($itema > $itemb) ? +1 : -1;
  2262. }
  2263. }