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

namespace qfq;

require_once(__DIR__ . '/Store.php');
require_once(__DIR__ . '/../Database.php');
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
    }

    /**
     * Loads a minimal definition of FormElement of the form specified in SIP.
     *
     * @throws CodeException
     * @throws DbException
56
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
57
58
     */
    private function loadFormElementsBasedOnSIP() {
59
        $formName = $this->store->getVar(SIP_FORM, STORE_SIP);
Carsten  Rose's avatar
Carsten Rose committed
60

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

        $feSpecNative = $this->db->sql(SQL_FORM_ELEMENT_SIMPLE_ALL_CONTAINER, ROW_REGULAR, [$formName]);
Carsten  Rose's avatar
Carsten Rose committed
65
66

        if (count($feSpecNative) === 0) {
67
            throw new UserFormException('Form not found or multiple forms with the same name.', ERROR_FORM_NOT_FOUND);
Carsten  Rose's avatar
Carsten Rose committed
68
69
        }

70
71
        HelperFormElement::explodeParameterInArrayElements($feSpecNative);

Carsten  Rose's avatar
Carsten Rose committed
72
73
74
75
76
77
78
79
        return $feSpecNative;
    }

    /**
     * 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
80
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
81
82
83
84
85
86
87
88
89
90
     */
    public function process() {
        $html = '';
        $newValues = array();

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

        // Retrieve SIP vars, e.g. for HIDDEN elements.
        $sipValues = $this->store->getStore(STORE_SIP);

91
        // Copy SIP Values; not necessarily defined as a FormElement.
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        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
107
108
109
110
111
        // 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];

Carsten  Rose's avatar
Carsten Rose committed
112
113
114
115
116
117
118
        // Iterate over all formelements. Sanatize values. Built an assoc array $newValues.
        foreach ($this->feSpecNative AS $formElement) {

            // Never get a predefined 'id'
            if ($formElement['name'] === 'id')
                continue;

119
120
121
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($formElement), STORE_SYSTEM);

122
123
            // Evaluate current FormElement: e.g. FE_MODE_SQL
            $formElement = $this->evaluate->parseArray($formElement, $debugStack);
124

125
            // Get related formElement. Construct the field name used in the form.
Carsten  Rose's avatar
#2067    
Carsten Rose committed
126
            $clientFieldName = HelperFormElement::buildFormElementName($formElement['name'], $fakeRecordId);
Carsten  Rose's avatar
Carsten Rose committed
127

128
129
            // Some Defaults
            $formElement = Support::setFeDefaults($formElement);
Carsten  Rose's avatar
Carsten Rose committed
130

131
132
            if ($formElement[FE_TYPE] === FE_TYPE_EXTRA) {
                // Extra elements will be transferred by SIP
Carsten  Rose's avatar
Carsten Rose committed
133
                if (!isset($sipValues[$formElement['name']])) {
134
                    throw new CodeException("Missing the " . FE_TYPE_EXTRA . " field '" . $formElement['name'] . "' in SIP.", ERROR_MISSING_HIDDEN_FIELD_IN_SIP);
Carsten  Rose's avatar
Carsten Rose committed
135
136
137
138
139
140
                }

                $newValues[$formElement['name']] = $sipValues[$formElement['name']];
                continue;
            }

141
            // Checkbox Multi: collect values
142
143
            if ($formElement[FE_TYPE] === 'checkbox') {
                $clientValues[$clientFieldName] = $this->collectMultiValues($clientFieldName, $clientValues);
144
145
            }

146
            if ($formElement[FE_MODE] === FE_MODE_REQUIRED) {
147
148
149
150
151
                if (!isset($clientValues[$clientFieldName]) || ($clientValues[$clientFieldName] === '')) {
                    throw new UserFormException("Missing required value.", ERROR_REQUIRED_VALUE_EMPTY);
                }
            }

152
153
154
155
156
157
158
159
160
161
162
            // 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
                                $newValues[$formElement['name']] = $this->doDateTime($formElement, $clientValues[$clientFieldName]);
                            break;
                        default:
163
164
165
166
167
168
169
                            // Check only if their is something
                            if($clientValues[$clientFieldName] !== '') {
                                $newValues[$formElement['name']] = Sanitize::sanitize($clientValues[$clientFieldName],
                                    $formElement['checkType'], $formElement['checkPattern'], SANATIZE_EXCEPTION);
                            } else {
                                $newValues[$formElement['name']] ='';
                            }
170
                            break;
171
                    }
172
                }
Carsten  Rose's avatar
Carsten Rose committed
173
174
175
176
177
178
            }
        }

        $this->store->setVarArray($newValues, STORE_FORM, true);
    }

179
    /**
180
181
182
     * 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 no multi values - return the already given `$clientValues[$clientFieldName]`.
     *
183
184
     * @param $clientFieldName
     * @param array $clientValues
185
     * @return string
186
     */
187
    private function collectMultiValues($clientFieldName, array $clientValues) {
188
189

        $checkboxKey = HelperFormElement::prependFormElementIdCheckBoxMulti($clientFieldName, 'h');
190

191
192
        // Check there is a hidden value with naming in checkbox multi syntax
        if (isset($clientValues[$checkboxKey])) {
193
            $checkboxValue = $clientValues[$checkboxKey];
194

195
196
197
            $pattern = '/' . HelperFormElement::prependFormElementIdCheckBoxMulti($clientFieldName, '\d+') . '/';
            foreach ($clientValues as $key => $value) {
                if (1 === preg_match($pattern, $key)) {
198
                    $checkboxValue .= ',' . $value;
199
200
201
                }
            }

202
203
204
205
            if (isset($checkboxValue[0]) && $checkboxValue[0] === ',') {
                $checkboxValue = substr($checkboxValue, 1);
            }

206
207
208
209
210
211
            $clientValues[$clientFieldName] = $checkboxValue;
        }

        return $clientValues[$clientFieldName];
    }

212
213
214
    /**
     * Check  $value as date/datime/time value and convert it to FORMAT_DATE_INTERNATIONAL.
     *
215
     * @param array $formElement - if not set, set $formElement[FE_DATE_FORMAT]
216
217
218
219
220
221
     * @param string $value - date/datetime/time value in format FORMAT_DATE_INTERNATIONAL or FORMAT_DATE_GERMAN
     * @return string - checked datetime string
     * @throws UserFormException
     */
    private function doDateTime(array &$formElement, $value) {

222
        $regexp = Support::dateTimeRegexp($formElement[FE_TYPE], $formElement[FE_DATE_FORMAT]);
223
224
225
226
227
228

        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);
        }

229
        $showTime = $formElement[FE_TYPE] == 'date' ? '0' : '1';
230
231
232
233
        $value = Support::convertDateTime($value, FORMAT_DATE_INTERNATIONAL, '1', $showTime, $formElement[FE_SHOW_SECONDS]);

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