Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace core\output;
18
 
19
use core\exception\coding_exception;
20
use core_table\output\html_table;
21
use core_table\output\html_table_cell;
22
use core_table\output\html_table_row;
23
use core_text;
24
use moodle_url;
25
 
26
/**
27
 * Simple html output class
28
 *
29
 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
30
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31
 * @since Moodle 2.0
32
 * @package core
33
 * @category output
34
 */
35
class html_writer {
36
    /**
37
     * Outputs a tag with attributes and contents
38
     *
39
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
40
     * @param string $contents What goes between the opening and closing tags
41
     * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
42
     * @return string HTML fragment
43
     */
44
    public static function tag($tagname, $contents, ?array $attributes = null) {
45
        return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
46
    }
47
 
48
    /**
49
     * Outputs an opening tag with attributes
50
     *
51
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
52
     * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
53
     * @return string HTML fragment
54
     */
55
    public static function start_tag($tagname, ?array $attributes = null) {
56
        return '<' . $tagname . self::attributes($attributes) . '>';
57
    }
58
 
59
    /**
60
     * Outputs a closing tag
61
     *
62
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
63
     * @return string HTML fragment
64
     */
65
    public static function end_tag($tagname) {
66
        return '</' . $tagname . '>';
67
    }
68
 
69
    /**
70
     * Outputs an empty tag with attributes
71
     *
72
     * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
73
     * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
74
     * @return string HTML fragment
75
     */
76
    public static function empty_tag($tagname, ?array $attributes = null) {
77
        return '<' . $tagname . self::attributes($attributes) . ' />';
78
    }
79
 
80
    /**
81
     * Outputs a tag, but only if the contents are not empty
82
     *
83
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
84
     * @param string $contents What goes between the opening and closing tags
85
     * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
86
     * @return string HTML fragment
87
     */
88
    public static function nonempty_tag($tagname, $contents, ?array $attributes = null) {
89
        if ($contents === '' || is_null($contents)) {
90
            return '';
91
        }
92
        return self::tag($tagname, $contents, $attributes);
93
    }
94
 
95
    /**
96
     * Outputs a HTML attribute and value
97
     *
98
     * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
99
     * @param string $value The value of the attribute. The value will be escaped with {@see s()}
100
     * @return string HTML fragment
101
     */
102
    public static function attribute($name, $value) {
103
        if ($value instanceof moodle_url) {
104
            return ' ' . $name . '="' . $value->out() . '"';
105
        }
106
 
107
        // Special case, we do not want these in output.
108
        if ($value === null) {
109
            return '';
110
        }
111
 
112
        // No sloppy trimming here!
113
        return ' ' . $name . '="' . s($value) . '"';
114
    }
115
 
116
    /**
117
     * Outputs a list of HTML attributes and values
118
     *
119
     * @param null|array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
120
     *       The values will be escaped with {@see s()}
121
     * @return string HTML fragment
122
     */
123
    public static function attributes(?array $attributes = null) {
124
        $attributes = (array)$attributes;
125
        $output = '';
126
        foreach ($attributes as $name => $value) {
127
            $output .= self::attribute($name, $value);
128
        }
129
        return $output;
130
    }
131
 
132
    /**
133
     * Generates a simple image tag with attributes.
134
     *
135
     * @param string $src The source of image
136
     * @param string $alt The alternate text for image
137
     * @param null|array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
138
     * @return string HTML fragment
139
     */
140
    public static function img($src, $alt, ?array $attributes = null) {
141
        $attributes = (array)$attributes;
142
        $attributes['src'] = $src;
143
        // In case a null alt text is provided, set it to an empty string.
144
        $attributes['alt'] = $alt ?? '';
145
        if (array_key_exists('role', $attributes) && core_text::strtolower($attributes['role']) === 'presentation') {
146
            // A presentation role is not necessary for the img tag.
147
            // If a non-empty alt text is provided, the presentation role will conflict with the alt text.
148
            // An empty alt text denotes a decorative image. The presence of a presentation role is redundant.
149
            unset($attributes['role']);
150
            debugging('The presentation role is not necessary for an img tag.', DEBUG_DEVELOPER);
151
        }
152
 
153
        return self::empty_tag('img', $attributes);
154
    }
155
 
156
    /**
157
     * Generates random html element id.
158
     *
159
     * @staticvar int $counter
160
     * @staticvar string $uniq
161
     * @param string $base A string fragment that will be included in the random ID.
162
     * @return string A unique ID
163
     */
164
    public static function random_id($base = 'random') {
165
        static $counter = 0;
166
        static $uniq;
167
 
168
        if (!isset($uniq)) {
169
            $uniq = uniqid();
170
        }
171
 
172
        $counter++;
173
        return $base . $uniq . $counter;
174
    }
175
 
176
    /**
177
     * Generates a simple html link
178
     *
179
     * @param string|moodle_url $url The URL
180
     * @param string $text The text
181
     * @param null|array $attributes HTML attributes
182
     * @return string HTML fragment
183
     */
184
    public static function link($url, $text, ?array $attributes = null) {
185
        $attributes = (array)$attributes;
186
        $attributes['href']  = $url;
187
        return self::tag('a', $text, $attributes);
188
    }
189
 
190
    /**
191
     * Generates a simple checkbox with optional label
192
     *
193
     * @param string $name The name of the checkbox
194
     * @param string $value The value of the checkbox
195
     * @param bool $checked Whether the checkbox is checked
196
     * @param string $label The label for the checkbox
197
     * @param null|array $attributes Any attributes to apply to the checkbox
198
     * @param null|array $labelattributes Any attributes to apply to the label, if present
199
     * @return string html fragment
200
     */
201
    public static function checkbox(
202
        $name,
203
        $value,
204
        $checked = true,
205
        $label = '',
206
        ?array $attributes = null,
207
        ?array $labelattributes = null,
208
    ) {
209
        $attributes = (array) $attributes;
210
        $output = '';
211
 
212
        if ($label !== '' && !is_null($label)) {
213
            if (empty($attributes['id'])) {
214
                $attributes['id'] = self::random_id('checkbox_');
215
            }
216
        }
217
        $attributes['type']    = 'checkbox';
218
        $attributes['value']   = $value;
219
        $attributes['name']    = $name;
220
        $attributes['checked'] = $checked ? 'checked' : null;
221
 
222
        $output .= self::empty_tag('input', $attributes);
223
 
224
        if ($label !== '' && !is_null($label)) {
225
            $labelattributes = (array) $labelattributes;
226
            $labelattributes['for'] = $attributes['id'];
227
            $output .= self::tag('label', $label, $labelattributes);
228
        }
229
 
230
        return $output;
231
    }
232
 
233
    /**
234
     * Generates a simple select yes/no form field
235
     *
236
     * @param string $name name of select element
237
     * @param bool $selected
238
     * @param null|array $attributes - html select element attributes
239
     * @return string HTML fragment
240
     */
241
    public static function select_yes_no($name, $selected = true, ?array $attributes = null) {
242
        $options = ['1' => get_string('yes'), '0' => get_string('no')];
243
        return self::select($options, $name, $selected, null, $attributes);
244
    }
245
 
246
    /**
247
     * Generates a simple select form field
248
     *
249
     * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
250
     *
251
     * @param array $options associative array value=>label ex.:
252
     *                array(1=>'One, 2=>Two)
253
     *              it is also possible to specify optgroup as complex label array ex.:
254
     *                array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
255
     *                array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
256
     * @param string $name name of select element
257
     * @param string|array $selected value or array of values depending on multiple attribute
258
     * @param array|bool|null $nothing add nothing selected option, or false of not added
259
     * @param null|array $attributes html select element attributes
260
     * @param array $disabled An array of disabled options.
261
     * @return string HTML fragment
262
     */
263
    public static function select(
264
        array $options,
265
        $name,
266
        $selected = '',
267
        $nothing = ['' => 'choosedots'],
268
        ?array $attributes = null,
269
        array $disabled = [],
270
    ): string {
271
        $attributes = (array)$attributes;
272
        if (is_array($nothing)) {
273
            foreach ($nothing as $k => $v) {
274
                if ($v === 'choose' || $v === 'choosedots') {
275
                    $nothing[$k] = get_string('choosedots');
276
                }
277
            }
278
            $options = $nothing + $options; // Keep keys, do not override.
279
        } else if (is_string($nothing) && $nothing !== '') {
280
            // BC.
281
            $options = ['' => $nothing] + $options;
282
        }
283
 
284
        // We may accept more values if multiple attribute specified.
285
        $selected = (array)$selected;
286
        foreach ($selected as $k => $v) {
287
            $selected[$k] = (string)$v;
288
        }
289
 
290
        if (!isset($attributes['id'])) {
291
            $id = 'menu' . $name;
292
            // Name may contain [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading.
293
            $id = str_replace('[', '', $id);
294
            $id = str_replace(']', '', $id);
295
            $attributes['id'] = $id;
296
        }
297
 
298
        if (!isset($attributes['class'])) {
299
            $class = 'menu' . $name;
300
            // Name may contain [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading.
301
            $class = str_replace('[', '', $class);
302
            $class = str_replace(']', '', $class);
303
            $attributes['class'] = $class;
304
        }
305
        $attributes['class'] = 'select form-select ' . $attributes['class']; // Add 'select' selector always.
306
 
307
        $attributes['name'] = $name;
308
 
309
        if (!empty($attributes['disabled'])) {
310
            $attributes['disabled'] = 'disabled';
311
        } else {
312
            unset($attributes['disabled']);
313
        }
314
 
315
        $output = '';
316
        foreach ($options as $value => $label) {
317
            if (is_array($label)) {
318
                // Ignore key, it just has to be unique.
319
                $output .= self::select_optgroup(key($label), current($label), $selected, $disabled);
320
            } else {
321
                $output .= self::select_option($label, $value, $selected, $disabled);
322
            }
323
        }
324
        return self::tag('select', $output, $attributes);
325
    }
326
 
327
    /**
328
     * Returns HTML to display a select box option.
329
     *
330
     * @param string $label The label to display as the option.
331
     * @param string|int $value The value the option represents
332
     * @param array $selected An array of selected options
333
     * @param array $disabled An array of disabled options.
334
     * @return string HTML fragment
335
     */
336
    private static function select_option($label, $value, array $selected, array $disabled = []): string {
337
        $attributes = [];
338
        $value = (string)$value;
339
        if (in_array($value, $selected, true)) {
340
            $attributes['selected'] = 'selected';
341
        }
342
        if (in_array($value, $disabled, true)) {
343
            $attributes['disabled'] = 'disabled';
344
        }
345
        $attributes['value'] = $value;
346
        return self::tag('option', $label, $attributes);
347
    }
348
 
349
    /**
350
     * Returns HTML to display a select box option group.
351
     *
352
     * @param string $groupname The label to use for the group
353
     * @param array $options The options in the group
354
     * @param array $selected An array of selected values.
355
     * @param array $disabled An array of disabled options.
356
     * @return string HTML fragment.
357
     */
358
    private static function select_optgroup($groupname, $options, array $selected, array $disabled = []): string {
359
        if (empty($options)) {
360
            return '';
361
        }
362
        $attributes = ['label' => $groupname];
363
        $output = '';
364
        foreach ($options as $value => $label) {
365
            $output .= self::select_option($label, $value, $selected, $disabled);
366
        }
367
        return self::tag('optgroup', $output, $attributes);
368
    }
369
 
370
    /**
371
     * This is a shortcut for making an hour selector menu.
372
     *
373
     * @param string $type The type of selector (years, months, days, hours, minutes)
374
     * @param string $name fieldname
375
     * @param int $currenttime A default timestamp in GMT
376
     * @param int $step minute spacing
377
     * @param null|array $attributes - html select element attributes
378
     * @param float|int|string $timezone the timezone to use to calculate the time
379
     *        {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
380
     * @return string HTML fragment
381
     */
382
    public static function select_time($type, $name, $currenttime = 0, $step = 5, ?array $attributes = null, $timezone = 99) {
383
        global $OUTPUT;
384
 
385
        if (!$currenttime) {
386
            $currenttime = time();
387
        }
388
        $calendartype = \core_calendar\type_factory::get_calendar_instance();
389
        $currentdate = $calendartype->timestamp_to_date_array($currenttime, $timezone);
390
 
391
        $userdatetype = $type;
392
        $timeunits = [];
393
 
394
        switch ($type) {
395
            case 'years':
396
                $timeunits = $calendartype->get_years();
397
                $userdatetype = 'year';
398
                break;
399
            case 'months':
400
                $timeunits = $calendartype->get_months();
401
                $userdatetype = 'month';
402
                $currentdate['month'] = (int)$currentdate['mon'];
403
                break;
404
            case 'days':
405
                $timeunits = $calendartype->get_days();
406
                $userdatetype = 'mday';
407
                break;
408
            case 'hours':
409
                for ($i = 0; $i <= 23; $i++) {
410
                    $timeunits[$i] = sprintf("%02d", $i);
411
                }
412
                break;
413
            case 'minutes':
414
                if ($step != 1) {
415
                    $currentdate['minutes'] = ceil($currentdate['minutes'] / $step) * $step;
416
                }
417
 
418
                for ($i = 0; $i <= 59; $i += $step) {
419
                    $timeunits[$i] = sprintf("%02d", $i);
420
                }
421
                break;
422
            default:
423
                throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
424
        }
425
 
426
        $attributes = (array) $attributes;
427
        $data = (object) [
428
            'name' => $name,
429
            'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
430
            'label' => get_string(substr($type, 0, -1), 'form'),
431
            'options' => array_map(function ($value) use ($timeunits, $currentdate, $userdatetype) {
432
                return [
433
                    'name' => $timeunits[$value],
434
                    'value' => $value,
435
                    'selected' => $currentdate[$userdatetype] == $value,
436
                ];
437
            }, array_keys($timeunits)),
438
        ];
439
 
440
        unset($attributes['id']);
441
        unset($attributes['name']);
442
        $data->attributes = array_map(function ($name) use ($attributes) {
443
            return [
444
                'name' => $name,
445
                'value' => $attributes[$name],
446
            ];
447
        }, array_keys($attributes));
448
 
449
        return $OUTPUT->render_from_template('core/select_time', $data);
450
    }
451
 
452
    /**
453
     * Shortcut for quick making of lists
454
     *
455
     * Note: 'list' is a reserved keyword ;-)
456
     *
457
     * @param array $items
458
     * @param null|array $attributes
459
     * @param string $tag ul or ol
460
     * @return string
461
     */
462
    public static function alist(array $items, ?array $attributes = null, $tag = 'ul') {
463
        $output = self::start_tag($tag, $attributes) . "\n";
464
        foreach ($items as $item) {
465
            $output .= self::tag('li', $item) . "\n";
466
        }
467
        $output .= self::end_tag($tag);
468
        return $output;
469
    }
470
 
471
    /**
472
     * Returns hidden input fields created from url parameters.
473
     *
474
     * @param moodle_url $url
475
     * @param null|array $exclude list of excluded parameters
476
     * @return string HTML fragment
477
     */
478
    public static function input_hidden_params(moodle_url $url, ?array $exclude = null) {
479
        $exclude = (array)$exclude;
480
        $params = $url->params();
481
        foreach ($exclude as $key) {
482
            unset($params[$key]);
483
        }
484
 
485
        $output = '';
486
        foreach ($params as $key => $value) {
487
            $attributes = ['type' => 'hidden', 'name' => $key, 'value' => $value];
488
            $output .= self::empty_tag('input', $attributes) . "\n";
489
        }
490
        return $output;
491
    }
492
 
493
    /**
494
     * Generate a script tag containing the the specified code.
495
     *
496
     * @param string $jscode the JavaScript code
497
     * @param moodle_url|string $url optional url of the external script, $code ignored if specified
498
     * @return string HTML, the code wrapped in <script> tags.
499
     */
500
    public static function script($jscode, $url = null) {
501
        if ($jscode) {
502
            return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
503
        } else if ($url) {
504
            return self::tag('script', '', ['src' => $url]) . "\n";
505
        } else {
506
            return '';
507
        }
508
    }
509
 
510
    /**
511
     * Renders HTML table
512
     *
513
     * This method may modify the passed instance by adding some default properties if they are not set yet.
514
     * If this is not what you want, you should make a full clone of your data before passing them to this
515
     * method. In most cases this is not an issue at all so we do not clone by default for performance
516
     * and memory consumption reasons.
517
     *
518
     * @param html_table $table data to be rendered
519
     * @return string HTML code
520
     */
521
    public static function table(html_table $table) {
522
        // Prepare table data and populate missing properties with reasonable defaults.
523
        if (!empty($table->align)) {
524
            foreach ($table->align as $key => $aa) {
525
                if ($aa) {
526
                    $table->align[$key] = 'text-align:' . fix_align_rtl($aa) . ';';  // Fix for RTL languages.
527
                } else {
528
                    $table->align[$key] = null;
529
                }
530
            }
531
        }
532
        if (!empty($table->size)) {
533
            foreach ($table->size as $key => $ss) {
534
                if ($ss) {
535
                    $table->size[$key] = 'width:' . $ss . ';';
536
                } else {
537
                    $table->size[$key] = null;
538
                }
539
            }
540
        }
541
        if (!empty($table->wrap)) {
542
            foreach ($table->wrap as $key => $ww) {
543
                if ($ww) {
544
                    $table->wrap[$key] = 'white-space:nowrap;';
545
                } else {
546
                    $table->wrap[$key] = '';
547
                }
548
            }
549
        }
550
        if (!empty($table->head)) {
551
            foreach ($table->head as $key => $val) {
552
                if (!isset($table->align[$key])) {
553
                    $table->align[$key] = null;
554
                }
555
                if (!isset($table->size[$key])) {
556
                    $table->size[$key] = null;
557
                }
558
                if (!isset($table->wrap[$key])) {
559
                    $table->wrap[$key] = null;
560
                }
561
            }
562
        }
563
        if (empty($table->attributes['class'])) {
564
            $table->attributes['class'] = 'generaltable table';
565
        }
566
        if (!empty($table->tablealign)) {
567
            $table->attributes['class'] .= ' boxalign' . $table->tablealign;
568
        }
569
 
570
        // Explicitly assigned properties override those defined via $table->attributes.
571
        $table->attributes['class'] = trim($table->attributes['class']);
572
        $attributes = array_merge($table->attributes, [
573
            'id'            => $table->id,
574
            'width'         => $table->width,
575
            'summary'       => $table->summary,
576
            'cellpadding'   => $table->cellpadding,
577
            'cellspacing'   => $table->cellspacing,
578
        ]);
579
        $output = self::start_tag('table', $attributes) . "\n";
580
 
581
        $countcols = 0;
582
 
583
        // Output a caption if present.
584
        if (!empty($table->caption)) {
585
            $captionattributes = [];
586
            if ($table->captionhide) {
587
                $captionattributes['class'] = 'accesshide';
588
            }
589
            $output .= self::tag(
590
                'caption',
591
                $table->caption,
592
                $captionattributes
593
            );
594
        }
595
 
596
        if (!empty($table->head)) {
597
            $countcols = count($table->head);
598
 
599
            $output .= self::start_tag('thead', []) . "\n";
600
            $output .= self::start_tag('tr', []) . "\n";
601
            $keys = array_keys($table->head);
602
            $lastkey = end($keys);
603
 
604
            foreach ($table->head as $key => $heading) {
605
                // Convert plain string headings into html_table_cell objects.
606
                if (!($heading instanceof html_table_cell)) {
607
                    $headingtext = $heading;
608
                    $heading = new html_table_cell();
609
                    $heading->text = $headingtext;
610
                    $heading->header = true;
611
                }
612
 
613
                if ($heading->header !== false) {
614
                    $heading->header = true;
615
                }
616
 
617
                $tagtype = 'td';
618
                if ($heading->header && (string)$heading->text != '') {
619
                    $tagtype = 'th';
620
                }
621
 
622
                $heading->attributes['class'] .= ' header c' . $key;
623
                if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
624
                    $heading->colspan = $table->headspan[$key];
625
                    $countcols += $table->headspan[$key] - 1;
626
                }
627
 
628
                if ($key == $lastkey) {
629
                    $heading->attributes['class'] .= ' lastcol';
630
                }
631
                if (isset($table->colclasses[$key])) {
632
                    $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
633
                }
634
                $heading->attributes['class'] = trim($heading->attributes['class']);
635
                $attributes = array_merge($heading->attributes, [
636
                    'style'     => $table->align[$key] . $table->size[$key] . $heading->style,
637
                    'colspan'   => $heading->colspan,
638
                ]);
639
 
640
                if ($tagtype == 'th') {
641
                    $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
642
                }
643
 
644
                $output .= self::tag($tagtype, $heading->text, $attributes) . "\n";
645
            }
646
            $output .= self::end_tag('tr') . "\n";
647
            $output .= self::end_tag('thead') . "\n";
648
 
649
            if (empty($table->data)) {
650
                // For valid XHTML strict every table must contain either a valid tr
651
                // or a valid tbody... both of which must contain a valid td.
652
                $output .= self::start_tag('tbody', ['class' => 'empty']);
653
                $output .= self::tag('tr', self::tag('td', '', ['colspan' => count($table->head)]));
654
                $output .= self::end_tag('tbody');
655
            }
656
        }
657
 
658
        if (!empty($table->data)) {
659
            $keys       = array_keys($table->data);
660
            $lastrowkey = end($keys);
661
            $output .= self::start_tag('tbody', []);
662
 
663
            foreach ($table->data as $key => $row) {
664
                if (($row === 'hr') && ($countcols)) {
665
                    $output .= self::tag('td', self::tag('div', '', ['class' => 'tabledivider']), ['colspan' => $countcols]);
666
                } else {
667
                    // Convert array rows to html_table_rows and cell strings to html_table_cell objects.
668
                    if (!($row instanceof html_table_row)) {
669
                        $newrow = new html_table_row();
670
 
671
                        foreach ($row as $cell) {
672
                            if (!($cell instanceof html_table_cell)) {
673
                                $cell = new html_table_cell($cell);
674
                            }
675
                            $newrow->cells[] = $cell;
676
                        }
677
                        $row = $newrow;
678
                    }
679
 
680
                    if (isset($table->rowclasses[$key])) {
681
                        $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
682
                    }
683
 
684
                    if ($key == $lastrowkey) {
685
                        $row->attributes['class'] .= ' lastrow';
686
                    }
687
 
688
                    // Explicitly assigned properties should override those defined in the attributes.
689
                    $row->attributes['class'] = trim($row->attributes['class']);
690
                    $trattributes = array_merge($row->attributes, [
691
                        'id'            => $row->id,
692
                        'style'         => $row->style,
693
                    ]);
694
                    $output .= self::start_tag('tr', $trattributes) . "\n";
695
                    $keys2 = array_keys($row->cells);
696
                    $lastkey = end($keys2);
697
 
698
                    $gotlastkey = false; // Flag for sanity checking.
699
                    foreach ($row->cells as $key => $cell) {
700
                        if ($gotlastkey) {
701
                            // This should never happen. Why do we have a cell after the last cell?
702
                            mtrace("A cell with key ($key) was found after the last key ($lastkey)");
703
                        }
704
 
705
                        if (!($cell instanceof html_table_cell)) {
706
                            $mycell = new html_table_cell();
707
                            $mycell->text = $cell;
708
                            $cell = $mycell;
709
                        }
710
 
711
                        if (($cell->header === true) && empty($cell->scope)) {
712
                            $cell->scope = 'row';
713
                        }
714
 
715
                        if (isset($table->colclasses[$key])) {
716
                            $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
717
                        }
718
 
719
                        $cell->attributes['class'] .= ' cell c' . $key;
720
                        if ($key == $lastkey) {
721
                            $cell->attributes['class'] .= ' lastcol';
722
                            $gotlastkey = true;
723
                        }
724
                        $tdstyle = '';
725
                        $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
726
                        $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
727
                        $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
728
                        $cell->attributes['class'] = trim($cell->attributes['class']);
729
                        $tdattributes = array_merge($cell->attributes, [
730
                            'style' => $tdstyle . $cell->style,
731
                            'colspan' => $cell->colspan,
732
                            'rowspan' => $cell->rowspan,
733
                            'id' => $cell->id,
734
                            'abbr' => $cell->abbr,
735
                            'scope' => $cell->scope,
736
                        ]);
737
                        $tagtype = 'td';
738
                        if ($cell->header === true) {
739
                            $tagtype = 'th';
740
                        }
741
                        $output .= self::tag($tagtype, $cell->text, $tdattributes) . "\n";
742
                    }
743
                }
744
                $output .= self::end_tag('tr') . "\n";
745
            }
746
            $output .= self::end_tag('tbody') . "\n";
747
        }
748
        $output .= self::end_tag('table') . "\n";
749
 
750
        if ($table->responsive) {
751
            return self::div($output, 'table-responsive');
752
        }
753
 
754
        return $output;
755
    }
