AbstractBuildForm.php 153 KB
Newer Older
1
<?php
Carsten  Rose's avatar
Carsten Rose committed
2 3 4 5 6 7
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/6/16
 * Time: 8:02 PM
 */
Carsten  Rose's avatar
Carsten Rose committed
8

Marc Egger's avatar
Marc Egger committed
9 10 11
namespace IMATHUZH\Qfq\Core;

use IMATHUZH\Qfq\Core\Database\Database;
12
use IMATHUZH\Qfq\Core\Form\Checkbox;
13
use IMATHUZH\Qfq\Core\Helper\HelperFile;
Marc Egger's avatar
Marc Egger committed
14
use IMATHUZH\Qfq\Core\Helper\HelperFormElement;
15
use IMATHUZH\Qfq\Core\Helper\KeyValueStringParser;
Marc Egger's avatar
Marc Egger committed
16 17
use IMATHUZH\Qfq\Core\Helper\Ldap;
use IMATHUZH\Qfq\Core\Helper\Logger;
18
use IMATHUZH\Qfq\Core\Helper\OnArray;
Marc Egger's avatar
Marc Egger committed
19
use IMATHUZH\Qfq\Core\Helper\Sanitize;
20 21
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Report\Link;
Marc Egger's avatar
Marc Egger committed
22
use IMATHUZH\Qfq\Core\Report\Report;
23 24
use IMATHUZH\Qfq\Core\Store\Sip;
use IMATHUZH\Qfq\Core\Store\Store;
25

26
/**
Carsten  Rose's avatar
Carsten Rose committed
27 28
 * Class AbstractBuildForm
 * @package qfq
29
 */
