FillStoreForm.php 11.4 KB
Newer Older
Carsten  Rose's avatar
Carsten Rose committed
1
2
3
4
5
6
7
8
9
10
11
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 3/23/16
 * Time: 1:31 PM
 */

namespace qfq;

require_once(__DIR__ . '/Store.php');
12
require_once(__DIR__ . '/../database/Database.php');
Carsten  Rose's avatar
Carsten Rose committed
13
14
require_once(__DIR__ . '/../Constants.php');
require_once(__DIR__ . '/../helper/HelperFormElement.php');
15
require_once(__DIR__ . '/../exceptions/UserFormException.php');
Carsten  Rose's avatar
Carsten Rose committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

class FillStoreForm {

    /**
     * @var Store
     */
    private $store = null;

    /**
     * @var Database
     */
    private $db = null;

    /**
     * @var array
     */
    private $feSpecNative = array();

34
35
36
37
38
    /**
     * @var Evaluate
     */
    private $evaluate = null;

Carsten  Rose's avatar
Carsten Rose committed
39
40
41
42
    /**
     *
     */
    public function __construct() {
43

Carsten  Rose's avatar
Carsten Rose committed
44
45
46
        $this->store = Store::getInstance();
        $this->db = new Database();
        $this->feSpecNative = $this->loadFormElementsBasedOnSIP();
47
48
        $this->evaluate = new Evaluate($this->store, $this->db);

Carsten  Rose's avatar
Carsten Rose committed
49
50
    }

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    /**
     * Loads a minimal definition of FormElement of the form specified in SIP.
     *
     * @return array
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     */
    private function loadFormElementsBasedOnSIP() {
        $formName = $this->store->getVar(SIP_FORM, STORE_SIP);

        // Preparation for Log, Debug
        $this->store->setVar(SYSTEM_FORM, $formName, STORE_SYSTEM);

        $feSpecNative = $this->db->sql(SQL_FORM_ELEMENT_SIMPLE_ALL_CONTAINER, ROW_EXPECT_GE_1, [$formName],
            'Form or FormElements not found: ' . ERROR_FORM_NOT_FOUND);
67
        HelperFormElement::explodeParameterInArrayElements($feSpecNative, FE_PARAMETER);
68
69

        $feSpecTemplateGroup = $this->db->sql(SQL_FORM_ELEMENT_CONTAINER_TEMPLATE_GROUP, ROW_REGULAR, [$formName]);
70
        HelperFormElement::explodeParameterInArrayElements($feSpecTemplateGroup, FE_PARAMETER);
71
72
73
74
75
76
77

        $feSpecNative = $this->expandTemplateGroupFormElement($feSpecTemplateGroup, $feSpecNative);


        return $feSpecNative;
    }

Carsten  Rose's avatar
Carsten Rose committed
78
79
80
81
82
    /**
     * Checks if there are templateGroups defined. If yes, expand them. Return expanded feSpecNative array.
     *
     * @param array $feSpecTemplateGroup
     * @param array $feSpecNative
Carsten  Rose's avatar
Carsten Rose committed
83
     *
Carsten  Rose's avatar
Carsten Rose committed
84
85
86
87
88
     * @return array
     */
    private function expandTemplateGroupFormElement(array $feSpecTemplateGroup, array $feSpecNative) {
        $expanded = array();

89
        if (count($feSpecTemplateGroup) == 0) {
Carsten  Rose's avatar
Carsten Rose committed
90
91
92
93
            return $feSpecNative; // No templateGroups >> nothing to do >> just return
        }

        // Iterate over all 'FormElements': part of a templateGroup?
94
95
        foreach ($feSpecNative as $fe) {
            $flagCopied = false;
Carsten  Rose's avatar
Carsten Rose committed
96

97
            if ($fe[FE_ID_CONTAINER] > 0) {
Carsten  Rose's avatar
Carsten Rose committed
98
99
                // Search for a corresponding template group.
                foreach ($feSpecTemplateGroup as $templateGroup) {
100
                    if ($fe[FE_ID_CONTAINER] == $templateGroup[FE_ID]) {
Carsten  Rose's avatar
Carsten Rose committed
101

102
                        $flagCopied = true;
Carsten  Rose's avatar
Carsten Rose committed
103
104

                        // Get max copies per template group
105
                        $maxCopies = HelperFormElement::tgGetMaxLength($templateGroup[FE_MAX_LENGTH]);
Carsten  Rose's avatar
Carsten Rose committed
106
107
108
109

                        // Copy each native FormElement
                        $template = $fe[FE_NAME];
                        for ($ii = 1; $ii <= $maxCopies; $ii++) {
110
                            $fe[FE_NAME] = str_replace(FE_TEMPLATE_GROUP_NAME_PATTERN, $ii, $template);
Carsten  Rose's avatar
Carsten Rose committed
111
112
113
114
115
116
                            $expanded[] = $fe;
                        }
                    }
                }
            }

117
            if (!$flagCopied) {
Carsten  Rose's avatar
Carsten Rose committed
118
119
120
121
122
123
124
                $expanded[] = $fe;
            }
        }

        return $expanded;
    }

Carsten  Rose's avatar
Carsten Rose committed
125
126
127
128
129
    /**
     * Copies all current form parameter from STORE_CLIENT to STORE_FORM. Checks the values against FormElement
     * definition and throws an exception if check fails. FormElements.type=hidden will be taken from STORE_SIP.
     *
     * @throws CodeException
130
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
131
132
     */
    public function process() {
133
        // The following will never be used during load (fe.type='upload').
134
        $skip = [FE_SQL_UPDATE, FE_SQL_INSERT, FE_SQL_DELETE, FE_SQL_AFTER, FE_SQL_BEFORE, FE_PARAMETER];
135

Carsten  Rose's avatar
Carsten Rose committed
136
137
138
139
140
        $html = '';
        $newValues = array();

        $clientValues = $this->store->getStore(STORE_CLIENT);

141
142
143
144
145
        // If called through 'api/...': get STORE_TYPO3 via SIP parameter.
        if (isset($clientValues[CLIENT_TYPO3VARS])) {
            $this->store->fillTypo3StoreFromSip($clientValues[CLIENT_TYPO3VARS]);
        }

Carsten  Rose's avatar
Carsten Rose committed
146
147
148
        // Retrieve SIP vars, e.g. for HIDDEN elements.
        $sipValues = $this->store->getStore(STORE_SIP);

149
        // Copy SIP Values; not necessarily defined as a FormElement.
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        foreach ($sipValues as $key => $value) {
            switch ($key) {
                case SIP_SIP:
                case SIP_RECORD_ID:
                case SIP_FORM:
                case SIP_TABLE:
                case SIP_URLPARAM:
                case 'id':
                    break;
                default:
                    $newValues[$key] = $value;
                    break;
            }
        }

Carsten  Rose's avatar
#2067    
Carsten Rose committed
165
166
167
168
169
        // Check if there is a 'new record already saved' situation:
        // yes: the names of the input fields are submitted with '<fieldname>:0' instead of '<fieldname>:<id>'
        // no: regular situation, take real 'recordid'
        $fakeRecordId = isset($sipValues[SIP_MAKE_URLPARAM_UNIQ]) ? 0 : $sipValues[SIP_RECORD_ID];

170
        // Iterate over all FormElements. Sanatize values. Built an assoc array $newValues.
Carsten  Rose's avatar
Carsten Rose committed
171
172
173
        foreach ($this->feSpecNative AS $formElement) {

            // Never get a predefined 'id'
174
            if ($formElement[FE_NAME] === COLUMN_ID)
Carsten  Rose's avatar
Carsten Rose committed
175
176
                continue;

177
178
179
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($formElement), STORE_SYSTEM);

180
            // Evaluate current FormElement: e.g. FE_MODE_SQL
181
            $formElement = $this->evaluate->parseArray($formElement, $skip, $debugStack);
182

183
            // Get related formElement. Construct the field name used in the form.
184
            $clientFieldName = HelperFormElement::buildFormElementName($formElement, $fakeRecordId);
Carsten  Rose's avatar
Carsten Rose committed
185

186
187
            // Some Defaults
            $formElement = Support::setFeDefaults($formElement);
Carsten  Rose's avatar
Carsten Rose committed
188

189
190
            if ($formElement[FE_TYPE] === FE_TYPE_EXTRA) {
                // Extra elements will be transferred by SIP
191
192
                if (!isset($sipValues[$formElement[FE_NAME]])) {
                    throw new CodeException("Missing the " . FE_TYPE_EXTRA . " field '" . $formElement[FE_NAME] . "' in SIP.", ERROR_MISSING_HIDDEN_FIELD_IN_SIP);
Carsten  Rose's avatar
Carsten Rose committed
193
194
                }

195
                $newValues[$formElement[FE_NAME]] = $sipValues[$formElement[FE_NAME]];
Carsten  Rose's avatar
Carsten Rose committed
196
197
198
                continue;
            }

199
            // Checkbox Multi: collect values
200
            if ($formElement[FE_TYPE] === 'checkbox') {
201
                $val = $this->collectMultiValues($clientFieldName, $clientValues);
Carsten  Rose's avatar
Carsten Rose committed
202
                if ($val !== false) {
203
204
                    $clientValues[$clientFieldName] = $val;
                }
205
206
            }

207
            if ($formElement[FE_MODE] === FE_MODE_REQUIRED) {
208
209
210
211
212
                if (!isset($clientValues[$clientFieldName]) || ($clientValues[$clientFieldName] === '')) {
                    throw new UserFormException("Missing required value.", ERROR_REQUIRED_VALUE_EMPTY);
                }
            }

213
214
215
216
217
218
219
220
            // copy value to $newValues
            if (isset($clientValues[$clientFieldName])) {
                if ($formElement[FE_DYNAMIC_UPDATE] === 'yes' || $formElement[FE_MODE] === FE_MODE_REQUIRED || $formElement[FE_MODE] === FE_MODE_SHOW) {
                    switch ($formElement[FE_TYPE]) {
                        case 'date':
                        case 'datetime':
                        case 'time':
                            if ($clientValues[$clientFieldName] !== '') // do not check empty values
221
                                $newValues[$formElement[FE_NAME]] = $this->doDateTime($formElement, $clientValues[$clientFieldName]);
222
223
                            break;
                        default:
224
                            $val = $clientValues[$clientFieldName];
225
                            // Check only if their is something
226
                            if ($val !== '') {
227
                                $val = Sanitize::sanitize($val, $formElement[FE_CHECK_TYPE], $formElement[FE_CHECK_PATTERN], SANITIZE_EXCEPTION);
228
229
230
                                if ($formElement[FE_ENCODE] === FE_ENCODE_SPECIALCHAR) {
                                    $val = htmlspecialchars($val, ENT_QUOTES);
                                }
231
                            }
232
                            $newValues[$formElement[FE_NAME]] = $val;
233
                            break;
234
                    }
235
                }
Carsten  Rose's avatar
Carsten Rose committed
236
237
238
            }
        }

239
        $this->store->setStore($newValues, STORE_FORM, true);
Carsten  Rose's avatar
Carsten Rose committed
240
241
    }

