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