30
abstract class AbstractBuildForm {
31 32 33
    /**
     * @var array
     */
34
    protected $formSpec = array();  // copy of the loaded form
35 36 37
    /**
     * @var array
     */
38
    protected $feSpecAction = array(); // copy of all formElement.class='action' of the loaded form
39 40 41
    /**
     * @var array
     */
42
    protected $feSpecNative = array(); // copy of all formElement.class='native' of the loaded form
43 44 45
    /**
     * @var array
     */
46
    protected $buildElementFunctionName = array();
47 48 49
    /**
     * @var array
     */
50
    protected $pattern = array();
51 52 53
    /**
     * @var array
     */
54
    protected $wrap = array();
55 56 57
    /**
     * @var array
     */
58
    protected $symbol = array();
59 60 61
    /**
     * @var bool
     */
62
    protected $showDebugInfoFlag = false;
Carsten  Rose's avatar
Carsten Rose committed
63

64
//    protected $feDivClass = array(); // Wrap FormElements in <div class="$feDivClass[type]">
65

66 67 68 69 70 71 72 73
    /**
     * @var Store
     */
    protected $store = null;
    /**
     * @var Evaluate
     */
    protected $evaluate = null;
74 75 76
    /**
     * @var string
     */
77
    private $formId = null;
78 79 80 81
    /**
     * @var Sip
     */
    private $sip = null;
82 83 84 85
    /**
     * @var Link
     */
    protected $link = null;
86 87 88 89 90 91 92 93
    /**
     * @var Report
     */
    private $report = null;
    /**
     * @var BodytextParser
     */
    private $bodytextParser = null;
94

95
    /**
Carsten  Rose's avatar
Carsten Rose committed
96
     * @var Database[] - Array of Database instantiated class
97 98 99
     */
    protected $dbArray = array();

100 101 102
    /**
     * @var bool|mixed
     */
103
    protected $dbIndexData = false;
104 105 106
    /**
     * @var bool|string
     */
107
    protected $dbIndexQfq = false;
Carsten  Rose's avatar
Carsten Rose committed
108

109 110 111 112 113 114
    /**
     * AbstractBuildForm constructor.
     *
     * @param array $formSpec
     * @param array $feSpecAction
     * @param array $feSpecNative
115
     * @param array Database $db
Marc Egger's avatar
Marc Egger committed
116 117 118
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
119
     */
120
    public function __construct(array $formSpec, array $feSpecAction, array $feSpecNative, array $db = null) {
121 122 123 124
        $this->formSpec = $formSpec;
        $this->feSpecAction = $feSpecAction;
        $this->feSpecNative = $feSpecNative;
        $this->store = Store::getInstance();
125 126
//        $this->dbIndexData = $this->store->getVar(SYSTEM_DB_INDEX_DATA, STORE_SYSTEM);
        $this->dbIndexData = $formSpec[F_DB_INDEX];
127 128 129 130
        $this->dbIndexQfq = $this->store->getVar(SYSTEM_DB_INDEX_QFQ, STORE_SYSTEM);

        $this->dbArray = $db;
        $this->evaluate = new Evaluate($this->store, $this->dbArray[$this->dbIndexData]);
131
        $this->showDebugInfoFlag = Support::findInSet(SYSTEM_SHOW_DEBUG_INFO_YES, $this->store->getVar(SYSTEM_SHOW_DEBUG_INFO, STORE_SYSTEM));
132

133
        $this->sip = $this->store->getSipInstance();
134

135 136
        $this->link = new Link($this->sip, $this->dbIndexData);

137
        // render mode specific
138
        $this->fillWrap();
139 140

        $this->buildElementFunctionName = [
141
            FE_TYPE_CHECKBOX => 'Checkbox',
Carsten  Rose's avatar
Carsten Rose committed
142
            FE_TYPE_DATE => 'DateTime',
143
            FE_TYPE_DATETIME => 'DateTime',
Carsten  Rose's avatar
Carsten Rose committed
144 145 146 147 148 149 150 151 152
            'dateJQW' => 'DateJQW',
            'datetimeJQW' => 'DateJQW',
            'email' => 'Input',
            'gridJQW' => 'GridJQW',
            FE_TYPE_EXTRA => 'Extra',
            FE_TYPE_TEXT => 'Input',
            FE_TYPE_EDITOR => 'Editor',
            FE_TYPE_TIME => 'DateTime',
            FE_TYPE_NOTE => 'Note',
153
            FE_TYPE_PASSWORD => 'Input',
Carsten  Rose's avatar
Carsten Rose committed
154 155
            FE_TYPE_RADIO => 'Radio',
            FE_TYPE_SELECT => 'Select',
156
            FE_TYPE_SUBRECORD => 'Subrecord',
Carsten  Rose's avatar
Carsten Rose committed
157
            FE_TYPE_UPLOAD => 'File',
158
            FE_TYPE_ANNOTATE => 'Annotate',
159
            FE_TYPE_IMAGE_CUT => 'ImageCut',
Carsten  Rose's avatar
Carsten Rose committed
160 161 162
            'fieldset' => 'Fieldset',
            'pill' => 'Pill',
            'templateGroup' => 'TemplateGroup',
163 164
        ];

165
        $this->buildRowName = [
166
            FE_TYPE_CHECKBOX => 'Native',
Carsten  Rose's avatar
Carsten Rose committed
167
            FE_TYPE_DATE => 'Native',
168
            FE_TYPE_DATETIME => 'Native',
Carsten  Rose's avatar
Carsten Rose committed
169 170 171 172 173 174 175 176 177
            'dateJQW' => 'Native',
            'datetimeJQW' => 'Native',
            'email' => 'Native',
            'gridJQW' => 'Native',
            FE_TYPE_EXTRA => 'Native',
            FE_TYPE_TEXT => 'Native',
            FE_TYPE_EDITOR => 'Native',
            FE_TYPE_TIME => 'Native',
            FE_TYPE_NOTE => 'Native',
178
            FE_TYPE_PASSWORD => 'Native',
Carsten  Rose's avatar
Carsten Rose committed
179 180
            FE_TYPE_RADIO => 'Native',
            FE_TYPE_SELECT => 'Native',
181
            FE_TYPE_SUBRECORD => 'Subrecord',
Carsten  Rose's avatar
Carsten Rose committed
182
            FE_TYPE_UPLOAD => 'Native',
183
            FE_TYPE_ANNOTATE => 'Native',
184
            FE_TYPE_IMAGE_CUT => 'Native',
Carsten  Rose's avatar
Carsten Rose committed
185 186 187
            'fieldset' => 'Fieldset',
            'pill' => 'Pill',
            'templateGroup' => 'TemplateGroup',
188 189
        ];

190
        $this->symbol[SYMBOL_EDIT] = "<span class='glyphicon " . GLYPH_ICON_EDIT . "'></span>";
191
        $this->symbol[SYMBOL_SHOW] = "<span class='glyphicon " . GLYPH_ICON_SHOW . "'></span>";
192 193
        $this->symbol[SYMBOL_NEW] = "<span class='glyphicon " . GLYPH_ICON_NEW . "'></span>";
        $this->symbol[SYMBOL_DELETE] = "<span class='glyphicon " . GLYPH_ICON_DELETE . "'></span>";
194 195
    }

196 197
    abstract public function fillWrap();

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

    /**
     * @param $filter
     * @param $modeCollectFe
     * @param array $rcJson
     * @return string
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     * @throws \UserReportException
     */
216
    private function buildMultiForm($filter, $modeCollectFe, array &$rcJson) {
217 218 219 220 221 222 223 224

        $htmlElements = '';
        $rcJson = array();

        $parentRecords = $this->evaluate->parse($this->formSpec[F_MULTI_SQL], ROW_REGULAR);

        // No rows: nothing to do.
        if (empty($parentRecords)) {
225
            return $this->formSpec[F_MULTI_MSG_NO_RECORD];
226 227 228
        }

        // Check for 'id' or '_id' as column name
229
        $idName = isset($parentRecords[0]['_' . F_MULTI_COL_ID]) ? '_' . F_MULTI_COL_ID : F_MULTI_COL_ID;
230 231 232 233 234 235 236 237

        // Check that an column 'id' is given
        if (!isset($parentRecords[0][$idName])) {
            throw new \UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'Missing column "_' . F_MULTI_COL_ID . '"', ERROR_MESSAGE_TO_DEVELOPER => $this->formSpec[F_MULTI_SQL]]),
                ERROR_INVALID_OR_MISSING_PARAMETER);
        }