756
 
757
    /**
758
     * Renders form element label
759
     *
760
     * By default, the label is suffixed with a label separator defined in the
761
     * current language pack (colon by default in the English lang pack).
762
     * Adding the colon can be explicitly disabled if needed. Label separators
763
     * are put outside the label tag itself so they are not read by
764
     * screenreaders (accessibility).
765
     *
766
     * Parameter $for explicitly associates the label with a form control. When
767
     * set, the value of this attribute must be the same as the value of
768
     * the id attribute of the form control in the same document. When null,
769
     * the label being defined is associated with the control inside the label
770
     * element.
771
     *
772
     * @param string $text content of the label tag
773
     * @param string|null $for id of the element this label is associated with, null for no association
774
     * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
775
     * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
776
     * @return string HTML of the label element
777
     */
778
    public static function label($text, $for, $colonize = true, array $attributes = []) {
779
        if (!is_null($for)) {
780
            $attributes = array_merge($attributes, ['for' => $for]);
781
        }
782
        $text = trim($text ?? '');
783
        $label = self::tag('label', $text, $attributes);
784
 
785
        // TODO MDL-12192 $colonize disabled for now yet
786
        // if (!empty($text) and $colonize) {
787
        // the $text may end with the colon already, though it is bad string definition style
788
        // $colon = get_string('labelsep', 'langconfig');
789
        // if (!empty($colon)) {
790
        // $trimmed = trim($colon);
791
        // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
792
        // debugging('The label text should not end with colon or other label separator,
793
        // please fix the string definition.', DEBUG_DEVELOPER);
794
        // } else {
795
        // $label .= $colon;
796
        // }
797
        // }
798
        // }
799
 
800
        return $label;
801
    }
