BuildForm.php 34.2 KB
Newer Older
1
2
3
4
5
<?php

namespace qfq;

use qfq;
6
7
8
use qfq\store\Store;
use qfq\exceptions\UserException;
use qfq\helper\OnArray;
9
10
11
12

require_once(__DIR__ . '/../qfq/store/Store.php');
require_once(__DIR__ . '/../qfq/Constants.php');
require_once(__DIR__ . '/../qfq/exceptions/DbException.php');
13
require_once(__DIR__ . '/../qfq/exceptions/UserException.php');
14
15
16
17
18
19
20
21
require_once(__DIR__ . '/../qfq/Database.php');

/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/6/16
 * Time: 8:02 PM
 */
22
class FormBuild {
23
24
25
    protected $formSpec = array();  // copy of the loaded form
    protected $feSpecAction = array(); // copy of all formElement.class='action' of the loaded form
    protected $feSpecNative = array(); // copy of all formElement.class='native' of the loaded form
26
    protected $store = null;
Carsten  Rose's avatar
Carsten Rose committed
27
    protected $evaluate = null;
28
29
    protected $buildElementFunctionName = array();
    protected $pattern = array();
30

31
32
33
34
35
    public function __construct(array $formSpec, array $feSpecAction, array $feSpecNative) {
        $this->formSpec = $formSpec;
        $this->feSpecAction = $feSpecAction;
        $this->feSpecNative = $feSpecNative;
        $this->store = Store::getInstance();
36
        $this->db = new Database();
Carsten  Rose's avatar
Carsten Rose committed
37
        $this->evaluate = new Evaluate($this->store, $this->db);
38
39
//        $sip = $this->store->getVar(CLIENT_SIP, STORE_CLIENT);

40
41
42
43
        switch ($formSpec['render']) {
            case 'plain':
                $this->wrap[WRAP_SETUP_TITLE][WRAP_SETUP_START] = '<h3>';
                $this->wrap[WRAP_SETUP_TITLE][WRAP_SETUP_END] = '</h3>';
44

45
46
                $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_START] = '<p>';
                $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_END] = '</p>';
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
                $this->wrap[WRAP_SETUP_LABEL][WRAP_SETUP_START] = '';
                $this->wrap[WRAP_SETUP_LABEL][WRAP_SETUP_END] = '';
                $this->wrap[WRAP_SETUP_INPUT][WRAP_SETUP_START] = '';
                $this->wrap[WRAP_SETUP_INPUT][WRAP_SETUP_END] = '';
                $this->wrap[WRAP_SETUP_NOTE][WRAP_SETUP_START] = '';
                $this->wrap[WRAP_SETUP_NOTE][WRAP_SETUP_END] = '';
                break;
            case 'table':
                $this->wrap[WRAP_SETUP_TITLE][WRAP_SETUP_START] = '<h3>';
                $this->wrap[WRAP_SETUP_TITLE][WRAP_SETUP_END] = '</h3>';

                $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_START] = '<tr>';
                $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_END] = '</tr>';

                $this->wrap[WRAP_SETUP_LABEL][WRAP_SETUP_START] = '<td align="right">';
                $this->wrap[WRAP_SETUP_LABEL][WRAP_SETUP_END] = '</td>';
                $this->wrap[WRAP_SETUP_INPUT][WRAP_SETUP_START] = '<td>';
                $this->wrap[WRAP_SETUP_INPUT][WRAP_SETUP_END] = '</td>';
                $this->wrap[WRAP_SETUP_NOTE][WRAP_SETUP_START] = '<td>';
                $this->wrap[WRAP_SETUP_NOTE][WRAP_SETUP_END] = '</td>';

                $this->wrap[WRAP_SETUP_SUBRECORD][WRAP_SETUP_START] = '<p>';
                $this->wrap[WRAP_SETUP_SUBRECORD][WRAP_SETUP_END] = '</p>';
                break;
            case 'bootstrap':
                $this->wrap[WRAP_SETUP_TITLE][WRAP_SETUP_START] = '<h3>';
                $this->wrap[WRAP_SETUP_TITLE][WRAP_SETUP_END] = '</h3>';

                $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_START] = '<p>';
                $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_END] = '</p>';

                $this->wrap[WRAP_SETUP_LABEL][WRAP_SETUP_START] = '';
                $this->wrap[WRAP_SETUP_LABEL][WRAP_SETUP_END] = '';
                $this->wrap[WRAP_SETUP_INPUT][WRAP_SETUP_START] = '';
                $this->wrap[WRAP_SETUP_INPUT][WRAP_SETUP_END] = '';
                $this->wrap[WRAP_SETUP_NOTE][WRAP_SETUP_START] = '';
                $this->wrap[WRAP_SETUP_NOTE][WRAP_SETUP_END] = '';
                break;
        }