238 239 240 241 242 243 244 245 246 247
        // This is a dirty workaround for formSave: clear FORM STORE (already outdated values).
        // Otherwise those outdated values will be taken to fill non primary FE in multiForm (which are garbage).
        // Better solution would be to have FORM_STORE in sync.
        $this->store::unsetStore(STORE_FORM);

        $storeVarBase = $this->evaluate->parse($this->formSpec[FE_FILL_STORE_VAR]);
        if (!is_array($storeVarBase)) {
            $storeVarBase = array();
        }

248 249
        // Per row, iterate over all form elements
        foreach ($parentRecords as $row) {
250 251
            // Always start with a clean STORE_VAR
            $this->store->setStore($storeVarBase, STORE_VAR, true);
252

253
            $this->store->setStore($row, STORE_PARENT_RECORD, true);
254 255 256 257
            $this->store->setVar(F_MULTI_COL_ID, $row[$idName], STORE_PARENT_RECORD); // In case '_id' is used, both '_id' and 'id' should be accessible.

            $record = $this->dbArray[$this->dbIndexData]->sql('SELECT * FROM `' . $this->formSpec[F_TABLE_NAME] . '` WHERE id=' . $row[F_MULTI_COL_ID], ROW_EXPECT_1);
            $this->store->setStore($record, STORE_RECORD, true);
258

259 260 261 262 263 264 265 266
            $jsonTmp = array();
            $feTmp = $this->feSpecNative;

            $leftColumns = $this->buildMultiFormLeftColumns($row);
            $rightInputs = $this->elements($row[$idName], $filter, 0, $jsonTmp, $modeCollectFe,
                false, STORE_USE_DEFAULT, FORM_LOAD, true);

            $htmlElements .= Support::wrapTag('<tr>', $leftColumns . $rightInputs);
267 268

            // Clean for the next round
269
            $this->feSpecNative = $feTmp;
270 271
            $this->store::unsetStore(STORE_RECORD);

272
            $rcJson = array_merge($rcJson, $jsonTmp);
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
        }

        $tableHead = Support::wrapTag('<tr>', $this->buildMultiFormTableHead($parentRecords[0]));

        return '<table class="table"><thead>' . $tableHead . '</thead><tbody>' . $htmlElements . '</tbody></table>';
    }

    /**
     * @param array $row
     * @return string
     */
    private function buildMultiFormLeftColumns(array $row) {
        $line = '';

        // Collect columns
        foreach ($row as $key => $value) {
            if (($key[0] ?? '') != '_') {
                $line .= "<td>$value</td>";
            }
        }

        return $line;
    }

    /**
     * @param array $row
     * @return string
300 301
     * @throws \CodeException
     * @throws \UserFormException
302 303 304 305 306 307 308 309 310 311 312 313
     */
    private function buildMultiFormTableHead(array $row) {
        $line = '';

        // Collect columns
        foreach ($row as $key => $value) {
            if (($key[0] ?? '') != '_') {
                $line .= "<th>$key</th>";
            }
        }

        // Collect label from FormElements
314 315 316 317 318 319 320 321 322 323 324 325 326
        foreach ($this->feSpecNative as $formElement) {
            $editFeHtml = '';

            // debugStack as Tooltip
            if ($this->showDebugInfoFlag) {
                // Build 'FormElement' Edit symbol
                $feEditUrl = $this->createFormEditorUrl(FORM_NAME_FORM_ELEMENT, $formElement[FE_ID], ['formId' => $formElement[FE_FORM_ID]]);
                $titleAttr = Support::doAttribute('title', $this->formSpec[FE_NAME] . ' / ' . $formElement[FE_NAME] . ' [' . $formElement[FE_ID] . ']');
                $icon = Support::wrapTag('<span class="' . GLYPH_ICON . ' ' . GLYPH_ICON_EDIT . '">', '');
                $editFeHtml = ' ' . Support::wrapTag("<a class='hidden " . CLASS_FORM_ELEMENT_EDIT . "' href='$feEditUrl' $titleAttr>", $icon);
            }

            $line .= '<th>' . $formElement[FE_LABEL] . $editFeHtml . '</th>';
327 328 329 330 331
        }

        return $line;
    }

332
    /**
333
     * Builds complete 'form'. Depending of form specification, the layout will be 'plain' / 'table' / 'bootstrap'.
334
     *
335
     * @param string $mode FORM_LOAD | FORM_UPDATE | FORM_SAVE
336
     *
337 338 339
     * @param bool $htmlElementNameIdZero
     * @param array $latestFeSpecNative
     * @return array|string $mode=LOAD_FORM: The whole form as HTML, $mode=FORM_UPDATE: array of all
340
     *                        formElement.dynamicUpdate-yes  values/states
Marc Egger's avatar
Marc Egger committed
341 342 343
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
344 345 346
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
347 348 349 350 351
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     * @throws \UserReportException
352
     */
