MDL-34011 Lesson module: fixed incorrect display of student attempt for short answer...
[moodle.git] / lib / outputcomponents.php
blobd00f6348a90244a5b9a94fa07d71873a4cae6350
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.
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/>.
17 /**
18 * Classes representing HTML elements, used by $OUTPUT methods
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
23 * @package core
24 * @category output
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Interface marking other classes as suitable for renderer_base::render()
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
35 * @package core
36 * @category output
38 interface renderable {
39 // intentionally empty
42 /**
43 * Data structure representing a file picker.
45 * @copyright 2010 Dongsheng Cai
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 * @since Moodle 2.0
48 * @package core
49 * @category output
51 class file_picker implements renderable {
53 /**
54 * @var stdClass An object containing options for the file picker
56 public $options;
58 /**
59 * Constructs a file picker object.
61 * The following are possible options for the filepicker:
62 * - accepted_types (*)
63 * - return_types (FILE_INTERNAL)
64 * - env (filepicker)
65 * - client_id (uniqid)
66 * - itemid (0)
67 * - maxbytes (-1)
68 * - maxfiles (1)
69 * - buttonname (false)
71 * @param stdClass $options An object containing options for the file picker.
73 public function __construct(stdClass $options) {
74 global $CFG, $USER, $PAGE;
75 require_once($CFG->dirroot. '/repository/lib.php');
76 $defaults = array(
77 'accepted_types'=>'*',
78 'return_types'=>FILE_INTERNAL,
79 'env' => 'filepicker',
80 'client_id' => uniqid(),
81 'itemid' => 0,
82 'maxbytes'=>-1,
83 'maxfiles'=>1,
84 'buttonname'=>false
86 foreach ($defaults as $key=>$value) {
87 if (empty($options->$key)) {
88 $options->$key = $value;
92 $options->currentfile = '';
93 if (!empty($options->itemid)) {
94 $fs = get_file_storage();
95 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
96 if (empty($options->filename)) {
97 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
98 $file = reset($files);
100 } else {
101 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
103 if (!empty($file)) {
104 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
108 // initilise options, getting files in root path
109 $this->options = initialise_filepicker($options);
111 // copying other options
112 foreach ($options as $name=>$value) {
113 if (!isset($this->options->$name)) {
114 $this->options->$name = $value;
121 * Data structure representing a user picture.
123 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
125 * @since Modle 2.0
126 * @package core
127 * @category output
129 class user_picture implements renderable {
131 * @var array List of mandatory fields in user record here. (do not include
132 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
134 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
137 * @var stdClass A user object with at least fields all columns specified
138 * in $fields array constant set.
140 public $user;
143 * @var int The course id. Used when constructing the link to the user's
144 * profile, page course id used if not specified.
146 public $courseid;
149 * @var bool Add course profile link to image
151 public $link = true;
154 * @var int Size in pixels. Special values are (true/1 = 100px) and
155 * (false/0 = 35px)
156 * for backward compatibility.
158 public $size = 35;
161 * @var bool Add non-blank alt-text to the image.
162 * Default true, set to false when image alt just duplicates text in screenreaders.
164 public $alttext = true;
167 * @var bool Whether or not to open the link in a popup window.
169 public $popup = false;
172 * @var string Image class attribute
174 public $class = 'userpicture';
177 * User picture constructor.
179 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
180 * It is recommended to add also contextid of the user for performance reasons.
182 public function __construct(stdClass $user) {
183 global $DB;
185 if (empty($user->id)) {
186 throw new coding_exception('User id is required when printing user avatar image.');
189 // only touch the DB if we are missing data and complain loudly...
190 $needrec = false;
191 foreach (self::$fields as $field) {
192 if (!array_key_exists($field, $user)) {
193 $needrec = true;
194 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
195 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
196 break;
200 if ($needrec) {
201 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
202 } else {
203 $this->user = clone($user);
208 * Returns a list of required user fields, useful when fetching required user info from db.
210 * In some cases we have to fetch the user data together with some other information,
211 * the idalias is useful there because the id would otherwise override the main
212 * id of the result record. Please note it has to be converted back to id before rendering.
214 * @param string $tableprefix name of database table prefix in query
215 * @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)
216 * @param string $idalias alias of id field
217 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
218 * @return string
220 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
221 if (!$tableprefix and !$extrafields and !$idalias) {
222 return implode(',', self::$fields);
224 if ($tableprefix) {
225 $tableprefix .= '.';
227 $fields = array();
228 foreach (self::$fields as $field) {
229 if ($field === 'id' and $idalias and $idalias !== 'id') {
230 $fields[$field] = "$tableprefix$field AS $idalias";
231 } else {
232 if ($fieldprefix and $field !== 'id') {
233 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
234 } else {
235 $fields[$field] = "$tableprefix$field";
239 // add extra fields if not already there
240 if ($extrafields) {
241 foreach ($extrafields as $e) {
242 if ($e === 'id' or isset($fields[$e])) {
243 continue;
245 if ($fieldprefix) {
246 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
247 } else {
248 $fields[$e] = "$tableprefix$e";
252 return implode(',', $fields);
256 * Extract the aliased user fields from a given record
258 * Given a record that was previously obtained using {@link self::fields()} with aliases,
259 * this method extracts user related unaliased fields.
261 * @param stdClass $record containing user picture fields
262 * @param array $extrafields extra fields included in the $record
263 * @param string $idalias alias of the id field
264 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
265 * @return stdClass object with unaliased user fields
267 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
269 if (empty($idalias)) {
270 $idalias = 'id';
273 $return = new stdClass();
275 foreach (self::$fields as $field) {
276 if ($field === 'id') {
277 if (property_exists($record, $idalias)) {
278 $return->id = $record->{$idalias};
280 } else {
281 if (property_exists($record, $fieldprefix.$field)) {
282 $return->{$field} = $record->{$fieldprefix.$field};
286 // add extra fields if not already there
287 if ($extrafields) {
288 foreach ($extrafields as $e) {
289 if ($e === 'id' or property_exists($return, $e)) {
290 continue;
292 $return->{$e} = $record->{$fieldprefix.$e};
296 return $return;
300 * Works out the URL for the users picture.
302 * This method is recommended as it avoids costly redirects of user pictures
303 * if requests are made for non-existent files etc.
305 * @param moodle_page $page
306 * @param renderer_base $renderer
307 * @return moodle_url
309 public function get_url(moodle_page $page, renderer_base $renderer = null) {
310 global $CFG;
312 if (is_null($renderer)) {
313 $renderer = $page->get_renderer('core');
316 // Sort out the filename and size. Size is only required for the gravatar
317 // implementation presently.
318 if (empty($this->size)) {
319 $filename = 'f2';
320 $size = 35;
321 } else if ($this->size === true or $this->size == 1) {
322 $filename = 'f1';
323 $size = 100;
324 } else if ($this->size > 100) {
325 $filename = 'f3';
326 $size = (int)$this->size;
327 } else if ($this->size >= 50) {
328 $filename = 'f1';
329 $size = (int)$this->size;
330 } else {
331 $filename = 'f2';
332 $size = (int)$this->size;
335 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
337 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
338 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
339 // Protect images if login required and not logged in;
340 // also if login is required for profile images and is not logged in or guest
341 // do not use require_login() because it is expensive and not suitable here anyway.
342 return $defaulturl;
345 // First try to detect deleted users - but do not read from database for performance reasons!
346 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
347 // All deleted users should have email replaced by md5 hash,
348 // all active users are expected to have valid email.
349 return $defaulturl;
352 // Did the user upload a picture?
353 if ($this->user->picture > 0) {
354 if (!empty($this->user->contextid)) {
355 $contextid = $this->user->contextid;
356 } else {
357 $context = context_user::instance($this->user->id, IGNORE_MISSING);
358 if (!$context) {
359 // This must be an incorrectly deleted user, all other users have context.
360 return $defaulturl;
362 $contextid = $context->id;
365 $path = '/';
366 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
367 // We append the theme name to the file path if we have it so that
368 // in the circumstance that the profile picture is not available
369 // when the user actually requests it they still get the profile
370 // picture for the correct theme.
371 $path .= $page->theme->name.'/';
373 // Set the image URL to the URL for the uploaded file and return.
374 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
375 $url->param('rev', $this->user->picture);
376 return $url;
379 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
380 // Normalise the size variable to acceptable bounds
381 if ($size < 1 || $size > 512) {
382 $size = 35;
384 // Hash the users email address
385 $md5 = md5(strtolower(trim($this->user->email)));
386 // Build a gravatar URL with what we know.
388 // Find the best default image URL we can (MDL-35669)
389 if (empty($CFG->gravatardefaulturl)) {
390 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
391 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
392 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
393 } else {
394 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
396 } else {
397 $gravatardefault = $CFG->gravatardefaulturl;
400 // If the currently requested page is https then we'll return an
401 // https gravatar page.
402 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
403 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
404 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
405 } else {
406 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
410 return $defaulturl;
415 * Data structure representing a help icon.
417 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 * @since Moodle 2.0
420 * @package core
421 * @category output
423 class old_help_icon implements renderable {
426 * @var string Lang pack identifier
428 public $helpidentifier;
431 * @var string A descriptive text for title tooltip
433 public $title = null;
436 * @var string Component name, the same as in get_string()
438 public $component = 'moodle';
441 * @var string Extra descriptive text next to the icon
443 public $linktext = null;
446 * Constructor: sets up the other components in case they are needed
448 * @param string $helpidentifier The keyword that defines a help page
449 * @param string $title A descriptive text for accessibility only
450 * @param string $component
452 public function __construct($helpidentifier, $title, $component = 'moodle') {
453 if (empty($title)) {
454 throw new coding_exception('A help_icon object requires a $text parameter');
456 if (empty($helpidentifier)) {
457 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
460 $this->helpidentifier = $helpidentifier;
461 $this->title = $title;
462 $this->component = $component;
467 * Data structure representing a help icon.
469 * @copyright 2010 Petr Skoda (info@skodak.org)
470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
471 * @since Moodle 2.0
472 * @package core
473 * @category output
475 class help_icon implements renderable {
478 * @var string lang pack identifier (without the "_help" suffix),
479 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
480 * must exist.
482 public $identifier;
485 * @var string Component name, the same as in get_string()
487 public $component;
490 * @var string Extra descriptive text next to the icon
492 public $linktext = null;
495 * Constructor
497 * @param string $identifier string for help page title,
498 * string with _help suffix is used for the actual help text.
499 * string with _link suffix is used to create a link to further info (if it exists)
500 * @param string $component
502 public function __construct($identifier, $component) {
503 $this->identifier = $identifier;
504 $this->component = $component;
508 * Verifies that both help strings exists, shows debug warnings if not
510 public function diag_strings() {
511 $sm = get_string_manager();
512 if (!$sm->string_exists($this->identifier, $this->component)) {
513 debugging("Help title string does not exist: [$this->identifier, $this->component]");
515 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
516 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
523 * Data structure representing an icon.
525 * @copyright 2010 Petr Skoda
526 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
527 * @since Moodle 2.0
528 * @package core
529 * @category output
531 class pix_icon implements renderable {
534 * @var string The icon name
536 var $pix;
539 * @var string The component the icon belongs to.
541 var $component;
544 * @var array An array of attributes to use on the icon
546 var $attributes = array();
549 * Constructor
551 * @param string $pix short icon name
552 * @param string $alt The alt text to use for the icon
553 * @param string $component component name
554 * @param array $attributes html attributes
556 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
557 $this->pix = $pix;
558 $this->component = $component;
559 $this->attributes = (array)$attributes;
561 $this->attributes['alt'] = $alt;
562 if (empty($this->attributes['class'])) {
563 $this->attributes['class'] = 'smallicon';
565 if (!isset($this->attributes['title'])) {
566 $this->attributes['title'] = $this->attributes['alt'];
567 } else if (empty($this->attributes['title'])) {
568 // Remove the title attribute if empty, we probably want to use the parent node's title
569 // and some browsers might overwrite it with an empty title.
570 unset($this->attributes['title']);
576 * Data structure representing an emoticon image
578 * @copyright 2010 David Mudrak
579 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
580 * @since Moodle 2.0
581 * @package core
582 * @category output
584 class pix_emoticon extends pix_icon implements renderable {
587 * Constructor
588 * @param string $pix short icon name
589 * @param string $alt alternative text
590 * @param string $component emoticon image provider
591 * @param array $attributes explicit HTML attributes
593 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
594 if (empty($attributes['class'])) {
595 $attributes['class'] = 'emoticon';
597 parent::__construct($pix, $alt, $component, $attributes);
602 * Data structure representing a simple form with only one button.
604 * @copyright 2009 Petr Skoda
605 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
606 * @since Moodle 2.0
607 * @package core
608 * @category output
610 class single_button implements renderable {
613 * @var moodle_url Target url
615 var $url;
618 * @var string Button label
620 var $label;
623 * @var string Form submit method post or get
625 var $method = 'post';
628 * @var string Wrapping div class
630 var $class = 'singlebutton';
633 * @var bool True if button disabled, false if normal
635 var $disabled = false;
638 * @var string Button tooltip
640 var $tooltip = null;
643 * @var string Form id
645 var $formid;
648 * @var array List of attached actions
650 var $actions = array();
653 * Constructor
654 * @param moodle_url $url
655 * @param string $label button text
656 * @param string $method get or post submit method
658 public function __construct(moodle_url $url, $label, $method='post') {
659 $this->url = clone($url);
660 $this->label = $label;
661 $this->method = $method;
665 * Shortcut for adding a JS confirm dialog when the button is clicked.
666 * The message must be a yes/no question.
668 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
670 public function add_confirm_action($confirmmessage) {
671 $this->add_action(new confirm_action($confirmmessage));
675 * Add action to the button.
676 * @param component_action $action
678 public function add_action(component_action $action) {
679 $this->actions[] = $action;
685 * Simple form with just one select field that gets submitted automatically.
687 * If JS not enabled small go button is printed too.
689 * @copyright 2009 Petr Skoda
690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
691 * @since Moodle 2.0
692 * @package core
693 * @category output
695 class single_select implements renderable {
698 * @var moodle_url Target url - includes hidden fields
700 var $url;
703 * @var string Name of the select element.
705 var $name;
708 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
709 * it is also possible to specify optgroup as complex label array ex.:
710 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
711 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
713 var $options;
716 * @var string Selected option
718 var $selected;
721 * @var array Nothing selected
723 var $nothing;
726 * @var array Extra select field attributes
728 var $attributes = array();
731 * @var string Button label
733 var $label = '';
736 * @var array Button label's attributes
738 var $labelattributes = array();
741 * @var string Form submit method post or get
743 var $method = 'get';
746 * @var string Wrapping div class
748 var $class = 'singleselect';
751 * @var bool True if button disabled, false if normal
753 var $disabled = false;
756 * @var string Button tooltip
758 var $tooltip = null;
761 * @var string Form id
763 var $formid = null;
766 * @var array List of attached actions
768 var $helpicon = null;
771 * Constructor
772 * @param moodle_url $url form action target, includes hidden fields
773 * @param string $name name of selection field - the changing parameter in url
774 * @param array $options list of options
775 * @param string $selected selected element
776 * @param array $nothing
777 * @param string $formid
779 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
780 $this->url = $url;
781 $this->name = $name;
782 $this->options = $options;
783 $this->selected = $selected;
784 $this->nothing = $nothing;
785 $this->formid = $formid;
789 * Shortcut for adding a JS confirm dialog when the button is clicked.
790 * The message must be a yes/no question.
792 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
794 public function add_confirm_action($confirmmessage) {
795 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
799 * Add action to the button.
801 * @param component_action $action
803 public function add_action(component_action $action) {
804 $this->actions[] = $action;
808 * Adds help icon.
810 * @param string $helppage The keyword that defines a help page
811 * @param string $title A descriptive text for accessibility only
812 * @param string $component
814 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
815 $this->helpicon = new old_help_icon($helppage, $title, $component);
819 * Adds help icon.
821 * @param string $identifier The keyword that defines a help page
822 * @param string $component
824 public function set_help_icon($identifier, $component = 'moodle') {
825 $this->helpicon = new help_icon($identifier, $component);
829 * Sets select's label
831 * @param string $label
832 * @param array $attributes (optional)
834 public function set_label($label, $attributes = array()) {
835 $this->label = $label;
836 $this->labelattributes = $attributes;
842 * Simple URL selection widget description.
844 * @copyright 2009 Petr Skoda
845 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
846 * @since Moodle 2.0
847 * @package core
848 * @category output
850 class url_select implements renderable {
852 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
853 * it is also possible to specify optgroup as complex label array ex.:
854 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
855 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
857 var $urls;
860 * @var string Selected option
862 var $selected;
865 * @var array Nothing selected
867 var $nothing;
870 * @var array Extra select field attributes
872 var $attributes = array();
875 * @var string Button label
877 var $label = '';
880 * @var array Button label's attributes
882 var $labelattributes = array();
885 * @var string Wrapping div class
887 var $class = 'urlselect';
890 * @var bool True if button disabled, false if normal
892 var $disabled = false;
895 * @var string Button tooltip
897 var $tooltip = null;
900 * @var string Form id
902 var $formid = null;
905 * @var array List of attached actions
907 var $helpicon = null;
910 * @var string If set, makes button visible with given name for button
912 var $showbutton = null;
915 * Constructor
916 * @param array $urls list of options
917 * @param string $selected selected element
918 * @param array $nothing
919 * @param string $formid
920 * @param string $showbutton Set to text of button if it should be visible
921 * or null if it should be hidden (hidden version always has text 'go')
923 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
924 $this->urls = $urls;
925 $this->selected = $selected;
926 $this->nothing = $nothing;
927 $this->formid = $formid;
928 $this->showbutton = $showbutton;
932 * Adds help icon.
934 * @param string $helppage The keyword that defines a help page
935 * @param string $title A descriptive text for accessibility only
936 * @param string $component
938 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
939 $this->helpicon = new old_help_icon($helppage, $title, $component);
943 * Adds help icon.
945 * @param string $identifier The keyword that defines a help page
946 * @param string $component
948 public function set_help_icon($identifier, $component = 'moodle') {
949 $this->helpicon = new help_icon($identifier, $component);
953 * Sets select's label
955 * @param string $label
956 * @param array $attributes (optional)
958 public function set_label($label, $attributes = array()) {
959 $this->label = $label;
960 $this->labelattributes = $attributes;
965 * Data structure describing html link with special action attached.
967 * @copyright 2010 Petr Skoda
968 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
969 * @since Moodle 2.0
970 * @package core
971 * @category output
973 class action_link implements renderable {
976 * @var moodle_url Href url
978 var $url;
981 * @var string Link text HTML fragment
983 var $text;
986 * @var array HTML attributes
988 var $attributes;
991 * @var array List of actions attached to link
993 var $actions;
996 * Constructor
997 * @param moodle_url $url
998 * @param string $text HTML fragment
999 * @param component_action $action
1000 * @param array $attributes associative array of html link attributes + disabled
1002 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
1003 $this->url = clone($url);
1004 $this->text = $text;
1005 $this->attributes = (array)$attributes;
1006 if ($action) {
1007 $this->add_action($action);
1012 * Add action to the link.
1014 * @param component_action $action
1016 public function add_action(component_action $action) {
1017 $this->actions[] = $action;
1021 * Adds a CSS class to this action link object
1022 * @param string $class
1024 public function add_class($class) {
1025 if (empty($this->attributes['class'])) {
1026 $this->attributes['class'] = $class;
1027 } else {
1028 $this->attributes['class'] .= ' ' . $class;
1034 * Simple html output class
1036 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1037 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1038 * @since Moodle 2.0
1039 * @package core
1040 * @category output
1042 class html_writer {
1045 * Outputs a tag with attributes and contents
1047 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1048 * @param string $contents What goes between the opening and closing tags
1049 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1050 * @return string HTML fragment
1052 public static function tag($tagname, $contents, array $attributes = null) {
1053 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1057 * Outputs an opening tag with attributes
1059 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1060 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1061 * @return string HTML fragment
1063 public static function start_tag($tagname, array $attributes = null) {
1064 return '<' . $tagname . self::attributes($attributes) . '>';
1068 * Outputs a closing tag
1070 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1071 * @return string HTML fragment
1073 public static function end_tag($tagname) {
1074 return '</' . $tagname . '>';
1078 * Outputs an empty tag with attributes
1080 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1081 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1082 * @return string HTML fragment
1084 public static function empty_tag($tagname, array $attributes = null) {
1085 return '<' . $tagname . self::attributes($attributes) . ' />';
1089 * Outputs a tag, but only if the contents are not empty
1091 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1092 * @param string $contents What goes between the opening and closing tags
1093 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1094 * @return string HTML fragment
1096 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1097 if ($contents === '' || is_null($contents)) {
1098 return '';
1100 return self::tag($tagname, $contents, $attributes);
1104 * Outputs a HTML attribute and value
1106 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1107 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1108 * @return string HTML fragment
1110 public static function attribute($name, $value) {
1111 if (is_array($value)) {
1112 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
1114 if ($value instanceof moodle_url) {
1115 return ' ' . $name . '="' . $value->out() . '"';
1118 // special case, we do not want these in output
1119 if ($value === null) {
1120 return '';
1123 // no sloppy trimming here!
1124 return ' ' . $name . '="' . s($value) . '"';
1128 * Outputs a list of HTML attributes and values
1130 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1131 * The values will be escaped with {@link s()}
1132 * @return string HTML fragment
1134 public static function attributes(array $attributes = null) {
1135 $attributes = (array)$attributes;
1136 $output = '';
1137 foreach ($attributes as $name => $value) {
1138 $output .= self::attribute($name, $value);
1140 return $output;
1144 * Generates random html element id.
1146 * @staticvar int $counter
1147 * @staticvar type $uniq
1148 * @param string $base A string fragment that will be included in the random ID.
1149 * @return string A unique ID
1151 public static function random_id($base='random') {
1152 static $counter = 0;
1153 static $uniq;
1155 if (!isset($uniq)) {
1156 $uniq = uniqid();
1159 $counter++;
1160 return $base.$uniq.$counter;
1164 * Generates a simple html link
1166 * @param string|moodle_url $url The URL
1167 * @param string $text The text
1168 * @param array $attributes HTML attributes
1169 * @return string HTML fragment
1171 public static function link($url, $text, array $attributes = null) {
1172 $attributes = (array)$attributes;
1173 $attributes['href'] = $url;
1174 return self::tag('a', $text, $attributes);
1178 * Generates a simple checkbox with optional label
1180 * @param string $name The name of the checkbox
1181 * @param string $value The value of the checkbox
1182 * @param bool $checked Whether the checkbox is checked
1183 * @param string $label The label for the checkbox
1184 * @param array $attributes Any attributes to apply to the checkbox
1185 * @return string html fragment
1187 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1188 $attributes = (array)$attributes;
1189 $output = '';
1191 if ($label !== '' and !is_null($label)) {
1192 if (empty($attributes['id'])) {
1193 $attributes['id'] = self::random_id('checkbox_');
1196 $attributes['type'] = 'checkbox';
1197 $attributes['value'] = $value;
1198 $attributes['name'] = $name;
1199 $attributes['checked'] = $checked ? 'checked' : null;
1201 $output .= self::empty_tag('input', $attributes);
1203 if ($label !== '' and !is_null($label)) {
1204 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1207 return $output;
1211 * Generates a simple select yes/no form field
1213 * @param string $name name of select element
1214 * @param bool $selected
1215 * @param array $attributes - html select element attributes
1216 * @return string HTML fragment
1218 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1219 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1220 return self::select($options, $name, $selected, null, $attributes);
1224 * Generates a simple select form field
1226 * @param array $options associative array value=>label ex.:
1227 * array(1=>'One, 2=>Two)
1228 * it is also possible to specify optgroup as complex label array ex.:
1229 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1230 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1231 * @param string $name name of select element
1232 * @param string|array $selected value or array of values depending on multiple attribute
1233 * @param array|bool $nothing add nothing selected option, or false of not added
1234 * @param array $attributes html select element attributes
1235 * @return string HTML fragment
1237 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1238 $attributes = (array)$attributes;
1239 if (is_array($nothing)) {
1240 foreach ($nothing as $k=>$v) {
1241 if ($v === 'choose' or $v === 'choosedots') {
1242 $nothing[$k] = get_string('choosedots');
1245 $options = $nothing + $options; // keep keys, do not override
1247 } else if (is_string($nothing) and $nothing !== '') {
1248 // BC
1249 $options = array(''=>$nothing) + $options;
1252 // we may accept more values if multiple attribute specified
1253 $selected = (array)$selected;
1254 foreach ($selected as $k=>$v) {
1255 $selected[$k] = (string)$v;
1258 if (!isset($attributes['id'])) {
1259 $id = 'menu'.$name;
1260 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1261 $id = str_replace('[', '', $id);
1262 $id = str_replace(']', '', $id);
1263 $attributes['id'] = $id;
1266 if (!isset($attributes['class'])) {
1267 $class = 'menu'.$name;
1268 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1269 $class = str_replace('[', '', $class);
1270 $class = str_replace(']', '', $class);
1271 $attributes['class'] = $class;
1273 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1275 $attributes['name'] = $name;
1277 if (!empty($attributes['disabled'])) {
1278 $attributes['disabled'] = 'disabled';
1279 } else {
1280 unset($attributes['disabled']);
1283 $output = '';
1284 foreach ($options as $value=>$label) {
1285 if (is_array($label)) {
1286 // ignore key, it just has to be unique
1287 $output .= self::select_optgroup(key($label), current($label), $selected);
1288 } else {
1289 $output .= self::select_option($label, $value, $selected);
1292 return self::tag('select', $output, $attributes);
1296 * Returns HTML to display a select box option.
1298 * @param string $label The label to display as the option.
1299 * @param string|int $value The value the option represents
1300 * @param array $selected An array of selected options
1301 * @return string HTML fragment
1303 private static function select_option($label, $value, array $selected) {
1304 $attributes = array();
1305 $value = (string)$value;
1306 if (in_array($value, $selected, true)) {
1307 $attributes['selected'] = 'selected';
1309 $attributes['value'] = $value;
1310 return self::tag('option', $label, $attributes);
1314 * Returns HTML to display a select box option group.
1316 * @param string $groupname The label to use for the group
1317 * @param array $options The options in the group
1318 * @param array $selected An array of selected values.
1319 * @return string HTML fragment.
1321 private static function select_optgroup($groupname, $options, array $selected) {
1322 if (empty($options)) {
1323 return '';
1325 $attributes = array('label'=>$groupname);
1326 $output = '';
1327 foreach ($options as $value=>$label) {
1328 $output .= self::select_option($label, $value, $selected);
1330 return self::tag('optgroup', $output, $attributes);
1334 * This is a shortcut for making an hour selector menu.
1336 * @param string $type The type of selector (years, months, days, hours, minutes)
1337 * @param string $name fieldname
1338 * @param int $currenttime A default timestamp in GMT
1339 * @param int $step minute spacing
1340 * @param array $attributes - html select element attributes
1341 * @return HTML fragment
1343 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1344 if (!$currenttime) {
1345 $currenttime = time();
1347 $currentdate = usergetdate($currenttime);
1348 $userdatetype = $type;
1349 $timeunits = array();
1351 switch ($type) {
1352 case 'years':
1353 for ($i=1970; $i<=2020; $i++) {
1354 $timeunits[$i] = $i;
1356 $userdatetype = 'year';
1357 break;
1358 case 'months':
1359 for ($i=1; $i<=12; $i++) {
1360 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1362 $userdatetype = 'month';
1363 $currentdate['month'] = (int)$currentdate['mon'];
1364 break;
1365 case 'days':
1366 for ($i=1; $i<=31; $i++) {
1367 $timeunits[$i] = $i;
1369 $userdatetype = 'mday';
1370 break;
1371 case 'hours':
1372 for ($i=0; $i<=23; $i++) {
1373 $timeunits[$i] = sprintf("%02d",$i);
1375 break;
1376 case 'minutes':
1377 if ($step != 1) {
1378 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1381 for ($i=0; $i<=59; $i+=$step) {
1382 $timeunits[$i] = sprintf("%02d",$i);
1384 break;
1385 default:
1386 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1389 if (empty($attributes['id'])) {
1390 $attributes['id'] = self::random_id('ts_');
1392 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1393 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1395 return $label.$timerselector;
1399 * Shortcut for quick making of lists
1401 * Note: 'list' is a reserved keyword ;-)
1403 * @param array $items
1404 * @param array $attributes
1405 * @param string $tag ul or ol
1406 * @return string
1408 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1409 $output = '';
1411 foreach ($items as $item) {
1412 $output .= html_writer::start_tag('li') . "\n";
1413 $output .= $item . "\n";
1414 $output .= html_writer::end_tag('li') . "\n";
1417 return html_writer::tag($tag, $output, $attributes);
1421 * Returns hidden input fields created from url parameters.
1423 * @param moodle_url $url
1424 * @param array $exclude list of excluded parameters
1425 * @return string HTML fragment
1427 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1428 $exclude = (array)$exclude;
1429 $params = $url->params();
1430 foreach ($exclude as $key) {
1431 unset($params[$key]);
1434 $output = '';
1435 foreach ($params as $key => $value) {
1436 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1437 $output .= self::empty_tag('input', $attributes)."\n";
1439 return $output;
1443 * Generate a script tag containing the the specified code.
1445 * @param string $jscode the JavaScript code
1446 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1447 * @return string HTML, the code wrapped in <script> tags.
1449 public static function script($jscode, $url=null) {
1450 if ($jscode) {
1451 $attributes = array('type'=>'text/javascript');
1452 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1454 } else if ($url) {
1455 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1456 return self::tag('script', '', $attributes) . "\n";
1458 } else {
1459 return '';
1464 * Renders HTML table
1466 * This method may modify the passed instance by adding some default properties if they are not set yet.
1467 * If this is not what you want, you should make a full clone of your data before passing them to this
1468 * method. In most cases this is not an issue at all so we do not clone by default for performance
1469 * and memory consumption reasons.
1471 * @param html_table $table data to be rendered
1472 * @return string HTML code
1474 public static function table(html_table $table) {
1475 // prepare table data and populate missing properties with reasonable defaults
1476 if (!empty($table->align)) {
1477 foreach ($table->align as $key => $aa) {
1478 if ($aa) {
1479 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1480 } else {
1481 $table->align[$key] = null;
1485 if (!empty($table->size)) {
1486 foreach ($table->size as $key => $ss) {
1487 if ($ss) {
1488 $table->size[$key] = 'width:'. $ss .';';
1489 } else {
1490 $table->size[$key] = null;
1494 if (!empty($table->wrap)) {
1495 foreach ($table->wrap as $key => $ww) {
1496 if ($ww) {
1497 $table->wrap[$key] = 'white-space:nowrap;';
1498 } else {
1499 $table->wrap[$key] = '';
1503 if (!empty($table->head)) {
1504 foreach ($table->head as $key => $val) {
1505 if (!isset($table->align[$key])) {
1506 $table->align[$key] = null;
1508 if (!isset($table->size[$key])) {
1509 $table->size[$key] = null;
1511 if (!isset($table->wrap[$key])) {
1512 $table->wrap[$key] = null;
1517 if (empty($table->attributes['class'])) {
1518 $table->attributes['class'] = 'generaltable';
1520 if (!empty($table->tablealign)) {
1521 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1524 // explicitly assigned properties override those defined via $table->attributes
1525 $table->attributes['class'] = trim($table->attributes['class']);
1526 $attributes = array_merge($table->attributes, array(
1527 'id' => $table->id,
1528 'width' => $table->width,
1529 'summary' => $table->summary,
1530 'cellpadding' => $table->cellpadding,
1531 'cellspacing' => $table->cellspacing,
1533 $output = html_writer::start_tag('table', $attributes) . "\n";
1535 $countcols = 0;
1537 if (!empty($table->head)) {
1538 $countcols = count($table->head);
1540 $output .= html_writer::start_tag('thead', array()) . "\n";
1541 $output .= html_writer::start_tag('tr', array()) . "\n";
1542 $keys = array_keys($table->head);
1543 $lastkey = end($keys);
1545 foreach ($table->head as $key => $heading) {
1546 // Convert plain string headings into html_table_cell objects
1547 if (!($heading instanceof html_table_cell)) {
1548 $headingtext = $heading;
1549 $heading = new html_table_cell();
1550 $heading->text = $headingtext;
1551 $heading->header = true;
1554 if ($heading->header !== false) {
1555 $heading->header = true;
1558 if ($heading->header && empty($heading->scope)) {
1559 $heading->scope = 'col';
1562 $heading->attributes['class'] .= ' header c' . $key;
1563 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1564 $heading->colspan = $table->headspan[$key];
1565 $countcols += $table->headspan[$key] - 1;
1568 if ($key == $lastkey) {
1569 $heading->attributes['class'] .= ' lastcol';
1571 if (isset($table->colclasses[$key])) {
1572 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1574 $heading->attributes['class'] = trim($heading->attributes['class']);
1575 $attributes = array_merge($heading->attributes, array(
1576 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1577 'scope' => $heading->scope,
1578 'colspan' => $heading->colspan,
1581 $tagtype = 'td';
1582 if ($heading->header === true) {
1583 $tagtype = 'th';
1585 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1587 $output .= html_writer::end_tag('tr') . "\n";
1588 $output .= html_writer::end_tag('thead') . "\n";
1590 if (empty($table->data)) {
1591 // For valid XHTML strict every table must contain either a valid tr
1592 // or a valid tbody... both of which must contain a valid td
1593 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1594 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1595 $output .= html_writer::end_tag('tbody');
1599 if (!empty($table->data)) {
1600 $oddeven = 1;
1601 $keys = array_keys($table->data);
1602 $lastrowkey = end($keys);
1603 $output .= html_writer::start_tag('tbody', array());
1605 foreach ($table->data as $key => $row) {
1606 if (($row === 'hr') && ($countcols)) {
1607 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1608 } else {
1609 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1610 if (!($row instanceof html_table_row)) {
1611 $newrow = new html_table_row();
1613 foreach ($row as $cell) {
1614 if (!($cell instanceof html_table_cell)) {
1615 $cell = new html_table_cell($cell);
1617 $newrow->cells[] = $cell;
1619 $row = $newrow;
1622 $oddeven = $oddeven ? 0 : 1;
1623 if (isset($table->rowclasses[$key])) {
1624 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1627 $row->attributes['class'] .= ' r' . $oddeven;
1628 if ($key == $lastrowkey) {
1629 $row->attributes['class'] .= ' lastrow';
1632 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1633 $keys2 = array_keys($row->cells);
1634 $lastkey = end($keys2);
1636 $gotlastkey = false; //flag for sanity checking
1637 foreach ($row->cells as $key => $cell) {
1638 if ($gotlastkey) {
1639 //This should never happen. Why do we have a cell after the last cell?
1640 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1643 if (!($cell instanceof html_table_cell)) {
1644 $mycell = new html_table_cell();
1645 $mycell->text = $cell;
1646 $cell = $mycell;
1649 if (($cell->header === true) && empty($cell->scope)) {
1650 $cell->scope = 'row';
1653 if (isset($table->colclasses[$key])) {
1654 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1657 $cell->attributes['class'] .= ' cell c' . $key;
1658 if ($key == $lastkey) {
1659 $cell->attributes['class'] .= ' lastcol';
1660 $gotlastkey = true;
1662 $tdstyle = '';
1663 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1664 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1665 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1666 $cell->attributes['class'] = trim($cell->attributes['class']);
1667 $tdattributes = array_merge($cell->attributes, array(
1668 'style' => $tdstyle . $cell->style,
1669 'colspan' => $cell->colspan,
1670 'rowspan' => $cell->rowspan,
1671 'id' => $cell->id,
1672 'abbr' => $cell->abbr,
1673 'scope' => $cell->scope,
1675 $tagtype = 'td';
1676 if ($cell->header === true) {
1677 $tagtype = 'th';
1679 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1682 $output .= html_writer::end_tag('tr') . "\n";
1684 $output .= html_writer::end_tag('tbody') . "\n";
1686 $output .= html_writer::end_tag('table') . "\n";
1688 return $output;
1692 * Renders form element label
1694 * By default, the label is suffixed with a label separator defined in the
1695 * current language pack (colon by default in the English lang pack).
1696 * Adding the colon can be explicitly disabled if needed. Label separators
1697 * are put outside the label tag itself so they are not read by
1698 * screenreaders (accessibility).
1700 * Parameter $for explicitly associates the label with a form control. When
1701 * set, the value of this attribute must be the same as the value of
1702 * the id attribute of the form control in the same document. When null,
1703 * the label being defined is associated with the control inside the label
1704 * element.
1706 * @param string $text content of the label tag
1707 * @param string|null $for id of the element this label is associated with, null for no association
1708 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1709 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1710 * @return string HTML of the label element
1712 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1713 if (!is_null($for)) {
1714 $attributes = array_merge($attributes, array('for' => $for));
1716 $text = trim($text);
1717 $label = self::tag('label', $text, $attributes);
1719 // TODO MDL-12192 $colonize disabled for now yet
1720 // if (!empty($text) and $colonize) {
1721 // // the $text may end with the colon already, though it is bad string definition style
1722 // $colon = get_string('labelsep', 'langconfig');
1723 // if (!empty($colon)) {
1724 // $trimmed = trim($colon);
1725 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1726 // //debugging('The label text should not end with colon or other label separator,
1727 // // please fix the string definition.', DEBUG_DEVELOPER);
1728 // } else {
1729 // $label .= $colon;
1730 // }
1731 // }
1732 // }
1734 return $label;
1739 * Simple javascript output class
1741 * @copyright 2010 Petr Skoda
1742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1743 * @since Moodle 2.0
1744 * @package core
1745 * @category output
1747 class js_writer {
1750 * Returns javascript code calling the function
1752 * @param string $function function name, can be complex like Y.Event.purgeElement
1753 * @param array $arguments parameters
1754 * @param int $delay execution delay in seconds
1755 * @return string JS code fragment
1757 public static function function_call($function, array $arguments = null, $delay=0) {
1758 if ($arguments) {
1759 $arguments = array_map('json_encode', convert_to_array($arguments));
1760 $arguments = implode(', ', $arguments);
1761 } else {
1762 $arguments = '';
1764 $js = "$function($arguments);";
1766 if ($delay) {
1767 $delay = $delay * 1000; // in miliseconds
1768 $js = "setTimeout(function() { $js }, $delay);";
1770 return $js . "\n";
1774 * Special function which adds Y as first argument of function call.
1776 * @param string $function The function to call
1777 * @param array $extraarguments Any arguments to pass to it
1778 * @return string Some JS code
1780 public static function function_call_with_Y($function, array $extraarguments = null) {
1781 if ($extraarguments) {
1782 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1783 $arguments = 'Y, ' . implode(', ', $extraarguments);
1784 } else {
1785 $arguments = 'Y';
1787 return "$function($arguments);\n";
1791 * Returns JavaScript code to initialise a new object
1793 * @param string $var If it is null then no var is assigned the new object.
1794 * @param string $class The class to initialise an object for.
1795 * @param array $arguments An array of args to pass to the init method.
1796 * @param array $requirements Any modules required for this class.
1797 * @param int $delay The delay before initialisation. 0 = no delay.
1798 * @return string Some JS code
1800 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1801 if (is_array($arguments)) {
1802 $arguments = array_map('json_encode', convert_to_array($arguments));
1803 $arguments = implode(', ', $arguments);
1806 if ($var === null) {
1807 $js = "new $class(Y, $arguments);";
1808 } else if (strpos($var, '.')!==false) {
1809 $js = "$var = new $class(Y, $arguments);";
1810 } else {
1811 $js = "var $var = new $class(Y, $arguments);";
1814 if ($delay) {
1815 $delay = $delay * 1000; // in miliseconds
1816 $js = "setTimeout(function() { $js }, $delay);";
1819 if (count($requirements) > 0) {
1820 $requirements = implode("', '", $requirements);
1821 $js = "Y.use('$requirements', function(Y){ $js });";
1823 return $js."\n";
1827 * Returns code setting value to variable
1829 * @param string $name
1830 * @param mixed $value json serialised value
1831 * @param bool $usevar add var definition, ignored for nested properties
1832 * @return string JS code fragment
1834 public static function set_variable($name, $value, $usevar = true) {
1835 $output = '';
1837 if ($usevar) {
1838 if (strpos($name, '.')) {
1839 $output .= '';
1840 } else {
1841 $output .= 'var ';
1845 $output .= "$name = ".json_encode($value).";";
1847 return $output;
1851 * Writes event handler attaching code
1853 * @param array|string $selector standard YUI selector for elements, may be
1854 * array or string, element id is in the form "#idvalue"
1855 * @param string $event A valid DOM event (click, mousedown, change etc.)
1856 * @param string $function The name of the function to call
1857 * @param array $arguments An optional array of argument parameters to pass to the function
1858 * @return string JS code fragment
1860 public static function event_handler($selector, $event, $function, array $arguments = null) {
1861 $selector = json_encode($selector);
1862 $output = "Y.on('$event', $function, $selector, null";
1863 if (!empty($arguments)) {
1864 $output .= ', ' . json_encode($arguments);
1866 return $output . ");\n";
1871 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1873 * Example of usage:
1874 * $t = new html_table();
1875 * ... // set various properties of the object $t as described below
1876 * echo html_writer::table($t);
1878 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1879 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1880 * @since Moodle 2.0
1881 * @package core
1882 * @category output
1884 class html_table {
1887 * @var string Value to use for the id attribute of the table
1889 public $id = null;
1892 * @var array Attributes of HTML attributes for the <table> element
1894 public $attributes = array();
1897 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1898 * For more control over the rendering of the headers, an array of html_table_cell objects
1899 * can be passed instead of an array of strings.
1901 * Example of usage:
1902 * $t->head = array('Student', 'Grade');
1904 public $head;
1907 * @var array An array that can be used to make a heading span multiple columns.
1908 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1909 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1911 * Example of usage:
1912 * $t->headspan = array(2,1);
1914 public $headspan;
1917 * @var array An array of column alignments.
1918 * The value is used as CSS 'text-align' property. Therefore, possible
1919 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1920 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1922 * Examples of usage:
1923 * $t->align = array(null, 'right');
1924 * or
1925 * $t->align[1] = 'right';
1927 public $align;
1930 * @var array The value is used as CSS 'size' property.
1932 * Examples of usage:
1933 * $t->size = array('50%', '50%');
1934 * or
1935 * $t->size[1] = '120px';
1937 public $size;
1940 * @var array An array of wrapping information.
1941 * The only possible value is 'nowrap' that sets the
1942 * CSS property 'white-space' to the value 'nowrap' in the given column.
1944 * Example of usage:
1945 * $t->wrap = array(null, 'nowrap');
1947 public $wrap;
1950 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1951 * $head specified, the string 'hr' (for horizontal ruler) can be used
1952 * instead of an array of cells data resulting in a divider rendered.
1954 * Example of usage with array of arrays:
1955 * $row1 = array('Harry Potter', '76 %');
1956 * $row2 = array('Hermione Granger', '100 %');
1957 * $t->data = array($row1, $row2);
1959 * Example with array of html_table_row objects: (used for more fine-grained control)
1960 * $cell1 = new html_table_cell();
1961 * $cell1->text = 'Harry Potter';
1962 * $cell1->colspan = 2;
1963 * $row1 = new html_table_row();
1964 * $row1->cells[] = $cell1;
1965 * $cell2 = new html_table_cell();
1966 * $cell2->text = 'Hermione Granger';
1967 * $cell3 = new html_table_cell();
1968 * $cell3->text = '100 %';
1969 * $row2 = new html_table_row();
1970 * $row2->cells = array($cell2, $cell3);
1971 * $t->data = array($row1, $row2);
1973 public $data;
1976 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1977 * @var string Width of the table, percentage of the page preferred.
1979 public $width = null;
1982 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1983 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
1985 public $tablealign = null;
1988 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1989 * @var int Padding on each cell, in pixels
1991 public $cellpadding = null;
1994 * @var int Spacing between cells, in pixels
1995 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1997 public $cellspacing = null;
2000 * @var array Array of classes to add to particular rows, space-separated string.
2001 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2002 * respectively. Class 'lastrow' is added automatically for the last row
2003 * in the table.
2005 * Example of usage:
2006 * $t->rowclasses[9] = 'tenth'
2008 public $rowclasses;
2011 * @var array An array of classes to add to every cell in a particular column,
2012 * space-separated string. Class 'cell' is added automatically by the renderer.
2013 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2014 * respectively. Class 'lastcol' is added automatically for all last cells
2015 * in a row.
2017 * Example of usage:
2018 * $t->colclasses = array(null, 'grade');
2020 public $colclasses;
2023 * @var string Description of the contents for screen readers.
2025 public $summary;
2028 * Constructor
2030 public function __construct() {
2031 $this->attributes['class'] = '';
2036 * Component representing a table row.
2038 * @copyright 2009 Nicolas Connault
2039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2040 * @since Moodle 2.0
2041 * @package core
2042 * @category output
2044 class html_table_row {
2047 * @var string Value to use for the id attribute of the row.
2049 public $id = null;
2052 * @var array Array of html_table_cell objects
2054 public $cells = array();
2057 * @var string Value to use for the style attribute of the table row
2059 public $style = null;
2062 * @var array Attributes of additional HTML attributes for the <tr> element
2064 public $attributes = array();
2067 * Constructor
2068 * @param array $cells
2070 public function __construct(array $cells=null) {
2071 $this->attributes['class'] = '';
2072 $cells = (array)$cells;
2073 foreach ($cells as $cell) {
2074 if ($cell instanceof html_table_cell) {
2075 $this->cells[] = $cell;
2076 } else {
2077 $this->cells[] = new html_table_cell($cell);
2084 * Component representing a table cell.
2086 * @copyright 2009 Nicolas Connault
2087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2088 * @since Moodle 2.0
2089 * @package core
2090 * @category output
2092 class html_table_cell {
2095 * @var string Value to use for the id attribute of the cell.
2097 public $id = null;
2100 * @var string The contents of the cell.
2102 public $text;
2105 * @var string Abbreviated version of the contents of the cell.
2107 public $abbr = null;
2110 * @var int Number of columns this cell should span.
2112 public $colspan = null;
2115 * @var int Number of rows this cell should span.
2117 public $rowspan = null;
2120 * @var string Defines a way to associate header cells and data cells in a table.
2122 public $scope = null;
2125 * @var bool Whether or not this cell is a header cell.
2127 public $header = null;
2130 * @var string Value to use for the style attribute of the table cell
2132 public $style = null;
2135 * @var array Attributes of additional HTML attributes for the <td> element
2137 public $attributes = array();
2140 * Constructs a table cell
2142 * @param string $text
2144 public function __construct($text = null) {
2145 $this->text = $text;
2146 $this->attributes['class'] = '';
2151 * Component representing a paging bar.
2153 * @copyright 2009 Nicolas Connault
2154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2155 * @since Moodle 2.0
2156 * @package core
2157 * @category output
2159 class paging_bar implements renderable {
2162 * @var int The maximum number of pagelinks to display.
2164 public $maxdisplay = 18;
2167 * @var int The total number of entries to be pages through..
2169 public $totalcount;
2172 * @var int The page you are currently viewing.
2174 public $page;
2177 * @var int The number of entries that should be shown per page.
2179 public $perpage;
2182 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2183 * an equals sign and the page number.
2184 * If this is a moodle_url object then the pagevar param will be replaced by
2185 * the page no, for each page.
2187 public $baseurl;
2190 * @var string This is the variable name that you use for the pagenumber in your
2191 * code (ie. 'tablepage', 'blogpage', etc)
2193 public $pagevar;
2196 * @var string A HTML link representing the "previous" page.
2198 public $previouslink = null;
2201 * @var string A HTML link representing the "next" page.
2203 public $nextlink = null;
2206 * @var string A HTML link representing the first page.
2208 public $firstlink = null;
2211 * @var string A HTML link representing the last page.
2213 public $lastlink = null;
2216 * @var array An array of strings. One of them is just a string: the current page
2218 public $pagelinks = array();
2221 * Constructor paging_bar with only the required params.
2223 * @param int $totalcount The total number of entries available to be paged through
2224 * @param int $page The page you are currently viewing
2225 * @param int $perpage The number of entries that should be shown per page
2226 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2227 * @param string $pagevar name of page parameter that holds the page number
2229 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2230 $this->totalcount = $totalcount;
2231 $this->page = $page;
2232 $this->perpage = $perpage;
2233 $this->baseurl = $baseurl;
2234 $this->pagevar = $pagevar;
2238 * Prepares the paging bar for output.
2240 * This method validates the arguments set up for the paging bar and then
2241 * produces fragments of HTML to assist display later on.
2243 * @param renderer_base $output
2244 * @param moodle_page $page
2245 * @param string $target
2246 * @throws coding_exception
2248 public function prepare(renderer_base $output, moodle_page $page, $target) {
2249 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2250 throw new coding_exception('paging_bar requires a totalcount value.');
2252 if (!isset($this->page) || is_null($this->page)) {
2253 throw new coding_exception('paging_bar requires a page value.');
2255 if (empty($this->perpage)) {
2256 throw new coding_exception('paging_bar requires a perpage value.');
2258 if (empty($this->baseurl)) {
2259 throw new coding_exception('paging_bar requires a baseurl value.');
2262 if ($this->totalcount > $this->perpage) {
2263 $pagenum = $this->page - 1;
2265 if ($this->page > 0) {
2266 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2269 if ($this->perpage > 0) {
2270 $lastpage = ceil($this->totalcount / $this->perpage);
2271 } else {
2272 $lastpage = 1;
2275 if ($this->page > round(($this->maxdisplay/3)*2)) {
2276 $currpage = $this->page - round($this->maxdisplay/3);
2278 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2279 } else {
2280 $currpage = 0;
2283 $displaycount = $displaypage = 0;
2285 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2286 $displaypage = $currpage + 1;
2288 if ($this->page == $currpage) {
2289 $this->pagelinks[] = $displaypage;
2290 } else {
2291 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2292 $this->pagelinks[] = $pagelink;
2295 $displaycount++;
2296 $currpage++;
2299 if ($currpage < $lastpage) {
2300 $lastpageactual = $lastpage - 1;
2301 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2304 $pagenum = $this->page + 1;
2306 if ($pagenum != $displaypage) {
2307 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2314 * This class represents how a block appears on a page.
2316 * During output, each block instance is asked to return a block_contents object,
2317 * those are then passed to the $OUTPUT->block function for display.
2319 * contents should probably be generated using a moodle_block_..._renderer.
2321 * Other block-like things that need to appear on the page, for example the
2322 * add new block UI, are also represented as block_contents objects.
2324 * @copyright 2009 Tim Hunt
2325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2326 * @since Moodle 2.0
2327 * @package core
2328 * @category output
2330 class block_contents {
2332 /** Used when the block cannot be collapsed **/
2333 const NOT_HIDEABLE = 0;
2335 /** Used when the block can be collapsed but currently is not **/
2336 const VISIBLE = 1;
2338 /** Used when the block has been collapsed **/
2339 const HIDDEN = 2;
2342 * @var int Used to set $skipid.
2344 protected static $idcounter = 1;
2347 * @var int All the blocks (or things that look like blocks) printed on
2348 * a page are given a unique number that can be used to construct id="" attributes.
2349 * This is set automatically be the {@link prepare()} method.
2350 * Do not try to set it manually.
2352 public $skipid;
2355 * @var int If this is the contents of a real block, this should be set
2356 * to the block_instance.id. Otherwise this should be set to 0.
2358 public $blockinstanceid = 0;
2361 * @var int If this is a real block instance, and there is a corresponding
2362 * block_position.id for the block on this page, this should be set to that id.
2363 * Otherwise it should be 0.
2365 public $blockpositionid = 0;
2368 * @var array An array of attribute => value pairs that are put on the outer div of this
2369 * block. {@link $id} and {@link $classes} attributes should be set separately.
2371 public $attributes;
2374 * @var string The title of this block. If this came from user input, it should already
2375 * have had format_string() processing done on it. This will be output inside
2376 * <h2> tags. Please do not cause invalid XHTML.
2378 public $title = '';
2381 * @var string HTML for the content
2383 public $content = '';
2386 * @var array An alternative to $content, it you want a list of things with optional icons.
2388 public $footer = '';
2391 * @var string Any small print that should appear under the block to explain
2392 * to the teacher about the block, for example 'This is a sticky block that was
2393 * added in the system context.'
2395 public $annotation = '';
2398 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2399 * the user can toggle whether this block is visible.
2401 public $collapsible = self::NOT_HIDEABLE;
2404 * @var array A (possibly empty) array of editing controls. Each element of
2405 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2406 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2408 public $controls = array();
2412 * Create new instance of block content
2413 * @param array $attributes
2415 public function __construct(array $attributes = null) {
2416 $this->skipid = self::$idcounter;
2417 self::$idcounter += 1;
2419 if ($attributes) {
2420 // standard block
2421 $this->attributes = $attributes;
2422 } else {
2423 // simple "fake" blocks used in some modules and "Add new block" block
2424 $this->attributes = array('class'=>'block');
2429 * Add html class to block
2431 * @param string $class
2433 public function add_class($class) {
2434 $this->attributes['class'] .= ' '.$class;
2440 * This class represents a target for where a block can go when it is being moved.
2442 * This needs to be rendered as a form with the given hidden from fields, and
2443 * clicking anywhere in the form should submit it. The form action should be
2444 * $PAGE->url.
2446 * @copyright 2009 Tim Hunt
2447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2448 * @since Moodle 2.0
2449 * @package core
2450 * @category output
2452 class block_move_target {
2455 * @var moodle_url Move url
2457 public $url;
2460 * @var string label
2462 public $text;
2465 * Constructor
2466 * @param string $text
2467 * @param moodle_url $url
2469 public function __construct($text, moodle_url $url) {
2470 $this->text = $text;
2471 $this->url = $url;
2476 * Custom menu item
2478 * This class is used to represent one item within a custom menu that may or may
2479 * not have children.
2481 * @copyright 2010 Sam Hemelryk
2482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2483 * @since Moodle 2.0
2484 * @package core
2485 * @category output
2487 class custom_menu_item implements renderable {
2490 * @var string The text to show for the item
2492 protected $text;
2495 * @var moodle_url The link to give the icon if it has no children
2497 protected $url;
2500 * @var string A title to apply to the item. By default the text
2502 protected $title;
2505 * @var int A sort order for the item, not necessary if you order things in
2506 * the CFG var.
2508 protected $sort;
2511 * @var custom_menu_item A reference to the parent for this item or NULL if
2512 * it is a top level item
2514 protected $parent;
2517 * @var array A array in which to store children this item has.
2519 protected $children = array();
2522 * @var int A reference to the sort var of the last child that was added
2524 protected $lastsort = 0;
2527 * Constructs the new custom menu item
2529 * @param string $text
2530 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2531 * @param string $title A title to apply to this item [Optional]
2532 * @param int $sort A sort or to use if we need to sort differently [Optional]
2533 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2534 * belongs to, only if the child has a parent. [Optional]
2536 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2537 $this->text = $text;
2538 $this->url = $url;
2539 $this->title = $title;
2540 $this->sort = (int)$sort;
2541 $this->parent = $parent;
2545 * Adds a custom menu item as a child of this node given its properties.
2547 * @param string $text
2548 * @param moodle_url $url
2549 * @param string $title
2550 * @param int $sort
2551 * @return custom_menu_item
2553 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2554 $key = count($this->children);
2555 if (empty($sort)) {
2556 $sort = $this->lastsort + 1;
2558 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2559 $this->lastsort = (int)$sort;
2560 return $this->children[$key];
2564 * Returns the text for this item
2565 * @return string
2567 public function get_text() {
2568 return $this->text;
2572 * Returns the url for this item
2573 * @return moodle_url
2575 public function get_url() {
2576 return $this->url;
2580 * Returns the title for this item
2581 * @return string
2583 public function get_title() {
2584 return $this->title;
2588 * Sorts and returns the children for this item
2589 * @return array
2591 public function get_children() {
2592 $this->sort();
2593 return $this->children;
2597 * Gets the sort order for this child
2598 * @return int
2600 public function get_sort_order() {
2601 return $this->sort;
2605 * Gets the parent this child belong to
2606 * @return custom_menu_item
2608 public function get_parent() {
2609 return $this->parent;
2613 * Sorts the children this item has
2615 public function sort() {
2616 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2620 * Returns true if this item has any children
2621 * @return bool
2623 public function has_children() {
2624 return (count($this->children) > 0);
2628 * Sets the text for the node
2629 * @param string $text
2631 public function set_text($text) {
2632 $this->text = (string)$text;
2636 * Sets the title for the node
2637 * @param string $title
2639 public function set_title($title) {
2640 $this->title = (string)$title;
2644 * Sets the url for the node
2645 * @param moodle_url $url
2647 public function set_url(moodle_url $url) {
2648 $this->url = $url;
2653 * Custom menu class
2655 * This class is used to operate a custom menu that can be rendered for the page.
2656 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2657 * of custom_menu_item nodes that can be rendered by the core renderer.
2659 * To configure the custom menu:
2660 * Settings: Administration > Appearance > Themes > Theme settings
2662 * @copyright 2010 Sam Hemelryk
2663 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2664 * @since Moodle 2.0
2665 * @package core
2666 * @category output
2668 class custom_menu extends custom_menu_item {
2671 * @var string The language we should render for, null disables multilang support.
2673 protected $currentlanguage = null;
2676 * Creates the custom menu
2678 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2679 * @param string $currentlanguage the current language code, null disables multilang support
2681 public function __construct($definition = '', $currentlanguage = null) {
2682 $this->currentlanguage = $currentlanguage;
2683 parent::__construct('root'); // create virtual root element of the menu
2684 if (!empty($definition)) {
2685 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2690 * Overrides the children of this custom menu. Useful when getting children
2691 * from $CFG->custommenuitems
2693 * @param array $children
2695 public function override_children(array $children) {
2696 $this->children = array();
2697 foreach ($children as $child) {
2698 if ($child instanceof custom_menu_item) {
2699 $this->children[] = $child;
2705 * Converts a string into a structured array of custom_menu_items which can
2706 * then be added to a custom menu.
2708 * Structure:
2709 * text|url|title|langs
2710 * The number of hyphens at the start determines the depth of the item. The
2711 * languages are optional, comma separated list of languages the line is for.
2713 * Example structure:
2714 * First level first item|http://www.moodle.com/
2715 * -Second level first item|http://www.moodle.com/partners/
2716 * -Second level second item|http://www.moodle.com/hq/
2717 * --Third level first item|http://www.moodle.com/jobs/
2718 * -Second level third item|http://www.moodle.com/development/
2719 * First level second item|http://www.moodle.com/feedback/
2720 * First level third item
2721 * English only|http://moodle.com|English only item|en
2722 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2725 * @static
2726 * @param string $text the menu items definition
2727 * @param string $language the language code, null disables multilang support
2728 * @return array
2730 public static function convert_text_to_menu_nodes($text, $language = null) {
2731 $lines = explode("\n", $text);
2732 $children = array();
2733 $lastchild = null;
2734 $lastdepth = null;
2735 $lastsort = 0;
2736 foreach ($lines as $line) {
2737 $line = trim($line);
2738 $bits = explode('|', $line, 4); // name|url|title|langs
2739 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2740 // Every item must have a name to be valid
2741 continue;
2742 } else {
2743 $bits[0] = ltrim($bits[0],'-');
2745 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2746 // Set the url to null
2747 $bits[1] = null;
2748 } else {
2749 // Make sure the url is a moodle url
2750 $bits[1] = new moodle_url(trim($bits[1]));
2752 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2753 // Set the title to null seeing as there isn't one
2754 $bits[2] = $bits[0];
2756 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2757 // The item is valid for all languages
2758 $itemlangs = null;
2759 } else {
2760 $itemlangs = array_map('trim', explode(',', $bits[3]));
2762 if (!empty($language) and !empty($itemlangs)) {
2763 // check that the item is intended for the current language
2764 if (!in_array($language, $itemlangs)) {
2765 continue;
2768 // Set an incremental sort order to keep it simple.
2769 $lastsort++;
2770 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2771 $depth = strlen($match[1]);
2772 if ($depth < $lastdepth) {
2773 $difference = $lastdepth - $depth;
2774 if ($lastdepth > 1 && $lastdepth != $difference) {
2775 $tempchild = $lastchild->get_parent();
2776 for ($i =0; $i < $difference; $i++) {
2777 $tempchild = $tempchild->get_parent();
2779 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2780 } else {
2781 $depth = 0;
2782 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2783 $children[] = $lastchild;
2785 } else if ($depth > $lastdepth) {
2786 $depth = $lastdepth + 1;
2787 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2788 } else {
2789 if ($depth == 0) {
2790 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2791 $children[] = $lastchild;
2792 } else {
2793 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2796 } else {
2797 $depth = 0;
2798 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2799 $children[] = $lastchild;
2801 $lastdepth = $depth;
2803 return $children;
2807 * Sorts two custom menu items
2809 * This function is designed to be used with the usort method
2810 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2812 * @static
2813 * @param custom_menu_item $itema
2814 * @param custom_menu_item $itemb
2815 * @return int
2817 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2818 $itema = $itema->get_sort_order();
2819 $itemb = $itemb->get_sort_order();
2820 if ($itema == $itemb) {
2821 return 0;
2823 return ($itema > $itemb) ? +1 : -1;