87
88
89

        $this->buildElementFunctionName = [
            'checkbox' => 'Checkbox',
90
91
            'dateJQW' => 'DateJQW',
            'datetimeJQW' => 'DateJQW',
92
93
94
95
96
97
98
99
            'email' => 'Input',
            'gridJQW' => 'GridJQW',
            'hidden' => 'Hidden',
            'input' => 'Input',
            'note' => 'Note',
            'password' => 'Input',
            'radio' => 'Radio',
            'select' => 'Select',
100
            'subrecord' => 'Subrecord',
Carsten  Rose's avatar
Carsten Rose committed
101
            'upload' => 'File',
102
103
104
105
106
107
108
109
110
            'url' => 'Input'
        ];

        $this->inputCheckPattern = [
            'min|max' => 'min="%s"|max="%s"',
            'pattern' => 'pattern="%s"',
            'number' => 'pattern="^[0-9]*$"',
            'email' => 'pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"'
        ];
Carsten  Rose's avatar
Carsten Rose committed
111

112
113
    }

114
115
116
117
118
119
120
121
122
    /**
     * @return string The whole form as HTML
     * @throws exceptions\CodeException
     * @throws exceptions\DbException
     */
    public function process() {

        $html = $this->head();

123
124
        $mode = ($this->formSpec['render']) == 'bootstrap' ? FORM_ELEMENTS_NATIVE_SUBRECORD : FORM_ELEMENTS_NATIVE;

125
        if ($this->formSpec['multiMode'] !== 'none') {
126

127
128
129
            $parentRecords = $this->db->sql($this->formSpec['multiSql']);
            foreach ($parentRecords as $row) {
                $this->store->setVarArray($row, STORE_PARENT_RECORD);
130
                $html .= $this->elements($row['_id'], $mode);
131
132
            }
        } else {
133
            $html .= $this->elements($this->store->getVar(SIP_RECORD_ID, STORE_SIP), $mode);
134
135
        }

136
        // close the form
137
138
        $html .= $this->tail();

139
140
141
142
143
        // render 'plain' and 'table': do subrecords below the form.
        if ($this->formSpec['render'] !== 'bootstrap') {
            $html .= $this->elements($this->store->getVar(SIP_RECORD_ID, STORE_SIP), FORM_ELEMENTS_SUBRECORD);
        }

144
145
146
147
148
149
        return $html;
    }

    /**
     * @return string
     */
150
    public function head() {
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        $html = '';

        switch ($this->formSpec['render']) {
            case 'plain':
                $html .= $this->wrapItem(WRAP_SETUP_TITLE, $this->formSpec['title'], true);
                $html .= '<form action="?" method="post" target="_top" accept-charset="UTF-8">';
                break;
            case 'table':

                $html .= $this->wrapItem(WRAP_SETUP_TITLE, $this->formSpec['title'], true);
                $html .= '<table>';
                $html .= '<form action="?" method="post" target="_top" accept-charset="UTF-8">';
                break;
            case 'bootstrap':
                $html .= $this->wrapItem(WRAP_SETUP_TITLE, $this->formSpec['title'], true);
                $html .= '<form action="?" method="post" target="_top" accept-charset="UTF-8">';
                break;
            default:
                throw new qfq\exceptions\CodeException('Unknown Form.render: \'' . $this->formSpec['render'] . '\'', ERROR_UNKNOWN_FORM_RENDER);
        }
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

        return $html;
    }

    /**
     * @param $item
     * @param $value
     * @param bool|false $flagOmitEmpty
     * @return string
     */
    private function wrapItem($item, $value, $flagOmitEmpty = false) {
        if ($flagOmitEmpty && $value === "")
            return '';
        return $this->wrap[$item][WRAP_SETUP_START] . $value . $this->wrap[$item][WRAP_SETUP_END];
    }

    /**
     * @param $recordId
189
     * @param string $elementType FORM_ELEMENTS_NATIVE | FORM_ELEMENTS_SUBRECORD | FORM_ELEMENTS_NATIVE_SUBRECORD
190
191
192
193
     * @return string
     * @throws exceptions\CodeException
     * @throws exceptions\DbException
     */
