-
Notifications
You must be signed in to change notification settings - Fork 4
/
Form.php
522 lines (444 loc) · 15.2 KB
/
Form.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
<?php
namespace Sunlight\Util;
use Sunlight\Extend;
use Sunlight\GenericTemplates;
use Sunlight\Xsrf;
abstract class Form
{
/**
* Check if a checkbox was submitted in POST data
*
* @param bool $default default checkbox state (requires $key_var to detect form submission)
*/
static function loadCheckbox(string $name, bool $default = false, ?string $key_var = null, bool $get = false): bool
{
$request = $GLOBALS[$get ? '_GET' : '_POST'];
if ($key_var !== null && !isset($request[$key_var])) {
return $default; // form not submitted
}
return isset($request[$name]);
}
/**
* Render an <input>
*/
static function input(string $type, ?string $name = null, ?string $value = null, array $attrs = [], bool $doubleEncodeValue = true): string
{
$output = Extend::buffer('form.input', [
'type' => &$type,
'name' => &$name,
'value' => &$value,
'attrs' => &$attrs,
'double_encode_value' => &$doubleEncodeValue,
]);
if ($output === '') {
$output = '<input'
. ($name !== null ? ' name="' . _e($name) . '"' : '')
. ' type="' . _e($type) . '"'
. ($value !== null ? ' value="' . _e($value, $doubleEncodeValue) . '"' : '')
. GenericTemplates::renderAttrs($attrs)
. '>';
}
Extend::call('form.input.after', [
'type' => $type,
'name' => $name,
'value' => $value,
'attrs' => $attrs,
'double_encode_value' => $doubleEncodeValue,
'output' => &$output,
]);
return $output;
}
/**
* Render a <textarea>
*/
static function textarea(?string $name, ?string $content, array $attrs = [], bool $doubleEncodeContent = true): string
{
$output = Extend::buffer('form.textarea', [
'name' => &$name,
'content' => &$content,
'attrs' => &$attrs,
'double_encode_content' => &$doubleEncodeContent,
]);
if ($output === '') {
$output = '<textarea'
. ($name !== null ? ' name="' . _e($name) . '"' : '')
. GenericTemplates::renderAttrs($attrs)
. '>'
. _e($content ?? '', $doubleEncodeContent)
. '</textarea>';
}
Extend::call('form.textarea.after', [
'name' => $name,
'content' => $content,
'attrs' => $attrs,
'double_encode_content' => $doubleEncodeContent,
'output' => &$output,
]);
return $output;
}
/**
* Render a <select>
*
* @param string $name select name
* @param array<array-key, string|array<array-key, string>> $choices value => label or optgroup => choices
* @param array-key|null $selected selected choice or null
* @param array<string, scalar|null> $attrs select tag attributes
* @param array{attrs?: array, selected?: array-key} $options
* @param bool $doubleEncodeLabels {@see _e()}
*/
static function select(?string $name, array $choices, $selected = null, array $attrs = [], bool $doubleEncodeLabels = true): string
{
$output = Extend::buffer('form.select', [
'name' => &$name,
'choices' => &$choices,
'selected' => &$selected,
'attrs' => &$attrs,
'double_encode_labels' => &$doubleEncodeLabels,
]);
if ($output === '') {
$output = '<select'
. ($name !== null ? ' name="' . _e($name) . '"' : '')
. GenericTemplates::renderAttrs($attrs)
. '>';
foreach ($choices as $k => $v) {
if (is_array($v)) {
// optgroup
$output .= '<optgroup label="' . _e((string) $k) . "\">\n";
foreach ($v as $kk => $vv) {
$output .= ' ' . self::option(
$kk,
$vv,
['selected' => $selected !== null && $kk == $selected],
$doubleEncodeLabels
);
$output .= "\n";
}
$output .= '</optgroup>';
} else {
// option
$output .= self::option(
$k,
$v,
['selected' => $selected !== null && $k == $selected],
$doubleEncodeLabels
);
}
$output .= "\n";
}
$output .= '</select>';
}
Extend::call('form.select.after', [
'name' => $name,
'choices' => $choices,
'selected' => $selected,
'attrs' => $attrs,
'double_encode_labels' => $doubleEncodeLabels,
'output' => &$output,
]);
return $output;
}
/**
* Render an <option>
*/
static function option(string $value, string $label, array $attrs = [], bool $doubleEncodeLabel = true): string
{
return '<option'
. ' value="' . _e($value) . '"'
. GenericTemplates::renderAttrs($attrs)
. '>'
. _e($label, $doubleEncodeLabel)
. '</option>';
}
/**
* Render data as hidden inputs
*/
static function renderHiddenInputs(array $data): string
{
$output = '';
$counter = 0;
foreach ($data as $key => $value) {
if ($counter > 0) {
$output .= "\n";
}
$output .= self::renderHiddenInput($key, $value);
++$counter;
}
return $output;
}
/**
* Render 1 or more hidden inputs
*/
static function renderHiddenInput(string $key, $value, array $parentKeys = []): string
{
if (is_array($value)) {
// array
$output = '';
$counter = 0;
foreach ($value as $vkey => $vvalue) {
if ($counter > 0) {
$output .= "\n";
}
$output .= self::renderHiddenInput($key, $vvalue, array_merge($parentKeys, [$vkey]));
++$counter;
}
return $output;
}
// value
$name = _e($key);
if (!empty($parentKeys)) {
$name .= _e('[' . implode('][', $parentKeys) . ']');
}
return self::input('hidden', $name, $value);
}
/**
* Render inputs for date-time selection
*
* Supported options:
* ------------------
* - input_class (-) input class name
* - now_toggle (0) add an option to set the timestamp to current time on save 1/0
* - now_toggle_default (0) enable the now_toggle by default 1/0
*
* @param string $name input name
* @param int|null $timestamp pre-filled timestamp
* @param array{input_class?: string|null, now_toggle?: bool, now_toggle_default?: bool} $options see description
*/
static function editTime(string $name, ?int $timestamp = null, array $options = []): string
{
$options += [
'input_class' => null,
'now_toggle' => false,
'now_toggle_default' => false,
];
$output = Extend::buffer('time.edit', [
'timestamp' => $timestamp,
'options' => &$options,
]);
if ($output === '') {
$attrs = [];
if($options['input_class'] !== null) {
$attrs['class'] = $options['input_class'];
}
$output .= self::input('datetime-local', $name, ($timestamp !== null ? date('Y-m-d\TH:i', $timestamp) : null), $attrs);
if ($options['now_toggle']) {
$output .= ' <label>'
. self::input('checkbox', $name . '_now', '1', ['checked' => (bool) $options['now_toggle_default']])
. _lang('time.update')
. '</label>';
}
}
return $output;
}
/**
* Load date-time value submitted by {@see Form::editTime()}
*
* @param string $name input name
* @param int|null $default default in case of invalid value
* @param bool $get load value from GET data instead of POST
*/
static function loadTime(string $name, ?int $default = null, bool $get = false): ?int
{
$value = Extend::fetch('time.load', [
'name' => $name,
'default' => $default,
]);
if ($value !== null) {
return $value;
}
if (self::loadCheckbox($name . '_now')) {
return time();
}
$value = $get ? Request::get($name) : Request::post($name);
if ($value === null) {
return $default;
}
$datetime = \DateTime::createFromFormat('Y-m-d\TH:i', $value) ?: \DateTime::createFromFormat('Y-m-d\TH:i:s', $value);
if ($datetime === false) {
return $default;
}
return $datetime->getTimestamp();
}
/**
* Render a form
*
* Supported options:
* ------------------
* - name (-) name attribute
* - method (post) method attribute
* - action (-) action attribute
* - autocomplete (-) autocomplete attribute
* - enctype (-) enctype attribute
* - multipart (0) set enctype to "multipart/form-data"
* - id (-) id attribute
* - class (-) class attribute
* - embedded (0) don't render <form> tag and XSRF input
* - table_attrs custom HTML at the end of the <table> tag
* - table_prepend custom after before <table>
* - table_append custom HTML before </table>
* - form_prepend custom HTML after <form>
* - form_append custom HTML before </form>
*
* Format of a single row in $rows:
* --------------------------------
* - label (-) row label
* - content (-) row content
* - top (0) align the row to the top 1/0
* - class (-) custom <tr> class
*
* - if both label and content is empty, the row is skipped
* - if label is null, the content cell will span the entire row
* - use {@see Form::getSubmitRow()} to add a submit button
*
* @param array{
* name?: string|null,
* method?: string,
* action?: string|null,
* autocomplete?: string|null,
* enctype?: string|null,
* multipart?: bool,
* id?: string|null,
* class?: string|null,
* embedded?: bool,
* table_attrs?: string,
* table_prepend?: string,
* table_append?: string,
* form_prepend?: string,
* form_append?: string,
* } $options see description
*
* @param array<array{
* label?: string|null,
* content?: string|null,
* top?: bool,
* class?: string
* }> $rows see description
*/
static function render(array $options, array $rows): string
{
$options += [
'name' => null,
'method' => 'post',
'action' => null,
'autocomplete' => null,
'enctype' => null,
'multipart' => false,
'id' => null,
'class' => $options['name'] ?? null,
'embedded' => false,
'table_attrs' => '',
'table_prepend' => '',
'table_append' => '',
'form_prepend' => '',
'form_append' => '',
];
// extend
$extend_buffer = Extend::buffer('form.output', [
'options' => &$options,
'rows' => &$rows,
]);
if ($options['multipart']) {
$options['enctype'] = 'multipart/form-data';
}
if ($extend_buffer !== '') {
// rendered by plugin
return $extend_buffer;
}
// render
$output = '';
// <form>
if (!$options['embedded']) {
$output .= '<form';
foreach (['name', 'method', 'action', 'enctype', 'id', 'class', 'autocomplete'] as $attr) {
if ($options[$attr] !== null) {
$output .= ' ' . $attr . '="' . _e($options[$attr]) . '"';
}
}
$output .= ">\n";
}
$output .= $options['form_prepend'];
// <table>
$output .= "<table{$options['table_attrs']}>\n";
$output .= $options['table_prepend'];
// rows
$useColspan = self::anyRowHasLabel($rows);
foreach ($rows as $row) {
$output .= self::renderRow($row, $useColspan);
}
// </table>
$output .= $options['table_append'];
$output .= "</table>\n";
// </form>
$output .= $options['form_append'];
if (!$options['embedded']) {
$output .= Xsrf::getInput();
$output .= "\n</form>\n";
}
return $output;
}
/**
* Create a form row with a submit button
*
* Supported options:
* ------------------
* - label ('') row label
* - name (-) submit button name
* - text submit button text
* - append HTML after submit button
*
* @param array{
* label?: string|null,
* name?: string|null,
* text?: string|null,
* append?: string|null,
* } $options see description
*/
static function getSubmitRow(array $options = []): array
{
return [
'label' => array_key_exists('label', $options) ? $options['label'] : '',
'content' => self::input('submit', $options['name'] ?? null, $options['text'] ?? _lang('global.send'))
. ($options['append'] ?? ''),
'_submit' => true, // mark the row for plugin purposes
];
}
private static function renderRow(array $row, bool $useColspan): string
{
$row += [
'label' => null,
'content' => null,
'top' => false,
'class' => '',
];
if ($row['top']) {
$row['class'] .= ($row['class'] !== '' ? ' ' : '') . 'valign-top';
}
// skip empty rows
if (empty($row['label']) && empty($row['content'])) {
return '';
}
// <tr>
$output = '<tr' . ($row['class'] !== '' ? ' class="' . $row['class'] . '"' : '') . ">\n";
// label
if ($row['label'] !== null) {
$output .= "<th>{$row['label']}</th>\n";
}
// content
$output .= '<td';
if ($row['label'] === null && $useColspan) {
$output .= ' colspan="2"';
}
$output .= ">{$row['content']}</td>\n";
// </tr>
$output .= "</tr>\n";
return $output;
}
private static function anyRowHasLabel(array $rows): bool
{
foreach ($rows as $row) {
if (isset($row['label'])) {
return true;
}
}
return false;
}
}