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