194
    public function elements($recordId, $elementType = FORM_ELEMENTS_NATIVE) {
195
196
197
        $html = '';

        // get current data record
198
        if ($recordId > 0 && $this->store->getVar('id', STORE_RECORD) === false) {
199
200
201
            $row = $this->db->sql("SELECT * FROM `" . $this->formSpec['tableName'] . "` WHERE id = ?", ROW_REGULAR, array($recordId));
            $this->store->setVarArray($row[0], STORE_RECORD);
        }
202
203
204

        // Iterate over all FormElements
        foreach ($this->feSpecNative as $fe) {
205
206
207
208
209
210
211

            if (($elementType === FORM_ELEMENTS_NATIVE && $fe['type'] === 'subrecord') ||
                ($elementType === FORM_ELEMENTS_SUBRECORD && $fe['type'] !== 'subrecord')
            ) {
                continue; // skip this FE
            }

212
213
214
215
216
217
            // Log / Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, $fe['name'] . ' / ' . $fe['id'], STORE_SYSTEM);

            // evaluate current FormElement
            $formElement = $this->evaluate->parseArray($fe);

218
            // Get default value
219
            $value = $formElement['value'] === '' ? $this->store->getVar($formElement['name']) : $value = $formElement['value'];
Carsten  Rose's avatar
Carsten Rose committed
220

221
            $htmlFormElementId = $formElement['name'] . ':' . $recordId;
222

223
224
225
            // Construct Marshaller Name
            $buildElementFunctionName = 'build' . $this->buildElementFunctionName[$formElement['type']];

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
            switch ($this->formSpec['render']) {
                case 'plain':
                    $html .= $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_START];
                    $html .= $this->wrapItem(WRAP_SETUP_LABEL, $this->buildLabel($htmlFormElementId, $formElement['label']));
                    $html .= $this->wrapItem(WRAP_SETUP_INPUT, $this->$buildElementFunctionName($formElement, $htmlFormElementId, $value));
                    $html .= $this->wrapItem(WRAP_SETUP_NOTE, $formElement['note']);
                    $html .= $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_END];
                    break;
                case 'table':
                    if ($formElement['type'] === 'subrecord') {
                        // subrecord in render='table' are outside the table
                        $html .= $this->wrapItem(WRAP_SETUP_SUBRECORD, $formElement['label']);
                        $html .= $this->wrapItem(WRAP_SETUP_SUBRECORD, $this->$buildElementFunctionName($formElement, $htmlFormElementId, $value));
                        $html .= $this->wrapItem(WRAP_SETUP_SUBRECORD, $formElement['note']);
                    } else {
                        $html .= $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_START];
                        $html .= $this->wrapItem(WRAP_SETUP_LABEL, $this->buildLabel($htmlFormElementId, $formElement['label']));
                        $html .= $this->wrapItem(WRAP_SETUP_INPUT, $this->$buildElementFunctionName($formElement, $htmlFormElementId, $value));
                        $html .= $this->wrapItem(WRAP_SETUP_NOTE, $formElement['note']);
                        $html .= $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_END];
                    }
                    break;
                case 'bootstrap':
                    $html .= $this->wrapItem(WRAP_SETUP_TITLE, $this->formSpec['title'], true);
                    $html .= '<form action="?" method="post" target="_top" accept-charset="UTF-8">';
                    break;
                default:
                    throw new qfq\exceptions\CodeException('Unknown Form.render: \'' . $this->formSpec['render'] . '\'', ERROR_UNKNOWN_FORM_RENDER);
            }
255
        }
256
257
258
        return $html;
    }

259
260
261
262
263
264
265
    /**
     * @param array $htmlFormElementId
     * @param $label
     * @return string
     */
    private function buildLabel($htmlFormElementId, $label) {
        $html = '<label for="' . $htmlFormElementId . '">' . $label . '</label>';
266
267
268
269

        return $html;
    }

270
271
272
273
    /**
     * @return string
     */
    public function tail() {
274
275
        $html = '';

276
//        $recordId = $this->store->getVar(SIP_RECORD_ID, STORE_SIP);
277
        $sip = $this->store->getVar(CLIENT_SIP, STORE_CLIENT);
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//        $sipName = CLIENT_SIP . ':' . $recordId;
        $sipName = CLIENT_SIP;
//        $html .= '<input type="hidden" name="' . $sipName . '" value="' . $sip . '">';
        $html .= $this->buildHidden(array(), $sipName, $sip);

        switch ($this->formSpec['render']) {
            case 'plain':
                $html .= $this->wrapItem(WRAP_SETUP_INPUT, '<input type="submit" value="Submit">');
                $html = $this->wrapItem(WRAP_SETUP_ELEMENT, $html);
                $html .= '</form>';
                break;
            case 'table':
                $html .= $this->wrapItem(WRAP_SETUP_LABEL, '', false);
                $html .= $this->wrapItem(WRAP_SETUP_INPUT, '<input type="submit" value="Submit">');
                $html = $this->wrapItem(WRAP_SETUP_ELEMENT, $html);
                $html .= '</table></form>';
                break;
            case 'bootstrap':
                // TODO: bootstrap
                break;
            default:
                throw new qfq\exceptions\CodeException('Unknown Form.render: \'' . $this->formSpec['render'] . '\'', ERROR_UNKNOWN_FORM_RENDER);
        }
301
302
303
304

        return $html;
    }

