HelperFormElement.php 30 KB
Newer Older
Carsten  Rose's avatar
Carsten Rose committed
1
2
3
4
5
6
7
8
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/26/16
 * Time: 11:25 AM
 */

Marc Egger's avatar
Marc Egger committed
9
namespace IMATHUZH\Qfq\Core\Helper;
Carsten  Rose's avatar
Carsten Rose committed
10

Marc Egger's avatar
Marc Egger committed
11
use IMATHUZH\Qfq\Core\Store\Store;
12

Carsten  Rose's avatar
Carsten Rose committed
13

14
15
16
17
/**
 * Class HelperFormElement
 * @package qfq
 */
18
class HelperFormElement {
Carsten  Rose's avatar
Carsten Rose committed
19

Carsten  Rose's avatar
Carsten Rose committed
20
21
22
    /**
     * @var Store
     */
23
    private static $store = null;
Carsten  Rose's avatar
Carsten Rose committed
24

25
    /**
26
     * Expand column $keyName to row array as virtual columns.
27
     * E.g.: [ 'id' => '1', 'name' => 'John', 'parameter' => 'detail=xId:grId\nShowEmptyAtStart=1' ] becomes:
Carsten  Rose's avatar
Carsten Rose committed
28
29
30
     *  [ 'id' => '1', 'name' => 'John', 'parameter' => 'detail=xId:grId\nShowEmptyAtStart=1', 'detail' => 'xId:grId',
     *  'showEmptyAtStart'='1']
     *
31
     * @param array $elements
32
     * @param string $keyName Typically F_PARAMETER or FE_PARAMETER (both: 'parameter')
Carsten  Rose's avatar
Carsten Rose committed
33
     *
Marc Egger's avatar
Marc Egger committed
34
35
36
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
37
     */
38
    public static function explodeParameterInArrayElements(array &$elements, $keyName) {
Carsten  Rose's avatar
Carsten Rose committed
39

40
        foreach ($elements AS $key => $element) {
41
            self::explodeParameter($element, $keyName);
42
43
44
45
            $elements[$key] = $element;
        }
    }

46
47

    /**
48
49
50
     * Set default values for given FormElement.
     * Hint: to copy values from Form, copyAttributesToFormElements() is more appropriate.
     *
51
     * @param array $elements
Carsten  Rose's avatar
Carsten Rose committed
52
     *
53
     * @param array $formSpec
54
55
     * @return array
     */
56
57
    public static function formElementSetDefault(array $elements, array $formSpec) {

Carsten  Rose's avatar
Carsten Rose committed
58
59
        // Do not add FE_SLAVE_ID - it's necessary to detect if a value is given or not.
        $default = [FE_SQL_BEFORE => '', FE_SQL_INSERT => '', FE_SQL_UPDATE => '', FE_SQL_DELETE => '', FE_SQL_AFTER => ''];
60

61
62
        foreach ($elements AS $key => $element) {
            $elements[$key][FE_TG_INDEX] = 0;
63
            unset($elements[$key][FE_ADMIN_NOTE]);
Carsten  Rose's avatar
Carsten Rose committed
64
//            $elements[$key][FE_DATA_REFERENCE] = '';
65
66

            $elements[$key] = array_merge($default, $elements[$key]);
67
68
        }

69

70
71
72
        return $elements;
    }

Carsten  Rose's avatar
Carsten Rose committed
73
    /**
74
     * Take all rows from field $element[$keyName] and merge them with $element itself. '$element' grows in size.
Carsten  Rose's avatar
Carsten Rose committed
75
     *
76
77
     * @param array $element
     * @param string $keyName Typically F_PARAMETER or FE_PARAMETER (both: 'parameter')
Carsten  Rose's avatar
Carsten Rose committed
78
     *
79
     * @param bool $flagAllowOverwrite
Marc Egger's avatar
Marc Egger committed
80
81
82
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
Carsten  Rose's avatar
Carsten Rose committed
83
     */
84
    public static function explodeParameter(array &$element, $keyName, $flagAllowOverwrite = false) {
Carsten  Rose's avatar
Carsten Rose committed
85

86
        // Something to explode?
87
        if (isset($element[$keyName]) && $element[$keyName] !== '') {
88
            // Explode
89
            $arr = KeyValueStringParser::parse($element[$keyName], "=", "\n");
90
91
92
93
94

            if (!$flagAllowOverwrite) {
                // Check if some of the exploded keys conflict with existing keys
                $checkKeys = array_keys($arr);
                foreach ($checkKeys AS $checkKey) {
95
                    if (!empty($element[$checkKey])) {
Carsten  Rose's avatar
Carsten Rose committed
96
97
98
                        self::$store = Store::getInstance();
                        self::$store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($element), STORE_SYSTEM);
                        self::$store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, $keyName, STORE_SYSTEM);
Marc Egger's avatar
Marc Egger committed
99
                        throw new \UserFormException("Found reserved keyname '$checkKey'", ERROR_RESERVED_KEY_NAME);
100
                    }
Carsten  Rose's avatar
Carsten Rose committed
101
102
                }
            }
103
            $element = array_merge($element, $arr);
104
105
106