242
    /**
Carsten  Rose's avatar
Carsten Rose committed
243
244
245
     * Steps through all $clientValues (POST vars) and collect all with the name _?_${clientFieldName} in a comma
     * seperated string (MYSQL ENUM type). If there is no element '_h_${clientFieldName}', than there are no multi
     * values - return the already given `$clientValues[$clientFieldName]`.
246
     *
Carsten  Rose's avatar
Carsten Rose committed
247
     * @param       $clientFieldName
248
     * @param array $clientValues
Carsten  Rose's avatar
Carsten Rose committed
249
     *
250
     * @return string
251
     */
252
    private function collectMultiValues($clientFieldName, array $clientValues) {
253

254
        $checkboxKey = HelperFormElement::prependFormElementNameCheckBoxMulti($clientFieldName, 'h');
255

256
257
        // For templateGroups: all expanded FormElements will be tried to collect - this fails for not submitted fields.
        // Therefore skip not existing clientvalues.
Carsten  Rose's avatar
Carsten Rose committed
258
        if (!isset($clientValues[$checkboxKey])) {
259
260
261
262
            return false;
        }

        // Check if there is a hidden value with naming in checkbox multi syntax
263
        if (isset($clientValues[$checkboxKey])) {
264
            $checkboxValue = $clientValues[$checkboxKey];
265

266
            $pattern = '/' . HelperFormElement::prependFormElementNameCheckBoxMulti($clientFieldName, '\d+') . '/';
267
268
            foreach ($clientValues as $key => $value) {
                if (1 === preg_match($pattern, $key)) {
269
                    $checkboxValue .= ',' . $value;
270
271
272
                }
            }

273
274
275
276
            if (isset($checkboxValue[0]) && $checkboxValue[0] === ',') {
                $checkboxValue = substr($checkboxValue, 1);
            }

277
278
279
280
281
282
            $clientValues[$clientFieldName] = $checkboxValue;
        }

        return $clientValues[$clientFieldName];
    }