305
306
307
308
309
310
311
312
313
314
    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return string
     */
    private function buildHidden(array $formElement, $htmlFormElementId, $value) {
        return '<input type="hidden" name="' . $htmlFormElementId . '" value="' . htmlentities($value) . '">';
    }

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    /**
     * Builds HTML 'input' element.
     * Format: <input name="$htmlFormElementId" <type="email|input|password|url" [autocomplete="autocomplete"] [autofocus="autofocus"]
     *           [maxlength="$maxLength"] [placeholder="$placeholder"] [size="$size"] [min="$min"] [max="$max"]
     *           [pattern="$pattern"] [readonly="readonly"] [required="required"] [disabled="disabled"] value="$value">
     *
     *
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return string
     * @throws UserException
     */
    private function buildInput(array $formElement, $htmlFormElementId, $value) {

Carsten  Rose's avatar
Carsten Rose committed
330
        $attribute = $this->getAttribute('name', $htmlFormElementId);
331
332
333
334
335
336
337
338
339
        $htmlTag = '<input';
        $htmlTagClosing = '';

        // Check for input type 'textarea'
        $colsRows = explode(',', $formElement['size']);
        if (count($colsRows) === 2) {
            $htmlTag = '<textarea';
            $htmlTagClosing = '</textarea>';

Carsten  Rose's avatar
Carsten Rose committed
340
341
            $attribute .= $this->getAttribute('cols', $colsRows[0]);
            $attribute .= $this->getAttribute('rows', $colsRows[1]);
342
343

        } else {
344
            $attribute .= $this->getAttributeList($formElement, ['type', 'size', 'maxLength']);
Carsten  Rose's avatar
Carsten Rose committed
345
        }
346
        // 'maxLength' needs an upper 'L': naming convention for DB tables!
347
        $attribute .= $this->getAttributeList($formElement, ['autocomplete', 'autofocus', 'placeholder']);
348
349
350
351

        if ($formElement['type'] === 'email' && $formElement['checkType'] === '')
            $formElement['checkType'] = 'email';

Carsten  Rose's avatar
Carsten Rose committed
352
        $attribute .= $this->getInputCheckPattern($formElement['checkType'], $formElement['checkPattern']);
353

Carsten  Rose's avatar
Carsten Rose committed
354
        $attribute .= $this->getAttributeMode($formElement);
355

356
        $attribute .= $this->getAttribute('value', htmlentities($value), false);
357
358
359
360
361
362
363
364
365
366

        return "$htmlTag $attribute>$htmlTagClosing";
    }

    /**
     * @param $type
     * @param $value
     * @param bool|false $flagOmitEmpty
     * @return string
     */
Carsten  Rose's avatar
Carsten Rose committed
367
    private function getAttribute($type, $value, $flagOmitEmpty = true) {
368
369
        if ($flagOmitEmpty && $value === "")
            return '';
Carsten  Rose's avatar
Carsten Rose committed
370

371
372
373
374
375
376
377
378
379
380
381
382
        return "$type=\"$value\" ";
    }

    /**
     * Builds a HTML attribute list, based on  $attributeList.
     * E.g.: attributeList: [ 'type', 'autofocus' ]
     *       generates: 'type="$formElement['type']" autofocus="$formElement['autofocus']" '
     *
     * @param array $formElement
     * @param array $attributeList
     * @return string
     */
Carsten  Rose's avatar
Carsten Rose committed
383
    private function getAttributeList(array $formElement, array $attributeList) {
384
385
386
        $attribute = '';
        foreach ($attributeList as $item) {
            if (isset($formElement[$item]))
Carsten  Rose's avatar
Carsten Rose committed
387
                $attribute .= $this->getAttribute(strtolower($item), $formElement[$item]);
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
        }
        return $attribute;
    }

    /**
     * Construct HTML Input attribute for Client Validation:
     *   type     data                      predefined
     *   -------  -----------------------   -------------------------------------------------------------------------------
     *   min|max  <min value>|<max value>   min="%s"|max="%s"
     *   pattern  <regexp>                  pattern="%s"
     *   number   -                         pattern="^[0-9]*$"
     *   email    -                         pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"
     *
     * For 'min|max' and 'pattern' the 'data' will be injected in the attribute string vai '%s'.
     *
     * @param $type
     * @param $data
     * @return string
     */
Carsten  Rose's avatar
Carsten Rose committed
407
    private function getInputCheckPattern($type, $data) {
408
409
        if ($type === '') {
            return '';
410
        }
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

        $attribute = '';

        $arrAttr = explode("|", $type);
        $arrData = explode("|", $data);

        for ($ii = 0; $ii < count($arrAttr); $ii++) {
            if ($arrAttr[$ii])
                $attribute .= str_replace('%s', $arrData[$ii], $arrAttr[$ii]) . ' ';
        }
        return $attribute;
    }

    /**
     * @param array $formElement
     * @return string
     * @throws UserException
     */
