Merge branch 'MDL-39518-24' of git://github.com/damyon/moodle into MOODLE_24_STABLE
[moodle.git] / lib / outputcomponents.php
blobf1d925b6bd3443d13403ed68075a5b2cc17299f7
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 = context_user::instance($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 ($value instanceof moodle_url) {
1112 return ' ' . $name . '="' . $value->out() . '"';
1115 // special case, we do not want these in output
1116 if ($value === null) {
1117 return '';
1120 // no sloppy trimming here!
1121 return ' ' . $name . '="' . s($value) . '"';
1125 * Outputs a list of HTML attributes and values
1127 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1128 * The values will be escaped with {@link s()}
1129 * @return string HTML fragment
1131 public static function attributes(array $attributes = null) {
1132 $attributes = (array)$attributes;
1133 $output = '';
1134 foreach ($attributes as $name => $value) {
1135 $output .= self::attribute($name, $value);
1137 return $output;
1141 * Generates random html element id.
1143 * @staticvar int $counter
1144 * @staticvar type $uniq
1145 * @param string $base A string fragment that will be included in the random ID.
1146 * @return string A unique ID
1148 public static function random_id($base='random') {
1149 static $counter = 0;
1150 static $uniq;
1152 if (!isset($uniq)) {
1153 $uniq = uniqid();
1156 $counter++;
1157 return $base.$uniq.$counter;
1161 * Generates a simple html link
1163 * @param string|moodle_url $url The URL
1164 * @param string $text The text
1165 * @param array $attributes HTML attributes
1166 * @return string HTML fragment
1168 public static function link($url, $text, array $attributes = null) {
1169 $attributes = (array)$attributes;
1170 $attributes['href'] = $url;
1171 return self::tag('a', $text, $attributes);
1175 * Generates a simple checkbox with optional label
1177 * @param string $name The name of the checkbox
1178 * @param string $value The value of the checkbox
1179 * @param bool $checked Whether the checkbox is checked
1180 * @param string $label The label for the checkbox
1181 * @param array $attributes Any attributes to apply to the checkbox
1182 * @return string html fragment
1184 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1185 $attributes = (array)$attributes;
1186 $output = '';
1188 if ($label !== '' and !is_null($label)) {
1189 if (empty($attributes['id'])) {
1190 $attributes['id'] = self::random_id('checkbox_');
1193 $attributes['type'] = 'checkbox';
1194 $attributes['value'] = $value;
1195 $attributes['name'] = $name;
1196 $attributes['checked'] = $checked ? 'checked' : null;
1198 $output .= self::empty_tag('input', $attributes);
1200 if ($label !== '' and !is_null($label)) {
1201 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1204 return $output;
1208 * Generates a simple select yes/no form field
1210 * @param string $name name of select element
1211 * @param bool $selected
1212 * @param array $attributes - html select element attributes
1213 * @return string HTML fragment
1215 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1216 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1217 return self::select($options, $name, $selected, null, $attributes);
1221 * Generates a simple select form field
1223 * @param array $options associative array value=>label ex.:
1224 * array(1=>'One, 2=>Two)
1225 * it is also possible to specify optgroup as complex label array ex.:
1226 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1227 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1228 * @param string $name name of select element
1229 * @param string|array $selected value or array of values depending on multiple attribute
1230 * @param array|bool $nothing add nothing selected option, or false of not added
1231 * @param array $attributes html select element attributes
1232 * @return string HTML fragment
1234 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1235 $attributes = (array)$attributes;
1236 if (is_array($nothing)) {
1237 foreach ($nothing as $k=>$v) {
1238 if ($v === 'choose' or $v === 'choosedots') {
1239 $nothing[$k] = get_string('choosedots');
1242 $options = $nothing + $options; // keep keys, do not override
1244 } else if (is_string($nothing) and $nothing !== '') {
1245 // BC
1246 $options = array(''=>$nothing) + $options;
1249 // we may accept more values if multiple attribute specified
1250 $selected = (array)$selected;
1251 foreach ($selected as $k=>$v) {
1252 $selected[$k] = (string)$v;
1255 if (!isset($attributes['id'])) {
1256 $id = 'menu'.$name;
1257 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1258 $id = str_replace('[', '', $id);
1259 $id = str_replace(']', '', $id);
1260 $attributes['id'] = $id;
1263 if (!isset($attributes['class'])) {
1264 $class = 'menu'.$name;
1265 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1266 $class = str_replace('[', '', $class);
1267 $class = str_replace(']', '', $class);
1268 $attributes['class'] = $class;
1270 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1272 $attributes['name'] = $name;
1274 if (!empty($attributes['disabled'])) {
1275 $attributes['disabled'] = 'disabled';
1276 } else {
1277 unset($attributes['disabled']);
1280 $output = '';
1281 foreach ($options as $value=>$label) {
1282 if (is_array($label)) {
1283 // ignore key, it just has to be unique
1284 $output .= self::select_optgroup(key($label), current($label), $selected);
1285 } else {
1286 $output .= self::select_option($label, $value, $selected);
1289 return self::tag('select', $output, $attributes);
1293 * Returns HTML to display a select box option.
1295 * @param string $label The label to display as the option.
1296 * @param string|int $value The value the option represents
1297 * @param array $selected An array of selected options
1298 * @return string HTML fragment
1300 private static function select_option($label, $value, array $selected) {
1301 $attributes = array();
1302 $value = (string)$value;
1303 if (in_array($value, $selected, true)) {
1304 $attributes['selected'] = 'selected';
1306 $attributes['value'] = $value;
1307 return self::tag('option', $label, $attributes);
1311 * Returns HTML to display a select box option group.
1313 * @param string $groupname The label to use for the group
1314 * @param array $options The options in the group
1315 * @param array $selected An array of selected values.
1316 * @return string HTML fragment.
1318 private static function select_optgroup($groupname, $options, array $selected) {
1319 if (empty($options)) {
1320 return '';
1322 $attributes = array('label'=>$groupname);
1323 $output = '';
1324 foreach ($options as $value=>$label) {
1325 $output .= self::select_option($label, $value, $selected);
1327 return self::tag('optgroup', $output, $attributes);
1331 * This is a shortcut for making an hour selector menu.
1333 * @param string $type The type of selector (years, months, days, hours, minutes)
1334 * @param string $name fieldname
1335 * @param int $currenttime A default timestamp in GMT
1336 * @param int $step minute spacing
1337 * @param array $attributes - html select element attributes
1338 * @return HTML fragment
1340 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1341 if (!$currenttime) {
1342 $currenttime = time();
1344 $currentdate = usergetdate($currenttime);
1345 $userdatetype = $type;
1346 $timeunits = array();
1348 switch ($type) {
1349 case 'years':
1350 for ($i=1970; $i<=2020; $i++) {
1351 $timeunits[$i] = $i;
1353 $userdatetype = 'year';
1354 break;
1355 case 'months':
1356 for ($i=1; $i<=12; $i++) {
1357 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1359 $userdatetype = 'month';
1360 $currentdate['month'] = (int)$currentdate['mon'];
1361 break;
1362 case 'days':
1363 for ($i=1; $i<=31; $i++) {
1364 $timeunits[$i] = $i;
1366 $userdatetype = 'mday';
1367 break;
1368 case 'hours':
1369 for ($i=0; $i<=23; $i++) {
1370 $timeunits[$i] = sprintf("%02d",$i);
1372 break;
1373 case 'minutes':
1374 if ($step != 1) {
1375 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1378 for ($i=0; $i<=59; $i+=$step) {
1379 $timeunits[$i] = sprintf("%02d",$i);
1381 break;
1382 default:
1383 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1386 if (empty($attributes['id'])) {
1387 $attributes['id'] = self::random_id('ts_');
1389 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1390 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1392 return $label.$timerselector;
1396 * Shortcut for quick making of lists
1398 * Note: 'list' is a reserved keyword ;-)
1400 * @param array $items
1401 * @param array $attributes
1402 * @param string $tag ul or ol
1403 * @return string
1405 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1406 $output = '';
1408 foreach ($items as $item) {
1409 $output .= html_writer::start_tag('li') . "\n";
1410 $output .= $item . "\n";
1411 $output .= html_writer::end_tag('li') . "\n";
1414 return html_writer::tag($tag, $output, $attributes);
1418 * Returns hidden input fields created from url parameters.
1420 * @param moodle_url $url
1421 * @param array $exclude list of excluded parameters
1422 * @return string HTML fragment
1424 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1425 $exclude = (array)$exclude;
1426 $params = $url->params();
1427 foreach ($exclude as $key) {
1428 unset($params[$key]);
1431 $output = '';
1432 foreach ($params as $key => $value) {
1433 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1434 $output .= self::empty_tag('input', $attributes)."\n";
1436 return $output;
1440 * Generate a script tag containing the the specified code.
1442 * @param string $jscode the JavaScript code
1443 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1444 * @return string HTML, the code wrapped in <script> tags.
1446 public static function script($jscode, $url=null) {
1447 if ($jscode) {
1448 $attributes = array('type'=>'text/javascript');
1449 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1451 } else if ($url) {
1452 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1453 return self::tag('script', '', $attributes) . "\n";
1455 } else {
1456 return '';
1461 * Renders HTML table
1463 * This method may modify the passed instance by adding some default properties if they are not set yet.
1464 * If this is not what you want, you should make a full clone of your data before passing them to this
1465 * method. In most cases this is not an issue at all so we do not clone by default for performance
1466 * and memory consumption reasons.
1468 * @param html_table $table data to be rendered
1469 * @return string HTML code
1471 public static function table(html_table $table) {
1472 // prepare table data and populate missing properties with reasonable defaults
1473 if (!empty($table->align)) {
1474 foreach ($table->align as $key => $aa) {
1475 if ($aa) {
1476 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1477 } else {
1478 $table->align[$key] = null;
1482 if (!empty($table->size)) {
1483 foreach ($table->size as $key => $ss) {
1484 if ($ss) {
1485 $table->size[$key] = 'width:'. $ss .';';
1486 } else {
1487 $table->size[$key] = null;
1491 if (!empty($table->wrap)) {
1492 foreach ($table->wrap as $key => $ww) {
1493 if ($ww) {
1494 $table->wrap[$key] = 'white-space:nowrap;';
1495 } else {
1496 $table->wrap[$key] = '';
1500 if (!empty($table->head)) {
1501 foreach ($table->head as $key => $val) {
1502 if (!isset($table->align[$key])) {
1503 $table->align[$key] = null;
1505 if (!isset($table->size[$key])) {
1506 $table->size[$key] = null;
1508 if (!isset($table->wrap[$key])) {
1509 $table->wrap[$key] = null;
1514 if (empty($table->attributes['class'])) {
1515 $table->attributes['class'] = 'generaltable';
1517 if (!empty($table->tablealign)) {
1518 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1521 // explicitly assigned properties override those defined via $table->attributes
1522 $table->attributes['class'] = trim($table->attributes['class']);
1523 $attributes = array_merge($table->attributes, array(
1524 'id' => $table->id,
1525 'width' => $table->width,
1526 'summary' => $table->summary,
1527 'cellpadding' => $table->cellpadding,
1528 'cellspacing' => $table->cellspacing,
1530 $output = html_writer::start_tag('table', $attributes) . "\n";
1532 $countcols = 0;
1534 if (!empty($table->head)) {
1535 $countcols = count($table->head);
1537 $output .= html_writer::start_tag('thead', array()) . "\n";
1538 $output .= html_writer::start_tag('tr', array()) . "\n";
1539 $keys = array_keys($table->head);
1540 $lastkey = end($keys);
1542 foreach ($table->head as $key => $heading) {
1543 // Convert plain string headings into html_table_cell objects
1544 if (!($heading instanceof html_table_cell)) {
1545 $headingtext = $heading;
1546 $heading = new html_table_cell();
1547 $heading->text = $headingtext;
1548 $heading->header = true;
1551 if ($heading->header !== false) {
1552 $heading->header = true;
1555 if ($heading->header && empty($heading->scope)) {
1556 $heading->scope = 'col';
1559 $heading->attributes['class'] .= ' header c' . $key;
1560 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1561 $heading->colspan = $table->headspan[$key];
1562 $countcols += $table->headspan[$key] - 1;
1565 if ($key == $lastkey) {
1566 $heading->attributes['class'] .= ' lastcol';
1568 if (isset($table->colclasses[$key])) {
1569 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1571 $heading->attributes['class'] = trim($heading->attributes['class']);
1572 $attributes = array_merge($heading->attributes, array(
1573 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1574 'scope' => $heading->scope,
1575 'colspan' => $heading->colspan,
1578 $tagtype = 'td';
1579 if ($heading->header === true) {
1580 $tagtype = 'th';
1582 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1584 $output .= html_writer::end_tag('tr') . "\n";
1585 $output .= html_writer::end_tag('thead') . "\n";
1587 if (empty($table->data)) {
1588 // For valid XHTML strict every table must contain either a valid tr
1589 // or a valid tbody... both of which must contain a valid td
1590 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1591 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1592 $output .= html_writer::end_tag('tbody');
1596 if (!empty($table->data)) {
1597 $oddeven = 1;
1598 $keys = array_keys($table->data);
1599 $lastrowkey = end($keys);
1600 $output .= html_writer::start_tag('tbody', array());
1602 foreach ($table->data as $key => $row) {
1603 if (($row === 'hr') && ($countcols)) {
1604 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1605 } else {
1606 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1607 if (!($row instanceof html_table_row)) {
1608 $newrow = new html_table_row();
1610 foreach ($row as $cell) {
1611 if (!($cell instanceof html_table_cell)) {
1612 $cell = new html_table_cell($cell);
1614 $newrow->cells[] = $cell;
1616 $row = $newrow;
1619 $oddeven = $oddeven ? 0 : 1;
1620 if (isset($table->rowclasses[$key])) {
1621 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1624 $row->attributes['class'] .= ' r' . $oddeven;
1625 if ($key == $lastrowkey) {
1626 $row->attributes['class'] .= ' lastrow';
1629 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1630 $keys2 = array_keys($row->cells);
1631 $lastkey = end($keys2);
1633 $gotlastkey = false; //flag for sanity checking
1634 foreach ($row->cells as $key => $cell) {
1635 if ($gotlastkey) {
1636 //This should never happen. Why do we have a cell after the last cell?
1637 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1640 if (!($cell instanceof html_table_cell)) {
1641 $mycell = new html_table_cell();
1642 $mycell->text = $cell;
1643 $cell = $mycell;
1646 if (($cell->header === true) && empty($cell->scope)) {
1647 $cell->scope = 'row';
1650 if (isset($table->colclasses[$key])) {
1651 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1654 $cell->attributes['class'] .= ' cell c' . $key;
1655 if ($key == $lastkey) {
1656 $cell->attributes['class'] .= ' lastcol';
1657 $gotlastkey = true;
1659 $tdstyle = '';
1660 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1661 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1662 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1663 $cell->attributes['class'] = trim($cell->attributes['class']);
1664 $tdattributes = array_merge($cell->attributes, array(
1665 'style' => $tdstyle . $cell->style,
1666 'colspan' => $cell->colspan,
1667 'rowspan' => $cell->rowspan,
1668 'id' => $cell->id,
1669 'abbr' => $cell->abbr,
1670 'scope' => $cell->scope,
1672 $tagtype = 'td';
1673 if ($cell->header === true) {
1674 $tagtype = 'th';
1676 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1679 $output .= html_writer::end_tag('tr') . "\n";
1681 $output .= html_writer::end_tag('tbody') . "\n";
1683 $output .= html_writer::end_tag('table') . "\n";
1685 return $output;
1689 * Renders form element label
1691 * By default, the label is suffixed with a label separator defined in the
1692 * current language pack (colon by default in the English lang pack).
1693 * Adding the colon can be explicitly disabled if needed. Label separators
1694 * are put outside the label tag itself so they are not read by
1695 * screenreaders (accessibility).
1697 * Parameter $for explicitly associates the label with a form control. When
1698 * set, the value of this attribute must be the same as the value of
1699 * the id attribute of the form control in the same document. When null,
1700 * the label being defined is associated with the control inside the label
1701 * element.
1703 * @param string $text content of the label tag
1704 * @param string|null $for id of the element this label is associated with, null for no association
1705 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1706 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1707 * @return string HTML of the label element
1709 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1710 if (!is_null($for)) {
1711 $attributes = array_merge($attributes, array('for' => $for));
1713 $text = trim($text);
1714 $label = self::tag('label', $text, $attributes);
1716 // TODO MDL-12192 $colonize disabled for now yet
1717 // if (!empty($text) and $colonize) {
1718 // // the $text may end with the colon already, though it is bad string definition style
1719 // $colon = get_string('labelsep', 'langconfig');
1720 // if (!empty($colon)) {
1721 // $trimmed = trim($colon);
1722 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1723 // //debugging('The label text should not end with colon or other label separator,
1724 // // please fix the string definition.', DEBUG_DEVELOPER);
1725 // } else {
1726 // $label .= $colon;
1727 // }
1728 // }
1729 // }
1731 return $label;
1736 * Simple javascript output class
1738 * @copyright 2010 Petr Skoda
1739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1740 * @since Moodle 2.0
1741 * @package core
1742 * @category output
1744 class js_writer {
1747 * Returns javascript code calling the function
1749 * @param string $function function name, can be complex like Y.Event.purgeElement
1750 * @param array $arguments parameters
1751 * @param int $delay execution delay in seconds
1752 * @return string JS code fragment
1754 public static function function_call($function, array $arguments = null, $delay=0) {
1755 if ($arguments) {
1756 $arguments = array_map('json_encode', convert_to_array($arguments));
1757 $arguments = implode(', ', $arguments);
1758 } else {
1759 $arguments = '';
1761 $js = "$function($arguments);";
1763 if ($delay) {
1764 $delay = $delay * 1000; // in miliseconds
1765 $js = "setTimeout(function() { $js }, $delay);";
1767 return $js . "\n";
1771 * Special function which adds Y as first argument of function call.
1773 * @param string $function The function to call
1774 * @param array $extraarguments Any arguments to pass to it
1775 * @return string Some JS code
1777 public static function function_call_with_Y($function, array $extraarguments = null) {
1778 if ($extraarguments) {
1779 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1780 $arguments = 'Y, ' . implode(', ', $extraarguments);
1781 } else {
1782 $arguments = 'Y';
1784 return "$function($arguments);\n";
1788 * Returns JavaScript code to initialise a new object
1790 * @param string $var If it is null then no var is assigned the new object.
1791 * @param string $class The class to initialise an object for.
1792 * @param array $arguments An array of args to pass to the init method.
1793 * @param array $requirements Any modules required for this class.
1794 * @param int $delay The delay before initialisation. 0 = no delay.
1795 * @return string Some JS code
1797 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1798 if (is_array($arguments)) {
1799 $arguments = array_map('json_encode', convert_to_array($arguments));
1800 $arguments = implode(', ', $arguments);
1803 if ($var === null) {
1804 $js = "new $class(Y, $arguments);";
1805 } else if (strpos($var, '.')!==false) {
1806 $js = "$var = new $class(Y, $arguments);";
1807 } else {
1808 $js = "var $var = new $class(Y, $arguments);";
1811 if ($delay) {
1812 $delay = $delay * 1000; // in miliseconds
1813 $js = "setTimeout(function() { $js }, $delay);";
1816 if (count($requirements) > 0) {
1817 $requirements = implode("', '", $requirements);
1818 $js = "Y.use('$requirements', function(Y){ $js });";
1820 return $js."\n";
1824 * Returns code setting value to variable
1826 * @param string $name
1827 * @param mixed $value json serialised value
1828 * @param bool $usevar add var definition, ignored for nested properties
1829 * @return string JS code fragment
1831 public static function set_variable($name, $value, $usevar = true) {
1832 $output = '';
1834 if ($usevar) {
1835 if (strpos($name, '.')) {
1836 $output .= '';
1837 } else {
1838 $output .= 'var ';
1842 $output .= "$name = ".json_encode($value).";";
1844 return $output;
1848 * Writes event handler attaching code
1850 * @param array|string $selector standard YUI selector for elements, may be
1851 * array or string, element id is in the form "#idvalue"
1852 * @param string $event A valid DOM event (click, mousedown, change etc.)
1853 * @param string $function The name of the function to call
1854 * @param array $arguments An optional array of argument parameters to pass to the function
1855 * @return string JS code fragment
1857 public static function event_handler($selector, $event, $function, array $arguments = null) {
1858 $selector = json_encode($selector);
1859 $output = "Y.on('$event', $function, $selector, null";
1860 if (!empty($arguments)) {
1861 $output .= ', ' . json_encode($arguments);
1863 return $output . ");\n";
1868 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1870 * Example of usage:
1871 * $t = new html_table();
1872 * ... // set various properties of the object $t as described below
1873 * echo html_writer::table($t);
1875 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1877 * @since Moodle 2.0
1878 * @package core
1879 * @category output
1881 class html_table {
1884 * @var string Value to use for the id attribute of the table
1886 public $id = null;
1889 * @var array Attributes of HTML attributes for the <table> element
1891 public $attributes = array();
1894 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1895 * For more control over the rendering of the headers, an array of html_table_cell objects
1896 * can be passed instead of an array of strings.
1898 * Example of usage:
1899 * $t->head = array('Student', 'Grade');
1901 public $head;
1904 * @var array An array that can be used to make a heading span multiple columns.
1905 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1906 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1908 * Example of usage:
1909 * $t->headspan = array(2,1);
1911 public $headspan;
1914 * @var array An array of column alignments.
1915 * The value is used as CSS 'text-align' property. Therefore, possible
1916 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1917 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1919 * Examples of usage:
1920 * $t->align = array(null, 'right');
1921 * or
1922 * $t->align[1] = 'right';
1924 public $align;
1927 * @var array The value is used as CSS 'size' property.
1929 * Examples of usage:
1930 * $t->size = array('50%', '50%');
1931 * or
1932 * $t->size[1] = '120px';
1934 public $size;
1937 * @var array An array of wrapping information.
1938 * The only possible value is 'nowrap' that sets the
1939 * CSS property 'white-space' to the value 'nowrap' in the given column.
1941 * Example of usage:
1942 * $t->wrap = array(null, 'nowrap');
1944 public $wrap;
1947 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1948 * $head specified, the string 'hr' (for horizontal ruler) can be used
1949 * instead of an array of cells data resulting in a divider rendered.
1951 * Example of usage with array of arrays:
1952 * $row1 = array('Harry Potter', '76 %');
1953 * $row2 = array('Hermione Granger', '100 %');
1954 * $t->data = array($row1, $row2);
1956 * Example with array of html_table_row objects: (used for more fine-grained control)
1957 * $cell1 = new html_table_cell();
1958 * $cell1->text = 'Harry Potter';
1959 * $cell1->colspan = 2;
1960 * $row1 = new html_table_row();
1961 * $row1->cells[] = $cell1;
1962 * $cell2 = new html_table_cell();
1963 * $cell2->text = 'Hermione Granger';
1964 * $cell3 = new html_table_cell();
1965 * $cell3->text = '100 %';
1966 * $row2 = new html_table_row();
1967 * $row2->cells = array($cell2, $cell3);
1968 * $t->data = array($row1, $row2);
1970 public $data;
1973 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1974 * @var string Width of the table, percentage of the page preferred.
1976 public $width = null;
1979 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1980 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
1982 public $tablealign = null;
1985 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1986 * @var int Padding on each cell, in pixels
1988 public $cellpadding = null;
1991 * @var int Spacing between cells, in pixels
1992 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1994 public $cellspacing = null;
1997 * @var array Array of classes to add to particular rows, space-separated string.
1998 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1999 * respectively. Class 'lastrow' is added automatically for the last row
2000 * in the table.
2002 * Example of usage:
2003 * $t->rowclasses[9] = 'tenth'
2005 public $rowclasses;
2008 * @var array An array of classes to add to every cell in a particular column,
2009 * space-separated string. Class 'cell' is added automatically by the renderer.
2010 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2011 * respectively. Class 'lastcol' is added automatically for all last cells
2012 * in a row.
2014 * Example of usage:
2015 * $t->colclasses = array(null, 'grade');
2017 public $colclasses;
2020 * @var string Description of the contents for screen readers.
2022 public $summary;
2025 * Constructor
2027 public function __construct() {
2028 $this->attributes['class'] = '';
2033 * Component representing a table row.
2035 * @copyright 2009 Nicolas Connault
2036 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2037 * @since Moodle 2.0
2038 * @package core
2039 * @category output
2041 class html_table_row {
2044 * @var string Value to use for the id attribute of the row.
2046 public $id = null;
2049 * @var array Array of html_table_cell objects
2051 public $cells = array();
2054 * @var string Value to use for the style attribute of the table row
2056 public $style = null;
2059 * @var array Attributes of additional HTML attributes for the <tr> element
2061 public $attributes = array();
2064 * Constructor
2065 * @param array $cells
2067 public function __construct(array $cells=null) {
2068 $this->attributes['class'] = '';
2069 $cells = (array)$cells;
2070 foreach ($cells as $cell) {
2071 if ($cell instanceof html_table_cell) {
2072 $this->cells[] = $cell;
2073 } else {
2074 $this->cells[] = new html_table_cell($cell);
2081 * Component representing a table cell.
2083 * @copyright 2009 Nicolas Connault
2084 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2085 * @since Moodle 2.0
2086 * @package core
2087 * @category output
2089 class html_table_cell {
2092 * @var string Value to use for the id attribute of the cell.
2094 public $id = null;
2097 * @var string The contents of the cell.
2099 public $text;
2102 * @var string Abbreviated version of the contents of the cell.
2104 public $abbr = null;
2107 * @var int Number of columns this cell should span.
2109 public $colspan = null;
2112 * @var int Number of rows this cell should span.
2114 public $rowspan = null;
2117 * @var string Defines a way to associate header cells and data cells in a table.
2119 public $scope = null;
2122 * @var bool Whether or not this cell is a header cell.
2124 public $header = null;
2127 * @var string Value to use for the style attribute of the table cell
2129 public $style = null;
2132 * @var array Attributes of additional HTML attributes for the <td> element
2134 public $attributes = array();
2137 * Constructs a table cell
2139 * @param string $text
2141 public function __construct($text = null) {
2142 $this->text = $text;
2143 $this->attributes['class'] = '';
2148 * Component representing a paging bar.
2150 * @copyright 2009 Nicolas Connault
2151 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2152 * @since Moodle 2.0
2153 * @package core
2154 * @category output
2156 class paging_bar implements renderable {
2159 * @var int The maximum number of pagelinks to display.
2161 public $maxdisplay = 18;
2164 * @var int The total number of entries to be pages through..
2166 public $totalcount;
2169 * @var int The page you are currently viewing.
2171 public $page;
2174 * @var int The number of entries that should be shown per page.
2176 public $perpage;
2179 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2180 * an equals sign and the page number.
2181 * If this is a moodle_url object then the pagevar param will be replaced by
2182 * the page no, for each page.
2184 public $baseurl;
2187 * @var string This is the variable name that you use for the pagenumber in your
2188 * code (ie. 'tablepage', 'blogpage', etc)
2190 public $pagevar;
2193 * @var string A HTML link representing the "previous" page.
2195 public $previouslink = null;
2198 * @var string A HTML link representing the "next" page.
2200 public $nextlink = null;
2203 * @var string A HTML link representing the first page.
2205 public $firstlink = null;
2208 * @var string A HTML link representing the last page.
2210 public $lastlink = null;
2213 * @var array An array of strings. One of them is just a string: the current page
2215 public $pagelinks = array();
2218 * Constructor paging_bar with only the required params.
2220 * @param int $totalcount The total number of entries available to be paged through
2221 * @param int $page The page you are currently viewing
2222 * @param int $perpage The number of entries that should be shown per page
2223 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2224 * @param string $pagevar name of page parameter that holds the page number
2226 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2227 $this->totalcount = $totalcount;
2228 $this->page = $page;
2229 $this->perpage = $perpage;
2230 $this->baseurl = $baseurl;
2231 $this->pagevar = $pagevar;
2235 * Prepares the paging bar for output.
2237 * This method validates the arguments set up for the paging bar and then
2238 * produces fragments of HTML to assist display later on.
2240 * @param renderer_base $output
2241 * @param moodle_page $page
2242 * @param string $target
2243 * @throws coding_exception
2245 public function prepare(renderer_base $output, moodle_page $page, $target) {
2246 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2247 throw new coding_exception('paging_bar requires a totalcount value.');
2249 if (!isset($this->page) || is_null($this->page)) {
2250 throw new coding_exception('paging_bar requires a page value.');
2252 if (empty($this->perpage)) {
2253 throw new coding_exception('paging_bar requires a perpage value.');
2255 if (empty($this->baseurl)) {
2256 throw new coding_exception('paging_bar requires a baseurl value.');
2259 if ($this->totalcount > $this->perpage) {
2260 $pagenum = $this->page - 1;
2262 if ($this->page > 0) {
2263 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2266 if ($this->perpage > 0) {
2267 $lastpage = ceil($this->totalcount / $this->perpage);
2268 } else {
2269 $lastpage = 1;
2272 if ($this->page > round(($this->maxdisplay/3)*2)) {
2273 $currpage = $this->page - round($this->maxdisplay/3);
2275 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2276 } else {
2277 $currpage = 0;
2280 $displaycount = $displaypage = 0;
2282 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2283 $displaypage = $currpage + 1;
2285 if ($this->page == $currpage) {
2286 $this->pagelinks[] = $displaypage;
2287 } else {
2288 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2289 $this->pagelinks[] = $pagelink;
2292 $displaycount++;
2293 $currpage++;
2296 if ($currpage < $lastpage) {
2297 $lastpageactual = $lastpage - 1;
2298 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2301 $pagenum = $this->page + 1;
2303 if ($pagenum != $displaypage) {
2304 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2311 * This class represents how a block appears on a page.
2313 * During output, each block instance is asked to return a block_contents object,
2314 * those are then passed to the $OUTPUT->block function for display.
2316 * contents should probably be generated using a moodle_block_..._renderer.
2318 * Other block-like things that need to appear on the page, for example the
2319 * add new block UI, are also represented as block_contents objects.
2321 * @copyright 2009 Tim Hunt
2322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2323 * @since Moodle 2.0
2324 * @package core
2325 * @category output
2327 class block_contents {
2329 /** Used when the block cannot be collapsed **/
2330 const NOT_HIDEABLE = 0;
2332 /** Used when the block can be collapsed but currently is not **/
2333 const VISIBLE = 1;
2335 /** Used when the block has been collapsed **/
2336 const HIDDEN = 2;
2339 * @var int Used to set $skipid.
2341 protected static $idcounter = 1;
2344 * @var int All the blocks (or things that look like blocks) printed on
2345 * a page are given a unique number that can be used to construct id="" attributes.
2346 * This is set automatically be the {@link prepare()} method.
2347 * Do not try to set it manually.
2349 public $skipid;
2352 * @var int If this is the contents of a real block, this should be set
2353 * to the block_instance.id. Otherwise this should be set to 0.
2355 public $blockinstanceid = 0;
2358 * @var int If this is a real block instance, and there is a corresponding
2359 * block_position.id for the block on this page, this should be set to that id.
2360 * Otherwise it should be 0.
2362 public $blockpositionid = 0;
2365 * @var array An array of attribute => value pairs that are put on the outer div of this
2366 * block. {@link $id} and {@link $classes} attributes should be set separately.
2368 public $attributes;
2371 * @var string The title of this block. If this came from user input, it should already
2372 * have had format_string() processing done on it. This will be output inside
2373 * <h2> tags. Please do not cause invalid XHTML.
2375 public $title = '';
2378 * @var string The label to use when the block does not, or will not have a visible title.
2379 * You should never set this as well as title... it will just be ignored.
2381 public $arialabel = '';
2384 * @var string HTML for the content
2386 public $content = '';
2389 * @var array An alternative to $content, it you want a list of things with optional icons.
2391 public $footer = '';
2394 * @var string Any small print that should appear under the block to explain
2395 * to the teacher about the block, for example 'This is a sticky block that was
2396 * added in the system context.'
2398 public $annotation = '';
2401 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2402 * the user can toggle whether this block is visible.
2404 public $collapsible = self::NOT_HIDEABLE;
2407 * @var array A (possibly empty) array of editing controls. Each element of
2408 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2409 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2411 public $controls = array();
2415 * Create new instance of block content
2416 * @param array $attributes
2418 public function __construct(array $attributes = null) {
2419 $this->skipid = self::$idcounter;
2420 self::$idcounter += 1;
2422 if ($attributes) {
2423 // standard block
2424 $this->attributes = $attributes;
2425 } else {
2426 // simple "fake" blocks used in some modules and "Add new block" block
2427 $this->attributes = array('class'=>'block');
2432 * Add html class to block
2434 * @param string $class
2436 public function add_class($class) {
2437 $this->attributes['class'] .= ' '.$class;
2443 * This class represents a target for where a block can go when it is being moved.
2445 * This needs to be rendered as a form with the given hidden from fields, and
2446 * clicking anywhere in the form should submit it. The form action should be
2447 * $PAGE->url.
2449 * @copyright 2009 Tim Hunt
2450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2451 * @since Moodle 2.0
2452 * @package core
2453 * @category output
2455 class block_move_target {
2458 * @var moodle_url Move url
2460 public $url;
2463 * @var string label
2465 public $text;
2468 * Constructor
2469 * @param string $text
2470 * @param moodle_url $url
2472 public function __construct($text, moodle_url $url) {
2473 $this->text = $text;
2474 $this->url = $url;
2479 * Custom menu item
2481 * This class is used to represent one item within a custom menu that may or may
2482 * not have children.
2484 * @copyright 2010 Sam Hemelryk
2485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2486 * @since Moodle 2.0
2487 * @package core
2488 * @category output
2490 class custom_menu_item implements renderable {
2493 * @var string The text to show for the item
2495 protected $text;
2498 * @var moodle_url The link to give the icon if it has no children
2500 protected $url;
2503 * @var string A title to apply to the item. By default the text
2505 protected $title;
2508 * @var int A sort order for the item, not necessary if you order things in
2509 * the CFG var.
2511 protected $sort;
2514 * @var custom_menu_item A reference to the parent for this item or NULL if
2515 * it is a top level item
2517 protected $parent;
2520 * @var array A array in which to store children this item has.
2522 protected $children = array();
2525 * @var int A reference to the sort var of the last child that was added
2527 protected $lastsort = 0;
2530 * Constructs the new custom menu item
2532 * @param string $text
2533 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2534 * @param string $title A title to apply to this item [Optional]
2535 * @param int $sort A sort or to use if we need to sort differently [Optional]
2536 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2537 * belongs to, only if the child has a parent. [Optional]
2539 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2540 $this->text = $text;
2541 $this->url = $url;
2542 $this->title = $title;
2543 $this->sort = (int)$sort;
2544 $this->parent = $parent;
2548 * Adds a custom menu item as a child of this node given its properties.
2550 * @param string $text
2551 * @param moodle_url $url
2552 * @param string $title
2553 * @param int $sort
2554 * @return custom_menu_item
2556 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2557 $key = count($this->children);
2558 if (empty($sort)) {
2559 $sort = $this->lastsort + 1;
2561 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2562 $this->lastsort = (int)$sort;
2563 return $this->children[$key];
2567 * Returns the text for this item
2568 * @return string
2570 public function get_text() {
2571 return $this->text;
2575 * Returns the url for this item
2576 * @return moodle_url
2578 public function get_url() {
2579 return $this->url;
2583 * Returns the title for this item
2584 * @return string
2586 public function get_title() {
2587 return $this->title;
2591 * Sorts and returns the children for this item
2592 * @return array
2594 public function get_children() {
2595 $this->sort();
2596 return $this->children;
2600 * Gets the sort order for this child
2601 * @return int
2603 public function get_sort_order() {
2604 return $this->sort;
2608 * Gets the parent this child belong to
2609 * @return custom_menu_item
2611 public function get_parent() {
2612 return $this->parent;
2616 * Sorts the children this item has
2618 public function sort() {
2619 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2623 * Returns true if this item has any children
2624 * @return bool
2626 public function has_children() {
2627 return (count($this->children) > 0);
2631 * Sets the text for the node
2632 * @param string $text
2634 public function set_text($text) {
2635 $this->text = (string)$text;
2639 * Sets the title for the node
2640 * @param string $title
2642 public function set_title($title) {
2643 $this->title = (string)$title;
2647 * Sets the url for the node
2648 * @param moodle_url $url
2650 public function set_url(moodle_url $url) {
2651 $this->url = $url;
2656 * Custom menu class
2658 * This class is used to operate a custom menu that can be rendered for the page.
2659 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2660 * of custom_menu_item nodes that can be rendered by the core renderer.
2662 * To configure the custom menu:
2663 * Settings: Administration > Appearance > Themes > Theme settings
2665 * @copyright 2010 Sam Hemelryk
2666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2667 * @since Moodle 2.0
2668 * @package core
2669 * @category output
2671 class custom_menu extends custom_menu_item {
2674 * @var string The language we should render for, null disables multilang support.
2676 protected $currentlanguage = null;
2679 * Creates the custom menu
2681 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2682 * @param string $currentlanguage the current language code, null disables multilang support
2684 public function __construct($definition = '', $currentlanguage = null) {
2685 $this->currentlanguage = $currentlanguage;
2686 parent::__construct('root'); // create virtual root element of the menu
2687 if (!empty($definition)) {
2688 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2693 * Overrides the children of this custom menu. Useful when getting children
2694 * from $CFG->custommenuitems
2696 * @param array $children
2698 public function override_children(array $children) {
2699 $this->children = array();
2700 foreach ($children as $child) {
2701 if ($child instanceof custom_menu_item) {
2702 $this->children[] = $child;
2708 * Converts a string into a structured array of custom_menu_items which can
2709 * then be added to a custom menu.
2711 * Structure:
2712 * text|url|title|langs
2713 * The number of hyphens at the start determines the depth of the item. The
2714 * languages are optional, comma separated list of languages the line is for.
2716 * Example structure:
2717 * First level first item|http://www.moodle.com/
2718 * -Second level first item|http://www.moodle.com/partners/
2719 * -Second level second item|http://www.moodle.com/hq/
2720 * --Third level first item|http://www.moodle.com/jobs/
2721 * -Second level third item|http://www.moodle.com/development/
2722 * First level second item|http://www.moodle.com/feedback/
2723 * First level third item
2724 * English only|http://moodle.com|English only item|en
2725 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2728 * @static
2729 * @param string $text the menu items definition
2730 * @param string $language the language code, null disables multilang support
2731 * @return array
2733 public static function convert_text_to_menu_nodes($text, $language = null) {
2734 $lines = explode("\n", $text);
2735 $children = array();
2736 $lastchild = null;
2737 $lastdepth = null;
2738 $lastsort = 0;
2739 foreach ($lines as $line) {
2740 $line = trim($line);
2741 $bits = explode('|', $line, 4); // name|url|title|langs
2742 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2743 // Every item must have a name to be valid
2744 continue;
2745 } else {
2746 $bits[0] = ltrim($bits[0],'-');
2748 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2749 // Set the url to null
2750 $bits[1] = null;
2751 } else {
2752 // Make sure the url is a moodle url
2753 $bits[1] = new moodle_url(trim($bits[1]));
2755 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2756 // Set the title to null seeing as there isn't one
2757 $bits[2] = $bits[0];
2759 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2760 // The item is valid for all languages
2761 $itemlangs = null;
2762 } else {
2763 $itemlangs = array_map('trim', explode(',', $bits[3]));
2765 if (!empty($language) and !empty($itemlangs)) {
2766 // check that the item is intended for the current language
2767 if (!in_array($language, $itemlangs)) {
2768 continue;
2771 // Set an incremental sort order to keep it simple.
2772 $lastsort++;
2773 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2774 $depth = strlen($match[1]);
2775 if ($depth < $lastdepth) {
2776 $difference = $lastdepth - $depth;
2777 if ($lastdepth > 1 && $lastdepth != $difference) {
2778 $tempchild = $lastchild->get_parent();
2779 for ($i =0; $i < $difference; $i++) {
2780 $tempchild = $tempchild->get_parent();
2782 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2783 } else {
2784 $depth = 0;
2785 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2786 $children[] = $lastchild;
2788 } else if ($depth > $lastdepth) {
2789 $depth = $lastdepth + 1;
2790 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2791 } else {
2792 if ($depth == 0) {
2793 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2794 $children[] = $lastchild;
2795 } else {
2796 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2799 } else {
2800 $depth = 0;
2801 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2802 $children[] = $lastchild;
2804 $lastdepth = $depth;
2806 return $children;
2810 * Sorts two custom menu items
2812 * This function is designed to be used with the usort method
2813 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2815 * @static
2816 * @param custom_menu_item $itema
2817 * @param custom_menu_item $itemb
2818 * @return int
2820 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2821 $itema = $itema->get_sort_order();
2822 $itemb = $itemb->get_sort_order();
2823 if ($itema == $itemb) {
2824 return 0;
2826 return ($itema > $itemb) ? +1 : -1;