MDL-32003 fix phpdocs in xmldb abstraction
[moodle.git] / lib / outputcomponents.php
blob4bd0673dc2b5a5ba1f201ef301fb9c21e5c0b86b
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.
387 // If the currently requested page is https then we'll return an
388 // https gravatar page.
389 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
390 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $defaulturl->out(false)));
391 } else {
392 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $defaulturl->out(false)));
396 return $defaulturl;
401 * Data structure representing a help icon.
403 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
404 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
405 * @since Moodle 2.0
406 * @package core
407 * @category output
409 class old_help_icon implements renderable {
412 * @var string Lang pack identifier
414 public $helpidentifier;
417 * @var string A descriptive text for title tooltip
419 public $title = null;
422 * @var string Component name, the same as in get_string()
424 public $component = 'moodle';
427 * @var string Extra descriptive text next to the icon
429 public $linktext = null;
432 * Constructor: sets up the other components in case they are needed
434 * @param string $helpidentifier The keyword that defines a help page
435 * @param string $title A descriptive text for accessibility only
436 * @param string $component
438 public function __construct($helpidentifier, $title, $component = 'moodle') {
439 if (empty($title)) {
440 throw new coding_exception('A help_icon object requires a $text parameter');
442 if (empty($helpidentifier)) {
443 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
446 $this->helpidentifier = $helpidentifier;
447 $this->title = $title;
448 $this->component = $component;
453 * Data structure representing a help icon.
455 * @copyright 2010 Petr Skoda (info@skodak.org)
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 * @since Moodle 2.0
458 * @package core
459 * @category output
461 class help_icon implements renderable {
464 * @var string lang pack identifier (without the "_help" suffix),
465 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
466 * must exist.
468 public $identifier;
471 * @var string Component name, the same as in get_string()
473 public $component;
476 * @var string Extra descriptive text next to the icon
478 public $linktext = null;
481 * Constructor
483 * @param string $identifier string for help page title,
484 * string with _help suffix is used for the actual help text.
485 * string with _link suffix is used to create a link to further info (if it exists)
486 * @param string $component
488 public function __construct($identifier, $component) {
489 $this->identifier = $identifier;
490 $this->component = $component;
494 * Verifies that both help strings exists, shows debug warnings if not
496 public function diag_strings() {
497 $sm = get_string_manager();
498 if (!$sm->string_exists($this->identifier, $this->component)) {
499 debugging("Help title string does not exist: [$this->identifier, $this->component]");
501 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
502 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
509 * Data structure representing an icon.
511 * @copyright 2010 Petr Skoda
512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
513 * @since Moodle 2.0
514 * @package core
515 * @category output
517 class pix_icon implements renderable {
520 * @var string The icon name
522 var $pix;
525 * @var string The component the icon belongs to.
527 var $component;
530 * @var array An array of attributes to use on the icon
532 var $attributes = array();
535 * Constructor
537 * @param string $pix short icon name
538 * @param string $alt The alt text to use for the icon
539 * @param string $component component name
540 * @param array $attributes html attributes
542 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
543 $this->pix = $pix;
544 $this->component = $component;
545 $this->attributes = (array)$attributes;
547 $this->attributes['alt'] = $alt;
548 if (empty($this->attributes['class'])) {
549 $this->attributes['class'] = 'smallicon';
551 if (!isset($this->attributes['title'])) {
552 $this->attributes['title'] = $this->attributes['alt'];
558 * Data structure representing an emoticon image
560 * @copyright 2010 David Mudrak
561 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
562 * @since Moodle 2.0
563 * @package core
564 * @category output
566 class pix_emoticon extends pix_icon implements renderable {
569 * Constructor
570 * @param string $pix short icon name
571 * @param string $alt alternative text
572 * @param string $component emoticon image provider
573 * @param array $attributes explicit HTML attributes
575 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
576 if (empty($attributes['class'])) {
577 $attributes['class'] = 'emoticon';
579 parent::__construct($pix, $alt, $component, $attributes);
584 * Data structure representing a simple form with only one button.
586 * @copyright 2009 Petr Skoda
587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
588 * @since Moodle 2.0
589 * @package core
590 * @category output
592 class single_button implements renderable {
595 * @var moodle_url Target url
597 var $url;
600 * @var string Button label
602 var $label;
605 * @var string Form submit method post or get
607 var $method = 'post';
610 * @var string Wrapping div class
612 var $class = 'singlebutton';
615 * @var bool True if button disabled, false if normal
617 var $disabled = false;
620 * @var string Button tooltip
622 var $tooltip = null;
625 * @var string Form id
627 var $formid;
630 * @var array List of attached actions
632 var $actions = array();
635 * Constructor
636 * @param moodle_url $url
637 * @param string $label button text
638 * @param string $method get or post submit method
640 public function __construct(moodle_url $url, $label, $method='post') {
641 $this->url = clone($url);
642 $this->label = $label;
643 $this->method = $method;
647 * Shortcut for adding a JS confirm dialog when the button is clicked.
648 * The message must be a yes/no question.
650 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
652 public function add_confirm_action($confirmmessage) {
653 $this->add_action(new confirm_action($confirmmessage));
657 * Add action to the button.
658 * @param component_action $action
660 public function add_action(component_action $action) {
661 $this->actions[] = $action;
667 * Simple form with just one select field that gets submitted automatically.
669 * If JS not enabled small go button is printed too.
671 * @copyright 2009 Petr Skoda
672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
673 * @since Moodle 2.0
674 * @package core
675 * @category output
677 class single_select implements renderable {
680 * @var moodle_url Target url - includes hidden fields
682 var $url;
685 * @var string Name of the select element.
687 var $name;
690 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
691 * it is also possible to specify optgroup as complex label array ex.:
692 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
693 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
695 var $options;
698 * @var string Selected option
700 var $selected;
703 * @var array Nothing selected
705 var $nothing;
708 * @var array Extra select field attributes
710 var $attributes = array();
713 * @var string Button label
715 var $label = '';
718 * @var string Form submit method post or get
720 var $method = 'get';
723 * @var string Wrapping div class
725 var $class = 'singleselect';
728 * @var bool True if button disabled, false if normal
730 var $disabled = false;
733 * @var string Button tooltip
735 var $tooltip = null;
738 * @var string Form id
740 var $formid = null;
743 * @var array List of attached actions
745 var $helpicon = null;
748 * Constructor
749 * @param moodle_url $url form action target, includes hidden fields
750 * @param string $name name of selection field - the changing parameter in url
751 * @param array $options list of options
752 * @param string $selected selected element
753 * @param array $nothing
754 * @param string $formid
756 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
757 $this->url = $url;
758 $this->name = $name;
759 $this->options = $options;
760 $this->selected = $selected;
761 $this->nothing = $nothing;
762 $this->formid = $formid;
766 * Shortcut for adding a JS confirm dialog when the button is clicked.
767 * The message must be a yes/no question.
769 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
771 public function add_confirm_action($confirmmessage) {
772 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
776 * Add action to the button.
778 * @param component_action $action
780 public function add_action(component_action $action) {
781 $this->actions[] = $action;
785 * Adds help icon.
787 * @param string $helppage The keyword that defines a help page
788 * @param string $title A descriptive text for accessibility only
789 * @param string $component
791 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
792 $this->helpicon = new old_help_icon($helppage, $title, $component);
796 * Adds help icon.
798 * @param string $identifier The keyword that defines a help page
799 * @param string $component
801 public function set_help_icon($identifier, $component = 'moodle') {
802 $this->helpicon = new help_icon($identifier, $component);
806 * Sets select's label
808 * @param string $label
810 public function set_label($label) {
811 $this->label = $label;
816 * Simple URL selection widget description.
818 * @copyright 2009 Petr Skoda
819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
820 * @since Moodle 2.0
821 * @package core
822 * @category output
824 class url_select implements renderable {
826 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
827 * it is also possible to specify optgroup as complex label array ex.:
828 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
829 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
831 var $urls;
834 * @var string Selected option
836 var $selected;
839 * @var array Nothing selected
841 var $nothing;
844 * @var array Extra select field attributes
846 var $attributes = array();
849 * @var string Button label
851 var $label = '';
854 * @var string Wrapping div class
856 var $class = 'urlselect';
859 * @var bool True if button disabled, false if normal
861 var $disabled = false;
864 * @var string Button tooltip
866 var $tooltip = null;
869 * @var string Form id
871 var $formid = null;
874 * @var array List of attached actions
876 var $helpicon = null;
879 * @var string If set, makes button visible with given name for button
881 var $showbutton = null;
884 * Constructor
885 * @param array $urls list of options
886 * @param string $selected selected element
887 * @param array $nothing
888 * @param string $formid
889 * @param string $showbutton Set to text of button if it should be visible
890 * or null if it should be hidden (hidden version always has text 'go')
892 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
893 $this->urls = $urls;
894 $this->selected = $selected;
895 $this->nothing = $nothing;
896 $this->formid = $formid;
897 $this->showbutton = $showbutton;
901 * Adds help icon.
903 * @param string $helppage The keyword that defines a help page
904 * @param string $title A descriptive text for accessibility only
905 * @param string $component
907 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
908 $this->helpicon = new old_help_icon($helppage, $title, $component);
912 * Adds help icon.
914 * @param string $identifier The keyword that defines a help page
915 * @param string $component
917 public function set_help_icon($identifier, $component = 'moodle') {
918 $this->helpicon = new help_icon($identifier, $component);
922 * Sets select's label
924 * @param string $label
926 public function set_label($label) {
927 $this->label = $label;
932 * Data structure describing html link with special action attached.
934 * @copyright 2010 Petr Skoda
935 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
936 * @since Moodle 2.0
937 * @package core
938 * @category output
940 class action_link implements renderable {
943 * @var moodle_url Href url
945 var $url;
948 * @var string Link text HTML fragment
950 var $text;
953 * @var array HTML attributes
955 var $attributes;
958 * @var array List of actions attached to link
960 var $actions;
963 * Constructor
964 * @param moodle_url $url
965 * @param string $text HTML fragment
966 * @param component_action $action
967 * @param array $attributes associative array of html link attributes + disabled
969 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
970 $this->url = clone($url);
971 $this->text = $text;
972 $this->attributes = (array)$attributes;
973 if ($action) {
974 $this->add_action($action);
979 * Add action to the link.
981 * @param component_action $action
983 public function add_action(component_action $action) {
984 $this->actions[] = $action;
988 * Adds a CSS class to this action link object
989 * @param string $class
991 public function add_class($class) {
992 if (empty($this->attributes['class'])) {
993 $this->attributes['class'] = $class;
994 } else {
995 $this->attributes['class'] .= ' ' . $class;
1001 * Simple html output class
1003 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1005 * @since Moodle 2.0
1006 * @package core
1007 * @category output
1009 class html_writer {
1012 * Outputs a tag with attributes and contents
1014 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1015 * @param string $contents What goes between the opening and closing tags
1016 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1017 * @return string HTML fragment
1019 public static function tag($tagname, $contents, array $attributes = null) {
1020 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1024 * Outputs an opening tag with attributes
1026 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1027 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1028 * @return string HTML fragment
1030 public static function start_tag($tagname, array $attributes = null) {
1031 return '<' . $tagname . self::attributes($attributes) . '>';
1035 * Outputs a closing tag
1037 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1038 * @return string HTML fragment
1040 public static function end_tag($tagname) {
1041 return '</' . $tagname . '>';
1045 * Outputs an empty tag with attributes
1047 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1048 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1049 * @return string HTML fragment
1051 public static function empty_tag($tagname, array $attributes = null) {
1052 return '<' . $tagname . self::attributes($attributes) . ' />';
1056 * Outputs a tag, but only if the contents are not empty
1058 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1059 * @param string $contents What goes between the opening and closing tags
1060 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1061 * @return string HTML fragment
1063 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1064 if ($contents === '' || is_null($contents)) {
1065 return '';
1067 return self::tag($tagname, $contents, $attributes);
1071 * Outputs a HTML attribute and value
1073 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1074 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1075 * @return string HTML fragment
1077 public static function attribute($name, $value) {
1078 if (is_array($value)) {
1079 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
1081 if ($value instanceof moodle_url) {
1082 return ' ' . $name . '="' . $value->out() . '"';
1085 // special case, we do not want these in output
1086 if ($value === null) {
1087 return '';
1090 // no sloppy trimming here!
1091 return ' ' . $name . '="' . s($value) . '"';
1095 * Outputs a list of HTML attributes and values
1097 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1098 * The values will be escaped with {@link s()}
1099 * @return string HTML fragment
1101 public static function attributes(array $attributes = null) {
1102 $attributes = (array)$attributes;
1103 $output = '';
1104 foreach ($attributes as $name => $value) {
1105 $output .= self::attribute($name, $value);
1107 return $output;
1111 * Generates random html element id.
1113 * @staticvar int $counter
1114 * @staticvar type $uniq
1115 * @param string $base A string fragment that will be included in the random ID.
1116 * @return string A unique ID
1118 public static function random_id($base='random') {
1119 static $counter = 0;
1120 static $uniq;
1122 if (!isset($uniq)) {
1123 $uniq = uniqid();
1126 $counter++;
1127 return $base.$uniq.$counter;
1131 * Generates a simple html link
1133 * @param string|moodle_url $url The URL
1134 * @param string $text The text
1135 * @param array $attributes HTML attributes
1136 * @return string HTML fragment
1138 public static function link($url, $text, array $attributes = null) {
1139 $attributes = (array)$attributes;
1140 $attributes['href'] = $url;
1141 return self::tag('a', $text, $attributes);
1145 * Generates a simple checkbox with optional label
1147 * @param string $name The name of the checkbox
1148 * @param string $value The value of the checkbox
1149 * @param bool $checked Whether the checkbox is checked
1150 * @param string $label The label for the checkbox
1151 * @param array $attributes Any attributes to apply to the checkbox
1152 * @return string html fragment
1154 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1155 $attributes = (array)$attributes;
1156 $output = '';
1158 if ($label !== '' and !is_null($label)) {
1159 if (empty($attributes['id'])) {
1160 $attributes['id'] = self::random_id('checkbox_');
1163 $attributes['type'] = 'checkbox';
1164 $attributes['value'] = $value;
1165 $attributes['name'] = $name;
1166 $attributes['checked'] = $checked ? 'checked' : null;
1168 $output .= self::empty_tag('input', $attributes);
1170 if ($label !== '' and !is_null($label)) {
1171 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1174 return $output;
1178 * Generates a simple select yes/no form field
1180 * @param string $name name of select element
1181 * @param bool $selected
1182 * @param array $attributes - html select element attributes
1183 * @return string HTML fragment
1185 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1186 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1187 return self::select($options, $name, $selected, null, $attributes);
1191 * Generates a simple select form field
1193 * @param array $options associative array value=>label ex.:
1194 * array(1=>'One, 2=>Two)
1195 * it is also possible to specify optgroup as complex label array ex.:
1196 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1197 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1198 * @param string $name name of select element
1199 * @param string|array $selected value or array of values depending on multiple attribute
1200 * @param array|bool $nothing add nothing selected option, or false of not added
1201 * @param array $attributes html select element attributes
1202 * @return string HTML fragment
1204 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1205 $attributes = (array)$attributes;
1206 if (is_array($nothing)) {
1207 foreach ($nothing as $k=>$v) {
1208 if ($v === 'choose' or $v === 'choosedots') {
1209 $nothing[$k] = get_string('choosedots');
1212 $options = $nothing + $options; // keep keys, do not override
1214 } else if (is_string($nothing) and $nothing !== '') {
1215 // BC
1216 $options = array(''=>$nothing) + $options;
1219 // we may accept more values if multiple attribute specified
1220 $selected = (array)$selected;
1221 foreach ($selected as $k=>$v) {
1222 $selected[$k] = (string)$v;
1225 if (!isset($attributes['id'])) {
1226 $id = 'menu'.$name;
1227 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1228 $id = str_replace('[', '', $id);
1229 $id = str_replace(']', '', $id);
1230 $attributes['id'] = $id;
1233 if (!isset($attributes['class'])) {
1234 $class = 'menu'.$name;
1235 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1236 $class = str_replace('[', '', $class);
1237 $class = str_replace(']', '', $class);
1238 $attributes['class'] = $class;
1240 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1242 $attributes['name'] = $name;
1244 if (!empty($attributes['disabled'])) {
1245 $attributes['disabled'] = 'disabled';
1246 } else {
1247 unset($attributes['disabled']);
1250 $output = '';
1251 foreach ($options as $value=>$label) {
1252 if (is_array($label)) {
1253 // ignore key, it just has to be unique
1254 $output .= self::select_optgroup(key($label), current($label), $selected);
1255 } else {
1256 $output .= self::select_option($label, $value, $selected);
1259 return self::tag('select', $output, $attributes);
1263 * Returns HTML to display a select box option.
1265 * @param string $label The label to display as the option.
1266 * @param string|int $value The value the option represents
1267 * @param array $selected An array of selected options
1268 * @return string HTML fragment
1270 private static function select_option($label, $value, array $selected) {
1271 $attributes = array();
1272 $value = (string)$value;
1273 if (in_array($value, $selected, true)) {
1274 $attributes['selected'] = 'selected';
1276 $attributes['value'] = $value;
1277 return self::tag('option', $label, $attributes);
1281 * Returns HTML to display a select box option group.
1283 * @param string $groupname The label to use for the group
1284 * @param array $options The options in the group
1285 * @param array $selected An array of selected values.
1286 * @return string HTML fragment.
1288 private static function select_optgroup($groupname, $options, array $selected) {
1289 if (empty($options)) {
1290 return '';
1292 $attributes = array('label'=>$groupname);
1293 $output = '';
1294 foreach ($options as $value=>$label) {
1295 $output .= self::select_option($label, $value, $selected);
1297 return self::tag('optgroup', $output, $attributes);
1301 * This is a shortcut for making an hour selector menu.
1303 * @param string $type The type of selector (years, months, days, hours, minutes)
1304 * @param string $name fieldname
1305 * @param int $currenttime A default timestamp in GMT
1306 * @param int $step minute spacing
1307 * @param array $attributes - html select element attributes
1308 * @return HTML fragment
1310 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1311 if (!$currenttime) {
1312 $currenttime = time();
1314 $currentdate = usergetdate($currenttime);
1315 $userdatetype = $type;
1316 $timeunits = array();
1318 switch ($type) {
1319 case 'years':
1320 for ($i=1970; $i<=2020; $i++) {
1321 $timeunits[$i] = $i;
1323 $userdatetype = 'year';
1324 break;
1325 case 'months':
1326 for ($i=1; $i<=12; $i++) {
1327 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1329 $userdatetype = 'month';
1330 $currentdate['month'] = (int)$currentdate['mon'];
1331 break;
1332 case 'days':
1333 for ($i=1; $i<=31; $i++) {
1334 $timeunits[$i] = $i;
1336 $userdatetype = 'mday';
1337 break;
1338 case 'hours':
1339 for ($i=0; $i<=23; $i++) {
1340 $timeunits[$i] = sprintf("%02d",$i);
1342 break;
1343 case 'minutes':
1344 if ($step != 1) {
1345 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1348 for ($i=0; $i<=59; $i+=$step) {
1349 $timeunits[$i] = sprintf("%02d",$i);
1351 break;
1352 default:
1353 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1356 if (empty($attributes['id'])) {
1357 $attributes['id'] = self::random_id('ts_');
1359 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1360 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1362 return $label.$timerselector;
1366 * Shortcut for quick making of lists
1368 * Note: 'list' is a reserved keyword ;-)
1370 * @param array $items
1371 * @param array $attributes
1372 * @param string $tag ul or ol
1373 * @return string
1375 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1376 $output = '';
1378 foreach ($items as $item) {
1379 $output .= html_writer::start_tag('li') . "\n";
1380 $output .= $item . "\n";
1381 $output .= html_writer::end_tag('li') . "\n";
1384 return html_writer::tag($tag, $output, $attributes);
1388 * Returns hidden input fields created from url parameters.
1390 * @param moodle_url $url
1391 * @param array $exclude list of excluded parameters
1392 * @return string HTML fragment
1394 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1395 $exclude = (array)$exclude;
1396 $params = $url->params();
1397 foreach ($exclude as $key) {
1398 unset($params[$key]);
1401 $output = '';
1402 foreach ($params as $key => $value) {
1403 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1404 $output .= self::empty_tag('input', $attributes)."\n";
1406 return $output;
1410 * Generate a script tag containing the the specified code.
1412 * @param string $jscode the JavaScript code
1413 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1414 * @return string HTML, the code wrapped in <script> tags.
1416 public static function script($jscode, $url=null) {
1417 if ($jscode) {
1418 $attributes = array('type'=>'text/javascript');
1419 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1421 } else if ($url) {
1422 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1423 return self::tag('script', '', $attributes) . "\n";
1425 } else {
1426 return '';
1431 * Renders HTML table
1433 * This method may modify the passed instance by adding some default properties if they are not set yet.
1434 * If this is not what you want, you should make a full clone of your data before passing them to this
1435 * method. In most cases this is not an issue at all so we do not clone by default for performance
1436 * and memory consumption reasons.
1438 * @param html_table $table data to be rendered
1439 * @return string HTML code
1441 public static function table(html_table $table) {
1442 // prepare table data and populate missing properties with reasonable defaults
1443 if (!empty($table->align)) {
1444 foreach ($table->align as $key => $aa) {
1445 if ($aa) {
1446 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1447 } else {
1448 $table->align[$key] = null;
1452 if (!empty($table->size)) {
1453 foreach ($table->size as $key => $ss) {
1454 if ($ss) {
1455 $table->size[$key] = 'width:'. $ss .';';
1456 } else {
1457 $table->size[$key] = null;
1461 if (!empty($table->wrap)) {
1462 foreach ($table->wrap as $key => $ww) {
1463 if ($ww) {
1464 $table->wrap[$key] = 'white-space:nowrap;';
1465 } else {
1466 $table->wrap[$key] = '';
1470 if (!empty($table->head)) {
1471 foreach ($table->head as $key => $val) {
1472 if (!isset($table->align[$key])) {
1473 $table->align[$key] = null;
1475 if (!isset($table->size[$key])) {
1476 $table->size[$key] = null;
1478 if (!isset($table->wrap[$key])) {
1479 $table->wrap[$key] = null;
1484 if (empty($table->attributes['class'])) {
1485 $table->attributes['class'] = 'generaltable';
1487 if (!empty($table->tablealign)) {
1488 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1491 // explicitly assigned properties override those defined via $table->attributes
1492 $table->attributes['class'] = trim($table->attributes['class']);
1493 $attributes = array_merge($table->attributes, array(
1494 'id' => $table->id,
1495 'width' => $table->width,
1496 'summary' => $table->summary,
1497 'cellpadding' => $table->cellpadding,
1498 'cellspacing' => $table->cellspacing,
1500 $output = html_writer::start_tag('table', $attributes) . "\n";
1502 $countcols = 0;
1504 if (!empty($table->head)) {
1505 $countcols = count($table->head);
1507 $output .= html_writer::start_tag('thead', array()) . "\n";
1508 $output .= html_writer::start_tag('tr', array()) . "\n";
1509 $keys = array_keys($table->head);
1510 $lastkey = end($keys);
1512 foreach ($table->head as $key => $heading) {
1513 // Convert plain string headings into html_table_cell objects
1514 if (!($heading instanceof html_table_cell)) {
1515 $headingtext = $heading;
1516 $heading = new html_table_cell();
1517 $heading->text = $headingtext;
1518 $heading->header = true;
1521 if ($heading->header !== false) {
1522 $heading->header = true;
1525 if ($heading->header && empty($heading->scope)) {
1526 $heading->scope = 'col';
1529 $heading->attributes['class'] .= ' header c' . $key;
1530 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1531 $heading->colspan = $table->headspan[$key];
1532 $countcols += $table->headspan[$key] - 1;
1535 if ($key == $lastkey) {
1536 $heading->attributes['class'] .= ' lastcol';
1538 if (isset($table->colclasses[$key])) {
1539 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1541 $heading->attributes['class'] = trim($heading->attributes['class']);
1542 $attributes = array_merge($heading->attributes, array(
1543 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1544 'scope' => $heading->scope,
1545 'colspan' => $heading->colspan,
1548 $tagtype = 'td';
1549 if ($heading->header === true) {
1550 $tagtype = 'th';
1552 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1554 $output .= html_writer::end_tag('tr') . "\n";
1555 $output .= html_writer::end_tag('thead') . "\n";
1557 if (empty($table->data)) {
1558 // For valid XHTML strict every table must contain either a valid tr
1559 // or a valid tbody... both of which must contain a valid td
1560 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1561 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1562 $output .= html_writer::end_tag('tbody');
1566 if (!empty($table->data)) {
1567 $oddeven = 1;
1568 $keys = array_keys($table->data);
1569 $lastrowkey = end($keys);
1570 $output .= html_writer::start_tag('tbody', array());
1572 foreach ($table->data as $key => $row) {
1573 if (($row === 'hr') && ($countcols)) {
1574 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1575 } else {
1576 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1577 if (!($row instanceof html_table_row)) {
1578 $newrow = new html_table_row();
1580 foreach ($row as $item) {
1581 $cell = new html_table_cell();
1582 $cell->text = $item;
1583 $newrow->cells[] = $cell;
1585 $row = $newrow;
1588 $oddeven = $oddeven ? 0 : 1;
1589 if (isset($table->rowclasses[$key])) {
1590 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1593 $row->attributes['class'] .= ' r' . $oddeven;
1594 if ($key == $lastrowkey) {
1595 $row->attributes['class'] .= ' lastrow';
1598 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1599 $keys2 = array_keys($row->cells);
1600 $lastkey = end($keys2);
1602 $gotlastkey = false; //flag for sanity checking
1603 foreach ($row->cells as $key => $cell) {
1604 if ($gotlastkey) {
1605 //This should never happen. Why do we have a cell after the last cell?
1606 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1609 if (!($cell instanceof html_table_cell)) {
1610 $mycell = new html_table_cell();
1611 $mycell->text = $cell;
1612 $cell = $mycell;
1615 if (($cell->header === true) && empty($cell->scope)) {
1616 $cell->scope = 'row';
1619 if (isset($table->colclasses[$key])) {
1620 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1623 $cell->attributes['class'] .= ' cell c' . $key;
1624 if ($key == $lastkey) {
1625 $cell->attributes['class'] .= ' lastcol';
1626 $gotlastkey = true;
1628 $tdstyle = '';
1629 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1630 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1631 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1632 $cell->attributes['class'] = trim($cell->attributes['class']);
1633 $tdattributes = array_merge($cell->attributes, array(
1634 'style' => $tdstyle . $cell->style,
1635 'colspan' => $cell->colspan,
1636 'rowspan' => $cell->rowspan,
1637 'id' => $cell->id,
1638 'abbr' => $cell->abbr,
1639 'scope' => $cell->scope,
1641 $tagtype = 'td';
1642 if ($cell->header === true) {
1643 $tagtype = 'th';
1645 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1648 $output .= html_writer::end_tag('tr') . "\n";
1650 $output .= html_writer::end_tag('tbody') . "\n";
1652 $output .= html_writer::end_tag('table') . "\n";
1654 return $output;
1658 * Renders form element label
1660 * By default, the label is suffixed with a label separator defined in the
1661 * current language pack (colon by default in the English lang pack).
1662 * Adding the colon can be explicitly disabled if needed. Label separators
1663 * are put outside the label tag itself so they are not read by
1664 * screenreaders (accessibility).
1666 * Parameter $for explicitly associates the label with a form control. When
1667 * set, the value of this attribute must be the same as the value of
1668 * the id attribute of the form control in the same document. When null,
1669 * the label being defined is associated with the control inside the label
1670 * element.
1672 * @param string $text content of the label tag
1673 * @param string|null $for id of the element this label is associated with, null for no association
1674 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1675 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1676 * @return string HTML of the label element
1678 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1679 if (!is_null($for)) {
1680 $attributes = array_merge($attributes, array('for' => $for));
1682 $text = trim($text);
1683 $label = self::tag('label', $text, $attributes);
1685 // TODO MDL-12192 $colonize disabled for now yet
1686 // if (!empty($text) and $colonize) {
1687 // // the $text may end with the colon already, though it is bad string definition style
1688 // $colon = get_string('labelsep', 'langconfig');
1689 // if (!empty($colon)) {
1690 // $trimmed = trim($colon);
1691 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1692 // //debugging('The label text should not end with colon or other label separator,
1693 // // please fix the string definition.', DEBUG_DEVELOPER);
1694 // } else {
1695 // $label .= $colon;
1696 // }
1697 // }
1698 // }
1700 return $label;
1705 * Simple javascript output class
1707 * @copyright 2010 Petr Skoda
1708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1709 * @since Moodle 2.0
1710 * @package core
1711 * @category output
1713 class js_writer {
1716 * Returns javascript code calling the function
1718 * @param string $function function name, can be complex like Y.Event.purgeElement
1719 * @param array $arguments parameters
1720 * @param int $delay execution delay in seconds
1721 * @return string JS code fragment
1723 public static function function_call($function, array $arguments = null, $delay=0) {
1724 if ($arguments) {
1725 $arguments = array_map('json_encode', convert_to_array($arguments));
1726 $arguments = implode(', ', $arguments);
1727 } else {
1728 $arguments = '';
1730 $js = "$function($arguments);";
1732 if ($delay) {
1733 $delay = $delay * 1000; // in miliseconds
1734 $js = "setTimeout(function() { $js }, $delay);";
1736 return $js . "\n";
1740 * Special function which adds Y as first argument of function call.
1742 * @param string $function The function to call
1743 * @param array $extraarguments Any arguments to pass to it
1744 * @return string Some JS code
1746 public static function function_call_with_Y($function, array $extraarguments = null) {
1747 if ($extraarguments) {
1748 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1749 $arguments = 'Y, ' . implode(', ', $extraarguments);
1750 } else {
1751 $arguments = 'Y';
1753 return "$function($arguments);\n";
1757 * Returns JavaScript code to initialise a new object
1759 * @param string $var If it is null then no var is assigned the new object.
1760 * @param string $class The class to initialise an object for.
1761 * @param array $arguments An array of args to pass to the init method.
1762 * @param array $requirements Any modules required for this class.
1763 * @param int $delay The delay before initialisation. 0 = no delay.
1764 * @return string Some JS code
1766 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1767 if (is_array($arguments)) {
1768 $arguments = array_map('json_encode', convert_to_array($arguments));
1769 $arguments = implode(', ', $arguments);
1772 if ($var === null) {
1773 $js = "new $class(Y, $arguments);";
1774 } else if (strpos($var, '.')!==false) {
1775 $js = "$var = new $class(Y, $arguments);";
1776 } else {
1777 $js = "var $var = new $class(Y, $arguments);";
1780 if ($delay) {
1781 $delay = $delay * 1000; // in miliseconds
1782 $js = "setTimeout(function() { $js }, $delay);";
1785 if (count($requirements) > 0) {
1786 $requirements = implode("', '", $requirements);
1787 $js = "Y.use('$requirements', function(Y){ $js });";
1789 return $js."\n";
1793 * Returns code setting value to variable
1795 * @param string $name
1796 * @param mixed $value json serialised value
1797 * @param bool $usevar add var definition, ignored for nested properties
1798 * @return string JS code fragment
1800 public static function set_variable($name, $value, $usevar = true) {
1801 $output = '';
1803 if ($usevar) {
1804 if (strpos($name, '.')) {
1805 $output .= '';
1806 } else {
1807 $output .= 'var ';
1811 $output .= "$name = ".json_encode($value).";";
1813 return $output;
1817 * Writes event handler attaching code
1819 * @param array|string $selector standard YUI selector for elements, may be
1820 * array or string, element id is in the form "#idvalue"
1821 * @param string $event A valid DOM event (click, mousedown, change etc.)
1822 * @param string $function The name of the function to call
1823 * @param array $arguments An optional array of argument parameters to pass to the function
1824 * @return string JS code fragment
1826 public static function event_handler($selector, $event, $function, array $arguments = null) {
1827 $selector = json_encode($selector);
1828 $output = "Y.on('$event', $function, $selector, null";
1829 if (!empty($arguments)) {
1830 $output .= ', ' . json_encode($arguments);
1832 return $output . ");\n";
1837 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1839 * Example of usage:
1840 * $t = new html_table();
1841 * ... // set various properties of the object $t as described below
1842 * echo html_writer::table($t);
1844 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1845 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1846 * @since Moodle 2.0
1847 * @package core
1848 * @category output
1850 class html_table {
1853 * @var string Value to use for the id attribute of the table
1855 public $id = null;
1858 * @var array Attributes of HTML attributes for the <table> element
1860 public $attributes = array();
1863 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1864 * For more control over the rendering of the headers, an array of html_table_cell objects
1865 * can be passed instead of an array of strings.
1867 * Example of usage:
1868 * $t->head = array('Student', 'Grade');
1870 public $head;
1873 * @var array An array that can be used to make a heading span multiple columns.
1874 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1875 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1877 * Example of usage:
1878 * $t->headspan = array(2,1);
1880 public $headspan;
1883 * @var array An array of column alignments.
1884 * The value is used as CSS 'text-align' property. Therefore, possible
1885 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1886 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1888 * Examples of usage:
1889 * $t->align = array(null, 'right');
1890 * or
1891 * $t->align[1] = 'right';
1893 public $align;
1896 * @var array The value is used as CSS 'size' property.
1898 * Examples of usage:
1899 * $t->size = array('50%', '50%');
1900 * or
1901 * $t->size[1] = '120px';
1903 public $size;
1906 * @var array An array of wrapping information.
1907 * The only possible value is 'nowrap' that sets the
1908 * CSS property 'white-space' to the value 'nowrap' in the given column.
1910 * Example of usage:
1911 * $t->wrap = array(null, 'nowrap');
1913 public $wrap;
1916 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1917 * $head specified, the string 'hr' (for horizontal ruler) can be used
1918 * instead of an array of cells data resulting in a divider rendered.
1920 * Example of usage with array of arrays:
1921 * $row1 = array('Harry Potter', '76 %');
1922 * $row2 = array('Hermione Granger', '100 %');
1923 * $t->data = array($row1, $row2);
1925 * Example with array of html_table_row objects: (used for more fine-grained control)
1926 * $cell1 = new html_table_cell();
1927 * $cell1->text = 'Harry Potter';
1928 * $cell1->colspan = 2;
1929 * $row1 = new html_table_row();
1930 * $row1->cells[] = $cell1;
1931 * $cell2 = new html_table_cell();
1932 * $cell2->text = 'Hermione Granger';
1933 * $cell3 = new html_table_cell();
1934 * $cell3->text = '100 %';
1935 * $row2 = new html_table_row();
1936 * $row2->cells = array($cell2, $cell3);
1937 * $t->data = array($row1, $row2);
1939 public $data;
1942 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1943 * @var string Width of the table, percentage of the page preferred.
1945 public $width = null;
1948 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1949 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
1951 public $tablealign = null;
1954 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1955 * @var int Padding on each cell, in pixels
1957 public $cellpadding = null;
1960 * @var int Spacing between cells, in pixels
1961 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1963 public $cellspacing = null;
1966 * @var array Array of classes to add to particular rows, space-separated string.
1967 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1968 * respectively. Class 'lastrow' is added automatically for the last row
1969 * in the table.
1971 * Example of usage:
1972 * $t->rowclasses[9] = 'tenth'
1974 public $rowclasses;
1977 * @var array An array of classes to add to every cell in a particular column,
1978 * space-separated string. Class 'cell' is added automatically by the renderer.
1979 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1980 * respectively. Class 'lastcol' is added automatically for all last cells
1981 * in a row.
1983 * Example of usage:
1984 * $t->colclasses = array(null, 'grade');
1986 public $colclasses;
1989 * @var string Description of the contents for screen readers.
1991 public $summary;
1994 * Constructor
1996 public function __construct() {
1997 $this->attributes['class'] = '';
2002 * Component representing a table row.
2004 * @copyright 2009 Nicolas Connault
2005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2006 * @since Moodle 2.0
2007 * @package core
2008 * @category output
2010 class html_table_row {
2013 * @var string Value to use for the id attribute of the row.
2015 public $id = null;
2018 * @var array Array of html_table_cell objects
2020 public $cells = array();
2023 * @var string Value to use for the style attribute of the table row
2025 public $style = null;
2028 * @var array Attributes of additional HTML attributes for the <tr> element
2030 public $attributes = array();
2033 * Constructor
2034 * @param array $cells
2036 public function __construct(array $cells=null) {
2037 $this->attributes['class'] = '';
2038 $cells = (array)$cells;
2039 foreach ($cells as $cell) {
2040 if ($cell instanceof html_table_cell) {
2041 $this->cells[] = $cell;
2042 } else {
2043 $this->cells[] = new html_table_cell($cell);
2050 * Component representing a table cell.
2052 * @copyright 2009 Nicolas Connault
2053 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2054 * @since Moodle 2.0
2055 * @package core
2056 * @category output
2058 class html_table_cell {
2061 * @var string Value to use for the id attribute of the cell.
2063 public $id = null;
2066 * @var string The contents of the cell.
2068 public $text;
2071 * @var string Abbreviated version of the contents of the cell.
2073 public $abbr = null;
2076 * @var int Number of columns this cell should span.
2078 public $colspan = null;
2081 * @var int Number of rows this cell should span.
2083 public $rowspan = null;
2086 * @var string Defines a way to associate header cells and data cells in a table.
2088 public $scope = null;
2091 * @var bool Whether or not this cell is a header cell.
2093 public $header = null;
2096 * @var string Value to use for the style attribute of the table cell
2098 public $style = null;
2101 * @var array Attributes of additional HTML attributes for the <td> element
2103 public $attributes = array();
2106 * Constructs a table cell
2108 * @param string $text
2110 public function __construct($text = null) {
2111 $this->text = $text;
2112 $this->attributes['class'] = '';
2117 * Component representing a paging bar.
2119 * @copyright 2009 Nicolas Connault
2120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2121 * @since Moodle 2.0
2122 * @package core
2123 * @category output
2125 class paging_bar implements renderable {
2128 * @var int The maximum number of pagelinks to display.
2130 public $maxdisplay = 18;
2133 * @var int The total number of entries to be pages through..
2135 public $totalcount;
2138 * @var int The page you are currently viewing.
2140 public $page;
2143 * @var int The number of entries that should be shown per page.
2145 public $perpage;
2148 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2149 * an equals sign and the page number.
2150 * If this is a moodle_url object then the pagevar param will be replaced by
2151 * the page no, for each page.
2153 public $baseurl;
2156 * @var string This is the variable name that you use for the pagenumber in your
2157 * code (ie. 'tablepage', 'blogpage', etc)
2159 public $pagevar;
2162 * @var string A HTML link representing the "previous" page.
2164 public $previouslink = null;
2167 * @var string A HTML link representing the "next" page.
2169 public $nextlink = null;
2172 * @var string A HTML link representing the first page.
2174 public $firstlink = null;
2177 * @var string A HTML link representing the last page.
2179 public $lastlink = null;
2182 * @var array An array of strings. One of them is just a string: the current page
2184 public $pagelinks = array();
2187 * Constructor paging_bar with only the required params.
2189 * @param int $totalcount The total number of entries available to be paged through
2190 * @param int $page The page you are currently viewing
2191 * @param int $perpage The number of entries that should be shown per page
2192 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2193 * @param string $pagevar name of page parameter that holds the page number
2195 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2196 $this->totalcount = $totalcount;
2197 $this->page = $page;
2198 $this->perpage = $perpage;
2199 $this->baseurl = $baseurl;
2200 $this->pagevar = $pagevar;
2204 * Prepares the paging bar for output.
2206 * This method validates the arguments set up for the paging bar and then
2207 * produces fragments of HTML to assist display later on.
2209 * @param renderer_base $output
2210 * @param moodle_page $page
2211 * @param string $target
2212 * @throws coding_exception
2214 public function prepare(renderer_base $output, moodle_page $page, $target) {
2215 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2216 throw new coding_exception('paging_bar requires a totalcount value.');
2218 if (!isset($this->page) || is_null($this->page)) {
2219 throw new coding_exception('paging_bar requires a page value.');
2221 if (empty($this->perpage)) {
2222 throw new coding_exception('paging_bar requires a perpage value.');
2224 if (empty($this->baseurl)) {
2225 throw new coding_exception('paging_bar requires a baseurl value.');
2228 if ($this->totalcount > $this->perpage) {
2229 $pagenum = $this->page - 1;
2231 if ($this->page > 0) {
2232 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2235 if ($this->perpage > 0) {
2236 $lastpage = ceil($this->totalcount / $this->perpage);
2237 } else {
2238 $lastpage = 1;
2241 if ($this->page > 15) {
2242 $startpage = $this->page - 10;
2244 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2245 } else {
2246 $startpage = 0;
2249 $currpage = $startpage;
2250 $displaycount = $displaypage = 0;
2252 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2253 $displaypage = $currpage + 1;
2255 if ($this->page == $currpage) {
2256 $this->pagelinks[] = $displaypage;
2257 } else {
2258 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2259 $this->pagelinks[] = $pagelink;
2262 $displaycount++;
2263 $currpage++;
2266 if ($currpage < $lastpage) {
2267 $lastpageactual = $lastpage - 1;
2268 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2271 $pagenum = $this->page + 1;
2273 if ($pagenum != $displaypage) {
2274 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2281 * This class represents how a block appears on a page.
2283 * During output, each block instance is asked to return a block_contents object,
2284 * those are then passed to the $OUTPUT->block function for display.
2286 * contents should probably be generated using a moodle_block_..._renderer.
2288 * Other block-like things that need to appear on the page, for example the
2289 * add new block UI, are also represented as block_contents objects.
2291 * @copyright 2009 Tim Hunt
2292 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2293 * @since Moodle 2.0
2294 * @package core
2295 * @category output
2297 class block_contents {
2299 /** Used when the block cannot be collapsed **/
2300 const NOT_HIDEABLE = 0;
2302 /** Used when the block can be collapsed but currently is not **/
2303 const VISIBLE = 1;
2305 /** Used when the block has been collapsed **/
2306 const HIDDEN = 2;
2309 * @var int Used to set $skipid.
2311 protected static $idcounter = 1;
2314 * @var int All the blocks (or things that look like blocks) printed on
2315 * a page are given a unique number that can be used to construct id="" attributes.
2316 * This is set automatically be the {@link prepare()} method.
2317 * Do not try to set it manually.
2319 public $skipid;
2322 * @var int If this is the contents of a real block, this should be set
2323 * to the block_instance.id. Otherwise this should be set to 0.
2325 public $blockinstanceid = 0;
2328 * @var int If this is a real block instance, and there is a corresponding
2329 * block_position.id for the block on this page, this should be set to that id.
2330 * Otherwise it should be 0.
2332 public $blockpositionid = 0;
2335 * @var array An array of attribute => value pairs that are put on the outer div of this
2336 * block. {@link $id} and {@link $classes} attributes should be set separately.
2338 public $attributes;
2341 * @var string The title of this block. If this came from user input, it should already
2342 * have had format_string() processing done on it. This will be output inside
2343 * <h2> tags. Please do not cause invalid XHTML.
2345 public $title = '';
2348 * @var string HTML for the content
2350 public $content = '';
2353 * @var array An alternative to $content, it you want a list of things with optional icons.
2355 public $footer = '';
2358 * @var string Any small print that should appear under the block to explain
2359 * to the teacher about the block, for example 'This is a sticky block that was
2360 * added in the system context.'
2362 public $annotation = '';
2365 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2366 * the user can toggle whether this block is visible.
2368 public $collapsible = self::NOT_HIDEABLE;
2371 * @var array A (possibly empty) array of editing controls. Each element of
2372 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2373 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2375 public $controls = array();
2379 * Create new instance of block content
2380 * @param array $attributes
2382 public function __construct(array $attributes = null) {
2383 $this->skipid = self::$idcounter;
2384 self::$idcounter += 1;
2386 if ($attributes) {
2387 // standard block
2388 $this->attributes = $attributes;
2389 } else {
2390 // simple "fake" blocks used in some modules and "Add new block" block
2391 $this->attributes = array('class'=>'block');
2396 * Add html class to block
2398 * @param string $class
2400 public function add_class($class) {
2401 $this->attributes['class'] .= ' '.$class;
2407 * This class represents a target for where a block can go when it is being moved.
2409 * This needs to be rendered as a form with the given hidden from fields, and
2410 * clicking anywhere in the form should submit it. The form action should be
2411 * $PAGE->url.
2413 * @copyright 2009 Tim Hunt
2414 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2415 * @since Moodle 2.0
2416 * @package core
2417 * @category output
2419 class block_move_target {
2422 * @var moodle_url Move url
2424 public $url;
2427 * @var string label
2429 public $text;
2432 * Constructor
2433 * @param string $text
2434 * @param moodle_url $url
2436 public function __construct($text, moodle_url $url) {
2437 $this->text = $text;
2438 $this->url = $url;
2443 * Custom menu item
2445 * This class is used to represent one item within a custom menu that may or may
2446 * not have children.
2448 * @copyright 2010 Sam Hemelryk
2449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2450 * @since Moodle 2.0
2451 * @package core
2452 * @category output
2454 class custom_menu_item implements renderable {
2457 * @var string The text to show for the item
2459 protected $text;
2462 * @var moodle_url The link to give the icon if it has no children
2464 protected $url;
2467 * @var string A title to apply to the item. By default the text
2469 protected $title;
2472 * @var int A sort order for the item, not necessary if you order things in
2473 * the CFG var.
2475 protected $sort;
2478 * @var custom_menu_item A reference to the parent for this item or NULL if
2479 * it is a top level item
2481 protected $parent;
2484 * @var array A array in which to store children this item has.
2486 protected $children = array();
2489 * @var int A reference to the sort var of the last child that was added
2491 protected $lastsort = 0;
2494 * Constructs the new custom menu item
2496 * @param string $text
2497 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2498 * @param string $title A title to apply to this item [Optional]
2499 * @param int $sort A sort or to use if we need to sort differently [Optional]
2500 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2501 * belongs to, only if the child has a parent. [Optional]
2503 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2504 $this->text = $text;
2505 $this->url = $url;
2506 $this->title = $title;
2507 $this->sort = (int)$sort;
2508 $this->parent = $parent;
2512 * Adds a custom menu item as a child of this node given its properties.
2514 * @param string $text
2515 * @param moodle_url $url
2516 * @param string $title
2517 * @param int $sort
2518 * @return custom_menu_item
2520 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2521 $key = count($this->children);
2522 if (empty($sort)) {
2523 $sort = $this->lastsort + 1;
2525 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2526 $this->lastsort = (int)$sort;
2527 return $this->children[$key];
2531 * Returns the text for this item
2532 * @return string
2534 public function get_text() {
2535 return $this->text;
2539 * Returns the url for this item
2540 * @return moodle_url
2542 public function get_url() {
2543 return $this->url;
2547 * Returns the title for this item
2548 * @return string
2550 public function get_title() {
2551 return $this->title;
2555 * Sorts and returns the children for this item
2556 * @return array
2558 public function get_children() {
2559 $this->sort();
2560 return $this->children;
2564 * Gets the sort order for this child
2565 * @return int
2567 public function get_sort_order() {
2568 return $this->sort;
2572 * Gets the parent this child belong to
2573 * @return custom_menu_item
2575 public function get_parent() {
2576 return $this->parent;
2580 * Sorts the children this item has
2582 public function sort() {
2583 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2587 * Returns true if this item has any children
2588 * @return bool
2590 public function has_children() {
2591 return (count($this->children) > 0);
2595 * Sets the text for the node
2596 * @param string $text
2598 public function set_text($text) {
2599 $this->text = (string)$text;
2603 * Sets the title for the node
2604 * @param string $title
2606 public function set_title($title) {
2607 $this->title = (string)$title;
2611 * Sets the url for the node
2612 * @param moodle_url $url
2614 public function set_url(moodle_url $url) {
2615 $this->url = $url;
2620 * Custom menu class
2622 * This class is used to operate a custom menu that can be rendered for the page.
2623 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2624 * of custom_menu_item nodes that can be rendered by the core renderer.
2626 * To configure the custom menu:
2627 * Settings: Administration > Appearance > Themes > Theme settings
2629 * @copyright 2010 Sam Hemelryk
2630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2631 * @since Moodle 2.0
2632 * @package core
2633 * @category output
2635 class custom_menu extends custom_menu_item {
2638 * @var string The language we should render for, null disables multilang support.
2640 protected $currentlanguage = null;
2643 * Creates the custom menu
2645 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2646 * @param string $currentlanguage the current language code, null disables multilang support
2648 public function __construct($definition = '', $currentlanguage = null) {
2649 $this->currentlanguage = $currentlanguage;
2650 parent::__construct('root'); // create virtual root element of the menu
2651 if (!empty($definition)) {
2652 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2657 * Overrides the children of this custom menu. Useful when getting children
2658 * from $CFG->custommenuitems
2660 * @param array $children
2662 public function override_children(array $children) {
2663 $this->children = array();
2664 foreach ($children as $child) {
2665 if ($child instanceof custom_menu_item) {
2666 $this->children[] = $child;
2672 * Converts a string into a structured array of custom_menu_items which can
2673 * then be added to a custom menu.
2675 * Structure:
2676 * text|url|title|langs
2677 * The number of hyphens at the start determines the depth of the item. The
2678 * languages are optional, comma separated list of languages the line is for.
2680 * Example structure:
2681 * First level first item|http://www.moodle.com/
2682 * -Second level first item|http://www.moodle.com/partners/
2683 * -Second level second item|http://www.moodle.com/hq/
2684 * --Third level first item|http://www.moodle.com/jobs/
2685 * -Second level third item|http://www.moodle.com/development/
2686 * First level second item|http://www.moodle.com/feedback/
2687 * First level third item
2688 * English only|http://moodle.com|English only item|en
2689 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2692 * @static
2693 * @param string $text the menu items definition
2694 * @param string $language the language code, null disables multilang support
2695 * @return array
2697 public static function convert_text_to_menu_nodes($text, $language = null) {
2698 $lines = explode("\n", $text);
2699 $children = array();
2700 $lastchild = null;
2701 $lastdepth = null;
2702 $lastsort = 0;
2703 foreach ($lines as $line) {
2704 $line = trim($line);
2705 $bits = explode('|', $line, 4); // name|url|title|langs
2706 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2707 // Every item must have a name to be valid
2708 continue;
2709 } else {
2710 $bits[0] = ltrim($bits[0],'-');
2712 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2713 // Set the url to null
2714 $bits[1] = null;
2715 } else {
2716 // Make sure the url is a moodle url
2717 $bits[1] = new moodle_url(trim($bits[1]));
2719 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2720 // Set the title to null seeing as there isn't one
2721 $bits[2] = $bits[0];
2723 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2724 // The item is valid for all languages
2725 $itemlangs = null;
2726 } else {
2727 $itemlangs = array_map('trim', explode(',', $bits[3]));
2729 if (!empty($language) and !empty($itemlangs)) {
2730 // check that the item is intended for the current language
2731 if (!in_array($language, $itemlangs)) {
2732 continue;
2735 // Set an incremental sort order to keep it simple.
2736 $lastsort++;
2737 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2738 $depth = strlen($match[1]);
2739 if ($depth < $lastdepth) {
2740 $difference = $lastdepth - $depth;
2741 if ($lastdepth > 1 && $lastdepth != $difference) {
2742 $tempchild = $lastchild->get_parent();
2743 for ($i =0; $i < $difference; $i++) {
2744 $tempchild = $tempchild->get_parent();
2746 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2747 } else {
2748 $depth = 0;
2749 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2750 $children[] = $lastchild;
2752 } else if ($depth > $lastdepth) {
2753 $depth = $lastdepth + 1;
2754 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2755 } else {
2756 if ($depth == 0) {
2757 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2758 $children[] = $lastchild;
2759 } else {
2760 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2763 } else {
2764 $depth = 0;
2765 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2766 $children[] = $lastchild;
2768 $lastdepth = $depth;
2770 return $children;
2774 * Sorts two custom menu items
2776 * This function is designed to be used with the usort method
2777 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2779 * @static
2780 * @param custom_menu_item $itema
2781 * @param custom_menu_item $itemb
2782 * @return int
2784 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2785 $itema = $itema->get_sort_order();
2786 $itemb = $itemb->get_sort_order();
2787 if ($itema == $itemb) {
2788 return 0;
2790 return ($itema > $itemb) ? +1 : -1;