802
 
803
    /**
804
     * Combines a class parameter with other attributes. Aids in code reduction
805
     * because the class parameter is very frequently used.
806
     *
807
     * If the class attribute is specified both in the attributes and in the
808
     * class parameter, the two values are combined with a space between.
809
     *
810
     * @param string $class Optional CSS class (or classes as space-separated list)
811
     * @param null|array $attributes Optional other attributes as array
812
     * @return array Attributes (or null if still none)
813
     */
814
    private static function add_class($class = '', ?array $attributes = null) {
815
        if ($class !== '') {
816
            $classattribute = ['class' => $class];
817
            if ($attributes) {
818
                if (array_key_exists('class', $attributes)) {
819
                    $attributes['class'] = trim($attributes['class'] . ' ' . $class);
820
                } else {
821
                    $attributes = $classattribute + $attributes;
822
                }
823
            } else {
824
                $attributes = $classattribute;
825
            }
826
        }
827
        return $attributes;
828
    }
829
 
830
    /**
831
     * Creates a <div> tag. (Shortcut function.)
832
     *
833
     * @param string $content HTML content of tag
834
     * @param string $class Optional CSS class (or classes as space-separated list)
835
     * @param null|array $attributes Optional other attributes as array
836
     * @return string HTML code for div
837
     */