Carsten  Rose's avatar
Carsten Rose committed
429
    private function getAttributeMode(array $formElement) {
430
431
432
433
434
435
        $attribute = '';

        switch ($formElement['mode']) {
            case 'show':
                break;
            case 'readonly':
Carsten  Rose's avatar
Carsten Rose committed
436
                $attribute .= $this->getAttribute('readonly', 'readonly');
437
438
                break;
            case 'required':
Carsten  Rose's avatar
Carsten Rose committed
439
                $attribute .= $this->getAttribute('required', 'required');
440
441
442
443
                break;
            case 'lock':
                break;
            case 'disabled':
Carsten  Rose's avatar
Carsten Rose committed
444
                $attribute .= $this->getAttribute('disabled', 'disabled');
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
                break;
            default:
                $this->store->setVar(SYSTEM_FORM_ELEMENT, $formElement['name'] . ' / ' . $formElement['id'], STORE_SYSTEM);
                $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, 'mode', STORE_SYSTEM);
                throw new UserException("Unexpected mode '" . $formElement['mode'] . "'");
                break;
        }
        return $attribute;
    }

    /**
     * Builds HTML 'checkbox' element.
     *
     * Checkboxes will only be submitted, if they are checked. Therefore, a hidden element with the unchecked value will be transfered first.
     *
     * Format: <input type="hidden" name="$htmlFormElementId" value="$valueUnChecked">
     *         <input name="$htmlFormElementId" type="checkbox" [autofocus="autofocus"]
     *            [readonly="readonly"] [required="required"] [disabled="disabled"] value="<value>" [checked="checked"] >
     *
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return string
     * @throws UserException
     */
    private function buildCheckbox(array $formElement, $htmlFormElementId, $value) {
        $itemKey = array();
        $itemValue = array();

        // Fill $itemKey & $itemValue
        $this->extractKeyValueList($formElement, $itemKey, $itemValue);

        // Get fallback, if 'checkBoxMode' is not defined:
        if (!isset($formElement['checkBoxMode'])) {
            // This fallback is problematic if 'set' or 'enum' has 2 elements: defaults to single but maybe multi is meant.
            $formElement['checkBoxMode'] = (count($itemKey) > 2) ? 'multi' : 'single';
        }

        if ($formElement['checkBoxMode'] === 'multi') {
            $htmlFormElementId .= '[]';
        } else {
            // Fill meaningfull defaults to parameter:checked|unchecked
            $this->prepareCheckboxCheckedUncheckedValue($itemKey, $formElement);
        }

Carsten  Rose's avatar
Carsten Rose committed
490
491
492
        $attributeBase = $this->getAttributeMode($formElement);
        $attributeBase .= $this->getAttribute('name', $htmlFormElementId);
        $attributeBase .= $this->getAttribute('type', $formElement['type']);
493
494
495
496
497
498
499
500
501
502
503
504

        switch ($formElement['checkBoxMode']) {
            case 'single':
                $html = $this->buildCheckboxSingle($formElement, $htmlFormElementId, $attributeBase, $value);
                break;
            case 'multi';
                $html = $this->buildCheckboxMulti($formElement, $htmlFormElementId, $attributeBase, $value, $itemKey, $itemValue);
                break;
            default:
                throw new UserException('checkBoxMode: \'' . $formElement['checkBoxMode'] . '\' is unknown.', ERROR_CHECKBOXMODE_UNKNOWN);
        }

505
506
507
        return $html;
    }