353
    public function process($mode, $htmlElementNameIdZero = false, $latestFeSpecNative = array()) {
Carsten  Rose's avatar
Carsten Rose committed
354 355
        $htmlHead = '';
        $htmlTail = '';
356
        $htmlT3vars = '';
Carsten  Rose's avatar
Carsten Rose committed
357 358
        $htmlElements = '';
        $json = array();
359

360
        // After action 'afterSave', it's necessary to reinitialize the FeSpecNative
361 362 363 364
        if (!empty($latestFeSpecNative)) {
            $this->feSpecNative = $latestFeSpecNative;
        }

365 366 367 368 369 370 371
        $modeCollectFe = FLAG_DYNAMIC_UPDATE;
        $storeUse = STORE_USE_DEFAULT;

        if ($mode === FORM_SAVE) {
            $modeCollectFe = FLAG_ALL;
            $storeUse = STORE_RECORD . STORE_TABLE_DEFAULT;
        }
372

373
        // <form>
Carsten  Rose's avatar
Carsten Rose committed
374 375 376
        if ($mode === FORM_LOAD) {
            $htmlHead = $this->head();
        }
377

378
        $filter = $this->getProcessFilter();
379

380 381
        // Form type
        if ($this->formSpec[F_MULTI_SQL] === '') {
382

383
            // Regular Form
384
            $recordId = $this->store->getVar(SIP_RECORD_ID, STORE_SIP);
385
            if (!($recordId == '' || is_numeric($recordId))) {
Marc Egger's avatar
Marc Egger committed
386
                throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
387
                    json_encode([ERROR_MESSAGE_TO_USER => 'Invalid record ID', ERROR_MESSAGE_TO_DEVELOPER => 'Invalid record ID: r="' . $recordId]),
388
                    ERROR_INVALID_VALUE);
389
            }
390

391
            // Build FormElements
392
            $htmlElements = $this->elements($recordId, $filter, 0, $json, $modeCollectFe, $htmlElementNameIdZero, $storeUse, $mode);
Carsten  Rose's avatar
Carsten Rose committed
393 394

            if ($mode === FORM_SAVE && $recordId != 0) {
395 396 397

                // element-update: with 'value'
                $recordId = $this->store->getVar(SIP_RECORD_ID, STORE_SIP . STORE_ZERO);
398
                $md5 = $this->buildRecordHashMd5($this->formSpec[F_TABLE_NAME], $recordId, $this->formSpec[F_PRIMARY_KEY]);
399 400

                // Via 'element-update'
401
                $json[][API_ELEMENT_UPDATE][DIRTY_RECORD_HASH_MD5][API_ELEMENT_ATTRIBUTE]['value'] = $md5;
Carsten  Rose's avatar
Carsten Rose committed
402
            }
403 404 405

        } else {
            // Multi Form
406
            if ($mode === FORM_LOAD || $mode === FORM_SAVE) {
407 408
                $htmlElements = $this->buildMultiForm($filter, $modeCollectFe, $json);
            }
409
        }
410 411 412

        // <form>
        if ($mode === FORM_LOAD) {
413
            $htmlT3vars = $this->prepareT3VarsForSave();
414
            $htmlTail = $this->tail();
415
        }
416
        $htmlHidden = $this->buildAdditionalFormElements();
417

418 419
        $htmlSip = $this->buildHiddenSip($json);

420
        return ($mode === FORM_LOAD) ? $htmlHead . $htmlHidden . $htmlElements . $htmlSip . $htmlT3vars . $htmlTail : $json;
421 422
    }

423
    /**
424
     * Build the head area of the form.
425
     *
426
     * @param string $mode
427
     * @return string
Marc Egger's avatar
Marc Egger committed
428 429 430
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
431
     */
432
    public function head($mode = FORM_LOAD) {
433
        $html = '';
434

435
        $html .= '<div ' . Support::doAttribute('class', $this->formSpec[F_CLASS], true) . '>'; // main <div class=...> around everything
436

437 438
        // Logged in BE User will see a FormEdit Link
        $sipParamString = OnArray::toString($this->store->getStore(STORE_SIP), ':', ', ', "'");
439
        $formEditUrl = $this->createFormEditorUrl(FORM_NAME_FORM, $this->formSpec[F_ID]);
440

441
        $html .= "<p><a " . Support::doAttribute('href', $formEditUrl) . ">Edit</a> <small>[$sipParamString]</small></p>";
442

443
        $html .= $this->wrapItem(WRAP_SETUP_TITLE, $this->formSpec[F_TITLE], true);
444

445 446 447
        $html .= $this->getFormTag();

        return $html;
448 449
    }

