Merge branch 'm22_MDL-33053_AICC_flattened_TOC' of git://github.com/scara/moodle...
[moodle.git] / lib / outputcomponents.php
blob337452af0b46699215143080765a48e9a86b9cbe
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Classes representing HTML elements, used by $OUTPUT methods
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
24 * @package core
25 * @subpackage lib
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 /**
33 * Interface marking other classes as suitable for renderer_base::render()
34 * @author 2010 Petr Skoda (skodak) info@skodak.org
36 interface renderable {
37 // intentionally empty
40 /**
41 * Data structure representing a file picker.
43 * @copyright 2010 Dongsheng Cai
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 * @since Moodle 2.0
47 class file_picker implements renderable {
48 public $options;
49 public function __construct(stdClass $options) {
50 global $CFG, $USER, $PAGE;
51 require_once($CFG->dirroot. '/repository/lib.php');
52 $defaults = array(
53 'accepted_types'=>'*',
54 'return_types'=>FILE_INTERNAL,
55 'env' => 'filepicker',
56 'client_id' => uniqid(),
57 'itemid' => 0,
58 'maxbytes'=>-1,
59 'maxfiles'=>1,
60 'buttonname'=>false
62 foreach ($defaults as $key=>$value) {
63 if (empty($options->$key)) {
64 $options->$key = $value;
68 $options->currentfile = '';
69 if (!empty($options->itemid)) {
70 $fs = get_file_storage();
71 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
72 if (empty($options->filename)) {
73 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
74 $file = reset($files);
76 } else {
77 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
79 if (!empty($file)) {
80 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
84 // initilise options, getting files in root path
85 $this->options = initialise_filepicker($options);
87 // copying other options
88 foreach ($options as $name=>$value) {
89 if (!isset($this->options->$name)) {
90 $this->options->$name = $value;
96 /**
97 * Data structure representing a user picture.
99 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
101 * @since Moodle 2.0
103 class user_picture implements renderable {
105 * @var array List of mandatory fields in user record here. (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
107 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email'); //TODO: add deleted
110 * @var object $user A user object with at least fields all columns specified in $fields array constant set.
112 public $user;
114 * @var int $courseid The course id. Used when constructing the link to the user's profile,
115 * page course id used if not specified.
117 public $courseid;
119 * @var bool $link add course profile link to image
121 public $link = true;
123 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
125 public $size = 35;
127 * @var boolean $alttext add non-blank alt-text to the image.
128 * Default true, set to false when image alt just duplicates text in screenreaders.
130 public $alttext = true;
132 * @var boolean $popup Whether or not to open the link in a popup window.
134 public $popup = false;
136 * @var string Image class attribute
138 public $class = 'userpicture';
141 * User picture constructor.
143 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
144 * @param array $options such as link, size, link, ...
146 public function __construct(stdClass $user) {
147 global $DB;
149 if (empty($user->id)) {
150 throw new coding_exception('User id is required when printing user avatar image.');
153 // only touch the DB if we are missing data and complain loudly...
154 $needrec = false;
155 foreach (self::$fields as $field) {
156 if (!array_key_exists($field, $user)) {
157 $needrec = true;
158 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
159 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
160 break;
164 if ($needrec) {
165 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
166 } else {
167 $this->user = clone($user);
172 * Returns a list of required user fields, useful when fetching required user info from db.
174 * In some cases we have to fetch the user data together with some other information,
175 * the idalias is useful there because the id would otherwise override the main
176 * id of the result record. Please note it has to be converted back to id before rendering.
178 * @param string $tableprefix name of database table prefix in query
179 * @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)
180 * @param string $idalias alias of id field
181 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
182 * @return string
184 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
185 if (!$tableprefix and !$extrafields and !$idalias) {
186 return implode(',', self::$fields);
188 if ($tableprefix) {
189 $tableprefix .= '.';
191 $fields = array();
192 foreach (self::$fields as $field) {
193 if ($field === 'id' and $idalias and $idalias !== 'id') {
194 $fields[$field] = "$tableprefix$field AS $idalias";
195 } else {
196 if ($fieldprefix and $field !== 'id') {
197 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
198 } else {
199 $fields[$field] = "$tableprefix$field";
203 // add extra fields if not already there
204 if ($extrafields) {
205 foreach ($extrafields as $e) {
206 if ($e === 'id' or isset($fields[$e])) {
207 continue;
209 if ($fieldprefix) {
210 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
211 } else {
212 $fields[$e] = "$tableprefix$e";
216 return implode(',', $fields);
220 * Extract the aliased user fields from a given record
222 * Given a record that was previously obtained using {@link self::fields()} with aliases,
223 * this method extracts user related unaliased fields.
225 * @param stdClass $record containing user picture fields
226 * @param array $extrafields extra fields included in the $record
227 * @param string $idalias alias of the id field
228 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
229 * @return stdClass object with unaliased user fields
231 public static function unalias(stdClass $record, array $extrafields=null, $idalias='id', $fieldprefix='') {
233 if (empty($idalias)) {
234 $idalias = 'id';
237 $return = new stdClass();
239 foreach (self::$fields as $field) {
240 if ($field === 'id') {
241 if (property_exists($record, $idalias)) {
242 $return->id = $record->{$idalias};
244 } else {
245 if (property_exists($record, $fieldprefix.$field)) {
246 $return->{$field} = $record->{$fieldprefix.$field};
250 // add extra fields if not already there
251 if ($extrafields) {
252 foreach ($extrafields as $e) {
253 if ($e === 'id' or property_exists($return, $e)) {
254 continue;
256 $return->{$e} = $record->{$fieldprefix.$e};
260 return $return;
264 * Works out the URL for the users picture.
266 * This method is recommended as it avoids costly redirects of user pictures
267 * if requests are made for non-existent files etc.
269 * @param renderer_base $renderer
270 * @return moodle_url
272 public function get_url(moodle_page $page, renderer_base $renderer = null) {
273 global $CFG;
275 if (is_null($renderer)) {
276 $renderer = $page->get_renderer('core');
279 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
280 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
281 // protect images if login required and not logged in;
282 // also if login is required for profile images and is not logged in or guest
283 // do not use require_login() because it is expensive and not suitable here anyway
284 return $renderer->pix_url('u/f1');
287 // Sort out the filename and size. Size is only required for the gravatar
288 // implementation presently.
289 if (empty($this->size)) {
290 $filename = 'f2';
291 $size = 35;
292 } else if ($this->size === true or $this->size == 1) {
293 $filename = 'f1';
294 $size = 100;
295 } else if ($this->size >= 50) {
296 $filename = 'f1';
297 $size = (int)$this->size;
298 } else {
299 $filename = 'f2';
300 $size = (int)$this->size;
303 // First we need to determine whether the user has uploaded a profile
304 // picture of not.
305 if (!empty($this->user->deleted) or !$context = context_user::instance($this->user->id, IGNORE_MISSING)) {
306 $hasuploadedfile = false;
307 } else {
308 $fs = get_file_storage();
309 $hasuploadedfile = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg'));
312 $imageurl = $renderer->pix_url('u/'.$filename);
313 if ($hasuploadedfile && $this->user->picture == 1) {
314 $path = '/';
315 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
316 // We append the theme name to the file path if we have it so that
317 // in the circumstance that the profile picture is not available
318 // when the user actually requests it they still get the profile
319 // picture for the correct theme.
320 $path .= $page->theme->name.'/';
322 // Set the image URL to the URL for the uploaded file.
323 $imageurl = moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, $path, $filename);
324 } else if (!empty($CFG->enablegravatar)) {
325 // Normalise the size variable to acceptable bounds
326 if ($size < 1 || $size > 512) {
327 $size = 35;
329 // Hash the users email address
330 $md5 = md5(strtolower(trim($this->user->email)));
331 // Build a gravatar URL with what we know.
332 // If the currently requested page is https then we'll return an
333 // https gravatar page.
334 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
335 $imageurl = new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
336 } else {
337 $imageurl = new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
341 // Return the URL that has been generated.
342 return $imageurl;
347 * Data structure representing a help icon.
349 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
350 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
351 * @since Moodle 2.0
353 class old_help_icon implements renderable {
355 * @var string $helpidentifier lang pack identifier
357 public $helpidentifier;
359 * @var string $title A descriptive text for title tooltip
361 public $title = null;
363 * @var string $component Component name, the same as in get_string()
365 public $component = 'moodle';
367 * @var string $linktext Extra descriptive text next to the icon
369 public $linktext = null;
372 * Constructor: sets up the other components in case they are needed
373 * @param string $helpidentifier The keyword that defines a help page
374 * @param string $title A descriptive text for accessibility only
375 * @param string $component
376 * @param bool $linktext add extra text to icon
377 * @return void
379 public function __construct($helpidentifier, $title, $component = 'moodle') {
380 if (empty($title)) {
381 throw new coding_exception('A help_icon object requires a $text parameter');
383 if (empty($helpidentifier)) {
384 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
387 $this->helpidentifier = $helpidentifier;
388 $this->title = $title;
389 $this->component = $component;
394 * Data structure representing a help icon.
396 * @copyright 2010 Petr Skoda (info@skodak.org)
397 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
398 * @since Moodle 2.0
400 class help_icon implements renderable {
402 * @var string $identifier lang pack identifier (without the "_help" suffix),
403 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
404 * must exist.
406 public $identifier;
408 * @var string $component Component name, the same as in get_string()
410 public $component;
412 * @var string $linktext Extra descriptive text next to the icon
414 public $linktext = null;
417 * Constructor
418 * @param string $identifier string for help page title,
419 * string with _help suffix is used for the actual help text.
420 * string with _link suffix is used to create a link to further info (if it exists)
421 * @param string $component
423 public function __construct($identifier, $component) {
424 $this->identifier = $identifier;
425 $this->component = $component;
429 * Verifies that both help strings exists, shows debug warnings if not
431 public function diag_strings() {
432 $sm = get_string_manager();
433 if (!$sm->string_exists($this->identifier, $this->component)) {
434 debugging("Help title string does not exist: [$this->identifier, $this->component]");
436 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
437 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
444 * Data structure representing an icon.
446 * @copyright 2010 Petr Skoda
447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
448 * @since Moodle 2.0
450 class pix_icon implements renderable {
451 var $pix;
452 var $component;
453 var $attributes = array();
456 * Constructor
457 * @param string $pix short icon name
458 * @param string $alt The alt text to use for the icon
459 * @param string $component component name
460 * @param array $attributes html attributes
462 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
463 $this->pix = $pix;
464 $this->component = $component;
465 $this->attributes = (array)$attributes;
467 $this->attributes['alt'] = $alt;
468 if (empty($this->attributes['class'])) {
469 $this->attributes['class'] = 'smallicon';
471 if (!isset($this->attributes['title'])) {
472 $this->attributes['title'] = $this->attributes['alt'];
478 * Data structure representing an emoticon image
480 * @since Moodle 2.0
482 class pix_emoticon extends pix_icon implements renderable {
485 * Constructor
486 * @param string $pix short icon name
487 * @param string $alt alternative text
488 * @param string $component emoticon image provider
489 * @param array $attributes explicit HTML attributes
491 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
492 if (empty($attributes['class'])) {
493 $attributes['class'] = 'emoticon';
495 parent::__construct($pix, $alt, $component, $attributes);
500 * Data structure representing a simple form with only one button.
502 * @copyright 2009 Petr Skoda
503 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
504 * @since Moodle 2.0
506 class single_button implements renderable {
508 * Target url
509 * @var moodle_url
511 var $url;
513 * Button label
514 * @var string
516 var $label;
518 * Form submit method
519 * @var string post or get
521 var $method = 'post';
523 * Wrapping div class
524 * @var string
525 * */
526 var $class = 'singlebutton';
528 * True if button disabled, false if normal
529 * @var boolean
531 var $disabled = false;
533 * Button tooltip
534 * @var string
536 var $tooltip = null;
538 * Form id
539 * @var string
541 var $formid;
543 * List of attached actions
544 * @var array of component_action
546 var $actions = array();
549 * Constructor
550 * @param string|moodle_url $url
551 * @param string $label button text
552 * @param string $method get or post submit method
554 public function __construct(moodle_url $url, $label, $method='post') {
555 $this->url = clone($url);
556 $this->label = $label;
557 $this->method = $method;
561 * Shortcut for adding a JS confirm dialog when the button is clicked.
562 * The message must be a yes/no question.
563 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
564 * @return void
566 public function add_confirm_action($confirmmessage) {
567 $this->add_action(new confirm_action($confirmmessage));
571 * Add action to the button.
572 * @param component_action $action
573 * @return void
575 public function add_action(component_action $action) {
576 $this->actions[] = $action;
582 * Simple form with just one select field that gets submitted automatically.
583 * If JS not enabled small go button is printed too.
585 * @copyright 2009 Petr Skoda
586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
587 * @since Moodle 2.0
589 class single_select implements renderable {
591 * Target url - includes hidden fields
592 * @var moodle_url
594 var $url;
596 * Name of the select element.
597 * @var string
599 var $name;
601 * @var array $options associative array value=>label ex.:
602 * array(1=>'One, 2=>Two)
603 * it is also possible to specify optgroup as complex label array ex.:
604 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
605 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
607 var $options;
609 * Selected option
610 * @var string
612 var $selected;
614 * Nothing selected
615 * @var array
617 var $nothing;
619 * Extra select field attributes
620 * @var array
622 var $attributes = array();
624 * Button label
625 * @var string
627 var $label = '';
629 * Form submit method
630 * @var string post or get
632 var $method = 'get';
634 * Wrapping div class
635 * @var string
636 * */
637 var $class = 'singleselect';
639 * True if button disabled, false if normal
640 * @var boolean
642 var $disabled = false;
644 * Button tooltip
645 * @var string
647 var $tooltip = null;
649 * Form id
650 * @var string
652 var $formid = null;
654 * List of attached actions
655 * @var array of component_action
657 var $helpicon = null;
659 * Constructor
660 * @param moodle_url $url form action target, includes hidden fields
661 * @param string $name name of selection field - the changing parameter in url
662 * @param array $options list of options
663 * @param string $selected selected element
664 * @param array $nothing
665 * @param string $formid
667 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
668 $this->url = $url;
669 $this->name = $name;
670 $this->options = $options;
671 $this->selected = $selected;
672 $this->nothing = $nothing;
673 $this->formid = $formid;
677 * Shortcut for adding a JS confirm dialog when the button is clicked.
678 * The message must be a yes/no question.
679 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
680 * @return void
682 public function add_confirm_action($confirmmessage) {
683 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
687 * Add action to the button.
688 * @param component_action $action
689 * @return void
691 public function add_action(component_action $action) {
692 $this->actions[] = $action;
696 * Adds help icon.
697 * @param string $page The keyword that defines a help page
698 * @param string $title A descriptive text for accessibility only
699 * @param string $component
700 * @param bool $linktext add extra text to icon
701 * @return void
703 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
704 $this->helpicon = new old_help_icon($helppage, $title, $component);
708 * Adds help icon.
709 * @param string $identifier The keyword that defines a help page
710 * @param string $component
711 * @param bool $linktext add extra text to icon
712 * @return void
714 public function set_help_icon($identifier, $component = 'moodle') {
715 $this->helpicon = new help_icon($identifier, $component);
719 * Sets select's label
720 * @param string $label
721 * @return void
723 public function set_label($label) {
724 $this->label = $label;
730 * Simple URL selection widget description.
731 * @copyright 2009 Petr Skoda
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
733 * @since Moodle 2.0
735 class url_select implements renderable {
737 * @var array $urls associative array value=>label ex.:
738 * array(1=>'One, 2=>Two)
739 * it is also possible to specify optgroup as complex label array ex.:
740 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
741 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
743 var $urls;
745 * Selected option
746 * @var string
748 var $selected;
750 * Nothing selected
751 * @var array
753 var $nothing;
755 * Extra select field attributes
756 * @var array
758 var $attributes = array();
760 * Button label
761 * @var string
763 var $label = '';
765 * Wrapping div class
766 * @var string
767 * */
768 var $class = 'urlselect';
770 * True if button disabled, false if normal
771 * @var boolean
773 var $disabled = false;
775 * Button tooltip
776 * @var string
778 var $tooltip = null;
780 * Form id
781 * @var string
783 var $formid = null;
785 * List of attached actions
786 * @var array of component_action
788 var $helpicon = null;
790 * @var string If set, makes button visible with given name for button
792 var $showbutton = null;
794 * Constructor
795 * @param array $urls list of options
796 * @param string $selected selected element
797 * @param array $nothing
798 * @param string $formid
799 * @param string $showbutton Set to text of button if it should be visible
800 * or null if it should be hidden (hidden version always has text 'go')
802 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
803 $formid=null, $showbutton=null) {
804 $this->urls = $urls;
805 $this->selected = $selected;
806 $this->nothing = $nothing;
807 $this->formid = $formid;
808 $this->showbutton = $showbutton;
812 * Adds help icon.
813 * @param string $page The keyword that defines a help page
814 * @param string $title A descriptive text for accessibility only
815 * @param string $component
816 * @param bool $linktext add extra text to icon
817 * @return void
819 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
820 $this->helpicon = new old_help_icon($helppage, $title, $component);
824 * Adds help icon.
825 * @param string $identifier The keyword that defines a help page
826 * @param string $component
827 * @param bool $linktext add extra text to icon
828 * @return void
830 public function set_help_icon($identifier, $component = 'moodle') {
831 $this->helpicon = new help_icon($identifier, $component);
835 * Sets select's label
836 * @param string $label
837 * @return void
839 public function set_label($label) {
840 $this->label = $label;
846 * Data structure describing html link with special action attached.
847 * @copyright 2010 Petr Skoda
848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
849 * @since Moodle 2.0
851 class action_link implements renderable {
853 * Href url
854 * @var moodle_url
856 var $url;
858 * Link text
859 * @var string HTML fragment
861 var $text;
863 * HTML attributes
864 * @var array
866 var $attributes;
868 * List of actions attached to link
869 * @var array of component_action
871 var $actions;
874 * Constructor
875 * @param string|moodle_url $url
876 * @param string $text HTML fragment
877 * @param component_action $action
878 * @param array $attributes associative array of html link attributes + disabled
880 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
881 $this->url = clone($url);
882 $this->text = $text;
883 $this->attributes = (array)$attributes;
884 if ($action) {
885 $this->add_action($action);
890 * Add action to the link.
891 * @param component_action $action
892 * @return void
894 public function add_action(component_action $action) {
895 $this->actions[] = $action;
898 public function add_class($class) {
899 if (empty($this->attributes['class'])) {
900 $this->attributes['class'] = $class;
901 } else {
902 $this->attributes['class'] .= ' ' . $class;
907 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
910 * Simple html output class
911 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
913 class html_writer {
915 * Outputs a tag with attributes and contents
916 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
917 * @param string $contents What goes between the opening and closing tags
918 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
919 * @return string HTML fragment
921 public static function tag($tagname, $contents, array $attributes = null) {
922 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
926 * Outputs an opening tag with attributes
927 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
928 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
929 * @return string HTML fragment
931 public static function start_tag($tagname, array $attributes = null) {
932 return '<' . $tagname . self::attributes($attributes) . '>';
936 * Outputs a closing tag
937 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
938 * @return string HTML fragment
940 public static function end_tag($tagname) {
941 return '</' . $tagname . '>';
945 * Outputs an empty tag with attributes
946 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
947 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
948 * @return string HTML fragment
950 public static function empty_tag($tagname, array $attributes = null) {
951 return '<' . $tagname . self::attributes($attributes) . ' />';
955 * Outputs a tag, but only if the contents are not empty
956 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
957 * @param string $contents What goes between the opening and closing tags
958 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
959 * @return string HTML fragment
961 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
962 if ($contents === '' || is_null($contents)) {
963 return '';
965 return self::tag($tagname, $contents, $attributes);
969 * Outputs a HTML attribute and value
970 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
971 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
972 * @return string HTML fragment
974 public static function attribute($name, $value) {
975 if (is_array($value)) {
976 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
978 if ($value instanceof moodle_url) {
979 return ' ' . $name . '="' . $value->out() . '"';
982 // special case, we do not want these in output
983 if ($value === null) {
984 return '';
987 // no sloppy trimming here!
988 return ' ' . $name . '="' . s($value) . '"';
992 * Outputs a list of HTML attributes and values
993 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
994 * The values will be escaped with {@link s()}
995 * @return string HTML fragment
997 public static function attributes(array $attributes = null) {
998 $attributes = (array)$attributes;
999 $output = '';
1000 foreach ($attributes as $name => $value) {
1001 $output .= self::attribute($name, $value);
1003 return $output;
1007 * Generates random html element id.
1008 * @param string $base
1009 * @return string
1011 public static function random_id($base='random') {
1012 static $counter = 0;
1013 static $uniq;
1015 if (!isset($uniq)) {
1016 $uniq = uniqid();
1019 $counter++;
1020 return $base.$uniq.$counter;
1024 * Generates a simple html link
1025 * @param string|moodle_url $url
1026 * @param string $text link txt
1027 * @param array $attributes extra html attributes
1028 * @return string HTML fragment
1030 public static function link($url, $text, array $attributes = null) {
1031 $attributes = (array)$attributes;
1032 $attributes['href'] = $url;
1033 return self::tag('a', $text, $attributes);
1037 * generates a simple checkbox with optional label
1038 * @param string $name
1039 * @param string $value
1040 * @param bool $checked
1041 * @param string $label
1042 * @param array $attributes
1043 * @return string html fragment
1045 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1046 $attributes = (array)$attributes;
1047 $output = '';
1049 if ($label !== '' and !is_null($label)) {
1050 if (empty($attributes['id'])) {
1051 $attributes['id'] = self::random_id('checkbox_');
1054 $attributes['type'] = 'checkbox';
1055 $attributes['value'] = $value;
1056 $attributes['name'] = $name;
1057 $attributes['checked'] = $checked ? 'checked' : null;
1059 $output .= self::empty_tag('input', $attributes);
1061 if ($label !== '' and !is_null($label)) {
1062 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1065 return $output;
1069 * Generates a simple select yes/no form field
1070 * @param string $name name of select element
1071 * @param bool $selected
1072 * @param array $attributes - html select element attributes
1073 * @return string HRML fragment
1075 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1076 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1077 return self::select($options, $name, $selected, null, $attributes);
1081 * Generates a simple select form field
1082 * @param array $options associative array value=>label ex.:
1083 * array(1=>'One, 2=>Two)
1084 * it is also possible to specify optgroup as complex label array ex.:
1085 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1086 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1087 * @param string $name name of select element
1088 * @param string|array $selected value or array of values depending on multiple attribute
1089 * @param array|bool $nothing, add nothing selected option, or false of not added
1090 * @param array $attributes - html select element attributes
1091 * @return string HTML fragment
1093 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
1094 $attributes = (array)$attributes;
1095 if (is_array($nothing)) {
1096 foreach ($nothing as $k=>$v) {
1097 if ($v === 'choose' or $v === 'choosedots') {
1098 $nothing[$k] = get_string('choosedots');
1101 $options = $nothing + $options; // keep keys, do not override
1103 } else if (is_string($nothing) and $nothing !== '') {
1104 // BC
1105 $options = array(''=>$nothing) + $options;
1108 // we may accept more values if multiple attribute specified
1109 $selected = (array)$selected;
1110 foreach ($selected as $k=>$v) {
1111 $selected[$k] = (string)$v;
1114 if (!isset($attributes['id'])) {
1115 $id = 'menu'.$name;
1116 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1117 $id = str_replace('[', '', $id);
1118 $id = str_replace(']', '', $id);
1119 $attributes['id'] = $id;
1122 if (!isset($attributes['class'])) {
1123 $class = 'menu'.$name;
1124 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1125 $class = str_replace('[', '', $class);
1126 $class = str_replace(']', '', $class);
1127 $attributes['class'] = $class;
1129 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
1131 $attributes['name'] = $name;
1133 if (!empty($attributes['disabled'])) {
1134 $attributes['disabled'] = 'disabled';
1135 } else {
1136 unset($attributes['disabled']);
1139 $output = '';
1140 foreach ($options as $value=>$label) {
1141 if (is_array($label)) {
1142 // ignore key, it just has to be unique
1143 $output .= self::select_optgroup(key($label), current($label), $selected);
1144 } else {
1145 $output .= self::select_option($label, $value, $selected);
1148 return self::tag('select', $output, $attributes);
1151 private static function select_option($label, $value, array $selected) {
1152 $attributes = array();
1153 $value = (string)$value;
1154 if (in_array($value, $selected, true)) {
1155 $attributes['selected'] = 'selected';
1157 $attributes['value'] = $value;
1158 return self::tag('option', $label, $attributes);
1161 private static function select_optgroup($groupname, $options, array $selected) {
1162 if (empty($options)) {
1163 return '';
1165 $attributes = array('label'=>$groupname);
1166 $output = '';
1167 foreach ($options as $value=>$label) {
1168 $output .= self::select_option($label, $value, $selected);
1170 return self::tag('optgroup', $output, $attributes);
1174 * This is a shortcut for making an hour selector menu.
1175 * @param string $type The type of selector (years, months, days, hours, minutes)
1176 * @param string $name fieldname
1177 * @param int $currenttime A default timestamp in GMT
1178 * @param int $step minute spacing
1179 * @param array $attributes - html select element attributes
1180 * @return HTML fragment
1182 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1183 if (!$currenttime) {
1184 $currenttime = time();
1186 $currentdate = usergetdate($currenttime);
1187 $userdatetype = $type;
1188 $timeunits = array();
1190 switch ($type) {
1191 case 'years':
1192 for ($i=1970; $i<=2020; $i++) {
1193 $timeunits[$i] = $i;
1195 $userdatetype = 'year';
1196 break;
1197 case 'months':
1198 for ($i=1; $i<=12; $i++) {
1199 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1201 $userdatetype = 'month';
1202 $currentdate['month'] = (int)$currentdate['mon'];
1203 break;
1204 case 'days':
1205 for ($i=1; $i<=31; $i++) {
1206 $timeunits[$i] = $i;
1208 $userdatetype = 'mday';
1209 break;
1210 case 'hours':
1211 for ($i=0; $i<=23; $i++) {
1212 $timeunits[$i] = sprintf("%02d",$i);
1214 break;
1215 case 'minutes':
1216 if ($step != 1) {
1217 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1220 for ($i=0; $i<=59; $i+=$step) {
1221 $timeunits[$i] = sprintf("%02d",$i);
1223 break;
1224 default:
1225 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1228 if (empty($attributes['id'])) {
1229 $attributes['id'] = self::random_id('ts_');
1231 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1232 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1234 return $label.$timerselector;
1238 * Shortcut for quick making of lists
1239 * @param array $items
1240 * @param string $tag ul or ol
1241 * @param array $attributes
1242 * @return string
1244 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1245 //note: 'list' is a reserved keyword ;-)
1247 $output = '';
1249 foreach ($items as $item) {
1250 $output .= html_writer::start_tag('li') . "\n";
1251 $output .= $item . "\n";
1252 $output .= html_writer::end_tag('li') . "\n";
1255 return html_writer::tag($tag, $output, $attributes);
1259 * Returns hidden input fields created from url parameters.
1260 * @param moodle_url $url
1261 * @param array $exclude list of excluded parameters
1262 * @return string HTML fragment
1264 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1265 $exclude = (array)$exclude;
1266 $params = $url->params();
1267 foreach ($exclude as $key) {
1268 unset($params[$key]);
1271 $output = '';
1272 foreach ($params as $key => $value) {
1273 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1274 $output .= self::empty_tag('input', $attributes)."\n";
1276 return $output;
1280 * Generate a script tag containing the the specified code.
1282 * @param string $js the JavaScript code
1283 * @param moodle_url|string optional url of the external script, $code ignored if specified
1284 * @return string HTML, the code wrapped in <script> tags.
1286 public static function script($jscode, $url=null) {
1287 if ($jscode) {
1288 $attributes = array('type'=>'text/javascript');
1289 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1291 } else if ($url) {
1292 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1293 return self::tag('script', '', $attributes) . "\n";
1295 } else {
1296 return '';
1301 * Renders HTML table
1303 * This method may modify the passed instance by adding some default properties if they are not set yet.
1304 * If this is not what you want, you should make a full clone of your data before passing them to this
1305 * method. In most cases this is not an issue at all so we do not clone by default for performance
1306 * and memory consumption reasons.
1308 * @param html_table $table data to be rendered
1309 * @return string HTML code
1311 public static function table(html_table $table) {
1312 // prepare table data and populate missing properties with reasonable defaults
1313 if (!empty($table->align)) {
1314 foreach ($table->align as $key => $aa) {
1315 if ($aa) {
1316 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1317 } else {
1318 $table->align[$key] = null;
1322 if (!empty($table->size)) {
1323 foreach ($table->size as $key => $ss) {
1324 if ($ss) {
1325 $table->size[$key] = 'width:'. $ss .';';
1326 } else {
1327 $table->size[$key] = null;
1331 if (!empty($table->wrap)) {
1332 foreach ($table->wrap as $key => $ww) {
1333 if ($ww) {
1334 $table->wrap[$key] = 'white-space:nowrap;';
1335 } else {
1336 $table->wrap[$key] = '';
1340 if (!empty($table->head)) {
1341 foreach ($table->head as $key => $val) {
1342 if (!isset($table->align[$key])) {
1343 $table->align[$key] = null;
1345 if (!isset($table->size[$key])) {
1346 $table->size[$key] = null;
1348 if (!isset($table->wrap[$key])) {
1349 $table->wrap[$key] = null;
1354 if (empty($table->attributes['class'])) {
1355 $table->attributes['class'] = 'generaltable';
1357 if (!empty($table->tablealign)) {
1358 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1361 // explicitly assigned properties override those defined via $table->attributes
1362 $table->attributes['class'] = trim($table->attributes['class']);
1363 $attributes = array_merge($table->attributes, array(
1364 'id' => $table->id,
1365 'width' => $table->width,
1366 'summary' => $table->summary,
1367 'cellpadding' => $table->cellpadding,
1368 'cellspacing' => $table->cellspacing,
1370 $output = html_writer::start_tag('table', $attributes) . "\n";
1372 $countcols = 0;
1374 if (!empty($table->head)) {
1375 $countcols = count($table->head);
1377 $output .= html_writer::start_tag('thead', array()) . "\n";
1378 $output .= html_writer::start_tag('tr', array()) . "\n";
1379 $keys = array_keys($table->head);
1380 $lastkey = end($keys);
1382 foreach ($table->head as $key => $heading) {
1383 // Convert plain string headings into html_table_cell objects
1384 if (!($heading instanceof html_table_cell)) {
1385 $headingtext = $heading;
1386 $heading = new html_table_cell();
1387 $heading->text = $headingtext;
1388 $heading->header = true;
1391 if ($heading->header !== false) {
1392 $heading->header = true;
1395 if ($heading->header && empty($heading->scope)) {
1396 $heading->scope = 'col';
1399 $heading->attributes['class'] .= ' header c' . $key;
1400 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1401 $heading->colspan = $table->headspan[$key];
1402 $countcols += $table->headspan[$key] - 1;
1405 if ($key == $lastkey) {
1406 $heading->attributes['class'] .= ' lastcol';
1408 if (isset($table->colclasses[$key])) {
1409 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1411 $heading->attributes['class'] = trim($heading->attributes['class']);
1412 $attributes = array_merge($heading->attributes, array(
1413 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1414 'scope' => $heading->scope,
1415 'colspan' => $heading->colspan,
1418 $tagtype = 'td';
1419 if ($heading->header === true) {
1420 $tagtype = 'th';
1422 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1424 $output .= html_writer::end_tag('tr') . "\n";
1425 $output .= html_writer::end_tag('thead') . "\n";
1427 if (empty($table->data)) {
1428 // For valid XHTML strict every table must contain either a valid tr
1429 // or a valid tbody... both of which must contain a valid td
1430 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1431 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1432 $output .= html_writer::end_tag('tbody');
1436 if (!empty($table->data)) {
1437 $oddeven = 1;
1438 $keys = array_keys($table->data);
1439 $lastrowkey = end($keys);
1440 $output .= html_writer::start_tag('tbody', array());
1442 foreach ($table->data as $key => $row) {
1443 if (($row === 'hr') && ($countcols)) {
1444 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1445 } else {
1446 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1447 if (!($row instanceof html_table_row)) {
1448 $newrow = new html_table_row();
1450 foreach ($row as $item) {
1451 $cell = new html_table_cell();
1452 $cell->text = $item;
1453 $newrow->cells[] = $cell;
1455 $row = $newrow;
1458 $oddeven = $oddeven ? 0 : 1;
1459 if (isset($table->rowclasses[$key])) {
1460 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1463 $row->attributes['class'] .= ' r' . $oddeven;
1464 if ($key == $lastrowkey) {
1465 $row->attributes['class'] .= ' lastrow';
1468 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1469 $keys2 = array_keys($row->cells);
1470 $lastkey = end($keys2);
1472 $gotlastkey = false; //flag for sanity checking
1473 foreach ($row->cells as $key => $cell) {
1474 if ($gotlastkey) {
1475 //This should never happen. Why do we have a cell after the last cell?
1476 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1479 if (!($cell instanceof html_table_cell)) {
1480 $mycell = new html_table_cell();
1481 $mycell->text = $cell;
1482 $cell = $mycell;
1485 if (($cell->header === true) && empty($cell->scope)) {
1486 $cell->scope = 'row';
1489 if (isset($table->colclasses[$key])) {
1490 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1493 $cell->attributes['class'] .= ' cell c' . $key;
1494 if ($key == $lastkey) {
1495 $cell->attributes['class'] .= ' lastcol';
1496 $gotlastkey = true;
1498 $tdstyle = '';
1499 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1500 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1501 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1502 $cell->attributes['class'] = trim($cell->attributes['class']);
1503 $tdattributes = array_merge($cell->attributes, array(
1504 'style' => $tdstyle . $cell->style,
1505 'colspan' => $cell->colspan,
1506 'rowspan' => $cell->rowspan,
1507 'id' => $cell->id,
1508 'abbr' => $cell->abbr,
1509 'scope' => $cell->scope,
1511 $tagtype = 'td';
1512 if ($cell->header === true) {
1513 $tagtype = 'th';
1515 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1518 $output .= html_writer::end_tag('tr') . "\n";
1520 $output .= html_writer::end_tag('tbody') . "\n";
1522 $output .= html_writer::end_tag('table') . "\n";
1524 return $output;
1528 * Renders form element label
1530 * By default, the label is suffixed with a label separator defined in the
1531 * current language pack (colon by default in the English lang pack).
1532 * Adding the colon can be explicitly disabled if needed. Label separators
1533 * are put outside the label tag itself so they are not read by
1534 * screenreaders (accessibility).
1536 * Parameter $for explicitly associates the label with a form control. When
1537 * set, the value of this attribute must be the same as the value of
1538 * the id attribute of the form control in the same document. When null,
1539 * the label being defined is associated with the control inside the label
1540 * element.
1542 * @param string $text content of the label tag
1543 * @param string|null $for id of the element this label is associated with, null for no association
1544 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1545 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1546 * @return string HTML of the label element
1548 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1549 if (!is_null($for)) {
1550 $attributes = array_merge($attributes, array('for' => $for));
1552 $text = trim($text);
1553 $label = self::tag('label', $text, $attributes);
1556 // TODO $colonize disabled for now yet - see MDL-12192 for details
1557 if (!empty($text) and $colonize) {
1558 // the $text may end with the colon already, though it is bad string definition style
1559 $colon = get_string('labelsep', 'langconfig');
1560 if (!empty($colon)) {
1561 $trimmed = trim($colon);
1562 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1563 //debugging('The label text should not end with colon or other label separator,
1564 // please fix the string definition.', DEBUG_DEVELOPER);
1565 } else {
1566 $label .= $colon;
1572 return $label;
1576 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1579 * Simple javascript output class
1580 * @copyright 2010 Petr Skoda
1582 class js_writer {
1584 * Returns javascript code calling the function
1585 * @param string $function function name, can be complex like Y.Event.purgeElement
1586 * @param array $arguments parameters
1587 * @param int $delay execution delay in seconds
1588 * @return string JS code fragment
1590 public static function function_call($function, array $arguments = null, $delay=0) {
1591 if ($arguments) {
1592 $arguments = array_map('json_encode', convert_to_array($arguments));
1593 $arguments = implode(', ', $arguments);
1594 } else {
1595 $arguments = '';
1597 $js = "$function($arguments);";
1599 if ($delay) {
1600 $delay = $delay * 1000; // in miliseconds
1601 $js = "setTimeout(function() { $js }, $delay);";
1603 return $js . "\n";
1607 * Special function which adds Y as first argument of fucntion call.
1608 * @param string $function
1609 * @param array $extraarguments
1610 * @return string
1612 public static function function_call_with_Y($function, array $extraarguments = null) {
1613 if ($extraarguments) {
1614 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1615 $arguments = 'Y, ' . implode(', ', $extraarguments);
1616 } else {
1617 $arguments = 'Y';
1619 return "$function($arguments);\n";
1623 * Returns JavaScript code to initialise a new object
1624 * @param string|null $var If it is null then no var is assigned the new object
1625 * @param string $class
1626 * @param array $arguments
1627 * @param array $requirements
1628 * @param int $delay
1629 * @return string
1631 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1632 if (is_array($arguments)) {
1633 $arguments = array_map('json_encode', convert_to_array($arguments));
1634 $arguments = implode(', ', $arguments);
1637 if ($var === null) {
1638 $js = "new $class(Y, $arguments);";
1639 } else if (strpos($var, '.')!==false) {
1640 $js = "$var = new $class(Y, $arguments);";
1641 } else {
1642 $js = "var $var = new $class(Y, $arguments);";
1645 if ($delay) {
1646 $delay = $delay * 1000; // in miliseconds
1647 $js = "setTimeout(function() { $js }, $delay);";
1650 if (count($requirements) > 0) {
1651 $requirements = implode("', '", $requirements);
1652 $js = "Y.use('$requirements', function(Y){ $js });";
1654 return $js."\n";
1658 * Returns code setting value to variable
1659 * @param string $name
1660 * @param mixed $value json serialised value
1661 * @param bool $usevar add var definition, ignored for nested properties
1662 * @return string JS code fragment
1664 public static function set_variable($name, $value, $usevar=true) {
1665 $output = '';
1667 if ($usevar) {
1668 if (strpos($name, '.')) {
1669 $output .= '';
1670 } else {
1671 $output .= 'var ';
1675 $output .= "$name = ".json_encode($value).";";
1677 return $output;
1681 * Writes event handler attaching code
1682 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1683 * @param string $event A valid DOM event (click, mousedown, change etc.)
1684 * @param string $function The name of the function to call
1685 * @param array $arguments An optional array of argument parameters to pass to the function
1686 * @return string JS code fragment
1688 public static function event_handler($selector, $event, $function, array $arguments = null) {
1689 $selector = json_encode($selector);
1690 $output = "Y.on('$event', $function, $selector, null";
1691 if (!empty($arguments)) {
1692 $output .= ', ' . json_encode($arguments);
1694 return $output . ");\n";
1699 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1701 * Example of usage:
1702 * $t = new html_table();
1703 * ... // set various properties of the object $t as described below
1704 * echo html_writer::table($t);
1706 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1707 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1708 * @since Moodle 2.0
1710 class html_table {
1712 * @var string value to use for the id attribute of the table
1714 public $id = null;
1716 * @var array attributes of HTML attributes for the <table> element
1718 public $attributes = array();
1720 * For more control over the rendering of the headers, an array of html_table_cell objects
1721 * can be passed instead of an array of strings.
1722 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1724 * Example of usage:
1725 * $t->head = array('Student', 'Grade');
1727 public $head;
1729 * @var array can be used to make a heading span multiple columns
1731 * Example of usage:
1732 * $t->headspan = array(2,1);
1734 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1735 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1737 public $headspan;
1739 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1740 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1741 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1743 * Examples of usage:
1744 * $t->align = array(null, 'right');
1745 * or
1746 * $t->align[1] = 'right';
1749 public $align;
1751 * @var array of column sizes. The value is used as CSS 'size' property.
1753 * Examples of usage:
1754 * $t->size = array('50%', '50%');
1755 * or
1756 * $t->size[1] = '120px';
1758 public $size;
1760 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1761 * CSS property 'white-space' to the value 'nowrap' in the given column.
1763 * Example of usage:
1764 * $t->wrap = array(null, 'nowrap');
1766 public $wrap;
1768 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1769 * $head specified, the string 'hr' (for horizontal ruler) can be used
1770 * instead of an array of cells data resulting in a divider rendered.
1772 * Example of usage with array of arrays:
1773 * $row1 = array('Harry Potter', '76 %');
1774 * $row2 = array('Hermione Granger', '100 %');
1775 * $t->data = array($row1, $row2);
1777 * Example with array of html_table_row objects: (used for more fine-grained control)
1778 * $cell1 = new html_table_cell();
1779 * $cell1->text = 'Harry Potter';
1780 * $cell1->colspan = 2;
1781 * $row1 = new html_table_row();
1782 * $row1->cells[] = $cell1;
1783 * $cell2 = new html_table_cell();
1784 * $cell2->text = 'Hermione Granger';
1785 * $cell3 = new html_table_cell();
1786 * $cell3->text = '100 %';
1787 * $row2 = new html_table_row();
1788 * $row2->cells = array($cell2, $cell3);
1789 * $t->data = array($row1, $row2);
1791 public $data;
1793 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1794 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1796 public $width = null;
1798 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1799 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1801 public $tablealign = null;
1803 * @var int padding on each cell, in pixels
1804 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1806 public $cellpadding = null;
1808 * @var int spacing between cells, in pixels
1809 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1811 public $cellspacing = null;
1813 * @var array classes to add to particular rows, space-separated string.
1814 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1815 * respectively. Class 'lastrow' is added automatically for the last row
1816 * in the table.
1818 * Example of usage:
1819 * $t->rowclasses[9] = 'tenth'
1821 public $rowclasses;
1823 * @var array classes to add to every cell in a particular column,
1824 * space-separated string. Class 'cell' is added automatically by the renderer.
1825 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1826 * respectively. Class 'lastcol' is added automatically for all last cells
1827 * in a row.
1829 * Example of usage:
1830 * $t->colclasses = array(null, 'grade');
1832 public $colclasses;
1834 * @var string description of the contents for screen readers.
1836 public $summary;
1839 * Constructor
1841 public function __construct() {
1842 $this->attributes['class'] = '';
1848 * Component representing a table row.
1850 * @copyright 2009 Nicolas Connault
1851 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1852 * @since Moodle 2.0
1854 class html_table_row {
1856 * @var string value to use for the id attribute of the row
1858 public $id = null;
1860 * @var array $cells Array of html_table_cell objects
1862 public $cells = array();
1864 * @var string $style value to use for the style attribute of the table row
1866 public $style = null;
1868 * @var array attributes of additional HTML attributes for the <tr> element
1870 public $attributes = array();
1873 * Constructor
1874 * @param array $cells
1876 public function __construct(array $cells=null) {
1877 $this->attributes['class'] = '';
1878 $cells = (array)$cells;
1879 foreach ($cells as $cell) {
1880 if ($cell instanceof html_table_cell) {
1881 $this->cells[] = $cell;
1882 } else {
1883 $this->cells[] = new html_table_cell($cell);
1891 * Component representing a table cell.
1893 * @copyright 2009 Nicolas Connault
1894 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1895 * @since Moodle 2.0
1897 class html_table_cell {
1899 * @var string value to use for the id attribute of the cell
1901 public $id = null;
1903 * @var string $text The contents of the cell
1905 public $text;
1907 * @var string $abbr Abbreviated version of the contents of the cell
1909 public $abbr = null;
1911 * @var int $colspan Number of columns this cell should span
1913 public $colspan = null;
1915 * @var int $rowspan Number of rows this cell should span
1917 public $rowspan = null;
1919 * @var string $scope Defines a way to associate header cells and data cells in a table
1921 public $scope = null;
1923 * @var boolean $header Whether or not this cell is a header cell
1925 public $header = null;
1927 * @var string $style value to use for the style attribute of the table cell
1929 public $style = null;
1931 * @var array attributes of additional HTML attributes for the <td> element
1933 public $attributes = array();
1935 public function __construct($text = null) {
1936 $this->text = $text;
1937 $this->attributes['class'] = '';
1942 /// Complex components aggregating simpler components
1946 * Component representing a paging bar.
1948 * @copyright 2009 Nicolas Connault
1949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1950 * @since Moodle 2.0
1952 class paging_bar implements renderable {
1954 * @var int $maxdisplay The maximum number of pagelinks to display
1956 public $maxdisplay = 18;
1958 * @var int $totalcount post or get
1960 public $totalcount;
1962 * @var int $page The page you are currently viewing
1964 public $page;
1966 * @var int $perpage The number of entries that should be shown per page
1968 public $perpage;
1970 * @var string $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
1971 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1973 public $baseurl;
1975 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1977 public $pagevar;
1979 * @var string $previouslink A HTML link representing the "previous" page
1981 public $previouslink = null;
1983 * @var tring $nextlink A HTML link representing the "next" page
1985 public $nextlink = null;
1987 * @var tring $firstlink A HTML link representing the first page
1989 public $firstlink = null;
1991 * @var tring $lastlink A HTML link representing the last page
1993 public $lastlink = null;
1995 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1997 public $pagelinks = array();
2000 * Constructor paging_bar with only the required params.
2002 * @param int $totalcount The total number of entries available to be paged through
2003 * @param int $page The page you are currently viewing
2004 * @param int $perpage The number of entries that should be shown per page
2005 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2006 * @param string $pagevar name of page parameter that holds the page number
2008 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2009 $this->totalcount = $totalcount;
2010 $this->page = $page;
2011 $this->perpage = $perpage;
2012 $this->baseurl = $baseurl;
2013 $this->pagevar = $pagevar;
2017 * @return void
2019 public function prepare(renderer_base $output, moodle_page $page, $target) {
2020 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2021 throw new coding_exception('paging_bar requires a totalcount value.');
2023 if (!isset($this->page) || is_null($this->page)) {
2024 throw new coding_exception('paging_bar requires a page value.');
2026 if (empty($this->perpage)) {
2027 throw new coding_exception('paging_bar requires a perpage value.');
2029 if (empty($this->baseurl)) {
2030 throw new coding_exception('paging_bar requires a baseurl value.');
2033 if ($this->totalcount > $this->perpage) {
2034 $pagenum = $this->page - 1;
2036 if ($this->page > 0) {
2037 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2040 if ($this->perpage > 0) {
2041 $lastpage = ceil($this->totalcount / $this->perpage);
2042 } else {
2043 $lastpage = 1;
2046 if ($this->page > 15) {
2047 $startpage = $this->page - 10;
2049 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2050 } else {
2051 $startpage = 0;
2054 $currpage = $startpage;
2055 $displaycount = $displaypage = 0;
2057 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2058 $displaypage = $currpage + 1;
2060 if ($this->page == $currpage) {
2061 $this->pagelinks[] = $displaypage;
2062 } else {
2063 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2064 $this->pagelinks[] = $pagelink;
2067 $displaycount++;
2068 $currpage++;
2071 if ($currpage < $lastpage) {
2072 $lastpageactual = $lastpage - 1;
2073 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2076 $pagenum = $this->page + 1;
2078 if ($pagenum != $displaypage) {
2079 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2087 * This class represents how a block appears on a page.
2089 * During output, each block instance is asked to return a block_contents object,
2090 * those are then passed to the $OUTPUT->block function for display.
2092 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2094 * Other block-like things that need to appear on the page, for example the
2095 * add new block UI, are also represented as block_contents objects.
2097 * @copyright 2009 Tim Hunt
2098 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2099 * @since Moodle 2.0
2101 class block_contents {
2102 /** @var int used to set $skipid. */
2103 protected static $idcounter = 1;
2105 const NOT_HIDEABLE = 0;
2106 const VISIBLE = 1;
2107 const HIDDEN = 2;
2110 * @var integer $skipid All the blocks (or things that look like blocks)
2111 * printed on a page are given a unique number that can be used to construct
2112 * id="" attributes. This is set automatically be the {@link prepare()} method.
2113 * Do not try to set it manually.
2115 public $skipid;
2118 * @var integer If this is the contents of a real block, this should be set to
2119 * the block_instance.id. Otherwise this should be set to 0.
2121 public $blockinstanceid = 0;
2124 * @var integer if this is a real block instance, and there is a corresponding
2125 * block_position.id for the block on this page, this should be set to that id.
2126 * Otherwise it should be 0.
2128 public $blockpositionid = 0;
2131 * @param array $attributes an array of attribute => value pairs that are put on the
2132 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2134 public $attributes;
2137 * @param string $title The title of this block. If this came from user input,
2138 * it should already have had format_string() processing done on it. This will
2139 * be output inside <h2> tags. Please do not cause invalid XHTML.
2141 public $title = '';
2144 * @param string $content HTML for the content
2146 public $content = '';
2149 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2151 public $footer = '';
2154 * Any small print that should appear under the block to explain to the
2155 * teacher about the block, for example 'This is a sticky block that was
2156 * added in the system context.'
2157 * @var string
2159 public $annotation = '';
2162 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2163 * the user can toggle whether this block is visible.
2165 public $collapsible = self::NOT_HIDEABLE;
2168 * A (possibly empty) array of editing controls. Each element of this array
2169 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2170 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2171 * @var array
2173 public $controls = array();
2177 * Create new instance of block content
2178 * @param array $attributes
2180 public function __construct(array $attributes=null) {
2181 $this->skipid = self::$idcounter;
2182 self::$idcounter += 1;
2184 if ($attributes) {
2185 // standard block
2186 $this->attributes = $attributes;
2187 } else {
2188 // simple "fake" blocks used in some modules and "Add new block" block
2189 $this->attributes = array('class'=>'block');
2194 * Add html class to block
2195 * @param string $class
2196 * @return void
2198 public function add_class($class) {
2199 $this->attributes['class'] .= ' '.$class;
2205 * This class represents a target for where a block can go when it is being moved.
2207 * This needs to be rendered as a form with the given hidden from fields, and
2208 * clicking anywhere in the form should submit it. The form action should be
2209 * $PAGE->url.
2211 * @copyright 2009 Tim Hunt
2212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2213 * @since Moodle 2.0
2215 class block_move_target {
2217 * Move url
2218 * @var moodle_url
2220 public $url;
2222 * label
2223 * @var string
2225 public $text;
2228 * Constructor
2229 * @param string $text
2230 * @param moodle_url $url
2232 public function __construct($text, moodle_url $url) {
2233 $this->text = $text;
2234 $this->url = $url;
2239 * Custom menu item
2241 * This class is used to represent one item within a custom menu that may or may
2242 * not have children.
2244 * @copyright 2010 Sam Hemelryk
2245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2246 * @since Moodle 2.0
2248 class custom_menu_item implements renderable {
2250 * The text to show for the item
2251 * @var string
2253 protected $text;
2255 * The link to give the icon if it has no children
2256 * @var moodle_url
2258 protected $url;
2260 * A title to apply to the item. By default the text
2261 * @var string
2263 protected $title;
2265 * A sort order for the item, not necessary if you order things in the CFG var
2266 * @var int
2268 protected $sort;
2270 * A reference to the parent for this item or NULL if it is a top level item
2271 * @var custom_menu_item
2273 protected $parent;
2275 * A array in which to store children this item has.
2276 * @var array
2278 protected $children = array();
2280 * A reference to the sort var of the last child that was added
2281 * @var int
2283 protected $lastsort = 0;
2285 * Constructs the new custom menu item
2287 * @param string $text
2288 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2289 * @param string $title A title to apply to this item [Optional]
2290 * @param int $sort A sort or to use if we need to sort differently [Optional]
2291 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2292 * belongs to, only if the child has a parent. [Optional]
2294 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2295 $this->text = $text;
2296 $this->url = $url;
2297 $this->title = $title;
2298 $this->sort = (int)$sort;
2299 $this->parent = $parent;
2303 * Adds a custom menu item as a child of this node given its properties.
2305 * @param string $text
2306 * @param moodle_url $url
2307 * @param string $title
2308 * @param int $sort
2309 * @return custom_menu_item
2311 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2312 $key = count($this->children);
2313 if (empty($sort)) {
2314 $sort = $this->lastsort + 1;
2316 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2317 $this->lastsort = (int)$sort;
2318 return $this->children[$key];
2321 * Returns the text for this item
2322 * @return string
2324 public function get_text() {
2325 return $this->text;
2328 * Returns the url for this item
2329 * @return moodle_url
2331 public function get_url() {
2332 return $this->url;
2335 * Returns the title for this item
2336 * @return string
2338 public function get_title() {
2339 return $this->title;
2342 * Sorts and returns the children for this item
2343 * @return array
2345 public function get_children() {
2346 $this->sort();
2347 return $this->children;
2350 * Gets the sort order for this child
2351 * @return int
2353 public function get_sort_order() {
2354 return $this->sort;
2357 * Gets the parent this child belong to
2358 * @return custom_menu_item
2360 public function get_parent() {
2361 return $this->parent;
2364 * Sorts the children this item has
2366 public function sort() {
2367 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2370 * Returns true if this item has any children
2371 * @return bool
2373 public function has_children() {
2374 return (count($this->children) > 0);
2378 * Sets the text for the node
2379 * @param string $text
2381 public function set_text($text) {
2382 $this->text = (string)$text;
2386 * Sets the title for the node
2387 * @param string $title
2389 public function set_title($title) {
2390 $this->title = (string)$title;
2394 * Sets the url for the node
2395 * @param moodle_url $url
2397 public function set_url(moodle_url $url) {
2398 $this->url = $url;
2403 * Custom menu class
2405 * This class is used to operate a custom menu that can be rendered for the page.
2406 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2407 * of custom_menu_item nodes that can be rendered by the core renderer.
2409 * To configure the custom menu:
2410 * Settings: Administration > Appearance > Themes > Theme settings
2412 * @copyright 2010 Sam Hemelryk
2413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2414 * @since Moodle 2.0
2416 class custom_menu extends custom_menu_item {
2418 /** @var string the language we should render for, null disables multilang support */
2419 protected $currentlanguage = null;
2422 * Creates the custom menu
2424 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2425 * @param string $language the current language code, null disables multilang support
2427 public function __construct($definition = '', $currentlanguage = null) {
2429 $this->currentlanguage = $currentlanguage;
2430 parent::__construct('root'); // create virtual root element of the menu
2431 if (!empty($definition)) {
2432 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2437 * Overrides the children of this custom menu. Useful when getting children
2438 * from $CFG->custommenuitems
2440 public function override_children(array $children) {
2441 $this->children = array();
2442 foreach ($children as $child) {
2443 if ($child instanceof custom_menu_item) {
2444 $this->children[] = $child;
2450 * Converts a string into a structured array of custom_menu_items which can
2451 * then be added to a custom menu.
2453 * Structure:
2454 * text|url|title|langs
2455 * The number of hyphens at the start determines the depth of the item. The
2456 * languages are optional, comma separated list of languages the line is for.
2458 * Example structure:
2459 * First level first item|http://www.moodle.com/
2460 * -Second level first item|http://www.moodle.com/partners/
2461 * -Second level second item|http://www.moodle.com/hq/
2462 * --Third level first item|http://www.moodle.com/jobs/
2463 * -Second level third item|http://www.moodle.com/development/
2464 * First level second item|http://www.moodle.com/feedback/
2465 * First level third item
2466 * English only|http://moodle.com|English only item|en
2467 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2470 * @static
2471 * @param string $text the menu items definition
2472 * @param string $language the language code, null disables multilang support
2473 * @return array
2475 public static function convert_text_to_menu_nodes($text, $language = null) {
2476 $lines = explode("\n", $text);
2477 $children = array();
2478 $lastchild = null;
2479 $lastdepth = null;
2480 $lastsort = 0;
2481 foreach ($lines as $line) {
2482 $line = trim($line);
2483 $bits = explode('|', $line, 4); // name|url|title|langs
2484 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2485 // Every item must have a name to be valid
2486 continue;
2487 } else {
2488 $bits[0] = ltrim($bits[0],'-');
2490 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2491 // Set the url to null
2492 $bits[1] = null;
2493 } else {
2494 // Make sure the url is a moodle url
2495 $bits[1] = new moodle_url(trim($bits[1]));
2497 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2498 // Set the title to null seeing as there isn't one
2499 $bits[2] = $bits[0];
2501 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2502 // The item is valid for all languages
2503 $itemlangs = null;
2504 } else {
2505 $itemlangs = array_map('trim', explode(',', $bits[3]));
2507 if (!empty($language) and !empty($itemlangs)) {
2508 // check that the item is intended for the current language
2509 if (!in_array($language, $itemlangs)) {
2510 continue;
2513 // Set an incremental sort order to keep it simple.
2514 $lastsort++;
2515 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2516 $depth = strlen($match[1]);
2517 if ($depth < $lastdepth) {
2518 $difference = $lastdepth - $depth;
2519 if ($lastdepth > 1 && $lastdepth != $difference) {
2520 $tempchild = $lastchild->get_parent();
2521 for ($i =0; $i < $difference; $i++) {
2522 $tempchild = $tempchild->get_parent();
2524 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2525 } else {
2526 $depth = 0;
2527 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2528 $children[] = $lastchild;
2530 } else if ($depth > $lastdepth) {
2531 $depth = $lastdepth + 1;
2532 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2533 } else {
2534 if ($depth == 0) {
2535 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2536 $children[] = $lastchild;
2537 } else {
2538 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2541 } else {
2542 $depth = 0;
2543 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2544 $children[] = $lastchild;
2546 $lastdepth = $depth;
2548 return $children;
2552 * Sorts two custom menu items
2554 * This function is designed to be used with the usort method
2555 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2557 * @param custom_menu_item $itema
2558 * @param custom_menu_item $itemb
2559 * @return int
2561 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2562 $itema = $itema->get_sort_order();
2563 $itemb = $itemb->get_sort_order();
2564 if ($itema == $itemb) {
2565 return 0;
2567 return ($itema > $itemb) ? +1 : -1;