508
    /**
Carsten  Rose's avatar
Carsten Rose committed
509
     * Look for key/value list in `sql1`, `parameter:itemList`, column definition (in this order, first match counts)
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
     * Copies the found keys to &$itemKey and the values to &$itemValue
     *
     * @param array $formElement
     * @param $itemKey
     * @param $itemValue
     * @throws UserException
     */
    private function extractKeyValueList(array $formElement, &$itemKey, &$itemValue) {
        $fieldType = '';
        $itemKey = array();
        $itemValue = array();

        $itemValue = $this->getItemsForEnumOrSet($formElement['name'], $fieldType);

        if (is_array($formElement['sql1'])) {
525
            $keys = array_keys($formElement['sql1'][0]);
526
527
            $itemKey = array_column($formElement['sql1'], 'id');

528
529
530
531
532
533
534
535
536
537
538
539
            // If there is no column 'id' and at least two columns in total
            if (count($itemKey) === 0 && count($keys) >= 2) {
                $itemKey = array_column($formElement['sql1'], $keys[0]);
            }

            $itemValue = array_column($formElement['sql1'], 'label');
            // If there is no column 'label' (e.g.: SHOW tables)
            if (count($itemValue) === 0) {
                $idx = count($keys) == 1 ? 0 : 1;
                $itemValue = array_column($formElement['sql1'], $keys[$idx]);
            }

540
        } elseif (isset($formElement['itemList'])) {
Carsten  Rose's avatar
Carsten Rose committed
541
            $arr = qfq\helper\KeyValueStringParser::parse($formElement['itemList'], ':', ',', IF_VALUE_EMPTY_COPY_KEY);
542
543
544
            $itemValue = array_values($arr);
            $itemKey = array_keys($arr);
        } elseif ($fieldType === 'enum' || $fieldType === 'set') {
Carsten  Rose's avatar
Carsten Rose committed
545
            // already done at the beginning with '$this->getItemsForEnumOrSet($formElement['name'], $fieldType);'
546
        } else {
547
            throw new UserException("Missing definition (- nothing found in 'sql1', 'parameter:itemValues', 'enum-' or 'set-definition'", ERROR_MISSING_ITEM_VALUES);
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
        }

        if (count($itemKey) === 0) {
            $itemKey = $itemValue;
        }
    }

    /**
     * @param $column
     * @param $fieldType
     * @return array
     * @throws UserException
     */
    private function getItemsForEnumOrSet($column, &$fieldType) {

        // Get column definition
        $fieldTypeDefinition = $this->store->getVar($column, STORE_TABLE_COLUMN_TYPES);

        if ($fieldTypeDefinition === false) {
            throw new UserException("Column '$column' unknown in table '" . $this->formSpec['tableName'] . "'", ERROR_UNKNOWN_COLUMN);
        }

        $length = strlen($fieldTypeDefinition);

        // enum('...   set('
        switch (substr($fieldTypeDefinition, 0, 4)) {
            case 'enum':
                $startPosition = 5;
                break;
            case 'set(':
                $startPosition = 4;
                break;
            default:
                $fieldType = 'string';
                return array();
        }

        // enum('a','b','c', ...)   >> [ 'a', 'b', 'c', ... ]
        // set('a','b','c', ...)   >> [ 'a', 'b', 'c', ... ]
        $items = OnArray::trimArray(explode(',', substr($fieldTypeDefinition, $startPosition, $length - $startPosition - 1)), "'");
        $fieldType = substr($fieldTypeDefinition, 0, $startPosition - 1);

        return $items;
    }

    /**
     * For CheckBox's with only one checkbox: if no parameter:checked|unchecked is defined, take defaults:
     *    checked: first Element in $itemKey
     *  unchecked: ''
     *
     * @param array $itemKey
     * @param array $formElement
     * @throws UserException
     */
    private function prepareCheckboxCheckedUncheckedValue(array $itemKey, array &$formElement) {

        if (!isset($formElement['checked'])) {
            if (isset($itemKey[0])) {
                // First element in $itemKey list
                $formElement['checked'] = $itemKey[0];
            } else {
                // Take column default value
                $formElement['checked'] = $this->store->getVar($formElement['name'], STORE_TABLE_DEFAULT);
            }
        }

        // unchecked
        if (!isset($formElement['unchecked'])) {
            if (isset($itemKey[1])) {
                $formElement['unchecked'] = ($itemKey[0] === $formElement['checked']) ? $itemKey[1] : $itemKey[0];
            } else {
                $formElement['unchecked'] = '';
            }
        }

        if ($formElement['checked'] === $formElement['unchecked']) {
            throw new UserException('FormElement: type=checkbox - checked and unchecked can\'t be the same: ' . $formElement['checked'], ERROR_CHECKBOX_EQUAL);
        }

    }

    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $attribute
     * @param $value
     * @return string
     */
    private function buildCheckboxSingle(array $formElement, $htmlFormElementId, $attribute, $value) {

Carsten  Rose's avatar
Carsten Rose committed
638
639
        $attribute .= $this->getAttribute('name', $htmlFormElementId);
        $attribute .= $this->getAttribute('value', $formElement['checked'], false);
640
        if ($formElement['checked'] === $value) {
Carsten  Rose's avatar
Carsten Rose committed
641
            $attribute .= $this->getAttribute('checked', 'checked');
642
643
        }

Carsten  Rose's avatar
Carsten Rose committed
644
        $attribute .= $this->getAttributeList($formElement, ['autofocus']);
645

Carsten  Rose's avatar
Carsten Rose committed
646
        $html = $this->buildHidden($formElement, $htmlFormElementId, $formElement['unchecked']);
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

        $html .= '<input ' . $attribute . '>';
        if (isset($formElement['label2'])) {
            $html .= $formElement['label2'];
        }

        return $html;
    }

    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $attributeBase
     * @param $value
     * @param $itemKey
     * @param $itemValue
     * @return string
     */
    private function buildCheckboxMulti(array $formElement, $htmlFormElementId, $attributeBase, $value, $itemKey, $itemValue) {
        // Defines which of the checkboxes will be checked.
        $values = explode($value, ',');

Carsten  Rose's avatar
Carsten Rose committed
669
        $attributeBase .= $this->getAttribute('name', $htmlFormElementId);
670

Carsten  Rose's avatar
Carsten Rose committed
671
        $html = $this->buildHidden($formElement, $htmlFormElementId, $value);
672
673
674
675
676
677
678
679
680
681
682

        $flagFirst = true;
        $ii = 0;
        $jj = 0;
        foreach ($itemKey as $item) {
            $ii++;
            $jj++;
            $attribute = $attributeBase;
            if ($flagFirst) {
                $flagFirst = false;
                if (isset($formElement['autofocus']))
Carsten  Rose's avatar
Carsten Rose committed
683
                    $attribute .= $this->getAttribute('autofocus', $formElement['autofocus']);
684
            }
Carsten  Rose's avatar
Carsten Rose committed
685
            $attribute .= $this->getAttribute('value', $item);
686
            if ($item === $values[$jj]) {
Carsten  Rose's avatar
Carsten Rose committed
687
                $attribute .= $this->getAttribute('checked', 'checked');
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
            }
            $html .= '<input ' . $attribute . '>';
            $html .= $itemValue[$ii];
            if ($ii === $formElement['maxLength']) {
                $ii = 0;
                $html .= '<br>';
            }
        }
        return $html;
    }

    /**
     * Build HTML 'radio' element.
     *
     * Checkboxes will only be submitted, if they are checked. Therefore, a hidden element with the unchecked value will be transfered first.
     *
     * Format: <input type="hidden" name="$htmlFormElementId" value="$valueUnChecked">
     *         <input name="$htmlFormElementId" type="radio" [autofocus="autofocus"]
     *            [readonly="readonly"] [required="required"] [disabled="disabled"] value="<value>" [checked="checked"] >
     *
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return string
     * @throws UserException
     */
    private function buildRadio(array $formElement, $htmlFormElementId, $value) {
        $itemKey = array();
        $itemValue = array();

        // Fill $itemKey & $itemValue
        $this->extractKeyValueList($formElement, $itemKey, $itemValue);

Carsten  Rose's avatar
Carsten Rose committed
721
722
723
        $attributeBase = $this->getAttributeMode($formElement);
        $attributeBase .= $this->getAttribute('name', $htmlFormElementId);
        $attributeBase .= $this->getAttribute('type', $formElement['type']);
724
725
726
727

        $jj = 0;
        $flagFirst = true;

Carsten  Rose's avatar
Carsten Rose committed
728
        $html = $this->buildHidden($formElement, $htmlFormElementId, $value);
729
730
731
732
733
734
        for ($ii = 0; $ii < count($itemValue); $ii++) {
            $jj++;
            $attribute = $attributeBase;
            if ($flagFirst) {
                $flagFirst = false;
                if (isset($formElement['autofocus']))
Carsten  Rose's avatar
Carsten Rose committed
735
                    $attribute .= $this->getAttribute('autofocus', $formElement['autofocus']);
736
737
            }

Carsten  Rose's avatar
Carsten Rose committed
738
            $attribute .= $this->getAttribute('value', $itemKey[$ii]);
739
            if ($itemKey[$ii] === $value) {
Carsten  Rose's avatar
Carsten Rose committed
740
                $attribute .= $this->getAttribute('checked', 'checked');
741
742
743
744
745
746
747
748
749
750
751
            }
            $html .= '<input ' . $attribute . '>';
            $html .= $itemValue[$ii];
            if ($jj === $formElement['maxLength']) {
                $jj = 0;
                $html .= '<br>';
            }
        }
        return $html;
    }