450
    /**
451 452
     * If SHOW_DEBUG_INFO=yes: create a link (incl. SIP) to edit the current form. Show also the hidden content of
     * the SIP.
453
     *
454
     * @param string $form FORM_NAME_FORM | FORM_NAME_FORM_ELEMENT
Carsten  Rose's avatar
Carsten Rose committed
455 456
     * @param int $recordId id of form or formElement
     * @param array $param
457 458 459
     *
     * @return string String: <a href="?pageId&sip=....">Edit</a> <small>[sip:..., r:..., urlparam:...,
     *                ...]</small>
Marc Egger's avatar
Marc Egger committed
460 461
     * @throws \CodeException
     * @throws \UserFormException
462
     */
463
    public function createFormEditorUrl($form, $recordId, array $param = array()) {
464

465
        if (!$this->showDebugInfoFlag) {
466 467
            return '';
        }
468

469
        $queryStringArray = [
470
            'id' => $this->store->getVar(SYSTEM_EDIT_FORM_PAGE, STORE_SYSTEM),
471
            'form' => $form,
Carsten  Rose's avatar
Carsten Rose committed
472
            'r' => $recordId,
473
            PARAM_DB_INDEX_DATA => $this->dbIndexQfq,
474
        ];
475
        $queryStringArray = array_merge($queryStringArray, $param);
476

477
        $queryString = Support::arrayToQueryString($queryStringArray);
478

479 480
        $sip = $this->store->getSipInstance();
        $url = $sip->queryStringToSip($queryString);
481

482
        return $url;
483 484 485
    }

    /**
486 487
     * Wrap's $this->wrap[$item][WRAP_SETUP_START] around $value. If $flagOmitEmpty==true && $value=='': return ''.
     *
Carsten  Rose's avatar
Carsten Rose committed
488 489
     * @param string $item
     * @param string $value
490
     * @param bool|false $flagOmitEmpty
491
     *
492 493 494
     * @return string
     */
    public function wrapItem($item, $value, $flagOmitEmpty = false) {
495 496

        if ($flagOmitEmpty && $value === "") {
497
            return '';
498 499
        }

500 501 502 503
        return $this->wrap[$item][WRAP_SETUP_START] . $value . $this->wrap[$item][WRAP_SETUP_END];
    }

    /**
504
     * Returns '<form ...>'-tag with various attributes.
505 506
     *
     * @return string
Marc Egger's avatar
Marc Egger committed
507 508 509
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
510 511
     */
    public function getFormTag() {
Carsten  Rose's avatar
Carsten Rose committed
512
        $md5 = '';
513

514
        $attribute = $this->getFormTagAttributes();
515

516 517
        $honeypot = $this->getHoneypotVars();

518
        $md5 = $this->buildInputRecordHashMd5();
Carsten  Rose's avatar
Carsten Rose committed
519 520 521 522 523 524

        return '<form ' . OnArray::toString($attribute, '=', ' ', "'") . '>' . $honeypot . $md5;
    }

    /**
     * Build MD5 from the current record. Return HTML Input element.
525
     *
526
     * @return string
Marc Egger's avatar
Marc Egger committed
527 528 529
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
Carsten  Rose's avatar
Carsten Rose committed
530
     */
531
    public function buildInputRecordHashMd5() {
532

Carsten  Rose's avatar
Carsten Rose committed
533
        $recordId = $this->store->getVar(SIP_RECORD_ID, STORE_SIP . STORE_ZERO);
534
        $md5 = $this->buildRecordHashMd5($this->formSpec[F_TABLE_NAME], $recordId, $this->formSpec[F_PRIMARY_KEY]);
535 536

        $data = "<input id='" . DIRTY_RECORD_HASH_MD5 . "' name='" . DIRTY_RECORD_HASH_MD5 . "' type='hidden' value='$md5'>";
537

538
//        $data = "<input id='" . DIRTY_RECORD_HASH_MD5 . "' name='" . DIRTY_RECORD_HASH_MD5 . "' type='text' value='$md5'>";
539 540 541 542 543 544 545 546

        return $data;
    }


    /**
     * @param $tableName
     * @param $recordId
547
     * @param string $primaryKey
548
     *
549
     * @return string
Marc Egger's avatar
Marc Egger committed
550 551 552
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
553
     */
554
    public function buildRecordHashMd5($tableName, $recordId, $primaryKey = F_PRIMARY_KEY_DEFAULT) {
555
        $record = array();
Carsten  Rose's avatar
Carsten Rose committed
556 557

        if ($recordId != 0) {
558
            $record = $this->dbArray[$this->dbIndexData]->sql("SELECT * FROM $tableName WHERE $primaryKey=?", ROW_EXPECT_1, [$recordId], "Record to load not found.");
Carsten  Rose's avatar
Carsten Rose committed
559 560
        }

561
        return OnArray::getMd5($record);
562 563
    }