283
284
285
    /**
     * Check  $value as date/datime/time value and convert it to FORMAT_DATE_INTERNATIONAL.
     *
Carsten  Rose's avatar
Carsten Rose committed
286
287
288
     * @param array  $formElement - if not set, set $formElement[FE_DATE_FORMAT]
     * @param string $value       - date/datetime/time value in format FORMAT_DATE_INTERNATIONAL or FORMAT_DATE_GERMAN
     *
289
290
291
292
293
     * @return string - checked datetime string
     * @throws UserFormException
     */
    private function doDateTime(array &$formElement, $value) {

294
        $regexp = Support::dateTimeRegexp($formElement[FE_TYPE], $formElement[FE_DATE_FORMAT]);
295
296
297
298
299
300

        if (1 !== preg_match('/' . $regexp . '/', $value, $matches)) {
            $placeholder = Support::getDateTimePlaceholder($formElement);
            throw new UserFormException("DateTime format not recognized: $placeholder / $value ", ERROR_DATE_TIME_FORMAT_NOT_RECOGNISED);
        }

301
        $showTime = $formElement[FE_TYPE] == 'date' ? '0' : '1';
302
303
304
305
        $value = Support::convertDateTime($value, FORMAT_DATE_INTERNATIONAL, '1', $showTime, $formElement[FE_SHOW_SECONDS]);

        return $value;
    }
Carsten  Rose's avatar
Carsten Rose committed
306
}