            // For retype elements: copy the language specific value.
            if (isset($element[FE_RETYPE_SOURCE_NAME])) {
107

108
109
110
                if (!empty($element[FE_RETYPE_LABEL])) {
                    $element[FE_LABEL] = $element[FE_RETYPE_LABEL];
                }
111

112
113
114
115
116
                if (!empty($element[FE_RETYPE_NOTE])) {
                    $element[FE_NOTE] = $element[FE_RETYPE_NOTE];
                }
            }

117
            $element[$keyName] = ''; // to not expand it a second time
118
119
120
        }
    }

121
122
123
124
125
    /**
     * Take language specific definitions and overwrite the default values.
     *
     * @param array $formSpecFeSpecNative
     *
126
     * @param $parameterLanguageFieldName
127
     * @return array
Marc Egger's avatar
Marc Egger committed
128
129
130
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
131
132
133
134
135
136
137
138
139
     */
    public static function setLanguage(array $formSpecFeSpecNative, $parameterLanguageFieldName) {

        if (is_string($parameterLanguageFieldName) && isset($formSpecFeSpecNative[$parameterLanguageFieldName])) {
            self::explodeParameter($formSpecFeSpecNative, $parameterLanguageFieldName, true);
        }

        return $formSpecFeSpecNative;
    }
Carsten  Rose's avatar
Carsten Rose committed
140

141
    /**
142
     * Build the FE name: <field>-<record index)
Carsten  Rose's avatar
Carsten Rose committed
143
     *
Carsten  Rose's avatar
Carsten Rose committed
144
     * @param array $formElement
145
     * @param string $id
Carsten  Rose's avatar
Carsten Rose committed
146
     *
147
148
     * @return string
     */
149
150
151
    public static function buildFormElementName(array $formElement, $id) {
        $field = ($formElement[FE_NAME] == '') ? $formElement[FE_ID] : $formElement[FE_NAME];

152
        return "$field" . HTML_DELIMITER_NAME . "$id";
153
154
    }

155
156
157
158
159
160
161
162
163
164
165
166
    /**
     * Build the internal FE name for an imageCut element (used only in SIP): <field>-imageCut
     *
     * @param array $formElement
     * @return string
     */
    public static function AppendFormElementNameImageCut(array $formElement) {
        $field = ($formElement[FE_NAME] == '') ? $formElement[FE_ID] : $formElement[FE_NAME];

        return "$field" . HTML_DELIMITER_NAME . FE_TYPE_IMAGE_CUT;
    }

