MDL-21695 new help_icon structure
[moodle.git] / lib / outputcomponents.php
CommitLineData
d9c8f425 1<?php
2
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.
14//
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/>.
17
18/**
19 * Classes representing HTML elements, used by $OUTPUT methods
20 *
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
23 *
24 * @package moodlecore
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
5d0c95a5
PS
29
30/**
31 * Interface marking other classes as suitable for renderer_base::render()
32 * @author 2010 Petr Skoda (skodak) info@skodak.org
33 */
34interface renderable {
35 // intentionally empty
36}
37
38
39/**
bf11293a 40 * Data structure representing a user picture.
5d0c95a5
PS
41 *
42 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 * @since Moodle 2.0
45 */
46class user_picture implements renderable {
47 /**
48 * List of mandatory fields in user record here.
49 * @var string
50 */
51 const FIELDS = 'id,picture,firstname,lastname,imagealt';
52
53 /**
54 * @var object $user A user object with at least fields id, picture, imagealt, firstname and lastname set.
55 */
56 public $user;
57 /**
58 * @var int $courseid The course id. Used when constructing the link to the user's profile,
59 * page course id used if not specified.
60 */
61 public $courseid;
62 /**
63 * @var bool $link add course profile link to image
64 */
65 public $link = true;
66 /**
67 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
68 */
69 public $size = 35;
70 /**
71 * @var boolean $alttext add non-blank alt-text to the image.
72 * Default true, set to false when image alt just duplicates text in screenreaders.
73 */
74 public $alttext = true;
75 /**
76 * @var boolean $popup Whether or not to open the link in a popup window.
77 */
78 public $popup = false;
79 /**
80 * @var string Image class attribute
81 */
82 public $class = 'userpicture';
83
84 /**
85 * User picture constructor.
86 *
87 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
88 * @param array $options such as link, size, link, ...
89 */
90 public function __construct(stdClass $user) {
91 global $DB;
92
93 static $fields = null;
94 if (is_null($fields)) {
95 $fields = explode(',', self::FIELDS);
96 }
97
98 if (empty($user->id)) {
99 throw new coding_exception('User id is required when printing user avatar image.');
100 }
101
102 // only touch the DB if we are missing data and complain loudly...
103 $needrec = false;
104 foreach ($fields as $field) {
105 if (!array_key_exists($field, $user)) {
106 $needrec = true;
107 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
108 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
109 break;
110 }
111 }
112
113 if ($needrec) {
114 $this->user = $DB->get_record('user', array('id'=>$user->id), self::FIELDS, MUST_EXIST);
115 } else {
116 $this->user = clone($user);
117 }
118 }
119
120 /**
121 * Returns a list of required user fields, usefull when fetching required user info from db.
f3afba4e
PS
122 *
123 * In some cases we have to fetch the user data together with some other information,
124 * the idalias is useful there because the id would otherwise override the main
125 * id of the result record. Please note it has to be converted back to id before rendering.
126 *
5d0c95a5 127 * @param string $tableprefix name of database table prefix in query
f3afba4e 128 * @param string $idalias alias of id field
5d0c95a5
PS
129 * @return string
130 */
f3afba4e
PS
131 public static function fields($tableprefix = '', $idalias = '') {
132 if ($tableprefix === '' and $idalias === '') {
5d0c95a5 133 return self::FIELDS;
5d0c95a5 134 }
f3afba4e
PS
135 $fields = explode(',', self::FIELDS);
136 foreach ($fields as $key=>$field) {
137 if ($field === 'id' and $idalias !== '') {
138 $field = "$field AS $idalias";
139 }
140 $fields[$key] = "$tableprefix.$field";
141 }
142 return implode(',', $fields);
5d0c95a5
PS
143 }
144}
145
bf11293a
PS
146
147/**
148 * Data structure representing a help icon.
149 *
150 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
151 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
152 * @since Moodle 2.0
153 */
596509e4 154class old_help_icon implements renderable {
bf11293a 155 /**
49f0d481 156 * @var string $helpidentifier lang pack identifier
bf11293a 157 */
53a78cef 158 public $helpidentifier;
bf11293a
PS
159 /**
160 * @var string $title A descriptive text for title tooltip
161 */
97c10099 162 public $title = null;
bf11293a
PS
163 /**
164 * @var string $component Component name, the same as in get_string()
165 */
166 public $component = 'moodle';
167 /**
168 * @var string $linktext Extra descriptive text next to the icon
169 */
97c10099 170 public $linktext = null;
bf11293a
PS
171
172 /**
173 * Constructor: sets up the other components in case they are needed
53a78cef 174 * @param string $helpidentifier The keyword that defines a help page
bf11293a
PS
175 * @param string $title A descriptive text for accesibility only
176 * @param string $component
177 * @param bool $linktext add extra text to icon
178 * @return void
179 */
53a78cef 180 public function __construct($helpidentifier, $title, $component = 'moodle') {
bf11293a
PS
181 if (empty($title)) {
182 throw new coding_exception('A help_icon object requires a $text parameter');
183 }
53a78cef
PS
184 if (empty($helpidentifier)) {
185 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
bf11293a
PS
186 }
187
53a78cef
PS
188 $this->helpidentifier = $helpidentifier;
189 $this->title = $title;
190 $this->component = $component;
bf11293a
PS
191 }
192}
193
49f0d481
PS
194/**
195 * Data structure representing a help icon.
196 *
197 * @copyright 2010 Petr Skoda (info@skodak.org)
198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
199 * @since Moodle 2.0
200 */
201class help_icon implements renderable {
202 /**
203 * @var string $identifier lang pack identifier (without the "_hlp" suffix),
204 * both get_string($identifier, $component) and get_string($identifier.'_hlp', $component)
205 * must exist.
206 */
207 public $identifier;
208 /**
209 * @var string $component Component name, the same as in get_string()
210 */
211 public $component;
212 /**
213 * @var string $linktext Extra descriptive text next to the icon
214 */
215 public $linktext = null;
216
217 /**
218 * Constructor
219 * @param string $identifier string for help page title,
220 * string with _hlp suffix is used for the actual help text.
221 * @param string $component
222 */
223 public function __construct($pidentifier, $component) {
224 $this->identifier = $helpidentifier;
225 $this->component = $component;
226 }
227}
228
bf11293a 229
000c278c
PS
230/**
231 * Data structure representing an icon.
232 *
233 * @copyright 2010 Petr Skoda
234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
235 * @since Moodle 2.0
236 */
237class pix_icon implements renderable {
238 var $pix;
239 var $component;
240 var $attributes = array();
241
242 /**
243 * Constructor
244 * @param string $pix short icon name
245 * @param string $component component name
246 * @param array $attributes html attributes
247 */
248 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
249 $this->pix = $pix;
250 $this->component = $component;
000c278c
PS
251 $this->attributes = (array)$attributes;
252
253 $this->attributes['alt'] = $alt;
254 if (empty($this->attributes['class'])) {
255 $this->attributes['class'] = 'smallicon';
256 }
257 if (!isset($this->attributes['title'])) {
258 $this->attributes['title'] = $this->attributes['alt'];
259 }
260 }
261}
262
263
3ba60ee1
PS
264/**
265 * Data structure representing a simple form with only one button.
266 *
267 * @copyright 2009 Petr Skoda
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
269 * @since Moodle 2.0
270 */
271class single_button implements renderable {
574fbea4
PS
272 /**
273 * Target url
274 * @var moodle_url
275 */
3ba60ee1 276 var $url;
574fbea4
PS
277 /**
278 * Button label
279 * @var string
280 */
3ba60ee1 281 var $label;
574fbea4
PS
282 /**
283 * Form submit method
284 * @var string post or get
285 */
3ba60ee1 286 var $method = 'post';
574fbea4
PS
287 /**
288 * Wrapping div class
289 * @var string
290 * */
3ba60ee1 291 var $class = 'singlebutton';
574fbea4
PS
292 /**
293 * True if button disabled, false if normal
294 * @var boolean
295 */
3ba60ee1 296 var $disabled = false;
574fbea4
PS
297 /**
298 * Button tooltip
299 * @var string
300 */
97c10099 301 var $tooltip = null;
574fbea4
PS
302 /**
303 * Form id
304 * @var string
305 */
3ba60ee1 306 var $formid;
574fbea4
PS
307 /**
308 * List of attached actions
309 * @var array of component_action
310 */
3ba60ee1
PS
311 var $actions = array();
312
313 /**
314 * Constructor
574fbea4 315 * @param string|moodle_url $url
3ba60ee1
PS
316 * @param string $label button text
317 * @param string $method get or post submit method
3ba60ee1
PS
318 */
319 public function __construct(moodle_url $url, $label, $method='post') {
320 $this->url = clone($url);
321 $this->label = $label;
322 $this->method = $method;
323 }
324
325 /**
574fbea4 326 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1
PS
327 * The message must be a yes/no question.
328 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
329 * @return void
330 */
331 public function add_confirm_action($confirmmessage) {
20fb563e 332 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
3ba60ee1
PS
333 }
334
574fbea4
PS
335 /**
336 * Add action to the button.
337 * @param component_action $action
338 * @return void
339 */
3ba60ee1
PS
340 public function add_action(component_action $action) {
341 $this->actions[] = $action;
342 }
343}
344
345
a9967cf5
PS
346/**
347 * Simple form with just one select field that gets submitted automatically.
348 * If JS not enabled small go button is printed too.
349 *
350 * @copyright 2009 Petr Skoda
351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
352 * @since Moodle 2.0
353 */
354class single_select implements renderable {
355 /**
356 * Target url - includes hidden fields
357 * @var moodle_url
358 */
359 var $url;
360 /**
361 * Name of the select element.
362 * @var string
363 */
364 var $name;
365 /**
366 * @var array $options associative array value=>label ex.:
367 * array(1=>'One, 2=>Two)
368 * it is also possible to specify optgroup as complex label array ex.:
369 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
370 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
371 */
372 var $options;
373 /**
374 * Selected option
375 * @var string
376 */
377 var $selected;
378 /**
379 * Nothing selected
380 * @var array
381 */
382 var $nothing;
383 /**
384 * Extra select field attributes
385 * @var array
386 */
387 var $attributes = array();
388 /**
389 * Button label
390 * @var string
391 */
392 var $label = '';
393 /**
394 * Form submit method
395 * @var string post or get
396 */
397 var $method = 'get';
398 /**
399 * Wrapping div class
400 * @var string
401 * */
402 var $class = 'singleselect';
403 /**
404 * True if button disabled, false if normal
405 * @var boolean
406 */
407 var $disabled = false;
408 /**
409 * Button tooltip
410 * @var string
411 */
412 var $tooltip = null;
413 /**
414 * Form id
415 * @var string
416 */
417 var $formid = null;
418 /**
419 * List of attached actions
420 * @var array of component_action
421 */
422 var $helpicon = null;
423 /**
424 * Constructor
425 * @param moodle_url $url form action target, includes hidden fields
426 * @param string $name name of selection field - the changing parameter in url
427 * @param array $options list of options
428 * @param string $selected selected element
429 * @param array $nothing
f8dab966 430 * @param string $formid
a9967cf5 431 */
f8dab966 432 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
a9967cf5
PS
433 $this->url = $url;
434 $this->name = $name;
435 $this->options = $options;
436 $this->selected = $selected;
437 $this->nothing = $nothing;
f8dab966 438 $this->formid = $formid;
a9967cf5
PS
439 }
440
441 /**
442 * Shortcut for adding a JS confirm dialog when the button is clicked.
443 * The message must be a yes/no question.
444 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
445 * @return void
446 */
447 public function add_confirm_action($confirmmessage) {
448 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
449 }
450
451 /**
452 * Add action to the button.
453 * @param component_action $action
454 * @return void
455 */
456 public function add_action(component_action $action) {
457 $this->actions[] = $action;
458 }
f8dab966
PS
459
460 /**
461 * Constructor: sets up the other components in case they are needed
462 * @param string $page The keyword that defines a help page
463 * @param string $title A descriptive text for accesibility only
464 * @param string $component
465 * @param bool $linktext add extra text to icon
466 * @return void
467 */
596509e4
PS
468 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
469 $this->helpicon = new old_help_icon($helppage, $title, $component);
f8dab966
PS
470 }
471
472 /**
473 * Set's select lable
474 * @param string $label
475 * @return void
476 */
477 public function set_label($label) {
478 $this->label = $label;
479 }
a9967cf5
PS
480}
481
482
4d10e579
PS
483/**
484 * Simple URL selection widget description.
485 * @copyright 2009 Petr Skoda
486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
487 * @since Moodle 2.0
488 */
489class url_select implements renderable {
490 /**
491 * @var array $urls associative array value=>label ex.:
492 * array(1=>'One, 2=>Two)
493 * it is also possible to specify optgroup as complex label array ex.:
494 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
495 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
496 */
497 var $urls;
498 /**
499 * Selected option
500 * @var string
501 */
502 var $selected;
503 /**
504 * Nothing selected
505 * @var array
506 */
507 var $nothing;
508 /**
509 * Extra select field attributes
510 * @var array
511 */
512 var $attributes = array();
513 /**
514 * Button label
515 * @var string
516 */
517 var $label = '';
518 /**
519 * Wrapping div class
520 * @var string
521 * */
522 var $class = 'urlselect';
523 /**
524 * True if button disabled, false if normal
525 * @var boolean
526 */
527 var $disabled = false;
528 /**
529 * Button tooltip
530 * @var string
531 */
532 var $tooltip = null;
533 /**
534 * Form id
535 * @var string
536 */
537 var $formid = null;
538 /**
539 * List of attached actions
540 * @var array of component_action
541 */
542 var $helpicon = null;
543 /**
544 * Constructor
545 * @param array $urls list of options
546 * @param string $selected selected element
547 * @param array $nothing
548 * @param string $formid
549 */
550 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
551 $this->urls = $urls;
552 $this->selected = $selected;
553 $this->nothing = $nothing;
554 $this->formid = $formid;
555 }
556
557 /**
558 * Constructor: sets up the other components in case they are needed
559 * @param string $page The keyword that defines a help page
560 * @param string $title A descriptive text for accesibility only
561 * @param string $component
562 * @param bool $linktext add extra text to icon
563 * @return void
564 */
596509e4
PS
565 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
566 $this->helpicon = new old_help_icon($helppage, $title, $component);
4d10e579
PS
567 }
568
569 /**
570 * Set's select lable
571 * @param string $label
572 * @return void
573 */
574 public function set_label($label) {
575 $this->label = $label;
576 }
577}
578
579
574fbea4
PS
580/**
581 * Data structure describing html link with special action attached.
582 * @copyright 2010 Petr Skoda
583 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
584 * @since Moodle 2.0
585 */
586class action_link implements renderable {
587 /**
588 * Href url
589 * @var moodle_url
590 */
591 var $url;
592 /**
593 * Link text
594 * @var string HTML fragment
595 */
596 var $text;
597 /**
598 * HTML attributes
599 * @var array
600 */
601 var $attributes;
602 /**
603 * List of actions attached to link
604 * @var array of component_action
605 */
606 var $actions;
607
608 /**
609 * Constructor
610 * @param string|moodle_url $url
611 * @param string $text HTML fragment
612 * @param component_action $action
11820bac 613 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
614 */
615 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
616 $this->url = clone($url);
617 $this->text = $text;
b0fef57b 618 $this->attributes = (array)$attributes;
f14b641b 619 if ($action) {
574fbea4
PS
620 $this->add_action($action);
621 }
622 }
623
624 /**
625 * Add action to the link.
626 * @param component_action $action
627 * @return void
628 */
629 public function add_action(component_action $action) {
630 $this->actions[] = $action;
631 }
c63923bd
PS
632
633 public function add_class($class) {
67da0bf7
DM
634 if (empty($this->attributes['class'])) {
635 $this->attributes['class'] = $class;
c63923bd 636 } else {
67da0bf7 637 $this->attributes['class'] .= ' ' . $class;
c63923bd
PS
638 }
639 }
574fbea4 640}
3ba60ee1 641
227255b8 642// ==== HTML writer and helper classes, will be probably moved elsewhere ======
5d0c95a5
PS
643
644/**
645 * Simple html output class
646 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
647 */
648class html_writer {
649 /**
650 * Outputs a tag with attributes and contents
651 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
5d0c95a5 652 * @param string $contents What goes between the opening and closing tags
26acc814 653 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
5d0c95a5
PS
654 * @return string HTML fragment
655 */
26acc814 656 public static function tag($tagname, $contents, array $attributes = null) {
5d0c95a5
PS
657 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
658 }
659
660 /**
661 * Outputs an opening tag with attributes
662 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
663 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
664 * @return string HTML fragment
665 */
666 public static function start_tag($tagname, array $attributes = null) {
667 return '<' . $tagname . self::attributes($attributes) . '>';
668 }
669
670 /**
671 * Outputs a closing tag
672 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
673 * @return string HTML fragment
674 */
675 public static function end_tag($tagname) {
676 return '</' . $tagname . '>';
677 }
678
679 /**
680 * Outputs an empty tag with attributes
681 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
682 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
683 * @return string HTML fragment
684 */
685 public static function empty_tag($tagname, array $attributes = null) {
686 return '<' . $tagname . self::attributes($attributes) . ' />';
687 }
688
689 /**
690 * Outputs a HTML attribute and value
691 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
692 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
693 * @return string HTML fragment
694 */
695 public static function attribute($name, $value) {
696 if (is_array($value)) {
697 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
698 }
bf11293a
PS
699 if ($value instanceof moodle_url) {
700 return ' ' . $name . '="' . $value->out() . '"';
701 }
97c10099
PS
702
703 // special case, we do not want these in output
704 if ($value === null) {
705 return '';
5d0c95a5 706 }
97c10099
PS
707
708 // no sloppy trimming here!
709 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
710 }
711
712 /**
713 * Outputs a list of HTML attributes and values
714 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
715 * The values will be escaped with {@link s()}
716 * @return string HTML fragment
717 */
718 public static function attributes(array $attributes = null) {
719 $attributes = (array)$attributes;
720 $output = '';
721 foreach ($attributes as $name => $value) {
722 $output .= self::attribute($name, $value);
723 }
724 return $output;
725 }
726
727 /**
728 * Generates random html element id.
729 * @param string $base
730 * @return string
731 */
732 public static function random_id($base='random') {
733 return uniqid($base);
734 }
0f4c64b7
PS
735
736 /**
737 * Generates a simple html link
738 * @param string|moodle_url $url
739 * @param string $text link txt
740 * @param array $attributes extra html attributes
741 * @return string HTML fragment
742 */
743 public static function link($url, $text, array $attributes = null) {
744 $attributes = (array)$attributes;
745 $attributes['href'] = $url;
26acc814 746 return self::tag('a', $text, $attributes);
0f4c64b7 747 }
3ff163c5 748
14dce022
PS
749 /**
750 * generates a simple checkbox with optional label
751 * @param string $name
752 * @param string $value
753 * @param bool $checked
754 * @param string $label
755 * @param array $attributes
756 * @return string html fragment
757 */
758 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
759 $attributes = (array)$attributes;
760 $output = '';
761
762 if ($label !== '' and !is_null($label)) {
763 if (empty($attributes['id'])) {
764 $attributes['id'] = self::random_id('checkbox_');
765 }
766 }
53868425
PS
767 $attributes['type'] = 'checkbox';
768 $attributes['value'] = $value;
769 $attributes['name'] = $name;
14dce022 770 $attributes['checked'] = $checked ? 'selected' : null;
53868425 771
14dce022
PS
772 $output .= self::empty_tag('input', $attributes);
773
774 if ($label !== '' and !is_null($label)) {
26acc814 775 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
14dce022
PS
776 }
777
778 return $output;
779 }
780
78bdac64
PS
781 /**
782 * Generates a simple select yes/no form field
783 * @param string $name name of select element
784 * @param bool $selected
785 * @param array $attributes - html select element attributes
786 * @return string HRML fragment
787 */
19f3bbb2 788 public static function select_yes_no($name, $selected=true, array $attributes = null) {
78bdac64
PS
789 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
790 return self::select($options, $name, $selected, null, $attributes);
791 }
792
3ff163c5
PS
793 /**
794 * Generates a simple select form field
6770330d
PS
795 * @param array $options associative array value=>label ex.:
796 * array(1=>'One, 2=>Two)
797 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 798 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 799 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5
PS
800 * @param string $name name of select element
801 * @param string|array $selected value or arary of values depending on multiple attribute
802 * @param array|bool $nothing, add nothing selected option, or false of not added
803 * @param array $attributes - html select element attributes
78bdac64 804 * @return string HTML fragment
3ff163c5 805 */
aa2dea70 806 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
3ff163c5
PS
807 $attributes = (array)$attributes;
808 if (is_array($nothing)) {
809 foreach ($nothing as $k=>$v) {
4b9210f3 810 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
811 $nothing[$k] = get_string('choosedots');
812 }
813 }
814 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
815
816 } else if (is_string($nothing) and $nothing !== '') {
817 // BC
818 $options = array(''=>$nothing) + $options;
bde156b3 819 }
3ff163c5
PS
820
821 // we may accept more values if multiple attribute specified
822 $selected = (array)$selected;
823 foreach ($selected as $k=>$v) {
824 $selected[$k] = (string)$v;
825 }
826
827 if (!isset($attributes['id'])) {
828 $id = 'menu'.$name;
829 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
830 $id = str_replace('[', '', $id);
831 $id = str_replace(']', '', $id);
832 $attributes['id'] = $id;
833 }
834
835 if (!isset($attributes['class'])) {
836 $class = 'menu'.$name;
837 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
838 $class = str_replace('[', '', $class);
839 $class = str_replace(']', '', $class);
840 $attributes['class'] = $class;
841 }
842 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
843
844 $attributes['name'] = $name;
845
846 $output = '';
847 foreach ($options as $value=>$label) {
6770330d
PS
848 if (is_array($label)) {
849 // ignore key, it just has to be unique
850 $output .= self::select_optgroup(key($label), current($label), $selected);
851 } else {
852 $output .= self::select_option($label, $value, $selected);
3ff163c5 853 }
3ff163c5 854 }
26acc814 855 return self::tag('select', $output, $attributes);
3ff163c5 856 }
6770330d
PS
857
858 private static function select_option($label, $value, array $selected) {
859 $attributes = array();
860 $value = (string)$value;
861 if (in_array($value, $selected, true)) {
862 $attributes['selected'] = 'selected';
863 }
864 $attributes['value'] = $value;
26acc814 865 return self::tag('option', $label, $attributes);
6770330d
PS
866 }
867
868 private static function select_optgroup($groupname, $options, array $selected) {
869 if (empty($options)) {
870 return '';
871 }
872 $attributes = array('label'=>$groupname);
873 $output = '';
874 foreach ($options as $value=>$label) {
875 $output .= self::select_option($label, $value, $selected);
876 }
26acc814 877 return self::tag('optgroup', $output, $attributes);
6770330d 878 }
6ea66ff3 879
f83b9b63
PS
880 /**
881 * This is a shortcut for making an hour selector menu.
882 * @param string $type The type of selector (years, months, days, hours, minutes)
883 * @param string $name fieldname
884 * @param int $currenttime A default timestamp in GMT
885 * @param int $step minute spacing
886 * @param array $attributes - html select element attributes
887 * @return HTML fragment
888 */
889 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
890 if (!$currenttime) {
891 $currenttime = time();
892 }
893 $currentdate = usergetdate($currenttime);
894 $userdatetype = $type;
895 $timeunits = array();
896
897 switch ($type) {
898 case 'years':
899 for ($i=1970; $i<=2020; $i++) {
900 $timeunits[$i] = $i;
901 }
902 $userdatetype = 'year';
903 break;
904 case 'months':
905 for ($i=1; $i<=12; $i++) {
906 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
907 }
908 $userdatetype = 'month';
909 $currentdate['month'] = $currentdate['mon'];
910 break;
911 case 'days':
912 for ($i=1; $i<=31; $i++) {
913 $timeunits[$i] = $i;
914 }
915 $userdatetype = 'mday';
916 break;
917 case 'hours':
918 for ($i=0; $i<=23; $i++) {
919 $timeunits[$i] = sprintf("%02d",$i);
920 }
921 break;
922 case 'minutes':
923 if ($step != 1) {
924 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
925 }
926
927 for ($i=0; $i<=59; $i+=$step) {
928 $timeunits[$i] = sprintf("%02d",$i);
929 }
930 break;
931 default:
932 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
933 }
934
935 if (empty($attributes['id'])) {
936 $attributes['id'] = self::random_id('ts_');
937 }
938 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
26acc814 939 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
f83b9b63
PS
940
941 return $label.$timerselector;
942 }
943
5be262b6
PS
944 /**
945 * Shortcut for quick making of lists
946 * @param array $items
947 * @param string $tag ul or ol
948 * @param array $attributes
949 * @return string
950 */
951 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
952 //note: 'list' is a reserved keyword ;-)
953
954 $output = '';
955
956 foreach ($items as $item) {
957 $output .= html_writer::start_tag('li') . "\n";
958 $output .= $item . "\n";
959 $output .= html_writer::end_tag('li') . "\n";
960 }
961
26acc814 962 return html_writer::tag($tag, $output, $attributes);
5be262b6
PS
963 }
964
6ea66ff3
PS
965 /**
966 * Returns hidden input fields created from url parameters.
967 * @param moodle_url $url
968 * @param array $exclude list of excluded parameters
969 * @return string HTML fragment
970 */
971 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
972 $exclude = (array)$exclude;
973 $params = $url->params();
974 foreach ($exclude as $key) {
975 unset($params[$key]);
976 }
977
978 $output = '';
bde156b3 979 foreach ($params as $key => $value) {
6ea66ff3
PS
980 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
981 $output .= self::empty_tag('input', $attributes)."\n";
982 }
983 return $output;
984 }
77774f6a
PS
985
986 /**
987 * Generate a script tag containing the the specified code.
988 *
989 * @param string $js the JavaScript code
e50b4c89 990 * @param moodle_url|string optional url of the external script, $code ignored if specified
77774f6a
PS
991 * @return string HTML, the code wrapped in <script> tags.
992 */
e50b4c89 993 public static function script($jscode, $url=null) {
77774f6a 994 if ($jscode) {
e50b4c89 995 $attributes = array('type'=>'text/javascript');
26acc814 996 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
e50b4c89
PS
997
998 } else if ($url) {
999 $attributes = array('type'=>'text/javascript', 'src'=>$url);
26acc814 1000 return self::tag('script', '', $attributes) . "\n";
a9967cf5 1001
77774f6a
PS
1002 } else {
1003 return '';
1004 }
1005 }
16be8974
DM
1006
1007 /**
1008 * Renders HTML table
1009 *
1010 * This method may modify the passed instance by adding some default properties if they are not set yet.
1011 * If this is not what you want, you should make a full clone of your data before passing them to this
1012 * method. In most cases this is not an issue at all so we do not clone by default for performance
1013 * and memory consumption reasons.
1014 *
1015 * @param html_table $table data to be rendered
1016 * @return string HTML code
1017 */
1018 public static function table(html_table $table) {
1019 // prepare table data and populate missing properties with reasonable defaults
1020 if (!empty($table->align)) {
1021 foreach ($table->align as $key => $aa) {
1022 if ($aa) {
1023 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1024 } else {
1025 $table->align[$key] = null;
1026 }
1027 }
1028 }
1029 if (!empty($table->size)) {
1030 foreach ($table->size as $key => $ss) {
1031 if ($ss) {
1032 $table->size[$key] = 'width:'. $ss .';';
1033 } else {
1034 $table->size[$key] = null;
1035 }
1036 }
1037 }
1038 if (!empty($table->wrap)) {
1039 foreach ($table->wrap as $key => $ww) {
1040 if ($ww) {
1041 $table->wrap[$key] = 'white-space:nowrap;';
1042 } else {
1043 $table->wrap[$key] = '';
1044 }
1045 }
1046 }
1047 if (!empty($table->head)) {
1048 foreach ($table->head as $key => $val) {
1049 if (!isset($table->align[$key])) {
1050 $table->align[$key] = null;
1051 }
1052 if (!isset($table->size[$key])) {
1053 $table->size[$key] = null;
1054 }
1055 if (!isset($table->wrap[$key])) {
1056 $table->wrap[$key] = null;
1057 }
1058
1059 }
1060 }
1061 if (empty($table->attributes['class'])) {
1062 $table->attributes['class'] = 'generaltable';
1063 }
1064 if (!empty($table->tablealign)) {
1065 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1066 }
1067
1068 // explicitly assigned properties override those defined via $table->attributes
e126c0cc 1069 $table->attributes['class'] = trim($table->attributes['class']);
16be8974
DM
1070 $attributes = array_merge($table->attributes, array(
1071 'id' => $table->id,
1072 'width' => $table->width,
1073 'summary' => $table->summary,
1074 'cellpadding' => $table->cellpadding,
1075 'cellspacing' => $table->cellspacing,
1076 ));
1077 $output = html_writer::start_tag('table', $attributes) . "\n";
1078
1079 $countcols = 0;
1080
1081 if (!empty($table->head)) {
1082 $countcols = count($table->head);
1083 $output .= html_writer::start_tag('thead', array()) . "\n";
1084 $output .= html_writer::start_tag('tr', array()) . "\n";
1085 $keys = array_keys($table->head);
1086 $lastkey = end($keys);
1087
1088 foreach ($table->head as $key => $heading) {
1089 // Convert plain string headings into html_table_cell objects
1090 if (!($heading instanceof html_table_cell)) {
1091 $headingtext = $heading;
1092 $heading = new html_table_cell();
1093 $heading->text = $headingtext;
1094 $heading->header = true;
1095 }
1096
1097 if ($heading->header !== false) {
1098 $heading->header = true;
1099 }
1100
e126c0cc
DM
1101 if ($heading->header && empty($heading->scope)) {
1102 $heading->scope = 'col';
1103 }
1104
16be8974
DM
1105 $heading->attributes['class'] .= ' header c' . $key;
1106 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1107 $heading->colspan = $table->headspan[$key];
1108 $countcols += $table->headspan[$key] - 1;
1109 }
1110
1111 if ($key == $lastkey) {
1112 $heading->attributes['class'] .= ' lastcol';
1113 }
1114 if (isset($table->colclasses[$key])) {
1115 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1116 }
e126c0cc 1117 $heading->attributes['class'] = trim($heading->attributes['class']);
16be8974
DM
1118 $attributes = array_merge($heading->attributes, array(
1119 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1120 'scope' => $heading->scope,
1121 'colspan' => $heading->colspan,
1122 ));
1123
1124 $tagtype = 'td';
1125 if ($heading->header === true) {
1126 $tagtype = 'th';
1127 }
1128 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1129 }
1130 $output .= html_writer::end_tag('tr') . "\n";
1131 $output .= html_writer::end_tag('thead') . "\n";
1132
1133 if (empty($table->data)) {
1134 // For valid XHTML strict every table must contain either a valid tr
1135 // or a valid tbody... both of which must contain a valid td
1136 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1137 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1138 $output .= html_writer::end_tag('tbody');
1139 }
1140 }
1141
1142 if (!empty($table->data)) {
1143 $oddeven = 1;
1144 $keys = array_keys($table->data);
1145 $lastrowkey = end($keys);
1146 $output .= html_writer::start_tag('tbody', array());
1147
1148 foreach ($table->data as $key => $row) {
1149 if (($row === 'hr') && ($countcols)) {
1150 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1151 } else {
1152 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1153 if (!($row instanceof html_table_row)) {
1154 $newrow = new html_table_row();
1155
e126c0cc 1156 foreach ($row as $item) {
16be8974
DM
1157 $cell = new html_table_cell();
1158 $cell->text = $item;
1159 $newrow->cells[] = $cell;
1160 }
1161 $row = $newrow;
1162 }
1163
1164 $oddeven = $oddeven ? 0 : 1;
1165 if (isset($table->rowclasses[$key])) {
1166 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1167 }
1168
1169 $row->attributes['class'] .= ' r' . $oddeven;
1170 if ($key == $lastrowkey) {
1171 $row->attributes['class'] .= ' lastrow';
1172 }
1173
e126c0cc 1174 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
16be8974
DM
1175 $keys2 = array_keys($row->cells);
1176 $lastkey = end($keys2);
1177
1178 foreach ($row->cells as $key => $cell) {
1179 if (!($cell instanceof html_table_cell)) {
1180 $mycell = new html_table_cell();
1181 $mycell->text = $cell;
1182 $cell = $mycell;
1183 }
1184
e126c0cc
DM
1185 if (($cell->header === true) && empty($cell->scope)) {
1186 $cell->scope = 'row';
1187 }
1188
16be8974
DM
1189 if (isset($table->colclasses[$key])) {
1190 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1191 }
1192
1193 $cell->attributes['class'] .= ' cell c' . $key;
1194 if ($key == $lastkey) {
1195 $cell->attributes['class'] .= ' lastcol';
1196 }
1197 $tdstyle = '';
1198 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1199 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1200 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1201 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1202 $tdattributes = array_merge($cell->attributes, array(
1203 'style' => $tdstyle . $cell->style,
1204 'colspan' => $cell->colspan,
1205 'rowspan' => $cell->rowspan,
1206 'id' => $cell->id,
1207 'abbr' => $cell->abbr,
1208 'scope' => $cell->scope,
1209 ));
1210 $tagtype = 'td';
1211 if ($cell->header === true) {
1212 $tagtype = 'th';
1213 }
1214 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1215 }
1216 }
1217 $output .= html_writer::end_tag('tr') . "\n";
1218 }
1219 $output .= html_writer::end_tag('tbody') . "\n";
1220 }
1221 $output .= html_writer::end_tag('table') . "\n";
1222
1223 return $output;
1224 }
1225
5d0c95a5
PS
1226}
1227
227255b8
PS
1228// ==== JS writer and helper classes, will be probably moved elsewhere ======
1229
1230/**
1231 * Simple javascript output class
1232 * @copyright 2010 Petr Skoda
1233 */
1234class js_writer {
1235 /**
1236 * Returns javascript code calling the function
1237 * @param string $function function name, can be complex lin Y.Event.purgeElement
1238 * @param array $arguments parameters
1239 * @param int $delay execution delay in seconds
1240 * @return string JS code fragment
1241 */
1242 public function function_call($function, array $arguments = null, $delay=0) {
1b4e41af
PS
1243 if ($arguments) {
1244 $arguments = array_map('json_encode', $arguments);
1245 $arguments = implode(', ', $arguments);
1246 } else {
1247 $arguments = '';
1248 }
227255b8
PS
1249 $js = "$function($arguments);";
1250
1251 if ($delay) {
1252 $delay = $delay * 1000; // in miliseconds
1253 $js = "setTimeout(function() { $js }, $delay);";
1254 }
1255 return $js . "\n";
1256 }
1257
3b01539c
PS
1258 /**
1259 * Special function which adds Y as first argument of fucntion call.
1260 * @param string $function
1261 * @param array $extraarguments
1262 * @return string
1263 */
1264 public function function_call_with_Y($function, array $extraarguments = null) {
1265 if ($extraarguments) {
1266 $extraarguments = array_map('json_encode', $extraarguments);
1267 $arguments = 'Y, ' . implode(', ', $extraarguments);
1268 } else {
1269 $arguments = 'Y';
1270 }
1271 return "$function($arguments);\n";
1272 }
1273
1ce15fda
SH
1274 /**
1275 * Returns JavaScript code to initialise a new object
1276 * @param string|null $var If it is null then no var is assigned the new object
1277 * @param string $class
1278 * @param array $arguments
1279 * @param array $requirements
1280 * @param int $delay
1281 * @return string
1282 */
1283 public function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1284 if (is_array($arguments)) {
1285 $arguments = array_map('json_encode', $arguments);
1286 $arguments = implode(', ', $arguments);
1287 }
1288
1289 if ($var === null) {
53fc3e70 1290 $js = "new $class(Y, $arguments);";
1ce15fda 1291 } else if (strpos($var, '.')!==false) {
53fc3e70 1292 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1293 } else {
53fc3e70 1294 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1295 }
1296
1297 if ($delay) {
1298 $delay = $delay * 1000; // in miliseconds
1299 $js = "setTimeout(function() { $js }, $delay);";
1300 }
1301
1302 if (count($requirements) > 0) {
1303 $requirements = implode("', '", $requirements);
53fc3e70 1304 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1305 }
1306 return $js."\n";
1307 }
1308
227255b8
PS
1309 /**
1310 * Returns code setting value to variable
1311 * @param string $name
1312 * @param mixed $value json serialised value
1313 * @param bool $usevar add var definition, ignored for nested properties
1314 * @return string JS code fragment
1315 */
1316 public function set_variable($name, $value, $usevar=true) {
1317 $output = '';
1318
1319 if ($usevar) {
1320 if (strpos($name, '.')) {
1321 $output .= '';
1322 } else {
1323 $output .= 'var ';
1324 }
1325 }
1326
1327 $output .= "$name = ".json_encode($value).";";
1328
1329 return $output;
1330 }
1331
1332 /**
1333 * Writes event handler attaching code
1334 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
1335 * @param string $event A valid DOM event (click, mousedown, change etc.)
1336 * @param string $function The name of the function to call
1337 * @param array $arguments An optional array of argument parameters to pass to the function
1338 * @return string JS code fragment
1339 */
1340 public function event_handler($selector, $event, $function, array $arguments = null) {
1341 $selector = json_encode($selector);
1342 $output = "Y.on('$event', $function, $selector, null";
1343 if (!empty($arguments)) {
1344 $output .= ', ' . json_encode($arguments);
1345 }
1346 return $output . ");\n";
1347 }
1348}
1349
d9c8f425 1350/**
16be8974 1351 * Holds all the information required to render a <table> by {@see core_renderer::table()}
d9c8f425 1352 *
16be8974
DM
1353 * Example of usage:
1354 * $t = new html_table();
1355 * ... // set various properties of the object $t as described below
1356 * echo html_writer::table($t);
d9c8f425 1357 *
16be8974 1358 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
d9c8f425 1359 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1360 * @since Moodle 2.0
1361 */
16be8974 1362class html_table {
d9c8f425 1363 /**
16be8974 1364 * @var string value to use for the id attribute of the table
d9c8f425 1365 */
97c10099 1366 public $id = null;
d9c8f425 1367 /**
16be8974 1368 * @var array attributes of HTML attributes for the <table> element
d9c8f425 1369 */
16be8974 1370 public $attributes = array();
7b1f2c82 1371 /**
a0ead5eb 1372 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1373 * can be passed instead of an array of strings.
7b1f2c82 1374 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1375 *
1376 * Example of usage:
1377 * $t->head = array('Student', 'Grade');
1378 */
1379 public $head;
1380 /**
1381 * @var array can be used to make a heading span multiple columns
1382 *
1383 * Example of usage:
1384 * $t->headspan = array(2,1);
1385 *
1386 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1387 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1388 */
1389 public $headspan;
1390 /**
1391 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1392 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1393 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1394 *
beb56299 1395 * Examples of usage:
1396 * $t->align = array(null, 'right');
1397 * or
1398 * $t->align[1] = 'right';
1399 *
d9c8f425 1400 */
beb56299 1401 public $align;
d9c8f425 1402 /**
beb56299 1403 * @var array of column sizes. The value is used as CSS 'size' property.
1404 *
1405 * Examples of usage:
1406 * $t->size = array('50%', '50%');
1407 * or
1408 * $t->size[1] = '120px';
d9c8f425 1409 */
beb56299 1410 public $size;
d9c8f425 1411 /**
beb56299 1412 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1413 * CSS property 'white-space' to the value 'nowrap' in the given column.
1414 *
1415 * Example of usage:
1416 * $t->wrap = array(null, 'nowrap');
d9c8f425 1417 */
beb56299 1418 public $wrap;
d9c8f425 1419 /**
beb56299 1420 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1421 * $head specified, the string 'hr' (for horizontal ruler) can be used
1422 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1423 *
beb56299 1424 * Example of usage with array of arrays:
1425 * $row1 = array('Harry Potter', '76 %');
1426 * $row2 = array('Hermione Granger', '100 %');
1427 * $t->data = array($row1, $row2);
d9c8f425 1428 *
beb56299 1429 * Example with array of html_table_row objects: (used for more fine-grained control)
1430 * $cell1 = new html_table_cell();
1431 * $cell1->text = 'Harry Potter';
1432 * $cell1->colspan = 2;
1433 * $row1 = new html_table_row();
1434 * $row1->cells[] = $cell1;
1435 * $cell2 = new html_table_cell();
1436 * $cell2->text = 'Hermione Granger';
1437 * $cell3 = new html_table_cell();
1438 * $cell3->text = '100 %';
1439 * $row2 = new html_table_row();
1440 * $row2->cells = array($cell2, $cell3);
1441 * $t->data = array($row1, $row2);
1442 */
1443 public $data;
1444 /**
16be8974 1445 * @var string width of the table, percentage of the page preferred. Defaults to 80%
beb56299 1446 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1447 */
1448 public $width = null;
1449 /**
1450 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1451 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1452 */
1453 public $tablealign = null;
1454 /**
1455 * @var int padding on each cell, in pixels
1456 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1457 */
1458 public $cellpadding = null;
1459 /**
1460 * @var int spacing between cells, in pixels
1461 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1462 */
1463 public $cellspacing = null;
1464 /**
1465 * @var array classes to add to particular rows, space-separated string.
1466 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1467 * respectively. Class 'lastrow' is added automatically for the last row
1468 * in the table.
d9c8f425 1469 *
beb56299 1470 * Example of usage:
1471 * $t->rowclasses[9] = 'tenth'
1472 */
1473 public $rowclasses;
1474 /**
1475 * @var array classes to add to every cell in a particular column,
1476 * space-separated string. Class 'cell' is added automatically by the renderer.
1477 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1478 * respectively. Class 'lastcol' is added automatically for all last cells
1479 * in a row.
d9c8f425 1480 *
beb56299 1481 * Example of usage:
1482 * $t->colclasses = array(null, 'grade');
d9c8f425 1483 */
beb56299 1484 public $colclasses;
1485 /**
1486 * @var string description of the contents for screen readers.
1487 */
1488 public $summary;
d9c8f425 1489
1490 /**
16be8974 1491 * Constructor
d9c8f425 1492 */
16be8974
DM
1493 public function __construct() {
1494 $this->attributes['class'] = '';
d9c8f425 1495 }
d9c8f425 1496}
1497
34059565 1498
d9c8f425 1499/**
7b1f2c82 1500 * Component representing a table row.
d9c8f425 1501 *
1502 * @copyright 2009 Nicolas Connault
1503 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1504 * @since Moodle 2.0
1505 */
16be8974
DM
1506class html_table_row {
1507 /**
1508 * @var string value to use for the id attribute of the row
1509 */
1510 public $id = null;
d9c8f425 1511 /**
7b1f2c82 1512 * @var array $cells Array of html_table_cell objects
d9c8f425 1513 */
7b1f2c82 1514 public $cells = array();
beb56299 1515 /**
16be8974 1516 * @var string $style value to use for the style attribute of the table row
beb56299 1517 */
16be8974
DM
1518 public $style = null;
1519 /**
1520 * @var array attributes of additional HTML attributes for the <tr> element
1521 */
1522 public $attributes = array();
a0ead5eb 1523
54a007e8 1524 /**
8cea545e 1525 * Constructor
54a007e8 1526 * @param array $cells
8cea545e
PS
1527 */
1528 public function __construct(array $cells=null) {
16be8974 1529 $this->attributes['class'] = '';
8cea545e
PS
1530 $cells = (array)$cells;
1531 foreach ($cells as $cell) {
1532 if ($cell instanceof html_table_cell) {
1533 $this->cells[] = $cell;
a019627a 1534 } else {
8cea545e 1535 $this->cells[] = new html_table_cell($cell);
a019627a 1536 }
1537 }
54a007e8 1538 }
d9c8f425 1539}
1540
34059565 1541
d9c8f425 1542/**
7b1f2c82 1543 * Component representing a table cell.
d9c8f425 1544 *
1545 * @copyright 2009 Nicolas Connault
1546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1547 * @since Moodle 2.0
1548 */
16be8974
DM
1549class html_table_cell {
1550 /**
1551 * @var string value to use for the id attribute of the cell
1552 */
1553 public $id = null;
d9c8f425 1554 /**
7b1f2c82 1555 * @var string $text The contents of the cell
d9c8f425 1556 */
7b1f2c82 1557 public $text;
d9c8f425 1558 /**
7b1f2c82 1559 * @var string $abbr Abbreviated version of the contents of the cell
d9c8f425 1560 */
97c10099 1561 public $abbr = null;
d9c8f425 1562 /**
7b1f2c82 1563 * @var int $colspan Number of columns this cell should span
d9c8f425 1564 */
97c10099 1565 public $colspan = null;
d9c8f425 1566 /**
7b1f2c82 1567 * @var int $rowspan Number of rows this cell should span
d9c8f425 1568 */
97c10099 1569 public $rowspan = null;
d9c8f425 1570 /**
7b1f2c82 1571 * @var string $scope Defines a way to associate header cells and data cells in a table
d9c8f425 1572 */
97c10099 1573 public $scope = null;
1ae3767a 1574 /**
1575 * @var boolean $header Whether or not this cell is a header cell
1576 */
a4998d01 1577 public $header = null;
16be8974
DM
1578 /**
1579 * @var string $style value to use for the style attribute of the table cell
1580 */
1581 public $style = null;
1582 /**
1583 * @var array attributes of additional HTML attributes for the <tr> element
1584 */
1585 public $attributes = array();
d9c8f425 1586
8cea545e
PS
1587 public function __construct($text = null) {
1588 $this->text = $text;
16be8974 1589 $this->attributes['class'] = '';
d9c8f425 1590 }
1591}
1592
34059565 1593
7b1f2c82 1594/// Complex components aggregating simpler components
1595
34059565 1596
d9c8f425 1597/**
beb56299 1598 * Component representing a paging bar.
d9c8f425 1599 *
1600 * @copyright 2009 Nicolas Connault
1601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1602 * @since Moodle 2.0
1603 */
929d7a83 1604class paging_bar implements renderable {
d9c8f425 1605 /**
beb56299 1606 * @var int $maxdisplay The maximum number of pagelinks to display
d9c8f425 1607 */
beb56299 1608 public $maxdisplay = 18;
d9c8f425 1609 /**
beb56299 1610 * @var int $totalcount post or get
d9c8f425 1611 */
beb56299 1612 public $totalcount;
d9c8f425 1613 /**
beb56299 1614 * @var int $page The page you are currently viewing
d9c8f425 1615 */
929d7a83 1616 public $page;
d9c8f425 1617 /**
beb56299 1618 * @var int $perpage The number of entries that should be shown per page
d9c8f425 1619 */
beb56299 1620 public $perpage;
d9c8f425 1621 /**
beb56299 1622 * @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.
1623 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 1624 */
beb56299 1625 public $baseurl;
d9c8f425 1626 /**
beb56299 1627 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 1628 */
929d7a83 1629 public $pagevar;
beb56299 1630 /**
56ddb719 1631 * @var string $previouslink A HTML link representing the "previous" page
beb56299 1632 */
1633 public $previouslink = null;
1634 /**
56ddb719 1635 * @var tring $nextlink A HTML link representing the "next" page
beb56299 1636 */
1637 public $nextlink = null;
1638 /**
56ddb719 1639 * @var tring $firstlink A HTML link representing the first page
beb56299 1640 */
1641 public $firstlink = null;
1642 /**
56ddb719 1643 * @var tring $lastlink A HTML link representing the last page
beb56299 1644 */
1645 public $lastlink = null;
1646 /**
56ddb719 1647 * @var array $pagelinks An array of strings. One of them is just a string: the current page
beb56299 1648 */
1649 public $pagelinks = array();
d9c8f425 1650
929d7a83
PS
1651 /**
1652 * Constructor paging_bar with only the required params.
1653 *
1654 * @param int $totalcount Thetotal number of entries available to be paged through
1655 * @param int $page The page you are currently viewing
1656 * @param int $perpage The number of entries that should be shown per page
1657 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1658 * @param string $pagevar name of page parameter that holds the page number
1659 */
1660 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1661 $this->totalcount = $totalcount;
1662 $this->page = $page;
1663 $this->perpage = $perpage;
1664 $this->baseurl = $baseurl;
1665 $this->pagevar = $pagevar;
1666 }
1667
d9c8f425 1668 /**
d9c8f425 1669 * @return void
1670 */
34059565 1671 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 1672 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 1673 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 1674 }
1675 if (!isset($this->page) || is_null($this->page)) {
929d7a83 1676 throw new coding_exception('paging_bar requires a page value.');
beb56299 1677 }
1678 if (empty($this->perpage)) {
929d7a83 1679 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 1680 }
1681 if (empty($this->baseurl)) {
929d7a83 1682 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 1683 }
d9c8f425 1684
beb56299 1685 if ($this->totalcount > $this->perpage) {
1686 $pagenum = $this->page - 1;
d9c8f425 1687
beb56299 1688 if ($this->page > 0) {
929d7a83 1689 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 1690 }
d9c8f425 1691
beb56299 1692 if ($this->perpage > 0) {
1693 $lastpage = ceil($this->totalcount / $this->perpage);
1694 } else {
1695 $lastpage = 1;
1696 }
1697
1698 if ($this->page > 15) {
1699 $startpage = $this->page - 10;
1700
929d7a83 1701 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 1702 } else {
1703 $startpage = 0;
1704 }
1705
1706 $currpage = $startpage;
1707 $displaycount = $displaypage = 0;
1708
1709 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1710 $displaypage = $currpage + 1;
1711
f43cdceb 1712 if ($this->page == $currpage) {
beb56299 1713 $this->pagelinks[] = $displaypage;
1714 } else {
56ddb719 1715 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 1716 $this->pagelinks[] = $pagelink;
1717 }
1718
1719 $displaycount++;
1720 $currpage++;
1721 }
1722
1723 if ($currpage < $lastpage) {
1724 $lastpageactual = $lastpage - 1;
abdac127 1725 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 1726 }
1727
1728 $pagenum = $this->page + 1;
1729
1730 if ($pagenum != $displaypage) {
abdac127 1731 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 1732 }
d9c8f425 1733 }
1734 }
d9c8f425 1735}
1736
34059565 1737
d9c8f425 1738/**
beb56299 1739 * This class represents how a block appears on a page.
d9c8f425 1740 *
beb56299 1741 * During output, each block instance is asked to return a block_contents object,
1742 * those are then passed to the $OUTPUT->block function for display.
1743 *
1744 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
1745 *
1746 * Other block-like things that need to appear on the page, for example the
1747 * add new block UI, are also represented as block_contents objects.
1748 *
1749 * @copyright 2009 Tim Hunt
d9c8f425 1750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1751 * @since Moodle 2.0
1752 */
dd72b308 1753class block_contents {
beb56299 1754 /** @var int used to set $skipid. */
1755 protected static $idcounter = 1;
1756
1757 const NOT_HIDEABLE = 0;
1758 const VISIBLE = 1;
1759 const HIDDEN = 2;
1760
d9c8f425 1761 /**
dd72b308 1762 * @var integer $skipid All the blocks (or things that look like blocks)
beb56299 1763 * printed on a page are given a unique number that can be used to construct
1764 * id="" attributes. This is set automatically be the {@link prepare()} method.
1765 * Do not try to set it manually.
d9c8f425 1766 */
beb56299 1767 public $skipid;
d9c8f425 1768
1769 /**
beb56299 1770 * @var integer If this is the contents of a real block, this should be set to
1771 * the block_instance.id. Otherwise this should be set to 0.
1772 */
1773 public $blockinstanceid = 0;
1774
1775 /**
1776 * @var integer if this is a real block instance, and there is a corresponding
1777 * block_position.id for the block on this page, this should be set to that id.
1778 * Otherwise it should be 0.
1779 */
1780 public $blockpositionid = 0;
1781
1782 /**
1783 * @param array $attributes an array of attribute => value pairs that are put on the
1784 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
1785 */
dd72b308 1786 public $attributes;
beb56299 1787
1788 /**
1789 * @param string $title The title of this block. If this came from user input,
1790 * it should already have had format_string() processing done on it. This will
1791 * be output inside <h2> tags. Please do not cause invalid XHTML.
1792 */
1793 public $title = '';
1794
1795 /**
1796 * @param string $content HTML for the content
1797 */
1798 public $content = '';
1799
1800 /**
1801 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1802 */
1803 public $footer = '';
1804
1805 /**
1806 * Any small print that should appear under the block to explain to the
1807 * teacher about the block, for example 'This is a sticky block that was
1808 * added in the system context.'
1809 * @var string
1810 */
1811 public $annotation = '';
1812
1813 /**
1814 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
1815 * the user can toggle whether this block is visible.
1816 */
1817 public $collapsible = self::NOT_HIDEABLE;
1818
1819 /**
1820 * A (possibly empty) array of editing controls. Each element of this array
1821 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 1822 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 1823 * @var array
1824 */
1825 public $controls = array();
1826
dd72b308 1827
beb56299 1828 /**
dd72b308
PS
1829 * Create new instance of block content
1830 * @param array $attributes
d9c8f425 1831 */
dd72b308 1832 public function __construct(array $attributes=null) {
beb56299 1833 $this->skipid = self::$idcounter;
1834 self::$idcounter += 1;
dd72b308
PS
1835
1836 if ($attributes) {
1837 // standard block
1838 $this->attributes = $attributes;
1839 } else {
1840 // simple "fake" blocks used in some modules and "Add new block" block
1841 $this->attributes = array('class'=>'sideblock');
beb56299 1842 }
dd72b308
PS
1843 }
1844
1845 /**
1846 * Add html class to block
1847 * @param string $class
1848 * @return void
1849 */
1850 public function add_class($class) {
1851 $this->attributes['class'] .= ' '.$class;
d9c8f425 1852 }
1853}
beb56299 1854
34059565 1855
beb56299 1856/**
1857 * This class represents a target for where a block can go when it is being moved.
1858 *
1859 * This needs to be rendered as a form with the given hidden from fields, and
1860 * clicking anywhere in the form should submit it. The form action should be
1861 * $PAGE->url.
1862 *
1863 * @copyright 2009 Tim Hunt
1864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1865 * @since Moodle 2.0
1866 */
dd72b308 1867class block_move_target {
beb56299 1868 /**
dd72b308
PS
1869 * Move url
1870 * @var moodle_url
beb56299 1871 */
dd72b308 1872 public $url;
beb56299 1873 /**
dd72b308
PS
1874 * label
1875 * @var string
beb56299 1876 */
dd72b308
PS
1877 public $text;
1878
1879 /**
1880 * Cosntructor
1881 * @param string $text
1882 * @param moodle_url $url
1883 */
1884 public function __construct($text, moodle_url $url) {
1885 $this->text = $text;
1886 $this->url = $url;
1887 }
beb56299 1888}