weekly release 2.2dev
[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 *
78bfb562
PS
24 * @package core
25 * @subpackage lib
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d9c8f425 28 */
29
78bfb562 30defined('MOODLE_INTERNAL') || die();
5d0c95a5
PS
31
32/**
33 * Interface marking other classes as suitable for renderer_base::render()
34 * @author 2010 Petr Skoda (skodak) info@skodak.org
35 */
36interface renderable {
37 // intentionally empty
38}
39
bb496de7
DC
40/**
41 * Data structure representing a file picker.
42 *
43 * @copyright 2010 Dongsheng Cai
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 * @since Moodle 2.0
46 */
47class file_picker implements renderable {
48 public $options;
49 public function __construct(stdClass $options) {
50 global $CFG, $USER, $PAGE;
51 require_once($CFG->dirroot. '/repository/lib.php');
52 $defaults = array(
53 'accepted_types'=>'*',
bb496de7
DC
54 'return_types'=>FILE_INTERNAL,
55 'env' => 'filepicker',
56 'client_id' => uniqid(),
57 'itemid' => 0,
58 'maxbytes'=>-1,
59 'maxfiles'=>1,
f50a61fb 60 'buttonname'=>false
bb496de7
DC
61 );
62 foreach ($defaults as $key=>$value) {
63 if (empty($options->$key)) {
64 $options->$key = $value;
65 }
66 }
67
68 $options->currentfile = '';
69 if (!empty($options->itemid)) {
70 $fs = get_file_storage();
71 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
e4256380 72 if (empty($options->filename)) {
64f93798 73 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
e4256380
DC
74 $file = reset($files);
75 }
76 } else {
64f93798 77 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
e4256380
DC
78 }
79 if (!empty($file)) {
ee9a4962 80 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
bb496de7
DC
81 }
82 }
83
bb496de7
DC
84 // initilise options, getting files in root path
85 $this->options = initialise_filepicker($options);
86
87 // copying other options
88 foreach ($options as $name=>$value) {
98e7ae63
DC
89 if (!isset($this->options->$name)) {
90 $this->options->$name = $value;
91 }
bb496de7
DC
92 }
93 }
94}
95
5d0c95a5 96/**
bf11293a 97 * Data structure representing a user picture.
5d0c95a5
PS
98 *
99 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
101 * @since Moodle 2.0
102 */
103class user_picture implements renderable {
104 /**
3a11c09f 105 * @var array List of mandatory fields in user record here. (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
5d0c95a5 106 */
3a11c09f 107 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
5d0c95a5
PS
108
109 /**
3a11c09f 110 * @var object $user A user object with at least fields all columns specified in $fields array constant set.
5d0c95a5
PS
111 */
112 public $user;
113 /**
114 * @var int $courseid The course id. Used when constructing the link to the user's profile,
115 * page course id used if not specified.
116 */
117 public $courseid;
118 /**
119 * @var bool $link add course profile link to image
120 */
121 public $link = true;
122 /**
123 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
124 */
125 public $size = 35;
126 /**
127 * @var boolean $alttext add non-blank alt-text to the image.
128 * Default true, set to false when image alt just duplicates text in screenreaders.
129 */
130 public $alttext = true;
131 /**
132 * @var boolean $popup Whether or not to open the link in a popup window.
133 */
134 public $popup = false;
135 /**
136 * @var string Image class attribute
137 */
138 public $class = 'userpicture';
139
140 /**
141 * User picture constructor.
142 *
143 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
144 * @param array $options such as link, size, link, ...
145 */
146 public function __construct(stdClass $user) {
147 global $DB;
148
5d0c95a5
PS
149 if (empty($user->id)) {
150 throw new coding_exception('User id is required when printing user avatar image.');
151 }
152
153 // only touch the DB if we are missing data and complain loudly...
154 $needrec = false;
3a11c09f 155 foreach (self::$fields as $field) {
5d0c95a5
PS
156 if (!array_key_exists($field, $user)) {
157 $needrec = true;
158 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
159 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
160 break;
161 }
162 }
163
164 if ($needrec) {
3a11c09f 165 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
5d0c95a5
PS
166 } else {
167 $this->user = clone($user);
168 }
169 }
170
171 /**
1a10840e 172 * Returns a list of required user fields, useful when fetching required user info from db.
f3afba4e
PS
173 *
174 * In some cases we have to fetch the user data together with some other information,
175 * the idalias is useful there because the id would otherwise override the main
176 * id of the result record. Please note it has to be converted back to id before rendering.
177 *
5d0c95a5 178 * @param string $tableprefix name of database table prefix in query
3a11c09f 179 * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
f3afba4e 180 * @param string $idalias alias of id field
9958e561 181 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
5d0c95a5
PS
182 * @return string
183 */
9958e561 184 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
3a11c09f
PS
185 if (!$tableprefix and !$extrafields and !$idalias) {
186 return implode(',', self::$fields);
5d0c95a5 187 }
3a11c09f
PS
188 if ($tableprefix) {
189 $tableprefix .= '.';
190 }
191 $fields = array();
192 foreach (self::$fields as $field) {
193 if ($field === 'id' and $idalias and $idalias !== 'id') {
6f7b89e2 194 $fields[$field] = "$tableprefix$field AS $idalias";
3a11c09f 195 } else {
9958e561
DM
196 if ($fieldprefix and $field !== 'id') {
197 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
198 } else {
199 $fields[$field] = "$tableprefix$field";
200 }
3a11c09f
PS
201 }
202 }
203 // add extra fields if not already there
204 if ($extrafields) {
205 foreach ($extrafields as $e) {
206 if ($e === 'id' or isset($fields[$e])) {
207 continue;
208 }
5c0d03ea
DM
209 if ($fieldprefix) {
210 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
211 } else {
212 $fields[$e] = "$tableprefix$e";
213 }
f3afba4e 214 }
f3afba4e
PS
215 }
216 return implode(',', $fields);
5d0c95a5 217 }
5d0c95a5 218
5c0d03ea
DM
219 /**
220 * Extract the aliased user fields from a given record
221 *
222 * Given a record that was previously obtained using {@link self::fields()} with aliases,
223 * this method extracts user related unaliased fields.
224 *
225 * @param stdClass $record containing user picture fields
226 * @param array $extrafields extra fields included in the $record
227 * @param string $idalias alias of the id field
228 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
229 * @return stdClass object with unaliased user fields
230 */
231 public static function unalias(stdClass $record, array $extrafields=null, $idalias='id', $fieldprefix='') {
232
233 if (empty($idalias)) {
234 $idalias = 'id';
235 }
236
237 $return = new stdClass();
238
239 foreach (self::$fields as $field) {
240 if ($field === 'id') {
9ecbf801 241 if (property_exists($record, $idalias)) {
5c0d03ea
DM
242 $return->id = $record->{$idalias};
243 }
244 } else {
9ecbf801 245 if (property_exists($record, $fieldprefix.$field)) {
5c0d03ea
DM
246 $return->{$field} = $record->{$fieldprefix.$field};
247 }
248 }
249 }
250 // add extra fields if not already there
251 if ($extrafields) {
252 foreach ($extrafields as $e) {
9ecbf801 253 if ($e === 'id' or property_exists($return, $e)) {
5c0d03ea
DM
254 continue;
255 }
256 $return->{$e} = $record->{$fieldprefix.$e};
257 }
258 }
259
260 return $return;
261 }
262}
bf11293a
PS
263
264/**
265 * Data structure representing a help icon.
266 *
267 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
269 * @since Moodle 2.0
270 */
596509e4 271class old_help_icon implements renderable {
bf11293a 272 /**
49f0d481 273 * @var string $helpidentifier lang pack identifier
bf11293a 274 */
53a78cef 275 public $helpidentifier;
bf11293a
PS
276 /**
277 * @var string $title A descriptive text for title tooltip
278 */
97c10099 279 public $title = null;
bf11293a
PS
280 /**
281 * @var string $component Component name, the same as in get_string()
282 */
283 public $component = 'moodle';
284 /**
285 * @var string $linktext Extra descriptive text next to the icon
286 */
97c10099 287 public $linktext = null;
bf11293a
PS
288
289 /**
290 * Constructor: sets up the other components in case they are needed
53a78cef 291 * @param string $helpidentifier The keyword that defines a help page
1a10840e 292 * @param string $title A descriptive text for accessibility only
bf11293a
PS
293 * @param string $component
294 * @param bool $linktext add extra text to icon
295 * @return void
296 */
53a78cef 297 public function __construct($helpidentifier, $title, $component = 'moodle') {
bf11293a
PS
298 if (empty($title)) {
299 throw new coding_exception('A help_icon object requires a $text parameter');
300 }
53a78cef
PS
301 if (empty($helpidentifier)) {
302 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
bf11293a
PS
303 }
304
53a78cef
PS
305 $this->helpidentifier = $helpidentifier;
306 $this->title = $title;
307 $this->component = $component;
bf11293a
PS
308 }
309}
310
49f0d481
PS
311/**
312 * Data structure representing a help icon.
313 *
314 * @copyright 2010 Petr Skoda (info@skodak.org)
315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
316 * @since Moodle 2.0
317 */
318class help_icon implements renderable {
319 /**
5435c9dc
MD
320 * @var string $identifier lang pack identifier (without the "_help" suffix),
321 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
49f0d481
PS
322 * must exist.
323 */
324 public $identifier;
325 /**
326 * @var string $component Component name, the same as in get_string()
327 */
328 public $component;
329 /**
330 * @var string $linktext Extra descriptive text next to the icon
331 */
332 public $linktext = null;
333
334 /**
335 * Constructor
336 * @param string $identifier string for help page title,
5435c9dc
MD
337 * string with _help suffix is used for the actual help text.
338 * string with _link suffix is used to create a link to further info (if it exists)
49f0d481
PS
339 * @param string $component
340 */
259c165d
PS
341 public function __construct($identifier, $component) {
342 $this->identifier = $identifier;
49f0d481
PS
343 $this->component = $component;
344 }
259c165d
PS
345
346 /**
347 * Verifies that both help strings exists, shows debug warnings if not
348 */
349 public function diag_strings() {
350 $sm = get_string_manager();
351 if (!$sm->string_exists($this->identifier, $this->component)) {
352 debugging("Help title string does not exist: [$this->identifier, $this->component]");
353 }
5435c9dc 354 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
876521ac 355 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
259c165d
PS
356 }
357 }
49f0d481
PS
358}
359
bf11293a 360
000c278c
PS
361/**
362 * Data structure representing an icon.
363 *
364 * @copyright 2010 Petr Skoda
365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
366 * @since Moodle 2.0
367 */
368class pix_icon implements renderable {
369 var $pix;
370 var $component;
371 var $attributes = array();
372
373 /**
374 * Constructor
375 * @param string $pix short icon name
7749e187 376 * @param string $alt The alt text to use for the icon
000c278c
PS
377 * @param string $component component name
378 * @param array $attributes html attributes
379 */
380 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
c80877aa
PS
381 $this->pix = $pix;
382 $this->component = $component;
000c278c
PS
383 $this->attributes = (array)$attributes;
384
385 $this->attributes['alt'] = $alt;
386 if (empty($this->attributes['class'])) {
387 $this->attributes['class'] = 'smallicon';
388 }
389 if (!isset($this->attributes['title'])) {
390 $this->attributes['title'] = $this->attributes['alt'];
391 }
392 }
393}
394
d63c5073
DM
395/**
396 * Data structure representing an emoticon image
397 *
398 * @since Moodle 2.0
399 */
400class pix_emoticon extends pix_icon implements renderable {
401
402 /**
403 * Constructor
404 * @param string $pix short icon name
b9fadae7
DM
405 * @param string $alt alternative text
406 * @param string $component emoticon image provider
407 * @param array $attributes explicit HTML attributes
d63c5073 408 */
b9fadae7
DM
409 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
410 if (empty($attributes['class'])) {
411 $attributes['class'] = 'emoticon';
412 }
d63c5073
DM
413 parent::__construct($pix, $alt, $component, $attributes);
414 }
415}
000c278c 416
3ba60ee1
PS
417/**
418 * Data structure representing a simple form with only one button.
419 *
420 * @copyright 2009 Petr Skoda
421 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
422 * @since Moodle 2.0
423 */
424class single_button implements renderable {
574fbea4
PS
425 /**
426 * Target url
427 * @var moodle_url
428 */
3ba60ee1 429 var $url;
574fbea4
PS
430 /**
431 * Button label
432 * @var string
433 */
3ba60ee1 434 var $label;
574fbea4
PS
435 /**
436 * Form submit method
437 * @var string post or get
438 */
3ba60ee1 439 var $method = 'post';
574fbea4
PS
440 /**
441 * Wrapping div class
442 * @var string
443 * */
3ba60ee1 444 var $class = 'singlebutton';
574fbea4
PS
445 /**
446 * True if button disabled, false if normal
447 * @var boolean
448 */
3ba60ee1 449 var $disabled = false;
574fbea4
PS
450 /**
451 * Button tooltip
452 * @var string
453 */
97c10099 454 var $tooltip = null;
574fbea4
PS
455 /**
456 * Form id
457 * @var string
458 */
3ba60ee1 459 var $formid;
574fbea4
PS
460 /**
461 * List of attached actions
462 * @var array of component_action
463 */
3ba60ee1
PS
464 var $actions = array();
465
466 /**
467 * Constructor
574fbea4 468 * @param string|moodle_url $url
3ba60ee1
PS
469 * @param string $label button text
470 * @param string $method get or post submit method
3ba60ee1
PS
471 */
472 public function __construct(moodle_url $url, $label, $method='post') {
473 $this->url = clone($url);
474 $this->label = $label;
475 $this->method = $method;
476 }
477
478 /**
574fbea4 479 * Shortcut for adding a JS confirm dialog when the button is clicked.
3ba60ee1
PS
480 * The message must be a yes/no question.
481 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
482 * @return void
483 */
484 public function add_confirm_action($confirmmessage) {
8f78cd5a 485 $this->add_action(new confirm_action($confirmmessage));
3ba60ee1
PS
486 }
487
574fbea4
PS
488 /**
489 * Add action to the button.
490 * @param component_action $action
491 * @return void
492 */
3ba60ee1
PS
493 public function add_action(component_action $action) {
494 $this->actions[] = $action;
495 }
496}
497
498
a9967cf5
PS
499/**
500 * Simple form with just one select field that gets submitted automatically.
501 * If JS not enabled small go button is printed too.
502 *
503 * @copyright 2009 Petr Skoda
504 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
505 * @since Moodle 2.0
506 */
507class single_select implements renderable {
508 /**
509 * Target url - includes hidden fields
510 * @var moodle_url
511 */
512 var $url;
513 /**
514 * Name of the select element.
515 * @var string
516 */
517 var $name;
518 /**
519 * @var array $options associative array value=>label ex.:
520 * array(1=>'One, 2=>Two)
521 * it is also possible to specify optgroup as complex label array ex.:
522 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
523 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
524 */
525 var $options;
526 /**
527 * Selected option
528 * @var string
529 */
530 var $selected;
531 /**
532 * Nothing selected
533 * @var array
534 */
535 var $nothing;
536 /**
537 * Extra select field attributes
538 * @var array
539 */
540 var $attributes = array();
541 /**
542 * Button label
543 * @var string
544 */
545 var $label = '';
546 /**
547 * Form submit method
548 * @var string post or get
549 */
550 var $method = 'get';
551 /**
552 * Wrapping div class
553 * @var string
554 * */
555 var $class = 'singleselect';
556 /**
557 * True if button disabled, false if normal
558 * @var boolean
559 */
560 var $disabled = false;
561 /**
562 * Button tooltip
563 * @var string
564 */
565 var $tooltip = null;
566 /**
567 * Form id
568 * @var string
569 */
570 var $formid = null;
571 /**
572 * List of attached actions
573 * @var array of component_action
574 */
575 var $helpicon = null;
576 /**
577 * Constructor
578 * @param moodle_url $url form action target, includes hidden fields
579 * @param string $name name of selection field - the changing parameter in url
580 * @param array $options list of options
581 * @param string $selected selected element
582 * @param array $nothing
f8dab966 583 * @param string $formid
a9967cf5 584 */
f8dab966 585 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
a9967cf5
PS
586 $this->url = $url;
587 $this->name = $name;
588 $this->options = $options;
589 $this->selected = $selected;
590 $this->nothing = $nothing;
f8dab966 591 $this->formid = $formid;
a9967cf5
PS
592 }
593
594 /**
595 * Shortcut for adding a JS confirm dialog when the button is clicked.
596 * The message must be a yes/no question.
597 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
598 * @return void
599 */
600 public function add_confirm_action($confirmmessage) {
601 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
602 }
603
604 /**
605 * Add action to the button.
606 * @param component_action $action
607 * @return void
608 */
609 public function add_action(component_action $action) {
610 $this->actions[] = $action;
611 }
f8dab966
PS
612
613 /**
259c165d 614 * Adds help icon.
f8dab966 615 * @param string $page The keyword that defines a help page
1a10840e 616 * @param string $title A descriptive text for accessibility only
f8dab966
PS
617 * @param string $component
618 * @param bool $linktext add extra text to icon
619 * @return void
620 */
596509e4
PS
621 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
622 $this->helpicon = new old_help_icon($helppage, $title, $component);
f8dab966
PS
623 }
624
259c165d
PS
625 /**
626 * Adds help icon.
627 * @param string $identifier The keyword that defines a help page
628 * @param string $component
629 * @param bool $linktext add extra text to icon
630 * @return void
631 */
632 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 633 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
634 }
635
f8dab966 636 /**
995f2d51 637 * Sets select's label
f8dab966
PS
638 * @param string $label
639 * @return void
640 */
641 public function set_label($label) {
642 $this->label = $label;
643 }
a9967cf5
PS
644}
645
646
4d10e579
PS
647/**
648 * Simple URL selection widget description.
649 * @copyright 2009 Petr Skoda
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
651 * @since Moodle 2.0
652 */
653class url_select implements renderable {
654 /**
655 * @var array $urls associative array value=>label ex.:
656 * array(1=>'One, 2=>Two)
657 * it is also possible to specify optgroup as complex label array ex.:
658 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
659 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
660 */
661 var $urls;
662 /**
663 * Selected option
664 * @var string
665 */
666 var $selected;
667 /**
668 * Nothing selected
669 * @var array
670 */
671 var $nothing;
672 /**
673 * Extra select field attributes
674 * @var array
675 */
676 var $attributes = array();
677 /**
678 * Button label
679 * @var string
680 */
681 var $label = '';
682 /**
683 * Wrapping div class
684 * @var string
685 * */
686 var $class = 'urlselect';
687 /**
688 * True if button disabled, false if normal
689 * @var boolean
690 */
691 var $disabled = false;
692 /**
693 * Button tooltip
694 * @var string
695 */
696 var $tooltip = null;
697 /**
698 * Form id
699 * @var string
700 */
701 var $formid = null;
702 /**
703 * List of attached actions
704 * @var array of component_action
705 */
706 var $helpicon = null;
15e48a1a
SM
707 /**
708 * @var string If set, makes button visible with given name for button
709 */
710 var $showbutton = null;
4d10e579
PS
711 /**
712 * Constructor
713 * @param array $urls list of options
714 * @param string $selected selected element
715 * @param array $nothing
716 * @param string $formid
15e48a1a
SM
717 * @param string $showbutton Set to text of button if it should be visible
718 * or null if it should be hidden (hidden version always has text 'go')
719 */
720 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
721 $formid=null, $showbutton=null) {
722 $this->urls = $urls;
723 $this->selected = $selected;
724 $this->nothing = $nothing;
725 $this->formid = $formid;
726 $this->showbutton = $showbutton;
4d10e579
PS
727 }
728
729 /**
259c165d 730 * Adds help icon.
4d10e579 731 * @param string $page The keyword that defines a help page
1a10840e 732 * @param string $title A descriptive text for accessibility only
4d10e579
PS
733 * @param string $component
734 * @param bool $linktext add extra text to icon
735 * @return void
736 */
596509e4
PS
737 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
738 $this->helpicon = new old_help_icon($helppage, $title, $component);
4d10e579
PS
739 }
740
259c165d
PS
741 /**
742 * Adds help icon.
743 * @param string $identifier The keyword that defines a help page
744 * @param string $component
745 * @param bool $linktext add extra text to icon
746 * @return void
747 */
748 public function set_help_icon($identifier, $component = 'moodle') {
9c7b24bf 749 $this->helpicon = new help_icon($identifier, $component);
259c165d
PS
750 }
751
4d10e579 752 /**
995f2d51 753 * Sets select's label
4d10e579
PS
754 * @param string $label
755 * @return void
756 */
757 public function set_label($label) {
758 $this->label = $label;
759 }
760}
761
762
574fbea4
PS
763/**
764 * Data structure describing html link with special action attached.
765 * @copyright 2010 Petr Skoda
766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
767 * @since Moodle 2.0
768 */
769class action_link implements renderable {
770 /**
771 * Href url
772 * @var moodle_url
773 */
774 var $url;
775 /**
776 * Link text
777 * @var string HTML fragment
778 */
779 var $text;
780 /**
781 * HTML attributes
782 * @var array
783 */
784 var $attributes;
785 /**
786 * List of actions attached to link
787 * @var array of component_action
788 */
789 var $actions;
790
791 /**
792 * Constructor
793 * @param string|moodle_url $url
794 * @param string $text HTML fragment
795 * @param component_action $action
11820bac 796 * @param array $attributes associative array of html link attributes + disabled
574fbea4
PS
797 */
798 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
799 $this->url = clone($url);
800 $this->text = $text;
b0fef57b 801 $this->attributes = (array)$attributes;
f14b641b 802 if ($action) {
574fbea4
PS
803 $this->add_action($action);
804 }
805 }
806
807 /**
808 * Add action to the link.
809 * @param component_action $action
810 * @return void
811 */
812 public function add_action(component_action $action) {
813 $this->actions[] = $action;
814 }
c63923bd
PS
815
816 public function add_class($class) {
67da0bf7
DM
817 if (empty($this->attributes['class'])) {
818 $this->attributes['class'] = $class;
c63923bd 819 } else {
67da0bf7 820 $this->attributes['class'] .= ' ' . $class;
c63923bd
PS
821 }
822 }
574fbea4 823}
3ba60ee1 824
227255b8 825// ==== HTML writer and helper classes, will be probably moved elsewhere ======
5d0c95a5
PS
826
827/**
828 * Simple html output class
829 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
830 */
831class html_writer {
832 /**
833 * Outputs a tag with attributes and contents
834 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
5d0c95a5 835 * @param string $contents What goes between the opening and closing tags
26acc814 836 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
5d0c95a5
PS
837 * @return string HTML fragment
838 */
26acc814 839 public static function tag($tagname, $contents, array $attributes = null) {
5d0c95a5
PS
840 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
841 }
842
843 /**
844 * Outputs an opening tag with attributes
845 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
846 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
847 * @return string HTML fragment
848 */
849 public static function start_tag($tagname, array $attributes = null) {
850 return '<' . $tagname . self::attributes($attributes) . '>';
851 }
852
853 /**
854 * Outputs a closing tag
855 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
856 * @return string HTML fragment
857 */
858 public static function end_tag($tagname) {
859 return '</' . $tagname . '>';
860 }
861
862 /**
863 * Outputs an empty tag with attributes
864 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
865 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
866 * @return string HTML fragment
867 */
868 public static function empty_tag($tagname, array $attributes = null) {
869 return '<' . $tagname . self::attributes($attributes) . ' />';
870 }
871
836c47d7
TH
872 /**
873 * Outputs a tag, but only if the contents are not empty
874 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
875 * @param string $contents What goes between the opening and closing tags
876 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
877 * @return string HTML fragment
878 */
879 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
880 if ($contents === '' || is_null($contents)) {
881 return '';
882 }
883 return self::tag($tagname, $contents, $attributes);
884 }
885
5d0c95a5
PS
886 /**
887 * Outputs a HTML attribute and value
888 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
889 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
890 * @return string HTML fragment
891 */
892 public static function attribute($name, $value) {
893 if (is_array($value)) {
894 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
895 }
bf11293a
PS
896 if ($value instanceof moodle_url) {
897 return ' ' . $name . '="' . $value->out() . '"';
898 }
97c10099
PS
899
900 // special case, we do not want these in output
901 if ($value === null) {
902 return '';
5d0c95a5 903 }
97c10099
PS
904
905 // no sloppy trimming here!
906 return ' ' . $name . '="' . s($value) . '"';
5d0c95a5
PS
907 }
908
909 /**
910 * Outputs a list of HTML attributes and values
911 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
912 * The values will be escaped with {@link s()}
913 * @return string HTML fragment
914 */
915 public static function attributes(array $attributes = null) {
916 $attributes = (array)$attributes;
917 $output = '';
918 foreach ($attributes as $name => $value) {
919 $output .= self::attribute($name, $value);
920 }
921 return $output;
922 }
923
924 /**
925 * Generates random html element id.
926 * @param string $base
927 * @return string
928 */
929 public static function random_id($base='random') {
930 return uniqid($base);
931 }
0f4c64b7
PS
932
933 /**
934 * Generates a simple html link
935 * @param string|moodle_url $url
936 * @param string $text link txt
937 * @param array $attributes extra html attributes
938 * @return string HTML fragment
939 */
940 public static function link($url, $text, array $attributes = null) {
941 $attributes = (array)$attributes;
942 $attributes['href'] = $url;
26acc814 943 return self::tag('a', $text, $attributes);
0f4c64b7 944 }
3ff163c5 945
14dce022
PS
946 /**
947 * generates a simple checkbox with optional label
948 * @param string $name
949 * @param string $value
950 * @param bool $checked
951 * @param string $label
952 * @param array $attributes
953 * @return string html fragment
954 */
955 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
956 $attributes = (array)$attributes;
957 $output = '';
958
959 if ($label !== '' and !is_null($label)) {
960 if (empty($attributes['id'])) {
961 $attributes['id'] = self::random_id('checkbox_');
962 }
963 }
53868425
PS
964 $attributes['type'] = 'checkbox';
965 $attributes['value'] = $value;
966 $attributes['name'] = $name;
621b4d08 967 $attributes['checked'] = $checked ? 'checked' : null;
53868425 968
14dce022
PS
969 $output .= self::empty_tag('input', $attributes);
970
971 if ($label !== '' and !is_null($label)) {
26acc814 972 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
14dce022
PS
973 }
974
975 return $output;
976 }
977
78bdac64
PS
978 /**
979 * Generates a simple select yes/no form field
980 * @param string $name name of select element
981 * @param bool $selected
982 * @param array $attributes - html select element attributes
983 * @return string HRML fragment
984 */
19f3bbb2 985 public static function select_yes_no($name, $selected=true, array $attributes = null) {
78bdac64
PS
986 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
987 return self::select($options, $name, $selected, null, $attributes);
988 }
989
3ff163c5
PS
990 /**
991 * Generates a simple select form field
6770330d
PS
992 * @param array $options associative array value=>label ex.:
993 * array(1=>'One, 2=>Two)
994 * it is also possible to specify optgroup as complex label array ex.:
bde156b3 995 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
6770330d 996 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
3ff163c5 997 * @param string $name name of select element
1a10840e 998 * @param string|array $selected value or array of values depending on multiple attribute
3ff163c5
PS
999 * @param array|bool $nothing, add nothing selected option, or false of not added
1000 * @param array $attributes - html select element attributes
78bdac64 1001 * @return string HTML fragment
3ff163c5 1002 */
aa2dea70 1003 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
3ff163c5
PS
1004 $attributes = (array)$attributes;
1005 if (is_array($nothing)) {
1006 foreach ($nothing as $k=>$v) {
4b9210f3 1007 if ($v === 'choose' or $v === 'choosedots') {
3ff163c5
PS
1008 $nothing[$k] = get_string('choosedots');
1009 }
1010 }
1011 $options = $nothing + $options; // keep keys, do not override
3750c3bd
PS
1012
1013 } else if (is_string($nothing) and $nothing !== '') {
1014 // BC
1015 $options = array(''=>$nothing) + $options;
bde156b3 1016 }
3ff163c5
PS
1017
1018 // we may accept more values if multiple attribute specified
1019 $selected = (array)$selected;
1020 foreach ($selected as $k=>$v) {
1021 $selected[$k] = (string)$v;
1022 }
1023
1024 if (!isset($attributes['id'])) {
1025 $id = 'menu'.$name;
1026 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1027 $id = str_replace('[', '', $id);
1028 $id = str_replace(']', '', $id);
1029 $attributes['id'] = $id;
1030 }
1031
1032 if (!isset($attributes['class'])) {
1033 $class = 'menu'.$name;
1034 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1035 $class = str_replace('[', '', $class);
1036 $class = str_replace(']', '', $class);
1037 $attributes['class'] = $class;
1038 }
1039 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
1040
1041 $attributes['name'] = $name;
1042
1a09fa6d
TH
1043 if (!empty($attributes['disabled'])) {
1044 $attributes['disabled'] = 'disabled';
1045 } else {
1046 unset($attributes['disabled']);
1047 }
1048
3ff163c5
PS
1049 $output = '';
1050 foreach ($options as $value=>$label) {
6770330d
PS
1051 if (is_array($label)) {
1052 // ignore key, it just has to be unique
1053 $output .= self::select_optgroup(key($label), current($label), $selected);
1054 } else {
1055 $output .= self::select_option($label, $value, $selected);
3ff163c5 1056 }
3ff163c5 1057 }
26acc814 1058 return self::tag('select', $output, $attributes);
3ff163c5 1059 }
6770330d
PS
1060
1061 private static function select_option($label, $value, array $selected) {
1062 $attributes = array();
1063 $value = (string)$value;
1064 if (in_array($value, $selected, true)) {
1065 $attributes['selected'] = 'selected';
1066 }
1067 $attributes['value'] = $value;
26acc814 1068 return self::tag('option', $label, $attributes);
6770330d
PS
1069 }
1070
1071 private static function select_optgroup($groupname, $options, array $selected) {
1072 if (empty($options)) {
1073 return '';
1074 }
1075 $attributes = array('label'=>$groupname);
1076 $output = '';
1077 foreach ($options as $value=>$label) {
1078 $output .= self::select_option($label, $value, $selected);
1079 }
26acc814 1080 return self::tag('optgroup', $output, $attributes);
6770330d 1081 }
6ea66ff3 1082
f83b9b63
PS
1083 /**
1084 * This is a shortcut for making an hour selector menu.
1085 * @param string $type The type of selector (years, months, days, hours, minutes)
1086 * @param string $name fieldname
1087 * @param int $currenttime A default timestamp in GMT
1088 * @param int $step minute spacing
1089 * @param array $attributes - html select element attributes
1090 * @return HTML fragment
1091 */
1092 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1093 if (!$currenttime) {
1094 $currenttime = time();
1095 }
1096 $currentdate = usergetdate($currenttime);
1097 $userdatetype = $type;
1098 $timeunits = array();
1099
1100 switch ($type) {
1101 case 'years':
1102 for ($i=1970; $i<=2020; $i++) {
1103 $timeunits[$i] = $i;
1104 }
1105 $userdatetype = 'year';
1106 break;
1107 case 'months':
1108 for ($i=1; $i<=12; $i++) {
1109 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1110 }
1111 $userdatetype = 'month';
1112 $currentdate['month'] = $currentdate['mon'];
1113 break;
1114 case 'days':
1115 for ($i=1; $i<=31; $i++) {
1116 $timeunits[$i] = $i;
1117 }
1118 $userdatetype = 'mday';
1119 break;
1120 case 'hours':
1121 for ($i=0; $i<=23; $i++) {
1122 $timeunits[$i] = sprintf("%02d",$i);
1123 }
1124 break;
1125 case 'minutes':
1126 if ($step != 1) {
1127 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1128 }
1129
1130 for ($i=0; $i<=59; $i+=$step) {
1131 $timeunits[$i] = sprintf("%02d",$i);
1132 }
1133 break;
1134 default:
1135 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1136 }
1137
1138 if (empty($attributes['id'])) {
1139 $attributes['id'] = self::random_id('ts_');
1140 }
1141 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
26acc814 1142 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
f83b9b63
PS
1143
1144 return $label.$timerselector;
1145 }
1146
5be262b6
PS
1147 /**
1148 * Shortcut for quick making of lists
1149 * @param array $items
1150 * @param string $tag ul or ol
1151 * @param array $attributes
1152 * @return string
1153 */
1154 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1155 //note: 'list' is a reserved keyword ;-)
1156
1157 $output = '';
1158
1159 foreach ($items as $item) {
1160 $output .= html_writer::start_tag('li') . "\n";
1161 $output .= $item . "\n";
1162 $output .= html_writer::end_tag('li') . "\n";
1163 }
1164
26acc814 1165 return html_writer::tag($tag, $output, $attributes);
5be262b6
PS
1166 }
1167
6ea66ff3
PS
1168 /**
1169 * Returns hidden input fields created from url parameters.
1170 * @param moodle_url $url
1171 * @param array $exclude list of excluded parameters
1172 * @return string HTML fragment
1173 */
1174 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1175 $exclude = (array)$exclude;
1176 $params = $url->params();
1177 foreach ($exclude as $key) {
1178 unset($params[$key]);
1179 }
1180
1181 $output = '';
bde156b3 1182 foreach ($params as $key => $value) {
6ea66ff3
PS
1183 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1184 $output .= self::empty_tag('input', $attributes)."\n";
1185 }
1186 return $output;
1187 }
77774f6a
PS
1188
1189 /**
1190 * Generate a script tag containing the the specified code.
1191 *
1192 * @param string $js the JavaScript code
e50b4c89 1193 * @param moodle_url|string optional url of the external script, $code ignored if specified
77774f6a
PS
1194 * @return string HTML, the code wrapped in <script> tags.
1195 */
e50b4c89 1196 public static function script($jscode, $url=null) {
77774f6a 1197 if ($jscode) {
e50b4c89 1198 $attributes = array('type'=>'text/javascript');
26acc814 1199 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
e50b4c89
PS
1200
1201 } else if ($url) {
1202 $attributes = array('type'=>'text/javascript', 'src'=>$url);
26acc814 1203 return self::tag('script', '', $attributes) . "\n";
a9967cf5 1204
77774f6a
PS
1205 } else {
1206 return '';
1207 }
1208 }
16be8974
DM
1209
1210 /**
1211 * Renders HTML table
1212 *
1213 * This method may modify the passed instance by adding some default properties if they are not set yet.
1214 * If this is not what you want, you should make a full clone of your data before passing them to this
1215 * method. In most cases this is not an issue at all so we do not clone by default for performance
1216 * and memory consumption reasons.
1217 *
1218 * @param html_table $table data to be rendered
1219 * @return string HTML code
1220 */
1221 public static function table(html_table $table) {
1222 // prepare table data and populate missing properties with reasonable defaults
1223 if (!empty($table->align)) {
1224 foreach ($table->align as $key => $aa) {
1225 if ($aa) {
1226 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1227 } else {
1228 $table->align[$key] = null;
1229 }
1230 }
1231 }
1232 if (!empty($table->size)) {
1233 foreach ($table->size as $key => $ss) {
1234 if ($ss) {
1235 $table->size[$key] = 'width:'. $ss .';';
1236 } else {
1237 $table->size[$key] = null;
1238 }
1239 }
1240 }
1241 if (!empty($table->wrap)) {
1242 foreach ($table->wrap as $key => $ww) {
1243 if ($ww) {
1244 $table->wrap[$key] = 'white-space:nowrap;';
1245 } else {
1246 $table->wrap[$key] = '';
1247 }
1248 }
1249 }
1250 if (!empty($table->head)) {
1251 foreach ($table->head as $key => $val) {
1252 if (!isset($table->align[$key])) {
1253 $table->align[$key] = null;
1254 }
1255 if (!isset($table->size[$key])) {
1256 $table->size[$key] = null;
1257 }
1258 if (!isset($table->wrap[$key])) {
1259 $table->wrap[$key] = null;
1260 }
1261
1262 }
1263 }
1264 if (empty($table->attributes['class'])) {
1265 $table->attributes['class'] = 'generaltable';
1266 }
1267 if (!empty($table->tablealign)) {
1268 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1269 }
1270
1271 // explicitly assigned properties override those defined via $table->attributes
e126c0cc 1272 $table->attributes['class'] = trim($table->attributes['class']);
16be8974
DM
1273 $attributes = array_merge($table->attributes, array(
1274 'id' => $table->id,
1275 'width' => $table->width,
1276 'summary' => $table->summary,
1277 'cellpadding' => $table->cellpadding,
1278 'cellspacing' => $table->cellspacing,
1279 ));
1280 $output = html_writer::start_tag('table', $attributes) . "\n";
1281
1282 $countcols = 0;
1283
1284 if (!empty($table->head)) {
1285 $countcols = count($table->head);
5174f3c5 1286
16be8974
DM
1287 $output .= html_writer::start_tag('thead', array()) . "\n";
1288 $output .= html_writer::start_tag('tr', array()) . "\n";
1289 $keys = array_keys($table->head);
1290 $lastkey = end($keys);
1291
1292 foreach ($table->head as $key => $heading) {
1293 // Convert plain string headings into html_table_cell objects
1294 if (!($heading instanceof html_table_cell)) {
1295 $headingtext = $heading;
1296 $heading = new html_table_cell();
1297 $heading->text = $headingtext;
1298 $heading->header = true;
1299 }
1300
1301 if ($heading->header !== false) {
1302 $heading->header = true;
1303 }
1304
e126c0cc
DM
1305 if ($heading->header && empty($heading->scope)) {
1306 $heading->scope = 'col';
1307 }
1308
16be8974
DM
1309 $heading->attributes['class'] .= ' header c' . $key;
1310 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1311 $heading->colspan = $table->headspan[$key];
1312 $countcols += $table->headspan[$key] - 1;
1313 }
1314
1315 if ($key == $lastkey) {
1316 $heading->attributes['class'] .= ' lastcol';
1317 }
1318 if (isset($table->colclasses[$key])) {
1319 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1320 }
e126c0cc 1321 $heading->attributes['class'] = trim($heading->attributes['class']);
16be8974
DM
1322 $attributes = array_merge($heading->attributes, array(
1323 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1324 'scope' => $heading->scope,
1325 'colspan' => $heading->colspan,
1326 ));
1327
1328 $tagtype = 'td';
1329 if ($heading->header === true) {
1330 $tagtype = 'th';
1331 }
1332 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1333 }
1334 $output .= html_writer::end_tag('tr') . "\n";
1335 $output .= html_writer::end_tag('thead') . "\n";
1336
1337 if (empty($table->data)) {
1338 // For valid XHTML strict every table must contain either a valid tr
1339 // or a valid tbody... both of which must contain a valid td
1340 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1341 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1342 $output .= html_writer::end_tag('tbody');
1343 }
1344 }
1345
1346 if (!empty($table->data)) {
1347 $oddeven = 1;
1348 $keys = array_keys($table->data);
1349 $lastrowkey = end($keys);
1350 $output .= html_writer::start_tag('tbody', array());
1351
1352 foreach ($table->data as $key => $row) {
1353 if (($row === 'hr') && ($countcols)) {
1354 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1355 } else {
1356 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1357 if (!($row instanceof html_table_row)) {
1358 $newrow = new html_table_row();
1359
e126c0cc 1360 foreach ($row as $item) {
16be8974
DM
1361 $cell = new html_table_cell();
1362 $cell->text = $item;
1363 $newrow->cells[] = $cell;
1364 }
1365 $row = $newrow;
1366 }
1367
1368 $oddeven = $oddeven ? 0 : 1;
1369 if (isset($table->rowclasses[$key])) {
1370 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1371 }
1372
1373 $row->attributes['class'] .= ' r' . $oddeven;
1374 if ($key == $lastrowkey) {
1375 $row->attributes['class'] .= ' lastrow';
1376 }
1377
e126c0cc 1378 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
16be8974
DM
1379 $keys2 = array_keys($row->cells);
1380 $lastkey = end($keys2);
1381
5174f3c5 1382 $gotlastkey = false; //flag for sanity checking
16be8974 1383 foreach ($row->cells as $key => $cell) {
5174f3c5
AD
1384 if ($gotlastkey) {
1385 //This should never happen. Why do we have a cell after the last cell?
1386 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1387 }
1388
16be8974
DM
1389 if (!($cell instanceof html_table_cell)) {
1390 $mycell = new html_table_cell();
1391 $mycell->text = $cell;
1392 $cell = $mycell;
1393 }
1394
e126c0cc
DM
1395 if (($cell->header === true) && empty($cell->scope)) {
1396 $cell->scope = 'row';
1397 }
1398
16be8974
DM
1399 if (isset($table->colclasses[$key])) {
1400 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1401 }
1402
1403 $cell->attributes['class'] .= ' cell c' . $key;
1404 if ($key == $lastkey) {
1405 $cell->attributes['class'] .= ' lastcol';
5174f3c5 1406 $gotlastkey = true;
16be8974
DM
1407 }
1408 $tdstyle = '';
1409 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1410 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1411 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
e126c0cc 1412 $cell->attributes['class'] = trim($cell->attributes['class']);
16be8974
DM
1413 $tdattributes = array_merge($cell->attributes, array(
1414 'style' => $tdstyle . $cell->style,
1415 'colspan' => $cell->colspan,
1416 'rowspan' => $cell->rowspan,
1417 'id' => $cell->id,
1418 'abbr' => $cell->abbr,
1419 'scope' => $cell->scope,
1420 ));
1421 $tagtype = 'td';
1422 if ($cell->header === true) {
1423 $tagtype = 'th';
1424 }
1425 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1426 }
1427 }
1428 $output .= html_writer::end_tag('tr') . "\n";
1429 }
1430 $output .= html_writer::end_tag('tbody') . "\n";
1431 }
1432 $output .= html_writer::end_tag('table') . "\n";
1433
1434 return $output;
1435 }
1436
995f2d51
DM
1437 /**
1438 * Renders form element label
1439 *
1440 * By default, the label is suffixed with a label separator defined in the
1441 * current language pack (colon by default in the English lang pack).
1442 * Adding the colon can be explicitly disabled if needed. Label separators
1443 * are put outside the label tag itself so they are not read by
1444 * screenreaders (accessibility).
1445 *
1446 * Parameter $for explicitly associates the label with a form control. When
1447 * set, the value of this attribute must be the same as the value of
1448 * the id attribute of the form control in the same document. When null,
1449 * the label being defined is associated with the control inside the label
1450 * element.
1451 *
1452 * @param string $text content of the label tag
1453 * @param string|null $for id of the element this label is associated with, null for no association
1454 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1455 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1456 * @return string HTML of the label element
1457 */
1458 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1459 if (!is_null($for)) {
1460 $attributes = array_merge($attributes, array('for' => $for));
1461 }
1462 $text = trim($text);
1463 $label = self::tag('label', $text, $attributes);
1464
81e62b6f
DM
1465 /*
1466 // TODO $colonize disabled for now yet - see MDL-12192 for details
1ce51635 1467 if (!empty($text) and $colonize) {
995f2d51
DM
1468 // the $text may end with the colon already, though it is bad string definition style
1469 $colon = get_string('labelsep', 'langconfig');
1470 if (!empty($colon)) {
1471 $trimmed = trim($colon);
1472 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1473 //debugging('The label text should not end with colon or other label separator,
1474 // please fix the string definition.', DEBUG_DEVELOPER);
1475 } else {
1476 $label .= $colon;
1477 }
1478 }
1479 }
81e62b6f 1480 */
995f2d51
DM
1481
1482 return $label;
1483 }
5d0c95a5
PS
1484}
1485
227255b8
PS
1486// ==== JS writer and helper classes, will be probably moved elsewhere ======
1487
1488/**
1489 * Simple javascript output class
1490 * @copyright 2010 Petr Skoda
1491 */
1492class js_writer {
1493 /**
1494 * Returns javascript code calling the function
1a10840e 1495 * @param string $function function name, can be complex like Y.Event.purgeElement
227255b8
PS
1496 * @param array $arguments parameters
1497 * @param int $delay execution delay in seconds
1498 * @return string JS code fragment
1499 */
e839dce1 1500 public static function function_call($function, array $arguments = null, $delay=0) {
1b4e41af
PS
1501 if ($arguments) {
1502 $arguments = array_map('json_encode', $arguments);
1503 $arguments = implode(', ', $arguments);
1504 } else {
1505 $arguments = '';
1506 }
227255b8
PS
1507 $js = "$function($arguments);";
1508
1509 if ($delay) {
1510 $delay = $delay * 1000; // in miliseconds
1511 $js = "setTimeout(function() { $js }, $delay);";
1512 }
1513 return $js . "\n";
1514 }
1515
3b01539c
PS
1516 /**
1517 * Special function which adds Y as first argument of fucntion call.
1518 * @param string $function
1519 * @param array $extraarguments
1520 * @return string
1521 */
e839dce1 1522 public static function function_call_with_Y($function, array $extraarguments = null) {
3b01539c
PS
1523 if ($extraarguments) {
1524 $extraarguments = array_map('json_encode', $extraarguments);
1525 $arguments = 'Y, ' . implode(', ', $extraarguments);
1526 } else {
1527 $arguments = 'Y';
1528 }
1529 return "$function($arguments);\n";
1530 }
1531
1ce15fda
SH
1532 /**
1533 * Returns JavaScript code to initialise a new object
1534 * @param string|null $var If it is null then no var is assigned the new object
1535 * @param string $class
1536 * @param array $arguments
1537 * @param array $requirements
1538 * @param int $delay
1539 * @return string
1540 */
e839dce1 1541 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1ce15fda
SH
1542 if (is_array($arguments)) {
1543 $arguments = array_map('json_encode', $arguments);
1544 $arguments = implode(', ', $arguments);
1545 }
1546
1547 if ($var === null) {
53fc3e70 1548 $js = "new $class(Y, $arguments);";
1ce15fda 1549 } else if (strpos($var, '.')!==false) {
53fc3e70 1550 $js = "$var = new $class(Y, $arguments);";
1ce15fda 1551 } else {
53fc3e70 1552 $js = "var $var = new $class(Y, $arguments);";
1ce15fda
SH
1553 }
1554
1555 if ($delay) {
1556 $delay = $delay * 1000; // in miliseconds
1557 $js = "setTimeout(function() { $js }, $delay);";
1558 }
1559
1560 if (count($requirements) > 0) {
1561 $requirements = implode("', '", $requirements);
53fc3e70 1562 $js = "Y.use('$requirements', function(Y){ $js });";
1ce15fda
SH
1563 }
1564 return $js."\n";
1565 }
1566
227255b8
PS
1567 /**
1568 * Returns code setting value to variable
1569 * @param string $name
1570 * @param mixed $value json serialised value
1571 * @param bool $usevar add var definition, ignored for nested properties
1572 * @return string JS code fragment
1573 */
e839dce1 1574 public static function set_variable($name, $value, $usevar=true) {
227255b8
PS
1575 $output = '';
1576
1577 if ($usevar) {
1578 if (strpos($name, '.')) {
1579 $output .= '';
1580 } else {
1581 $output .= 'var ';
1582 }
1583 }
1584
1585 $output .= "$name = ".json_encode($value).";";
1586
1587 return $output;
1588 }
1589
1590 /**
1591 * Writes event handler attaching code
1a10840e 1592 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
227255b8
PS
1593 * @param string $event A valid DOM event (click, mousedown, change etc.)
1594 * @param string $function The name of the function to call
1595 * @param array $arguments An optional array of argument parameters to pass to the function
1596 * @return string JS code fragment
1597 */
e839dce1 1598 public static function event_handler($selector, $event, $function, array $arguments = null) {
227255b8
PS
1599 $selector = json_encode($selector);
1600 $output = "Y.on('$event', $function, $selector, null";
1601 if (!empty($arguments)) {
1602 $output .= ', ' . json_encode($arguments);
1603 }
1604 return $output . ");\n";
1605 }
1606}
1607
d9c8f425 1608/**
16be8974 1609 * Holds all the information required to render a <table> by {@see core_renderer::table()}
d9c8f425 1610 *
16be8974
DM
1611 * Example of usage:
1612 * $t = new html_table();
1613 * ... // set various properties of the object $t as described below
1614 * echo html_writer::table($t);
d9c8f425 1615 *
16be8974 1616 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
d9c8f425 1617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1618 * @since Moodle 2.0
1619 */
16be8974 1620class html_table {
d9c8f425 1621 /**
16be8974 1622 * @var string value to use for the id attribute of the table
d9c8f425 1623 */
97c10099 1624 public $id = null;
d9c8f425 1625 /**
16be8974 1626 * @var array attributes of HTML attributes for the <table> element
d9c8f425 1627 */
16be8974 1628 public $attributes = array();
7b1f2c82 1629 /**
a0ead5eb 1630 * For more control over the rendering of the headers, an array of html_table_cell objects
54a007e8 1631 * can be passed instead of an array of strings.
7b1f2c82 1632 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1633 *
1634 * Example of usage:
1635 * $t->head = array('Student', 'Grade');
1636 */
1637 public $head;
1638 /**
1639 * @var array can be used to make a heading span multiple columns
1640 *
1641 * Example of usage:
1642 * $t->headspan = array(2,1);
1643 *
1644 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1645 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1646 */
1647 public $headspan;
1648 /**
1649 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1650 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1651 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1652 *
beb56299 1653 * Examples of usage:
1654 * $t->align = array(null, 'right');
1655 * or
1656 * $t->align[1] = 'right';
1657 *
d9c8f425 1658 */
beb56299 1659 public $align;
d9c8f425 1660 /**
beb56299 1661 * @var array of column sizes. The value is used as CSS 'size' property.
1662 *
1663 * Examples of usage:
1664 * $t->size = array('50%', '50%');
1665 * or
1666 * $t->size[1] = '120px';
d9c8f425 1667 */
beb56299 1668 public $size;
d9c8f425 1669 /**
beb56299 1670 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1671 * CSS property 'white-space' to the value 'nowrap' in the given column.
1672 *
1673 * Example of usage:
1674 * $t->wrap = array(null, 'nowrap');
d9c8f425 1675 */
beb56299 1676 public $wrap;
d9c8f425 1677 /**
beb56299 1678 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1679 * $head specified, the string 'hr' (for horizontal ruler) can be used
1680 * instead of an array of cells data resulting in a divider rendered.
d9c8f425 1681 *
beb56299 1682 * Example of usage with array of arrays:
1683 * $row1 = array('Harry Potter', '76 %');
1684 * $row2 = array('Hermione Granger', '100 %');
1685 * $t->data = array($row1, $row2);
d9c8f425 1686 *
beb56299 1687 * Example with array of html_table_row objects: (used for more fine-grained control)
1688 * $cell1 = new html_table_cell();
1689 * $cell1->text = 'Harry Potter';
1690 * $cell1->colspan = 2;
1691 * $row1 = new html_table_row();
1692 * $row1->cells[] = $cell1;
1693 * $cell2 = new html_table_cell();
1694 * $cell2->text = 'Hermione Granger';
1695 * $cell3 = new html_table_cell();
1696 * $cell3->text = '100 %';
1697 * $row2 = new html_table_row();
1698 * $row2->cells = array($cell2, $cell3);
1699 * $t->data = array($row1, $row2);
1700 */
1701 public $data;
1702 /**
16be8974 1703 * @var string width of the table, percentage of the page preferred. Defaults to 80%
beb56299 1704 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1705 */
1706 public $width = null;
1707 /**
1708 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1709 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1710 */
1711 public $tablealign = null;
1712 /**
1713 * @var int padding on each cell, in pixels
1714 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1715 */
1716 public $cellpadding = null;
1717 /**
1718 * @var int spacing between cells, in pixels
1719 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1720 */
1721 public $cellspacing = null;
1722 /**
1723 * @var array classes to add to particular rows, space-separated string.
1724 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1725 * respectively. Class 'lastrow' is added automatically for the last row
1726 * in the table.
d9c8f425 1727 *
beb56299 1728 * Example of usage:
1729 * $t->rowclasses[9] = 'tenth'
1730 */
1731 public $rowclasses;
1732 /**
1733 * @var array classes to add to every cell in a particular column,
1734 * space-separated string. Class 'cell' is added automatically by the renderer.
1735 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1736 * respectively. Class 'lastcol' is added automatically for all last cells
1737 * in a row.
d9c8f425 1738 *
beb56299 1739 * Example of usage:
1740 * $t->colclasses = array(null, 'grade');
d9c8f425 1741 */
beb56299 1742 public $colclasses;
1743 /**
1744 * @var string description of the contents for screen readers.
1745 */
1746 public $summary;
d9c8f425 1747
1748 /**
16be8974 1749 * Constructor
d9c8f425 1750 */
16be8974
DM
1751 public function __construct() {
1752 $this->attributes['class'] = '';
d9c8f425 1753 }
d9c8f425 1754}
1755
34059565 1756
d9c8f425 1757/**
7b1f2c82 1758 * Component representing a table row.
d9c8f425 1759 *
1760 * @copyright 2009 Nicolas Connault
1761 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1762 * @since Moodle 2.0
1763 */
16be8974
DM
1764class html_table_row {
1765 /**
1766 * @var string value to use for the id attribute of the row
1767 */
1768 public $id = null;
d9c8f425 1769 /**
7b1f2c82 1770 * @var array $cells Array of html_table_cell objects
d9c8f425 1771 */
7b1f2c82 1772 public $cells = array();
beb56299 1773 /**
16be8974 1774 * @var string $style value to use for the style attribute of the table row
beb56299 1775 */
16be8974
DM
1776 public $style = null;
1777 /**
1778 * @var array attributes of additional HTML attributes for the <tr> element
1779 */
1780 public $attributes = array();
a0ead5eb 1781
54a007e8 1782 /**
8cea545e 1783 * Constructor
54a007e8 1784 * @param array $cells
8cea545e
PS
1785 */
1786 public function __construct(array $cells=null) {
16be8974 1787 $this->attributes['class'] = '';
8cea545e
PS
1788 $cells = (array)$cells;
1789 foreach ($cells as $cell) {
1790 if ($cell instanceof html_table_cell) {
1791 $this->cells[] = $cell;
a019627a 1792 } else {
8cea545e 1793 $this->cells[] = new html_table_cell($cell);
a019627a 1794 }
1795 }
54a007e8 1796 }
d9c8f425 1797}
1798
34059565 1799
d9c8f425 1800/**
7b1f2c82 1801 * Component representing a table cell.
d9c8f425 1802 *
1803 * @copyright 2009 Nicolas Connault
1804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1805 * @since Moodle 2.0
1806 */
16be8974
DM
1807class html_table_cell {
1808 /**
1809 * @var string value to use for the id attribute of the cell
1810 */
1811 public $id = null;
d9c8f425 1812 /**
7b1f2c82 1813 * @var string $text The contents of the cell
d9c8f425 1814 */
7b1f2c82 1815 public $text;
d9c8f425 1816 /**
7b1f2c82 1817 * @var string $abbr Abbreviated version of the contents of the cell
d9c8f425 1818 */
97c10099 1819 public $abbr = null;
d9c8f425 1820 /**
7b1f2c82 1821 * @var int $colspan Number of columns this cell should span
d9c8f425 1822 */
97c10099 1823 public $colspan = null;
d9c8f425 1824 /**
7b1f2c82 1825 * @var int $rowspan Number of rows this cell should span
d9c8f425 1826 */
97c10099 1827 public $rowspan = null;
d9c8f425 1828 /**
7b1f2c82 1829 * @var string $scope Defines a way to associate header cells and data cells in a table
d9c8f425 1830 */
97c10099 1831 public $scope = null;
1ae3767a 1832 /**
1833 * @var boolean $header Whether or not this cell is a header cell
1834 */
a4998d01 1835 public $header = null;
16be8974
DM
1836 /**
1837 * @var string $style value to use for the style attribute of the table cell
1838 */
1839 public $style = null;
1840 /**
70dc9b38 1841 * @var array attributes of additional HTML attributes for the <td> element
16be8974
DM
1842 */
1843 public $attributes = array();
d9c8f425 1844
8cea545e
PS
1845 public function __construct($text = null) {
1846 $this->text = $text;
16be8974 1847 $this->attributes['class'] = '';
d9c8f425 1848 }
1849}
1850
34059565 1851
7b1f2c82 1852/// Complex components aggregating simpler components
1853
34059565 1854
d9c8f425 1855/**
beb56299 1856 * Component representing a paging bar.
d9c8f425 1857 *
1858 * @copyright 2009 Nicolas Connault
1859 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1860 * @since Moodle 2.0
1861 */
929d7a83 1862class paging_bar implements renderable {
d9c8f425 1863 /**
beb56299 1864 * @var int $maxdisplay The maximum number of pagelinks to display
d9c8f425 1865 */
beb56299 1866 public $maxdisplay = 18;
d9c8f425 1867 /**
beb56299 1868 * @var int $totalcount post or get
d9c8f425 1869 */
beb56299 1870 public $totalcount;
d9c8f425 1871 /**
beb56299 1872 * @var int $page The page you are currently viewing
d9c8f425 1873 */
929d7a83 1874 public $page;
d9c8f425 1875 /**
beb56299 1876 * @var int $perpage The number of entries that should be shown per page
d9c8f425 1877 */
beb56299 1878 public $perpage;
d9c8f425 1879 /**
beb56299 1880 * @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.
1881 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
d9c8f425 1882 */
beb56299 1883 public $baseurl;
d9c8f425 1884 /**
beb56299 1885 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
d9c8f425 1886 */
929d7a83 1887 public $pagevar;
beb56299 1888 /**
56ddb719 1889 * @var string $previouslink A HTML link representing the "previous" page
beb56299 1890 */
1891 public $previouslink = null;
1892 /**
56ddb719 1893 * @var tring $nextlink A HTML link representing the "next" page
beb56299 1894 */
1895 public $nextlink = null;
1896 /**
56ddb719 1897 * @var tring $firstlink A HTML link representing the first page
beb56299 1898 */
1899 public $firstlink = null;
1900 /**
56ddb719 1901 * @var tring $lastlink A HTML link representing the last page
beb56299 1902 */
1903 public $lastlink = null;
1904 /**
56ddb719 1905 * @var array $pagelinks An array of strings. One of them is just a string: the current page
beb56299 1906 */
1907 public $pagelinks = array();
d9c8f425 1908
929d7a83
PS
1909 /**
1910 * Constructor paging_bar with only the required params.
1911 *
1a10840e 1912 * @param int $totalcount The total number of entries available to be paged through
929d7a83
PS
1913 * @param int $page The page you are currently viewing
1914 * @param int $perpage The number of entries that should be shown per page
1915 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1916 * @param string $pagevar name of page parameter that holds the page number
1917 */
1918 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1919 $this->totalcount = $totalcount;
1920 $this->page = $page;
1921 $this->perpage = $perpage;
1922 $this->baseurl = $baseurl;
1923 $this->pagevar = $pagevar;
1924 }
1925
d9c8f425 1926 /**
d9c8f425 1927 * @return void
1928 */
34059565 1929 public function prepare(renderer_base $output, moodle_page $page, $target) {
1c1f64a2 1930 if (!isset($this->totalcount) || is_null($this->totalcount)) {
929d7a83 1931 throw new coding_exception('paging_bar requires a totalcount value.');
beb56299 1932 }
1933 if (!isset($this->page) || is_null($this->page)) {
929d7a83 1934 throw new coding_exception('paging_bar requires a page value.');
beb56299 1935 }
1936 if (empty($this->perpage)) {
929d7a83 1937 throw new coding_exception('paging_bar requires a perpage value.');
beb56299 1938 }
1939 if (empty($this->baseurl)) {
929d7a83 1940 throw new coding_exception('paging_bar requires a baseurl value.');
beb56299 1941 }
d9c8f425 1942
beb56299 1943 if ($this->totalcount > $this->perpage) {
1944 $pagenum = $this->page - 1;
d9c8f425 1945
beb56299 1946 if ($this->page > 0) {
929d7a83 1947 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
beb56299 1948 }
d9c8f425 1949
beb56299 1950 if ($this->perpage > 0) {
1951 $lastpage = ceil($this->totalcount / $this->perpage);
1952 } else {
1953 $lastpage = 1;
1954 }
1955
1956 if ($this->page > 15) {
1957 $startpage = $this->page - 10;
1958
929d7a83 1959 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
beb56299 1960 } else {
1961 $startpage = 0;
1962 }
1963
1964 $currpage = $startpage;
1965 $displaycount = $displaypage = 0;
1966
1967 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1968 $displaypage = $currpage + 1;
1969
f43cdceb 1970 if ($this->page == $currpage) {
beb56299 1971 $this->pagelinks[] = $displaypage;
1972 } else {
56ddb719 1973 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
beb56299 1974 $this->pagelinks[] = $pagelink;
1975 }
1976
1977 $displaycount++;
1978 $currpage++;
1979 }
1980
1981 if ($currpage < $lastpage) {
1982 $lastpageactual = $lastpage - 1;
abdac127 1983 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
beb56299 1984 }
1985
1986 $pagenum = $this->page + 1;
1987
1988 if ($pagenum != $displaypage) {
abdac127 1989 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
beb56299 1990 }
d9c8f425 1991 }
1992 }
d9c8f425 1993}
1994
34059565 1995
d9c8f425 1996/**
beb56299 1997 * This class represents how a block appears on a page.
d9c8f425 1998 *
beb56299 1999 * During output, each block instance is asked to return a block_contents object,
2000 * those are then passed to the $OUTPUT->block function for display.
2001 *
2002 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2003 *
2004 * Other block-like things that need to appear on the page, for example the
2005 * add new block UI, are also represented as block_contents objects.
2006 *
2007 * @copyright 2009 Tim Hunt
d9c8f425 2008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2009 * @since Moodle 2.0
2010 */
dd72b308 2011class block_contents {
beb56299 2012 /** @var int used to set $skipid. */
2013 protected static $idcounter = 1;
2014
2015 const NOT_HIDEABLE = 0;
2016 const VISIBLE = 1;
2017 const HIDDEN = 2;
2018
d9c8f425 2019 /**
dd72b308 2020 * @var integer $skipid All the blocks (or things that look like blocks)
beb56299 2021 * printed on a page are given a unique number that can be used to construct
2022 * id="" attributes. This is set automatically be the {@link prepare()} method.
2023 * Do not try to set it manually.
d9c8f425 2024 */
beb56299 2025 public $skipid;
d9c8f425 2026
2027 /**
beb56299 2028 * @var integer If this is the contents of a real block, this should be set to
2029 * the block_instance.id. Otherwise this should be set to 0.
2030 */
2031 public $blockinstanceid = 0;
2032
2033 /**
2034 * @var integer if this is a real block instance, and there is a corresponding
2035 * block_position.id for the block on this page, this should be set to that id.
2036 * Otherwise it should be 0.
2037 */
2038 public $blockpositionid = 0;
2039
2040 /**
2041 * @param array $attributes an array of attribute => value pairs that are put on the
2042 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2043 */
dd72b308 2044 public $attributes;
beb56299 2045
2046 /**
2047 * @param string $title The title of this block. If this came from user input,
2048 * it should already have had format_string() processing done on it. This will
2049 * be output inside <h2> tags. Please do not cause invalid XHTML.
2050 */
2051 public $title = '';
2052
2053 /**
2054 * @param string $content HTML for the content
2055 */
2056 public $content = '';
2057
2058 /**
2059 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2060 */
2061 public $footer = '';
2062
2063 /**
2064 * Any small print that should appear under the block to explain to the
2065 * teacher about the block, for example 'This is a sticky block that was
2066 * added in the system context.'
2067 * @var string
2068 */
2069 public $annotation = '';
2070
2071 /**
2072 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2073 * the user can toggle whether this block is visible.
2074 */
2075 public $collapsible = self::NOT_HIDEABLE;
2076
2077 /**
2078 * A (possibly empty) array of editing controls. Each element of this array
2079 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
b5d0cafc 2080 * $icon is the icon name. Fed to $OUTPUT->pix_url.
beb56299 2081 * @var array
2082 */
2083 public $controls = array();
2084
dd72b308 2085
beb56299 2086 /**
dd72b308
PS
2087 * Create new instance of block content
2088 * @param array $attributes
d9c8f425 2089 */
dd72b308 2090 public function __construct(array $attributes=null) {
beb56299 2091 $this->skipid = self::$idcounter;
2092 self::$idcounter += 1;
dd72b308
PS
2093
2094 if ($attributes) {
2095 // standard block
2096 $this->attributes = $attributes;
2097 } else {
2098 // simple "fake" blocks used in some modules and "Add new block" block
6605ff8c 2099 $this->attributes = array('class'=>'block');
beb56299 2100 }
dd72b308
PS
2101 }
2102
2103 /**
2104 * Add html class to block
2105 * @param string $class
2106 * @return void
2107 */
2108 public function add_class($class) {
2109 $this->attributes['class'] .= ' '.$class;
d9c8f425 2110 }
2111}
beb56299 2112
34059565 2113
beb56299 2114/**
2115 * This class represents a target for where a block can go when it is being moved.
2116 *
2117 * This needs to be rendered as a form with the given hidden from fields, and
2118 * clicking anywhere in the form should submit it. The form action should be
2119 * $PAGE->url.
2120 *
2121 * @copyright 2009 Tim Hunt
2122 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2123 * @since Moodle 2.0
2124 */
dd72b308 2125class block_move_target {
beb56299 2126 /**
dd72b308
PS
2127 * Move url
2128 * @var moodle_url
beb56299 2129 */
dd72b308 2130 public $url;
beb56299 2131 /**
dd72b308
PS
2132 * label
2133 * @var string
beb56299 2134 */
dd72b308
PS
2135 public $text;
2136
2137 /**
1a10840e 2138 * Constructor
dd72b308
PS
2139 * @param string $text
2140 * @param moodle_url $url
2141 */
2142 public function __construct($text, moodle_url $url) {
2143 $this->text = $text;
2144 $this->url = $url;
2145 }
beb56299 2146}
d2dbd0c0
SH
2147
2148/**
2149 * Custom menu item
2150 *
2151 * This class is used to represent one item within a custom menu that may or may
2152 * not have children.
2153 *
2154 * @copyright 2010 Sam Hemelryk
2155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2156 * @since Moodle 2.0
2157 */
2158class custom_menu_item implements renderable {
2159 /**
2160 * The text to show for the item
2161 * @var string
2162 */
2163 protected $text;
2164 /**
2165 * The link to give the icon if it has no children
2166 * @var moodle_url
2167 */
2168 protected $url;
2169 /**
2170 * A title to apply to the item. By default the text
2171 * @var string
2172 */
2173 protected $title;
2174 /**
1a10840e 2175 * A sort order for the item, not necessary if you order things in the CFG var
d2dbd0c0
SH
2176 * @var int
2177 */
2178 protected $sort;
2179 /**
2180 * A reference to the parent for this item or NULL if it is a top level item
2181 * @var custom_menu_item
2182 */
2183 protected $parent;
2184 /**
2185 * A array in which to store children this item has.
2186 * @var array
2187 */
2188 protected $children = array();
2189 /**
2190 * A reference to the sort var of the last child that was added
2191 * @var int
2192 */
2193 protected $lastsort = 0;
2194 /**
2195 * Constructs the new custom menu item
2196 *
2197 * @param string $text
2198 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2199 * @param string $title A title to apply to this item [Optional]
2200 * @param int $sort A sort or to use if we need to sort differently [Optional]
2201 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2202 * belongs to, only if the child has a parent. [Optional]
2203 */
2204 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2205 $this->text = $text;
2206 $this->url = $url;
2207 $this->title = $title;
2208 $this->sort = (int)$sort;
2209 $this->parent = $parent;
2210 }
2211
2212 /**
2213 * Adds a custom menu item as a child of this node given its properties.
2214 *
2215 * @param string $text
2216 * @param moodle_url $url
2217 * @param string $title
2218 * @param int $sort
2219 * @return custom_menu_item
2220 */
2221 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2222 $key = count($this->children);
2223 if (empty($sort)) {
2224 $sort = $this->lastsort + 1;
2225 }
2226 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2227 $this->lastsort = (int)$sort;
2228 return $this->children[$key];
2229 }
2230 /**
2231 * Returns the text for this item
2232 * @return string
2233 */
2234 public function get_text() {
2235 return $this->text;
2236 }
2237 /**
2238 * Returns the url for this item
2239 * @return moodle_url
2240 */
2241 public function get_url() {
2242 return $this->url;
2243 }
2244 /**
2245 * Returns the title for this item
2246 * @return string
2247 */
2248 public function get_title() {
2249 return $this->title;
2250 }
2251 /**
2252 * Sorts and returns the children for this item
2253 * @return array
2254 */
2255 public function get_children() {
2256 $this->sort();
2257 return $this->children;
2258 }
2259 /**
2260 * Gets the sort order for this child
2261 * @return int
2262 */
2263 public function get_sort_order() {
2264 return $this->sort;
2265 }
2266 /**
2267 * Gets the parent this child belong to
2268 * @return custom_menu_item
2269 */
2270 public function get_parent() {
2271 return $this->parent;
2272 }
2273 /**
2274 * Sorts the children this item has
2275 */
2276 public function sort() {
2277 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2278 }
2279 /**
2280 * Returns true if this item has any children
2281 * @return bool
2282 */
2283 public function has_children() {
2284 return (count($this->children) > 0);
2285 }
f3827323
SH
2286
2287 /**
2288 * Sets the text for the node
2289 * @param string $text
2290 */
2291 public function set_text($text) {
2292 $this->text = (string)$text;
2293 }
2294
2295 /**
2296 * Sets the title for the node
2297 * @param string $title
2298 */
2299 public function set_title($title) {
2300 $this->title = (string)$title;
2301 }
2302
2303 /**
2304 * Sets the url for the node
2305 * @param moodle_url $url
2306 */
2307 public function set_url(moodle_url $url) {
2308 $this->url = $url;
2309 }
d2dbd0c0
SH
2310}
2311
2312/**
2313 * Custom menu class
2314 *
2315 * This class is used to operate a custom menu that can be rendered for the page.
2316 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2317 * of custom_menu_item nodes that can be rendered by the core renderer.
2318 *
2319 * To configure the custom menu:
2320 * Settings: Administration > Appearance > Themes > Theme settings
2321 *
2322 * @copyright 2010 Sam Hemelryk
2323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2324 * @since Moodle 2.0
2325 */
2326class custom_menu extends custom_menu_item {
155fffe6 2327
4564d58f
DM
2328 /** @var string the language we should render for, null disables multilang support */
2329 protected $currentlanguage = null;
2330
d2dbd0c0
SH
2331 /**
2332 * Creates the custom menu
155fffe6
DM
2333 *
2334 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
4564d58f 2335 * @param string $language the current language code, null disables multilang support
d2dbd0c0 2336 */
4564d58f 2337 public function __construct($definition = '', $currentlanguage = null) {
155fffe6 2338
4564d58f 2339 $this->currentlanguage = $currentlanguage;
155fffe6
DM
2340 parent::__construct('root'); // create virtual root element of the menu
2341 if (!empty($definition)) {
4564d58f 2342 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
12cc75ae 2343 }
d2dbd0c0
SH
2344 }
2345
2346 /**
2347 * Overrides the children of this custom menu. Useful when getting children
2348 * from $CFG->custommenuitems
2349 */
2350 public function override_children(array $children) {
2351 $this->children = array();
2352 foreach ($children as $child) {
2353 if ($child instanceof custom_menu_item) {
2354 $this->children[] = $child;
2355 }
2356 }
2357 }
2358
2359 /**
2360 * Converts a string into a structured array of custom_menu_items which can
2361 * then be added to a custom menu.
2362 *
2363 * Structure:
4564d58f
DM
2364 * text|url|title|langs
2365 * The number of hyphens at the start determines the depth of the item. The
2366 * languages are optional, comma separated list of languages the line is for.
d2dbd0c0
SH
2367 *
2368 * Example structure:
2369 * First level first item|http://www.moodle.com/
2370 * -Second level first item|http://www.moodle.com/partners/
2371 * -Second level second item|http://www.moodle.com/hq/
2372 * --Third level first item|http://www.moodle.com/jobs/
2373 * -Second level third item|http://www.moodle.com/development/
2374 * First level second item|http://www.moodle.com/feedback/
2375 * First level third item
4564d58f
DM
2376 * English only|http://moodle.com|English only item|en
2377 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2378 *
4d2ee4c2 2379 *
d2dbd0c0 2380 * @static
4564d58f
DM
2381 * @param string $text the menu items definition
2382 * @param string $language the language code, null disables multilang support
d2dbd0c0
SH
2383 * @return array
2384 */
4564d58f 2385 public static function convert_text_to_menu_nodes($text, $language = null) {
d2dbd0c0
SH
2386 $lines = explode("\n", $text);
2387 $children = array();
2388 $lastchild = null;
2389 $lastdepth = null;
2390 $lastsort = 0;
2391 foreach ($lines as $line) {
2392 $line = trim($line);
4564d58f
DM
2393 $bits = explode('|', $line, 4); // name|url|title|langs
2394 if (!array_key_exists(0, $bits) or empty($bits[0])) {
d2dbd0c0
SH
2395 // Every item must have a name to be valid
2396 continue;
2397 } else {
2398 $bits[0] = ltrim($bits[0],'-');
2399 }
4564d58f 2400 if (!array_key_exists(1, $bits) or empty($bits[1])) {
d2dbd0c0
SH
2401 // Set the url to null
2402 $bits[1] = null;
2403 } else {
2404 // Make sure the url is a moodle url
a26f25ae 2405 $bits[1] = new moodle_url(trim($bits[1]));
d2dbd0c0 2406 }
4564d58f 2407 if (!array_key_exists(2, $bits) or empty($bits[2])) {
d2dbd0c0
SH
2408 // Set the title to null seeing as there isn't one
2409 $bits[2] = $bits[0];
2410 }
4564d58f
DM
2411 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2412 // The item is valid for all languages
2413 $itemlangs = null;
2414 } else {
2415 $itemlangs = array_map('trim', explode(',', $bits[3]));
2416 }
2417 if (!empty($language) and !empty($itemlangs)) {
2418 // check that the item is intended for the current language
2419 if (!in_array($language, $itemlangs)) {
2420 continue;
2421 }
2422 }
d2dbd0c0 2423 // Set an incremental sort order to keep it simple.
4564d58f 2424 $lastsort++;
d2dbd0c0
SH
2425 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2426 $depth = strlen($match[1]);
2427 if ($depth < $lastdepth) {
57bedaee
SH
2428 $difference = $lastdepth - $depth;
2429 if ($lastdepth > 1 && $lastdepth != $difference) {
2430 $tempchild = $lastchild->get_parent();
2431 for ($i =0; $i < $difference; $i++) {
2432 $tempchild = $tempchild->get_parent();
2433 }
4564d58f 2434 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2435 } else {
2436 $depth = 0;
4564d58f 2437 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2438 $children[] = $lastchild;
2439 }
2440 } else if ($depth > $lastdepth) {
2441 $depth = $lastdepth + 1;
4564d58f 2442 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2443 } else {
2444 if ($depth == 0) {
4564d58f 2445 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2446 $children[] = $lastchild;
2447 } else {
4564d58f 2448 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2449 }
2450 }
2451 } else {
2452 $depth = 0;
4564d58f 2453 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
d2dbd0c0
SH
2454 $children[] = $lastchild;
2455 }
2456 $lastdepth = $depth;
2457 }
2458 return $children;
2459 }
2460
2461 /**
2462 * Sorts two custom menu items
2463 *
2464 * This function is designed to be used with the usort method
2465 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2466 *
2467 * @param custom_menu_item $itema
2468 * @param custom_menu_item $itemb
2469 * @return int
2470 */
2471 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2472 $itema = $itema->get_sort_order();
2473 $itemb = $itemb->get_sort_order();
2474 if ($itema == $itemb) {
2475 return 0;
2476 }
2477 return ($itema > $itemb) ? +1 : -1;
2478 }
4d2ee4c2 2479}