564 565 566 567
    /**
     * Create HTML Input vars to detect bot automatic filling of forms.
     *
     * @return string
Marc Egger's avatar
Marc Egger committed
568 569
     * @throws \CodeException
     * @throws \UserFormException
570 571 572 573 574 575 576 577 578
     */
    public function getHoneypotVars() {
        $html = '';

        $vars = $this->store->getVar(SYSTEM_SECURITY_VARS_HONEYPOT, STORE_SYSTEM);

        // Iterate over all fake vars
        $arr = explode(',', $vars);
        foreach ($arr as $name) {
579 580 581 582
            $name = trim($name);
            if ($name === '') {
                continue;
            }
583 584 585 586 587
            $html .= "<input name='$name' type='hidden' value='' readonly>";
        }

        return $html;
    }
588

Carsten  Rose's avatar
Carsten Rose committed
589

590 591 592
    /**
     * Build an assoc array with standard form attributes.
     *
593
     * @return array
Marc Egger's avatar
Marc Egger committed
594 595 596
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
597
     */
598
    public function getFormTagAttributes() {
599

600
        $attribute['id'] = $this->getFormId();
601 602 603 604
        $attribute['method'] = 'post';
        $attribute['action'] = $this->getActionUrl();
        $attribute['target'] = '_top';
        $attribute['accept-charset'] = 'UTF-8';
605
        $attribute[FE_INPUT_AUTOCOMPLETE] = 'on';
606
        $attribute['enctype'] = $this->getEncType();
607
        $attribute['data-disable-return-key-submit'] = $this->formSpec[F_ENTER_AS_SUBMIT] == '1' ? "false" : "true"; // attribute meaning is inverted
608
        $attribute['data-activate-first-required-tab'] = $this->formSpec[F_ACTIVATE_FIRST_REQUIRED_TAB] == '1' ? "true" : "false"; // attribute meaning is inverted
609 610 611 612

        return $attribute;
    }

613
    /**
Carsten  Rose's avatar
Carsten Rose committed
614 615
     * Return a uniq form id
     *
616 617 618 619 620 621
     * @return string
     */
    public function getFormId() {
        if ($this->formId === null) {
            $this->formId = uniqid('qfq-form-');
        }
622

623 624 625
        return $this->formId;
    }

626 627 628
    /**
     * Builds the HTML 'form'-tag inlcuding all attributes and target.
     *
629 630
     * Notice: the SIP will be transferred as POST Parameter.
     *
631 632 633 634
     * @return string
     */
    public function getActionUrl() {

635
        return API_DIR . '/save.php';
636 637 638 639 640 641 642 643
    }

    /**
     * Determines the enctype.
     *
     * See: https://www.w3.org/wiki/HTML/Elements/form#HTML_Attributes
     *
     * @return string
Marc Egger's avatar
Marc Egger committed
644 645 646
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
647 648 649
     */
    public function getEncType() {

650
        $result = $this->dbArray[$this->dbIndexQfq]->sql("SELECT id FROM FormElement AS fe WHERE fe.formId=? AND fe.type='upload' LIMIT 1", ROW_REGULAR, [$this->formSpec['id']], 'Look for Formelement.type="upload"');
651

652 653 654
        return (count($result) === 1) ? 'multipart/form-data' : 'application/x-www-form-urlencoded';

    }
655

656
    abstract public function getProcessFilter();
657

658 659 660 661
    /**
     * @param array|string $value
     *
     * @return array|string
Marc Egger's avatar
Marc Egger committed
662 663 664
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
665 666 667
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
668 669 670 671 672
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     * @throws \UserReportException
673
     */
674 675
    private function processReportSyntax($value) {

676 677 678 679 680 681 682 683 684 685 686
        if (is_array($value)) {
            $new = array();

            //might happen for e.g Template Groups
            foreach ($value as $item) {
                $new[] = $this->processReportSyntax($item);
            }

            return $new;
        }

687
        $value = trim($value);
688 689 690 691 692 693 694 695 696
        if (substr($value, 0, 8) == SHEBANG_REPORT) {
            if ($this->report === null) {
                $this->report = new Report(array(), $this->evaluate, false);
            }

            if ($this->bodytextParser === null) {
                $this->bodytextParser = new BodytextParser();
            }

697
            $storeRecord = $this->store->getStore(STORE_RECORD);
698
            $value = $this->report->process($this->bodytextParser->process($value));
699
            $this->store->setStore($storeRecord, STORE_RECORD, true);
Carsten  Rose's avatar
Carsten Rose committed
700
            $this->store->setVar(SYSTEM_REPORT_FULL_LEVEL, '', STORE_SYSTEM); // debug
701 702 703 704 705
        }

        return $value;
    }

706