838
    public static function div($content, $class = '', ?array $attributes = null) {
839
        return self::tag('div', $content, self::add_class($class, $attributes));
840
    }
841
 
842
    /**
843
     * Starts a <div> tag. (Shortcut function.)
844
     *
845
     * @param string $class Optional CSS class (or classes as space-separated list)
846
     * @param null|array $attributes Optional other attributes as array
847
     * @return string HTML code for open div tag
848
     */
849
    public static function start_div($class = '', ?array $attributes = null) {
850
        return self::start_tag('div', self::add_class($class, $attributes));
851
    }
852
 
853
    /**
854
     * Ends a <div> tag. (Shortcut function.)
855
     *
856
     * @return string HTML code for close div tag
857
     */
858
    public static function end_div() {
859
        return self::end_tag('div');
860
    }
861
 
862
    /**
863
     * Creates a <span> tag. (Shortcut function.)
864
     *
865
     * @param string $content HTML content of tag
866
     * @param string $class Optional CSS class (or classes as space-separated list)
867
     * @param null|array $attributes Optional other attributes as array
868
     * @return string HTML code for span
869
     */
870
    public static function span($content, $class = '', ?array $attributes = null) {
871
        return self::tag('span', $content, self::add_class($class, $attributes));
872
    }
873
 
874
    /**
875
     * Starts a <span> tag. (Shortcut function.)
876
     *
877
     * @param string $class Optional CSS class (or classes as space-separated list)
878
     * @param null|array $attributes Optional other attributes as array
879
     * @return string HTML code for open span tag
880
     */
881
    public static function start_span($class = '', ?array $attributes = null) {
882
        return self::start_tag('span', self::add_class($class, $attributes));
883
    }
884
 
885
    /**
886
     * Ends a <span> tag. (Shortcut function.)
887
     *
888
     * @return string HTML code for close span tag
889
     */
890
    public static function end_span() {
891
        return self::end_tag('span');
892
    }
893
}
894
 
895
// Alias this class to the old name.
896
// This file will be autoloaded by the legacyclasses autoload system.
897
// In future all uses of this class will be corrected and the legacy references will be removed.
898
class_alias(html_writer::class, \html_writer::class);