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