Carsten  Rose's avatar
Carsten Rose committed
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return mixed
     */
    private function buildSelect(array $formElement, $htmlFormElementId, $value) {
        $itemKey = array();
        $itemValue = array();

        // Fill $itemKey & $itemValue
        $this->extractKeyValueList($formElement, $itemKey, $itemValue);

        $attribute = $this->getAttributeMode($formElement);
        $attribute .= $this->getAttribute('name', $htmlFormElementId);
        $attribute .= $this->getAttributeList($formElement, ['type', 'autofocus']);

        if (isset($formElement['size']) && $formElement['size'] > 1) {
            $attribute .= $this->getAttribute('size', $formElement['size']);
            $attribute .= $this->getAttribute('multiple', 'multiple');
        }

        $option = '';

        if (isset($formElement['emptyItemAtStart']))
            $option = '<option></option>';

        for ($ii = 0; $ii < count($itemValue); $ii++) {
            $option .= '<option ';

            $option .= $this->getAttribute('value', $itemKey[$ii]);
            if ($itemKey[$ii] === $value) {
                $attribute .= 'selected ';
            }

            $option .= '>' . $itemValue[$ii] . '</option>';
        }

        if (isset($formElement['emptyItemAtEnd']))
            $option = '<option></option>';

        return '<select ' . $attribute . '>' . $option . '</select>';
794
795
    }

