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