707
    /**
708
     * Process all FormElements in $this->feSpecNative: Collect and return all HTML code & JSON.
709
     *
Carsten  Rose's avatar
Carsten Rose committed
710
     * @param int $recordId
711
     * @param string $filter FORM_ELEMENTS_NATIVE | FORM_ELEMENTS_SUBRECORD | FORM_ELEMENTS_NATIVE_SUBRECORD
Carsten  Rose's avatar
Carsten Rose committed
712 713
     * @param int $feIdContainer
     * @param array $json
714
     * @param string $modeCollectFe
Carsten  Rose's avatar
Carsten Rose committed
715
     * @param bool $htmlElementNameIdZero
716
     * @param string $storeUseDefault
717
     * @param string $mode FORM_LOAD | FORM_UPDATE | FORM_SAVE
718
     * @param bool $flagMulti
719
     *
720
     * @return string
Marc Egger's avatar
Marc Egger committed
721 722 723
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
724 725 726
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
727 728 729 730 731
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     * @throws \UserReportException
732
     */
733
    public function elements($recordId, $filter, $feIdContainer, array &$json,
734
                             $modeCollectFe = FLAG_DYNAMIC_UPDATE, $htmlElementNameIdZero = false,
735
                             $storeUseDefault = STORE_USE_DEFAULT, $mode = FORM_LOAD, $flagMulti = false) {
736
        $html = '';
737

738
        // The following 'FormElement.parameter' will never be used during load (fe.type='upload'). FE_PARAMETER has been already expanded.
739
        $skip = [FE_SQL_UPDATE, FE_SQL_INSERT, FE_SQL_DELETE, FE_SQL_AFTER, FE_SQL_BEFORE, FE_PARAMETER, FE_FILL_STORE_VAR, FE_FILE_DOWNLOAD_BUTTON];
740

741
        // get current data record
742 743
        $primaryKey = $this->formSpec[F_PRIMARY_KEY];
        if ($recordId > 0 && $this->store->getVar($primaryKey, STORE_RECORD) === false) {
744
            $tableName = $this->formSpec[F_TABLE_NAME];
745 746
            $row = $this->dbArray[$this->dbIndexData]->sql("SELECT * FROM $tableName WHERE $primaryKey = ?", ROW_EXPECT_1,
                array($recordId), "Form '" . $this->formSpec[F_NAME] . "' failed to load record '$primaryKey'='$recordId' from table '" .
747
                $this->formSpec[F_TABLE_NAME] . "'.");
748
            $this->store->setStore($row, STORE_RECORD);
749
        }
750

751 752
        $this->checkAutoFocus();

753 754
        $parameterLanguageFieldName = $this->store->getVar(SYSTEM_PARAMETER_LANGUAGE_FIELD_NAME, STORE_SYSTEM);

755 756
        // Iterate over all FormElements
        foreach ($this->feSpecNative as $fe) {
757
            $storeUse = $storeUseDefault;
758

759 760
            if (($filter === FORM_ELEMENTS_NATIVE && $fe[FE_TYPE] === 'subrecord')
                || ($filter === FORM_ELEMENTS_SUBRECORD && $fe[FE_TYPE] !== 'subrecord')
761
//                || ($filter === FORM_ELEMENTS_DYNAMIC_UPDATE && $fe[FE_DYNAMIC_UPDATE] === 'no')
762 763 764 765
            ) {
                continue; // skip this FE
            }

766 767 768 769
            // #7705. Dirty fix: 'form_save and fresh created tg element can't be updated, cause the HTML id is unknown: skip those.
            if ($mode == FORM_SAVE && false != stripos($fe[FE_NAME], '%d')) {
                continue; // skip this FE
            }
770
            $flagOutput = ($fe[FE_TYPE] !== FE_TYPE_EXTRA); // type='extra' will not displayed and not transmitted to the form.
771

772 773
            $debugStack = array();

774 775
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($fe), STORE_SYSTEM);
776
            $this->store->setVar(SYSTEM_FORM_ELEMENT_ID, $fe[FE_ID], STORE_SYSTEM);
777

Carsten  Rose's avatar
Carsten Rose committed
778 779
            // Fill STORE_LDAP
            $fe = $this->prepareFillStoreFireLdap($fe);
780

781 782 783 784 785 786
            if (isset($fe[FE_FILL_STORE_VAR])) {
                $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, FE_FILL_STORE_VAR, STORE_SYSTEM); // debug
                $fe[FE_FILL_STORE_VAR] = $this->evaluate->parse($fe[FE_FILL_STORE_VAR], ROW_EXPECT_0_1);
                $this->store->appendToStore($fe[FE_FILL_STORE_VAR], STORE_VAR);
            }

787 788
            // If given, slaveId will be copied to STORE_VAR
            if (!empty($fe[FE_SLAVE_ID])) {
789
                $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, FE_SLAVE_ID, STORE_SYSTEM); // debug
790 791
                $slaveId = Support::falseEmptyToZero($this->evaluate->parse($fe[FE_SLAVE_ID]));
                $this->store->setVar(VAR_SLAVE_ID, $slaveId, STORE_VAR);
792 793
            }

794
            $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, FE_VALUE, STORE_SYSTEM); // debug
795
            $fe[FE_VALUE] = $this->processReportSyntax($fe[FE_VALUE]);
796 797

            $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, FE_NOTE, STORE_SYSTEM); // debug