Carsten  Rose's avatar
Carsten Rose committed
796
797
798
799
800
801
802
803
804
805
806
    /**
     * Constuct a HTML table of the subrecord data.
     * Column syntax definition: https://wikiit.math.uzh.ch/it/projekt/qfq/qfq-jqwidgets/Documentation#Type:_subrecord
     *
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return string
     * @throws UserException
     */
    private function buildSubrecord(array $formElement, $htmlFormElementId, $value) {
807
808
        $html = '';

Carsten  Rose's avatar
Carsten Rose committed
809
810
811
812
813
814
        if (!is_array($formElement['sql1'])) {
            throw new UserException('Missing \'sql1\' Query', ERROR_MISSING_SQL1);
        }

        // construct column attributes
        $control = $this->getSubrecordColumnControl(array_keys($formElement['sql1'][0]));
815
816
//        $html .= '<b>' . $formElement['label'] . '</b>';
        $html .= '<table border="1">';
Carsten  Rose's avatar
Carsten Rose committed
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        $html .= '<tr><th>' . implode('</th><th>', $control['title']) . '</th></tr>';
        foreach ($formElement['sql1'] as $row) {
            $html .= '<tr>';
            foreach ($row as $col => $value) {
                if (isset($control['icon'][$col])) {
                    $cell = ($value === '') ? '' : "<image src='fileadmin/icons/$value'>";
                } else {
                    $cell = isset($control['nostrip'][$col]) ? $value : strip_tags($value);
                    $cell = substr($cell, 0, $control['width'][$col]);
                }
                $html .= "<td>$cell</td>";
            }
            $html .= '</tr>';
        }
        $html .= '</table>';

833
        return $html;
834
835
    }

Carsten  Rose's avatar
Carsten Rose committed
836
837
838
839
840
841
842
843
    /**
     * @param $titleRaw
     * @return array
     * @throws UserException
     */
    private function getSubrecordColumnControl($titleRaw) {
        $control = array();

844
        foreach ($titleRaw AS $col) {
Carsten  Rose's avatar
Carsten Rose committed
845
846
847
            $control['width'][$col] = SUBRECORD_COLUMN_WIDTH;

            // a) 'City@width=40', b) 'Status@icon', c) 'Mailto@width=80@nostrip'
848
849
850
            $arr = qfq\helper\KeyValueStringParser::parse($col, '=', '@', IF_VALUE_EMPTY_COPY_KEY);
            foreach ($arr as $attribute => $value) {
                switch ($attribute) {
Carsten  Rose's avatar
Carsten Rose committed
851
852
853
854
855
                    case 'width':
                    case 'nostrip':
                    case 'icon':
                        break;
                    default:
856
                        $attribute = 'title';
Carsten  Rose's avatar
Carsten Rose committed
857
858
                        break;
                }
859
                $control[$attribute][$col] = $value;
Carsten  Rose's avatar
Carsten Rose committed
860
            }
861
862
            // Limit title length
            $control['title'][$col] = substr($control['title'][$col], 0, $control['width'][$col]);
Carsten  Rose's avatar
Carsten Rose committed
863
864
        }
        return $control;
865
866
    }

Carsten  Rose's avatar
Carsten Rose committed
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return string
     * @throws UserException
     */
    private function buildFile(array $formElement, $htmlFormElementId, $value) {

        $attribute = $this->getAttributeMode($formElement);
        $attribute .= $this->getAttribute('type', 'file');
        $attribute .= $this->getAttribute('name', $htmlFormElementId);
        $attribute .= $this->getAttributeList($formElement, ['autofocus', 'accept']);

        return '<input ' . $attribute . '>';
    }

    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @throws UserException
     */
    private function buildDateJQW(array $formElement, $htmlFormElementId, $value) {
891
892
893
894
        // TODO: implement
        throw new UserException("Not implemented yet: buildDateJQW()");
    }

Carsten  Rose's avatar
Carsten Rose committed
895
896
897
898
899
900
901
    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @throws UserException
     */
    private function buildGridJQW(array $formElement, $htmlFormElementId, $value) {
902
903
904
        // TODO: implement
        throw new UserException("Not implemented yet: buildGridJQW()");
    }
Carsten  Rose's avatar
Carsten Rose committed
905
906
907
908
909
910
911
912
913
914
915

    /**
     * @param array $formElement
     * @param $htmlFormElementId
     * @param $value
     * @return mixed
     */
    private function buildNote(array $formElement, $htmlFormElementId, $value) {
        return $value;
    }

916
}