167
168
    /**
     * Build the FE id: <$formId>-<$formElementId>-<$formElementCopy>
Carsten  Rose's avatar
Carsten Rose committed
169
     * Attention: Radio's get's an additional index count as fourth parameter (not here).
170
171
172
173
174
     *
     * @param $formId
     * @param $formElementId
     * @param $recordId
     * @param $formElementCopy
Carsten  Rose's avatar
Carsten Rose committed
175
     *
176
177
178
     * @return string
     */
    public static function buildFormElementId($formId, $formElementId, $recordId, $formElementCopy) {
179
        return "$formId" . HTML_DELIMITER_ID . "$formElementId" . HTML_DELIMITER_ID . "$recordId" . HTML_DELIMITER_ID . "$formElementCopy";
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
    /**
     * In an array for $feSpecNative, set FE_HTML_ID for all fe.class=FE_CONTAINER Elements.
     *
     * @param array $feSpecNative
     * @param $formId
     * @param $recordId
     * @param int $formElementCopy
     * @return array
     */
    public static function setFeContainerFormElementId(array $feSpecNative, $formId, $recordId, $formElementCopy = 0) {

        foreach ($feSpecNative as $key => $fe) {

            switch ($fe[FE_CLASS]) {
                case FE_CLASS_CONTAINER:
                    $feSpecNative[$key][FE_HTML_ID] = self::buildFormElementId($formId, $fe[FE_ID], $recordId, $formElementCopy);
                    break;
                default:
                    break;
            }

        }

        return $feSpecNative;
    }

209
    /**
Carsten  Rose's avatar
Carsten Rose committed
210
211
     * Checkboxen, belonging to one element, grouped together by name: <fe>_<field>_<index>
     *
212
213
     * @param string $field
     * @param string $index
Carsten  Rose's avatar
Carsten Rose committed
214
     *
215
     * @param bool $appendArray
216
217
     * @return string
     */
218
219
220
221
    public static function prependFormElementNameCheckBoxMulti($field, $index, $appendArray = false) {
//        return '_' . $index . '_' . $field;

        if ($appendArray) {
222
            return $field . '[]';
223
        }
224
        return $field;
225
226
    }

227
228
229
230
231
    /**
     * Check all FormElements if there are some with the attribute FE_RETYPE.
     * If yes: duplicate such elements and update FE_NAME, FE_LABEL, FE_NOTE.
     *
     * @param array $elements
Carsten  Rose's avatar
Carsten Rose committed
232
     *
233
234
235
236
237
238
239
     * @return array
     */
    public static function duplicateRetypeElements(array $elements) {
        $arr = array();

        foreach ($elements as $fe) {

240
            // adjust FE_RETYPE=1
241
242
243
244
245
246
247
248
            if (isset($fe[FE_RETYPE]) && ($fe[FE_RETYPE] == '' || $fe[FE_RETYPE] == '1')) {
                $fe[FE_RETYPE] = '1';
            }

            $arr[] = $fe;

            if (isset($fe[FE_RETYPE]) && $fe[FE_RETYPE] == '1') {

249
250
                // Reference to Source FormElement
                $fe[FE_RETYPE_SOURCE_NAME] = $fe[FE_NAME];
251
252
253
254
255
256
257
258
259
260
261
262
263
264

                // Create copy of FE, adjust name, label, note
                $fe[FE_NAME] .= RETYPE_FE_NAME_EXTENSION;

                if (isset($fe[FE_RETYPE_LABEL])) {
                    $fe[FE_LABEL] = $fe[FE_RETYPE_LABEL];
                    unset($fe[FE_RETYPE_LABEL]);
                }

                if (isset($fe[FE_RETYPE_NOTE])) {
                    $fe[FE_NOTE] = $fe[FE_RETYPE_NOTE];
                    unset($fe[FE_RETYPE_NOTE]);
                }

265
266
                $fe[FE_TG_INDEX] = 1; // Not sure if this is helpfull in case of dynamic update - but it will make the element uniqe.

267
268
269
270
271
272
273
274
                unset($fe[FE_RETYPE]);
                $arr[] = $fe;
            }
        }

        return $arr;
    }

275
276
277
278
279
    /**
     * Copy specific attributes defined on the form to all FormElements.
     *
     * @param array $formSpec
     * @param array $feSpecNative
Carsten  Rose's avatar
Carsten Rose committed
280
     *
281
282
283
     * @return mixed
     */
    public static function copyAttributesToFormElements(array $formSpec, array $feSpecNative) {
284
285

        // Iterate over all FormElement
286
        foreach ($feSpecNative as $key => $element) {
287
288
289

            $feSpecNative[$key][F_FE_DATA_PATTERN_ERROR_SYSTEM] = $formSpec[F_FE_DATA_PATTERN_ERROR_SYSTEM];

290
291
292
293
            Support::setIfNotSet($feSpecNative[$key], F_FE_DATA_PATTERN_ERROR, $formSpec[F_FE_DATA_PATTERN_ERROR]);
            Support::setIfNotSet($feSpecNative[$key], F_FE_DATA_REQUIRED_ERROR, $formSpec[F_FE_DATA_REQUIRED_ERROR]);
            Support::setIfNotSet($feSpecNative[$key], F_FE_DATA_MATCH_ERROR, $formSpec[F_FE_DATA_MATCH_ERROR]);
            Support::setIfNotSet($feSpecNative[$key], F_FE_DATA_ERROR, $formSpec[F_FE_DATA_ERROR]);
294
295
296
            if ($feSpecNative[$key][F_FE_LABEL_ALIGN] == F_FE_LABEL_ALIGN_DEFAULT) {
                $feSpecNative[$key][F_FE_LABEL_ALIGN] = $formSpec[F_FE_LABEL_ALIGN];
            }
297
            Support::setIfNotSet($feSpecNative[$key], F_FE_REQUIRED_POSITION, $formSpec[F_FE_REQUIRED_POSITION]);
298
            Support::setIfNotSet($feSpecNative[$key], F_FE_MIN_WIDTH, $formSpec[F_FE_MIN_WIDTH]);
299
            Support::setIfNotSet($feSpecNative[$key], FE_INPUT_EXTRA_BUTTON_INFO_MIN_WIDTH, $formSpec[FE_INPUT_EXTRA_BUTTON_INFO_MIN_WIDTH]);
300
301
302
303
304
        }

        return $feSpecNative;
    }

305
306
307
308
309

    /**
     * Set all necessary keys - subsequent 'isset()' are not necessary anymore.
     *
     * @param array $fe
Carsten  Rose's avatar
Carsten Rose committed
310
     *
311
312
313
314
     * @return array
     */
    public static function initActionFormElement(array $fe) {

315
        $list = [FE_TYPE, FE_SQL_VALIDATE, FE_SLAVE_ID, FE_SQL_BEFORE, FE_SQL_INSERT, FE_SQL_UPDATE, FE_SQL_DELETE,
316
317
            FE_SQL_AFTER, FE_EXPECT_RECORDS, FE_REQUIRED_LIST, FE_MESSAGE_FAIL, FE_SENDMAIL_TO, FE_SENDMAIL_CC,
            FE_SENDMAIL_BCC, FE_SENDMAIL_FROM, FE_SENDMAIL_SUBJECT, FE_SENDMAIL_REPLY_TO, FE_SENDMAIL_FLAG_AUTO_SUBMIT,
318
319
            FE_SENDMAIL_GR_ID, FE_SENDMAIL_X_ID, FE_SENDMAIL_X_ID2, FE_SENDMAIL_X_ID3, FE_SENDMAIL_BODY_MODE,
            FE_SENDMAIL_BODY_HTML_ENTITY, FE_SENDMAIL_SUBJECT_HTML_ENTITY];
320
321
322
323
324
325
326
327
328
329
330
331

        foreach ($list as $key) {
            Support::setIfNotSet($fe, $key);
        }

        return $fe;
    }

    /**
     * Set all necessary keys - subsequent 'isset()' are not necessary anymore.
     *
     * @param array $fe
Carsten  Rose's avatar
Carsten Rose committed
332
     *
333
334
335
336
337
338
339
340
341
342
343
344
345
     * @return array
     */
    public static function initUploadFormElement(array $fe) {

        $list = [FE_SQL_BEFORE, FE_SQL_INSERT, FE_SQL_UPDATE, FE_SQL_DELETE, FE_SQL_AFTER];

        foreach ($list as $key) {
            Support::setIfNotSet($fe, $key);
        }

        return $fe;
    }

346
347
348
349
350
351
352
353
354
355
356
357
358
359
    /**
     * Prepare code of 'lock', 'password', 'info' to extend a FormElement.
     * The 'info' will always be added, 'lock' and 'password' only on FE with mode=show|required
     * Depending on $showInside:
     *    * true: a button is shown inside the 'input' or 'select' element.
     *    * false: an icon is shown below the FormElement.
     *
     * 'Add' means:
     *    * $rcButton contains all HTML button code. The calling function is responsible to build the correct code.
     *    * $formElement[FE_INPUT_EXTRA_BUTTON_INFO] has been wrapped with HTML-tag and HTML-id.
     *    * $formElement[FE_MODE] - for 'lock' it will be faked to 'readonly'
     *    * $formElement[FE_TYPE] - for 'password' it will be faked to 'password'
     *
     * @param array $formElement
Carsten  Rose's avatar
Carsten Rose committed
360
     * @param bool $showInline
Carsten  Rose's avatar
Carsten Rose committed
361
     *
362
     * @return array
Marc Egger's avatar
Marc Egger committed
363
364
365
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
366
     */
367
    public static function prepareExtraButton(array $formElement, $showInline) {
368

Carsten  Rose's avatar
Carsten Rose committed
369
        self::$store = Store::getInstance();
370

Carsten  Rose's avatar
Carsten Rose committed
371
372
        $infoSymbolInside = self::$store->getVar(SYSTEM_EXTRA_BUTTON_INFO_INLINE, STORE_SYSTEM);
        $infoSymbolOutside = self::$store->getVar(SYSTEM_EXTRA_BUTTON_INFO_BELOW, STORE_SYSTEM);
373

Carsten  Rose's avatar
Carsten Rose committed
374
        if (SYSTEM_EXTRA_BUTTON_INFO_POSITION_BELOW == self::$store->getVar(SYSTEM_EXTRA_BUTTON_INFO_POSITION, STORE_SYSTEM)) {
375
376
377
            $showInline = false;
        }

378
        $extraButton = '';
379
        $id = $formElement[FE_HTML_ID];
380
381
382
383
384

        if (false !== strpos($formElement[FE_NAME], FE_TEMPLATE_GROUP_NAME_PATTERN)) {
            $id .= '-' . FE_TEMPLATE_GROUP_NAME_PATTERN;
        }

385
        $formElement[FE_TMP_EXTRA_BUTTON_HTML] = '';
386
387
        $minWidth = $formElement[FE_INPUT_EXTRA_BUTTON_INFO_MIN_WIDTH] ?? '';
        $minWidth .= 'px';
388

389
390

        // INFO: $showinline =- TRUE ('input' elements)
391
        if (isset($formElement[FE_INPUT_EXTRA_BUTTON_INFO]) && $showInline) {
392
            $extraButton .= <<<EOF
393
            <button type="button" class="btn btn-info" onclick="$('#$id-extra-info').slideToggle('swing')">
394
395
                $infoSymbolInside
            </button>
396
397
398
399
EOF;

            $value = $formElement[FE_INPUT_EXTRA_BUTTON_INFO];
            $formElement[FE_INPUT_EXTRA_BUTTON_INFO] = <<<EOF
400
            <div class="alert alert-info" id="$id-extra-info" style="display: none; min-width: $minWidth;">
401
402
403
404
405
                <p>$value</p>
            </div>
EOF;
        }

406
407
408
409
410
//        <span class="glyphicon glyphicon-info-sign text-info" aria-hidden="true" onclick="$('#$id-extra-info').slideToggle('swing')"></span>

        $js = " onclick=\"$('#$id-extra-info').slideToggle('swing')\" ";
        $arr = explode(' ', $infoSymbolOutside, 2);
        $infoSymbolOutside = $arr[0] . $js . $arr[1];
411

412
        // INFO: $showinline == FALSE (e.g. 'textarea' elements)
413
        if (isset($formElement[FE_INPUT_EXTRA_BUTTON_INFO]) && !$showInline) {
414
            $class = $formElement[FE_INPUT_EXTRA_BUTTON_INFO_CLASS];
415
            $extraButton .= <<<EOF
416
            <span class="$class">$infoSymbolOutside</span>
417
418
419
420
EOF;

            $value = $formElement[FE_INPUT_EXTRA_BUTTON_INFO];
            $formElement[FE_INPUT_EXTRA_BUTTON_INFO] = <<<EOF
421
            <div class="alert alert-info" id="$id-extra-info" style="display: none; min-width: $minWidth;">
422
423
424
425
426
                <p>$value</p>
            </div>
EOF;
        }

427
428
429
        $skip = (!($formElement[FE_MODE] == FE_MODE_SHOW
            || $formElement[FE_MODE] == FE_MODE_REQUIRED
            || $formElement[FE_MODE] == FE_MODE_SHOW_REQUIRED));
430
431

        // LOCK
432
        if (!$skip && HelperFormElement::booleParameter($formElement[FE_INPUT_EXTRA_BUTTON_LOCK] ?? '-')) {
433
434
            $formElement[FE_MODE] = FE_MODE_READONLY;

435
436
437
438
439
440
441
442
            switch ($formElement[FE_TYPE]) {
                case FE_TYPE_CHECKBOX:
                case FE_TYPE_RADIO:
                    $extraButton .= <<<EOF
                    <button class="btn btn-info"
                            onclick="$('[id^=$id]').parent('label').toggleClass('qfq-disabled')">
                        <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
                    </button>
443
EOF;
444
445
446
447
448
449
450
451
452
                    break;
                default:
                    $extraButton .= <<<EOF
                    <button class="btn btn-info"
                            onclick="$('#$id').prop('readonly',!$('#$id').prop('readonly'))">
                        <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>
                    </button>
EOF;
                    break;
453

454
455
            }
        }
456
        // PASSWORD
457
458
//        if (!$skip && isset($formElement[FE_INPUT_EXTRA_BUTTON_PASSWORD])) {
        if (!$skip && HelperFormElement::booleParameter($formElement[FE_INPUT_EXTRA_BUTTON_PASSWORD] ?? '-')) {
459
460
461

            $formElement[FE_TYPE] = 'password';

462
            $extraButton .= <<<EOF
463
464
465
466
            <button class="btn btn-info"
                    onclick="$('#$id').attr('type',$('#$id').attr('type')==='password' ? 'text': 'password')">
                <span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
            </button>
467
468
469
EOF;
        }

470
471
//        $formElement[FE_TMP_EXTRA_BUTTON_HTML] = Support::wrapTag('<div class="input-group-btn" style="font-size: 1em;">', $extraButton, true);
        $formElement[FE_TMP_EXTRA_BUTTON_HTML] = Support::wrapTag('<div class="input-group-btn">', $extraButton, true);
472
473
        Support::setIfNotSet($formElement, FE_INPUT_EXTRA_BUTTON_INFO);

474
475
476
        return $formElement;
    }

477
    /**
478
     * Returns $maxLength if greater than 0, else FE_TEMPLATE_GROUP_DEFAULT_MAX_LENGTH
479
480
     *
     * @param $maxLength
Carsten  Rose's avatar
Carsten Rose committed
481
     *
482
483
484
485
486
     * @return int
     */
    public static function tgGetMaxLength($maxLength) {
        return (empty($maxLength)) ? FE_TEMPLATE_GROUP_DEFAULT_MAX_LENGTH : $maxLength;
    }
487
488
489
490
491
492

    /**
     * Converts a string of '00ff00' and returns a string of '{"red": 0, "green": 255, "blue": 0}'.
     *
     * @param array $formElement
     * @return string
Marc Egger's avatar
Marc Egger committed
493
     * @throws \UserFormException
494
495
496
497
498
499
500
501
     */
    public static function penColorToHex(array $formElement) {

        if (empty($formElement[FE_DEFAULT_PEN_COLOR])) {
            return '';
        }

        if (strlen($formElement[FE_DEFAULT_PEN_COLOR]) != LENGTH_HEX_COLOR) {
Marc Egger's avatar
Marc Egger committed
502
            throw new \UserFormException("Invalid Format for " . FE_DEFAULT_PEN_COLOR .
503
504
505
506
507
508
509
510
511
                ". Expect like '#ffdd00', got: '" . $formElement[FE_DEFAULT_PEN_COLOR] . "'", ERROR_INVALID_OR_MISSING_PARAMETER);
        }

        $rgb['red'] = hexdec($formElement[FE_DEFAULT_PEN_COLOR][0] . $formElement[FE_DEFAULT_PEN_COLOR][1]);
        $rgb['green'] = hexdec($formElement[FE_DEFAULT_PEN_COLOR][2] . $formElement[FE_DEFAULT_PEN_COLOR][3]);
        $rgb['blue'] = hexdec($formElement[FE_DEFAULT_PEN_COLOR][4] . $formElement[FE_DEFAULT_PEN_COLOR][5]);

        return json_encode($rgb);
    }
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548

    /**
     * Depending on value in $requiredPosition the array $classArr will contain the CSS class to align the required mark.
     * @param $requiredPosition
     * @return array
     * @throws \UserFormException
     */
    public static function getRequiredPositionClass($requiredPosition) {
        $classArr[FE_LABEL] = '';
        $classArr[FE_TYPE] = '';
        $classArr[FE_NOTE] = '';

        switch ($requiredPosition) {
            case F_FE_REQUIRED_POSITION_LABEL_LEFT:
                $classArr[FE_LABEL] = CSS_REQUIRED_LEFT;
                break;
            case F_FE_REQUIRED_POSITION_LABEL_RIGHT:
                $classArr[FE_LABEL] = CSS_REQUIRED_RIGHT;
                break;
            case F_FE_REQUIRED_POSITION_INPUT_LEFT:
                $classArr[FE_INPUT] = CSS_REQUIRED_LEFT;
                break;
            case F_FE_REQUIRED_POSITION_INPUT_RIGHT:
                $classArr[FE_INPUT] = CSS_REQUIRED_RIGHT;
                break;
            case F_FE_REQUIRED_POSITION_NOTE_LEFT:
                $classArr[FE_NOTE] = CSS_REQUIRED_LEFT;
                break;
            case F_FE_REQUIRED_POSITION_NOTE_RIGHT:
                $classArr[FE_NOTE] = CSS_REQUIRED_RIGHT;
                break;
            default:
                throw new \UserFormException('Unkown value for ' . F_FE_REQUIRED_POSITION . ': ' . $requiredPosition, ERROR_INVALID_VALUE);
        }

        return $classArr;
    }
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566

    /**
     * Function to check if a parameter is set (no value) or 0 or 1
     * Example:
     *   a) extraButtonLock
     *   b) extraButtonLock=0
     *   c) extraButtonLock=1
     *
     * a) and c) means 'on' and b) means off
     *
     * IMPORTANT: Call this function :   HelperFormElement::booleParameter( $fe[FE_INPUT_EXTRA_BUTTON_LOCK] ?? '-' )
     *
     * @param $data
     * @return bool
     */
    public static function booleParameter($data) {
        return $data == '' || $data == '1';
    }
567

Carsten  Rose's avatar
Carsten Rose committed
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

    /**
     * Look for key/value list (in this order, first match counts) in
     *  a) `sql1`
     *  b) `parameter:itemList`
     *  c) table.column definition
     *
     * Copies the found keys to &$itemKey and the values to &$itemValue
     * If there are no &$itemKey, copy &$itemValue to &$itemKey.
     *
     * @param array $formElement
     * @param array $itemKey
     * @param array $itemValue
     *
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    public static function getKeyValueListFromSqlEnumSpec(array $formElement, array &$itemKey, array &$itemValue) {
        $fieldType = '';
        $itemKey = array();
        $itemValue = array();

        self::$store = Store::getInstance();

        // Call getItemsForEnumOrSet() only if there a corresponding column really exist.
        if (false !== self::$store->getVar($formElement[FE_NAME], STORE_TABLE_COLUMN_TYPES)) {
            $itemValue = self::getItemsForEnumOrSet($formElement[FE_NAME], $fieldType);
        }

        if (is_array($formElement[FE_SQL1])) {
            if (count($formElement[FE_SQL1]) > 0) {
                $keys = array_keys($formElement[FE_SQL1][0]);
                $itemKey = array_column($formElement[FE_SQL1], 'id');

                // If there is no column 'id' and at least two columns in total
                if (count($itemKey) === 0 && count($keys) >= 2) {
                    $itemKey = array_column($formElement[FE_SQL1], $keys[0]);
                }

                $itemValue = array_column($formElement[FE_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[FE_SQL1], $keys[$idx]);
                }
            }
Carsten  Rose's avatar
Carsten Rose committed
615
616
        } elseif (isset($formElement[FE_ITEM_LIST]) && strlen($formElement[FE_ITEM_LIST]) > 0) {
            $arr = KeyValueStringParser::parse($formElement[FE_ITEM_LIST], ':', ',', KVP_IF_VALUE_EMPTY_COPY_KEY);
Carsten  Rose's avatar
Carsten Rose committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
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
            $itemValue = array_values($arr);
            $itemKey = array_keys($arr);
        } elseif ($fieldType === 'enum' || $fieldType === 'set') {
            // already done at the beginning with '$this->getItemsForEnumOrSet($formElement[FE_NAME], $fieldType);'
        } elseif (isset($formElement[FE_CHECKBOX_CHECKED]) && $formElement[FE_TYPE] == FE_TYPE_CHECKBOX) {
            // Nothing to do here.
        } else {
            throw new \UserFormException("Missing definition (- nothing found in 'sql1', 'parameter:itemList', 'enum-' or 'set-definition'", ERROR_MISSING_ITEM_LIST);
        }

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

        // Process 'emptyHide'  before 'emptyItemAtStart' / 'emptyItemAtEnd': than 'emptyItem*' are still possible.
        if (isset($formElement['emptyHide'])) {
            $itemKey = OnArray::removeEmptyElementsFromArray($itemKey);
            $itemValue = OnArray::removeEmptyElementsFromArray($itemValue);
        }

        if (isset($formElement[FE_EMPTY_ITEM_AT_START])) {
            $placeholder = isset($formElement[FE_PLACEHOLDER]) ? $formElement[FE_PLACEHOLDER] : '';
            array_unshift($itemKey, '');
            array_unshift($itemValue, $placeholder);
        }

        if (isset($formElement[FE_EMPTY_ITEM_AT_END])) {
            $itemKey[] = '';
            $itemValue[] = '';
        }
    }

    /**
     * Get the attribute definition list of an enum or set column. For strings, get the default value.
     * Return elements as an array.
     *
     * @param string $column
     * @param string $fieldType
     *
     * @return array
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private static function getItemsForEnumOrSet($column, &$fieldType) {

        self::$store = Store::getInstance();

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

        if ($fieldTypeDefinition === false) {
            throw new \UserFormException("Column '$column' in primary table.", ERROR_DB_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', ... ]
        $values = substr($fieldTypeDefinition, $startPosition, $length - $startPosition - 1);
        $items = OnArray::trimArray(explode(',', $values), "'");
        $fieldType = substr($fieldTypeDefinition, 0, $startPosition - 1);

        return $items;
    }

    /**
     * Set corresponding html attributes readonly/required/disabled, based on $formElement[FE_MODE].
     *
     * @param string $feMode
     *
     * @param bool $cssDisable
     * @return string
     * @throws \CodeException
     * @throws \UserFormException
     */
    public static function getAttributeFeMode($feMode, $cssDisable = true) {
        $attribute = '';

        self::getFeMode($feMode, $hidden, $disabled, $required);

        switch ($feMode) {
            case FE_MODE_HIDDEN:
            case FE_MODE_SHOW:
            case FE_MODE_SHOW_REQUIRED:
                break;
            case FE_MODE_REQUIRED:
            case FE_MODE_READONLY:
                $attribute .= Support::doAttribute($feMode, $feMode);
                break;
            default:
                throw new \UserFormException("Unknown mode '$feMode'", ERROR_UNKNOWN_MODE);
                break;
        }

        // Attributes: data-...
        $attribute .= Support::doAttribute(DATA_HIDDEN, $hidden);
        if ($cssDisable) {
            $attribute .= Support::doAttribute(DATA_DISABLED, $disabled);
        }
        $attribute .= Support::doAttribute(DATA_REQUIRED, $required);

        return $attribute;
    }

    /**
     * Depending of $feMode set variables $hidden, $disabled, $required to 'yes' or 'no'.
     *
     * @param string $feMode
     * @param string $hidden
     * @param string $disabled
     * @param string $required
     *
     * @throws \UserFormException
     */
    public static function getFeMode($feMode, &$hidden, &$disabled, &$required) {
        $hidden = 'no';
        $disabled = 'no';
        $required = 'no';

        switch ($feMode) {
            case FE_MODE_SHOW:
            case FE_MODE_SHOW_REQUIRED:
                break;
            case FE_MODE_REQUIRED:
                $required = 'yes';
                break;
            case FE_MODE_READONLY:
                $disabled = 'yes';  // convert the UI status 'readonly' to the HTML/CSS status 'disabled'.
                break;
            case FE_MODE_HIDDEN:
                $hidden = 'yes';
                break;
            default:
                throw new \UserFormException("Unknown mode '$feMode'", ERROR_UNKNOWN_MODE);
                break;
        }
    }

    /**
     * Builds a HTML attribute list, based on  $attributeList.
     *
     * E.g.: attributeList: [ 'type', 'autofocus' ]
     *       generates: 'type="$formElement[FE_TYPE]" autofocus="$formElement[FE_AUTOFOCUS]" '
     *
     * @param array $formElement
     * @param array $attributeList
     * @param bool $flagOmitEmpty
     *
     * @return string
     * @throws \CodeException
     */
    public static function getAttributeList(array $formElement, array $attributeList, $flagOmitEmpty = true) {
        $attribute = '';
        foreach ($attributeList as $item) {
            if (isset($formElement[$item]))
                $attribute .= Support::doAttribute(strtolower($item), $formElement[$item], $flagOmitEmpty);
        }

        return $attribute;
    }

793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
    /**
     * Builds a real HTML hidden form element. Useful for checkboxes, Multiple-Select and Radios.
     *
     * @param        $htmlFormElementName
     * @param string $value
     *
     * @return string
     */
    public static function buildNativeHidden($htmlFormElementName, $value) {
        return '<input type="hidden" name="' . $htmlFormElementName . '" value="' . htmlentities($value) . '">';
    }

    /**
     * Set corresponding JSON attributes readonly/required/disabled, based on $formElement[FE_MODE].
     *
     * @param string $feMode
     *
     * @return array
     * @throws \UserFormException
     */
    public static function getJsonFeMode($feMode) {

        self::getFeMode($feMode, $dummy, $disabled, $required);

        return [API_FORM_UPDATE_DISABLED => ($disabled === 'yes'), API_FORM_UPDATE_REQUIRED => ($required === 'yes')];
    }

    /**
     * Builds a label, typically for an html-'<input>'-element.
     *
     * @param string $htmlFormElementName
     * @param string $label
     * @param string $addClass
     *
     * @return string
     * @throws \CodeException
     */
    public static function buildLabel($htmlFormElementName, $label, $addClass = '') {
        $attributes = Support::doAttribute('for', $htmlFormElementName);
        $attributes .= Support::doAttribute('class', ['control-label', $addClass]);

        $html = Support::wrapTag("<label $attributes>", $label);

        return $html;
    }

    /**
     * Construct HTML ID for checkbox/radio option elements.
     * Optional add $type.
     * Example: $base='173-21612-1-0', $index='0', $type='l' >> '173-21612-1-0-0-l'
     *
     * @param $base
     * @param $index
     * @param string $type -  ';' for label
     * @return string
     */
    public static function getCheckboxRadioOptionId($base, $index, $type = '') {
        return $base . '-' . $index . $type;
    }

    /**
     * Build HelpBlock
     *
     * @return string
     */
    public static function getHelpBlock() {
        return '<div class="help-block with-errors hidden"></div>';
    }


Carsten  Rose's avatar
Carsten Rose committed
863
}