798 799
            $fe[FE_NOTE] = $this->processReportSyntax($fe[FE_NOTE]);

Carsten  Rose's avatar
Carsten Rose committed
800
            // ** evaluate current FormElement **
801
            $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, 'Some of the columns of current FormElement', STORE_SYSTEM); // debug
802
            $formElement = $this->evaluate->parseArray($fe, $skip, $debugStack);
803
            $this->store->setVar(SYSTEM_FORM_ELEMENT_COLUMN, 'Set language', STORE_SYSTEM); // debug
804
            $formElement = HelperFormElement::setLanguage($formElement, $parameterLanguageFieldName);
805

806
            // Some Defaults
807
            $formElement = Support::setFeDefaults($formElement, $this->formSpec);
808

809 810 811 812 813 814
//            // Copy global readonly mode.
//            if ($this->formSpec[F_MODE] == F_MODE_READONLY) {
//                $fe[FE_MODE] = FE_MODE_READONLY;
//                $fe[FE_MODE_SQL] = '';
//            }

815
            if ($flagOutput === true && !$flagMulti) {
816
                $this->fillWrapLabelInputNote($formElement[FE_BS_LABEL_COLUMNS], $formElement[FE_BS_INPUT_COLUMNS], $formElement[FE_BS_NOTE_COLUMNS]);
817
            }
818

819 820
            Support::setIfNotSet($formElement, FE_VALUE);

821 822 823
            if (is_array($formElement[FE_VALUE])) {
                $formElement[FE_VALUE] = (count($formElement[FE_VALUE])) > 0 ? current($formElement[FE_VALUE][0]) : '';
            }
824

825
            $value = $formElement[FE_VALUE];
826

827
            if ($value === '') {
828 829 830 831
                // #2064 / Only take the default, if the FE is a real tablecolumn.
                // #3426 / Dynamic Update: Inputs loose the new content and shows the old value.
                if ($storeUse == STORE_USE_DEFAULT && $this->store->getVar($formElement[FE_NAME], STORE_TABLE_COLUMN_TYPES) === false) {
                    $storeUse = str_replace(STORE_TABLE_DEFAULT, '', $storeUse); // Remove STORE_DEFAULT
832
                }
833 834 835 836

                // In case the current element is a 'RETYPE' element: take the element name of the source FormElement. Needed to retrieve the default value later.
                $name = (isset($formElement[FE_RETYPE_SOURCE_NAME])) ? $formElement[FE_RETYPE_SOURCE_NAME] : $formElement[FE_NAME];

837
                // Retrieve value via FSRVD
838
                $sanitizeClass = ($mode == FORM_UPDATE) ? SANITIZE_ALLOW_ALL : $formElement[FE_CHECK_TYPE];
839
                $value = $this->store->getVar($name, $storeUse, $sanitizeClass, $foundInStore);
840 841 842
            }

            if ($formElement[FE_ENCODE] === FE_ENCODE_SPECIALCHAR) {
843 844
//                $value = htmlspecialchars_decode($value, ENT_QUOTES);
                $value = Support::htmlEntityEncodeDecode(MODE_DECODE, $value);
845
            }
846

847 848
            // Typically: $htmlElementNameIdZero = true
            // After Saving a record, staying on the form, the FormElements on the Client are still known as '<feName>:0'.
849
            $htmlFormElementName = HelperFormElement::buildFormElementName($formElement, ($htmlElementNameIdZero) ? 0 : $recordId);
850 851 852
            $formElement[FE_HTML_ID] = HelperFormElement::buildFormElementId($this->formSpec[F_ID], $formElement[FE_ID],
                ($htmlElementNameIdZero) ? 0 : $recordId,
                $formElement[FE_TG_INDEX]);
853

Carsten  Rose's avatar
Carsten Rose committed
854
            // Construct Marshaller Name: buildElement
855
            $buildElementFunctionName = 'build' . $this->buildElementFunctionName[$formElement[FE_TYPE]];
856

Carsten  Rose's avatar
Carsten Rose committed
857
            $jsonElement = array();
858
            $elementExtra = '';
859
            // Render pure element
860
            $elementHtml = $this->$buildElementFunctionName($formElement, $htmlFormElementName, $value, $jsonElement, $mode);
Carsten  Rose's avatar
Carsten Rose committed
861 862

            // container elements do not have dynamicUpdate='yes'. Instead they deliver nested elements.
863
            if ($formElement[FE_CLASS] == FE_CLASS_CONTAINER) {
Carsten  Rose's avatar
Carsten Rose committed
864 865 866 867
                if (count($jsonElement) > 0) {
                    $json = array_merge($json, $jsonElement);
                }
            } else {
868
                // for non-container elements: just add the current json status
869
                if ($modeCollectFe === FLAG_ALL || ($modeCollectFe == FLAG_DYNAMIC_UPDATE && $fe[FE_DYNAMIC_UPDATE] === 'yes')) {
Carsten  Rose's avatar
Carsten Rose committed