Save.php 53 KB
Newer Older
1
2
3
4
5
6
7
8
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 1/30/16
 * Time: 7:59 PM
 */

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\FormAction;
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
use IMATHUZH\Qfq\Core\Helper\Logger;
17
use IMATHUZH\Qfq\Core\Helper\OnArray;
18
use IMATHUZH\Qfq\Core\Helper\Path;
Marc Egger's avatar
Marc Egger committed
19
use IMATHUZH\Qfq\Core\Helper\Sanitize;
20
use IMATHUZH\Qfq\Core\Helper\SqlQuery;
Marc Egger's avatar
Marc Egger committed
21
use IMATHUZH\Qfq\Core\Helper\Support;
22
use IMATHUZH\Qfq\Core\Store\FillStoreForm;
Marc Egger's avatar
Marc Egger committed
23
use IMATHUZH\Qfq\Core\Store\Sip;
24
use IMATHUZH\Qfq\Core\Store\Store;
25
use ZipArchive;
26

27
28
29
30
/**
 * Class Save
 * @package qfq
 */
31
32
33
34
35
class Save {

    private $formSpec = array();  // copy of the loaded form
    private $feSpecAction = array(); // copy of all formElement.class='action' of the loaded form
    private $feSpecNative = array(); // copy of all formElement.class='native' of the loaded form
36
    private $feSpecNativeRaw = array(); // copy of all formElement.class='native' of the loaded form
37
38
39
40
41
42

    /**
     * @var FormAction
     */
    private $formAction = null;

43
44
45
46
    /**
     * @var null|Store
     */
    private $store = null;
Carsten  Rose's avatar
Carsten Rose committed
47
48
49
50

    /**
     * @var Database
     */
51
52
53
54
    private $db = null;

    private $evaluate = null;

55
56
    private $qfqLogFilename = '';

57
58
59
60
    /**
     * @param array $formSpec
     * @param array $feSpecAction
     * @param array $feSpecNative
61
     * @param array $feSpecNativeRaw
Marc Egger's avatar
Marc Egger committed
62
63
64
65
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
66
     */
67
    public function __construct(array $formSpec, array $feSpecAction, array $feSpecNative, array $feSpecNativeRaw) {
68

69
70
71
        $this->formSpec = $formSpec;
        $this->feSpecAction = $feSpecAction;
        $this->feSpecNative = $feSpecNative;
72
        $this->feSpecNativeRaw = $feSpecNativeRaw;
73
        $this->store = Store::getInstance();
74
        $this->db = new Database($formSpec[F_DB_INDEX]);
75
        $this->evaluate = new Evaluate($this->store, $this->db);
76
        $this->formAction = new FormAction($formSpec, $this->db);
77

78
        $this->qfqLogFilename = Path::absoluteQfqLogFile();
79
80
81
    }

    /**
Carsten  Rose's avatar
Carsten Rose committed
82
     * Starts save process. Returns recordId.
83
     *
84
     * @return int
Marc Egger's avatar
Marc Egger committed
85
86
87
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
88
     * @throws \UserReportException
89
90
     */
    public function process() {
91
        $rc = 0;
92

93
        if ($this->formSpec[F_MULTI_SQL] == '') {
94
95
            $recordId = $this->store->getVar(SIP_RECORD_ID, STORE_SIP . STORE_ZERO);
            $rc = $this->elements($recordId);
96
97
        } else {
            $rc = $this->saveMultiForm();
98
        }
99
100

        return $rc;
101
102
    }

103
104
105
106
107
108
109
110
111
112
113
    /**
     * @return int|string
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private function saveMultiForm() {

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

114
        // No rows: This must be an error, cause MultiForms must have at least one record.
115
        if (empty($parentRecords)) {
116
117
118
119
            throw new \UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => $this->formSpec[F_MULTI_MSG_NO_RECORD],
                    ERROR_MESSAGE_TO_DEVELOPER => 'Query selects no records: ' . $this->formSpec[F_MULTI_SQL]]),
                ERROR_MISSING_EXPECT_RECORDS);
120
121
122
123
124
125
126
127
128
129
130
131
132
        }

        // Check for 'id' or '_id' as column name
        $idName = isset($parentRecords[0]['_' . F_MULTI_COL_ID]) ? '_' . F_MULTI_COL_ID : F_MULTI_COL_ID;

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

        $fillStoreForm = new FillStoreForm();
133
        $storeVarBase = $this->store->getStore(STORE_VAR);
134
135

        foreach ($parentRecords as $row) {
136
137
138
139

            // Always start with a clean STORE_VAR
            $this->store->setStore($storeVarBase, STORE_VAR, true);

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

143
            $record = $this->db->sql('SELECT * FROM `' . $this->formSpec[F_TABLE_NAME] . '` WHERE `id`=' . $row[$idName], ROW_EXPECT_1);
144
145
            $this->store->setStore($record, STORE_RECORD, true);

146
147
148
149
150
151
152
153
154
155
            // Fake current recordId
            $this->store->setVar(SIP_RECORD_ID, $row[$idName], STORE_SIP);
            $fillStoreForm->process(FORM_SAVE);

            $rc = $this->elements($row[$idName]);
        }

        return $rc;
    }

156
    /**
Carsten  Rose's avatar
Carsten Rose committed
157
158
     * Create empty FormElements based on templateGroups, for those who not already exist.
     *
159
     * @param array $formValues
Carsten  Rose's avatar
Carsten Rose committed
160
     *
161
     * @return array
Marc Egger's avatar
Marc Egger committed
162
     * @throws \UserFormException
163
164
165
166
167
     */
    private function createEmptyTemplateGroupElements(array $formValues) {

        foreach ($this->feSpecNative as $formElement) {

168
169
170
171
172
173
174
175
            switch ($formElement[FE_TYPE]) {
//                case FE_TYPE_EXTRA:
                case FE_TYPE_NOTE:
                case FE_TYPE_SUBRECORD:
                    continue 2;
                default:
                    break;
            }
176
            $feName = $formElement[FE_NAME];
177
178
179

            // #7705. Skip FE, which are not already expanded. Detect them by '%' (== '%d')
            if (!isset($formValues[$feName]) && false === stripos($feName, '%d') && $this->isMemberOfTemplateGroup($formElement)) {
180
181
182
                $formValues[$feName] = $formElement[FE_VALUE];
            }
        }
Carsten  Rose's avatar
Carsten Rose committed
183

184
185
186
        return $formValues;
    }

187
    /**
188
189
190
191
192
     * Check if the current $formElement is member of a templateGroup.
     *
     * @param array $formElement
     * @param int $depth
     * @return bool
Marc Egger's avatar
Marc Egger committed
193
     * @throws \UserFormException
194
195
196
197
198
     */
    private function isMemberOfTemplateGroup(array $formElement, $depth = 0) {
        $depth++;

        if ($depth > 15) {
Marc Egger's avatar
Marc Egger committed
199
            throw new \UserFormException('FormElement nested too much (in each other - endless?): stop recursion', ERROR_FE_NESTED_TOO_MUCH);
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        }

        if ($formElement[FE_TYPE] == FE_TYPE_TEMPLATE_GROUP) {
            return true;
        }

        if ($formElement[FE_ID_CONTAINER] == 0) {
            return false;
        }

        // Get the parent element
        $formElementArr = OnArray::filter($this->feSpecNativeRaw, FE_ID, $formElement[FE_ID_CONTAINER]);
        if (isset($formElementArr[0])) {
            return $this->isMemberOfTemplateGroup($formElementArr[0], $depth);
        }

        return false; // This should not be reached,
    }

    /**
     *
221
     * @param $feName
Carsten  Rose's avatar
Carsten Rose committed
222
     *
223
224
225
226
227
228
229
230
231
232
233
     * @return bool
     */
    private function isSetEmptyMeansNull($feName) {

        $fe = OnArray::filter($this->feSpecNative, FE_NAME, $feName);

        $flag = isset($fe[0][FE_EMPTY_MEANS_NULL]) && $fe[0][FE_EMPTY_MEANS_NULL] != '0';

        return $flag;
    }

234
    /**
Carsten  Rose's avatar
Carsten Rose committed
235
236
     * Build an array of all values which should be saved. Values must exist as a 'form value' as well as a regular
     * 'table column'.
Carsten  Rose's avatar
Carsten Rose committed
237
     *
238
     * @param $recordId
Carsten  Rose's avatar
Carsten Rose committed
239
     *
240
     * @return int    record id (in case of insert, it's different from $recordId)
Marc Egger's avatar
Marc Egger committed
241
242
     * @throws \CodeException
     * @throws \DbException
243
244
     * @throws \UserFormException
     * @throws \UserReportException
245
     */
246
    private function elements($recordId) {
247
248
        $columnCreated = false;
        $columnModified = false;
249
        $realColumnFound = false;
Carsten  Rose's avatar
Carsten Rose committed
250

251
252
253
        $newValues = array();

        $tableColumns = array_keys($this->store->getStore(STORE_TABLE_COLUMN_TYPES));
254
        $formValues = $this->store->getStore(STORE_FORM);
255
        $formValues = $this->createEmptyTemplateGroupElements($formValues);
256
257

        // Iterate over all table.columns. Built an assoc array $newValues.
258
        foreach ($tableColumns as $column) {
259

260
            // Never save a predefined 'id': autoincrement values will be given by database..
261
            if ($column === COLUMN_ID) {
262
                continue;
263
            }
264

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
265
266
            // Skip Upload Elements: those will be processed later.
            if ($this->isColumnUploadField($column)) {
267
                $realColumnFound = true;
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
268
269
270
                continue;
            }

271
272
273
274
275
276
277
278
            if ($column === COLUMN_CREATED) {
                $columnCreated = true;
            }

            if ($column === COLUMN_MODIFIED) {
                $columnModified = true;
            }

279
280
            // Is there a value? Do not forget SIP values. Those do not have necessarily a FormElement.
            if (!isset($formValues[$column])) {
281
                continue;
282
283
            }

284
            $this->store->setVar(SYSTEM_FORM_ELEMENT, "Column: $column", STORE_SYSTEM);
285

286
287
288
289
290
291
            // Check if an empty string has to be converted to null.
            if (isset($formValues[$column]) && $formValues[$column] == '' && $this->isSetEmptyMeansNull($column)) {
                $formValues[$column] = null;
            } else {
                Support::setIfNotSet($formValues, $column);
            }
292
            $newValues[$column] = $formValues[$column];
293
            $realColumnFound = true;
294
295
        }

296
297
        // Only save record if real columns exist.
        if ($realColumnFound) {
298

299
300
            if ($columnModified && !isset($newValues[COLUMN_MODIFIED])) {
                $newValues[COLUMN_MODIFIED] = date('YmdHis');
301
            }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
302

303
304
305
306
307
308
309
            if ($recordId == 0) {
                if ($columnCreated && !isset($newValues[COLUMN_CREATED])) {
                    $newValues[COLUMN_CREATED] = date('YmdHis');
                }
                $recordId = $this->insertRecord($this->formSpec[F_TABLE_NAME], $newValues);

            } else {
310
311
                $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
            }
312
313
        }

314
315
316
        // Reload fresh saved record and fill STORE_RECORD with it. Do this before nativeDoSlave().
        $this->store->fillStoreWithRecord($this->formSpec[F_TABLE_NAME], $recordId, $this->db, $this->formSpec[F_PRIMARY_KEY]);

317
        $this->nativeDoSlave($recordId);
318

319
        return $recordId;
320
321
    }

322
    /**
323
324
     * Process sqlBefore, sqlInsert|.... for all native FE.
     *
325
     * @param $recordId
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
326
     *
327
328
329
330
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
331
     */
332
333
334
335
336
337
338
339
    private function nativeDoSlave($recordId) {

        foreach ($this->feSpecNative as $fe) {
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($fe), STORE_SYSTEM);
            $this->store->setVar(SYSTEM_FORM_ELEMENT_ID, $fe[FE_ID], STORE_SYSTEM);

            $this->formAction->doSqlBeforeSlaveAfter($fe, $recordId, false);
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
            $this->typeAheadDoTagGlue($fe);
        }
    }

    /**
     * typeAhead: if given, process Tag or Glue.
     *
     * @param array $fe
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private function typeAheadDoTagGlue(array $fe) {

355
        // Update 'glue' records?
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
        if (($fe[FE_TYPEAHEAD_TAG] ?? '0') == '0' || (!isset($fe[FE_TYPEAHEAD_GLUE_INSERT]) && !isset($fe[FE_TYPEAHEAD_TAG_INSERT]))) {
            return;
        }

        if (empty($fe[FE_TYPEAHEAD_GLUE_INSERT]) || empty($fe[FE_TYPEAHEAD_GLUE_DELETE])) {
            throw new \UserFormException("Missing 'typeAheadGlueInsert' or 'typeAheadGlueDelete'", ERROR_MISSING_REQUIRED_PARAMETER);
        }

        // Extract assigned tags: last
        $tagLast = KeyValueStringParser::parse($this->evaluate->parse($fe[FE_VALUE], ROW_EXPECT_0_1));

        // Extract assigned tags: new
        $tagNew = KeyValueStringParser::parse($this->store->getVar($fe[FE_NAME], STORE_FORM,
            ($fe[FE_CHECK_TYPE] == SANITIZE_ALLOW_AUTO) ? SANITIZE_ALLOW_ALNUMX : $fe[FE_CHECK_TYPE]));

        // Get all tags who are new
        $result = array_diff_assoc($tagNew, $tagLast);

        // Create glue records
        foreach ($result as $id => $value) {
376

377
378
            $this->store->setVar(VAR_TAG_ID, $id, STORE_VAR);
            $this->store->setVar(VAR_TAG_VALUE, $value, STORE_VAR);
379
380
381
382
383
384
385
386
387
388

            if ($id == 0) {
                if (empty($fe[FE_TYPEAHEAD_TAG_INSERT])) {
                    throw new \UserFormException("Missing 'typeAheadTagInsert'", ERROR_MISSING_REQUIRED_PARAMETER);
                }
                // Create tag
                $id = $this->evaluate->parse($fe[FE_TYPEAHEAD_TAG_INSERT]);
                $this->store->setVar(VAR_TAG_ID, $id, STORE_VAR);
            }

389
390
391
392
393
394
395
396
397
398
399
400
401
            // Create glue
            $this->evaluate->parse($fe[FE_TYPEAHEAD_GLUE_INSERT]);
        }

        // Get all tags who has been removed
        $result = array_diff_assoc($tagLast, $tagNew);

        // Delete Glue records
        foreach ($result as $id => $value) {
            $this->store->setVar(VAR_TAG_ID, $id, STORE_VAR);
            $this->store->setVar(VAR_TAG_VALUE, $value, STORE_VAR);
            // Delete glue
            $this->evaluate->parse($fe[FE_TYPEAHEAD_GLUE_DELETE]);
402
403
404
        }
    }

405
    /**
406
407
     * Checks if there is a formElement with name '$feName' of type 'upload'
     *
408
409
410
     * @param $feName
     * @return bool
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
411
412
    private function isColumnUploadField($feName) {

413
        foreach ($this->feSpecNative as $formElement) {
414
            if ($formElement[FE_NAME] === $feName && $formElement[FE_TYPE] == FE_TYPE_UPLOAD)
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
415
416
                return true;
        }
Carsten  Rose's avatar
Carsten Rose committed
417

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
418
419
420
421
422
423
        return false;
    }

    /**
     * Insert new record in table $this->formSpec['tableName'].
     *
424
     * @param $tableName
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
425
     * @param array $values
Carsten  Rose's avatar
Carsten Rose committed
426
     *
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
427
     * @return int  last insert id
Marc Egger's avatar
Marc Egger committed
428
429
430
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
431
432
433
434
435
436
     */
    public function insertRecord($tableName, array $values) {

        if (count($values) === 0)
            return 0; // nothing to write, last insert id=0

437
        list($sql, $parameterArray) = SqlQuery::insertRecord($tableName, $values);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
438

439
        $rc = $this->db->sql($sql, ROW_REGULAR, $parameterArray);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
440
441
442
443
444
445

        return $rc;
    }

    /**
     * @param string $tableName
Carsten  Rose's avatar
Carsten Rose committed
446
447
     * @param array $values
     * @param int $recordId
448
     * @param string $primaryKey
Carsten  Rose's avatar
Carsten Rose committed
449
     *
450
     * @return bool|int     false if $values is empty, else affected rows
Marc Egger's avatar
Marc Egger committed
451
452
453
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
454
     */
455
    public function updateRecord($tableName, array $values, $recordId, $primaryKey = F_PRIMARY_KEY_DEFAULT) {
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
456
457
458
459

        if (count($values) === 0)
            return 0; // nothing to write, 0 rows affected

460
        list($sql, $parameterArray) = SqlQuery::updateRecord($tableName, $values, $recordId, $primaryKey);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
461

462
        $rc = $this->db->sql($sql, ROW_REGULAR, $parameterArray);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
463
464
465
466

        return $rc;
    }

467
    /**
Carsten  Rose's avatar
Carsten Rose committed
468
469
     * Process all Upload Formelements for the given $recordId. After processing &$formValues will be updated with the
     * final filenames.
470
471
472
473
474
475
476
477
     *
     * Constellation: # FILE OLD   FILE NEW     FILESIZE
     *                1 none       none
     *                2 none       new
     *                3 exist      no change
     *                4 delete     none
     *                5 delete     new
     *
478
     * @param $recordId
Marc Egger's avatar
Marc Egger committed
479
480
481
482
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
483
484
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
485
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
486
487
488
489
    public function processAllUploads($recordId) {

        $sip = new Sip(false);
        $newValues = array();
490
491

        $flagDoUnzip = false;
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
492
493

        $formValues = $this->store->getStore(STORE_FORM);
494
        $primaryRecord = $this->store->getStore(STORE_RECORD); // necessary to check if the current formElement exist as a column of the primary table.
495

496
497
        // Upload - Take care the necessary target directories exist.
        $cwd = getcwd();
498
        $sitePath = Path::cwdToApp();
499
500
501
502
503
504
505
        if ($cwd === false || $sitePath === false || !HelperFile::chdir($sitePath)) {
            throw new \UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'getcwd() failed or SITE_PATH undefined or chdir() failed', ERROR_MESSAGE_TO_DEVELOPER => "getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed."]),
                ERROR_IO_CHDIR);
        }

        foreach ($this->feSpecNative as $formElement) {
506
            // skip non upload formElements
507
            if ($formElement[FE_TYPE] != FE_TYPE_UPLOAD) {
508
509
510
                continue;
            }

511
512
513
514
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($formElement), STORE_SYSTEM);
            $this->store->setVar(SYSTEM_FORM_ELEMENT_ID, $formElement[FE_ID], STORE_SYSTEM);

515
            $formElement = HelperFormElement::initUploadFormElement($formElement);
516
            if (isset($formElement[FE_FILL_STORE_VAR])) {
517
                $formElement[FE_FILL_STORE_VAR] = $this->evaluate->parse($formElement[FE_FILL_STORE_VAR], ROW_EXPECT_0_1);
518
                $this->store->appendToStore($formElement[FE_FILL_STORE_VAR], STORE_VAR);
519
            }
520

521
            $column = $formElement[FE_NAME];
522
523
524
525

            $statusUpload = $this->store->getVar($formValues[$column] ?? '', STORE_EXTRA);
            // Get file stats
            $vars = array();
526
527
            $vars[VAR_FILE_SIZE] = $statusUpload[FILES_SIZE] ?? '';
            $vars[VAR_FILE_MIME_TYPE] = $statusUpload[FILES_TYPE] ?? '';
528
529

            // Check for 'unzip'.
530
531
532
            if (isset($formElement[FE_FILE_UNZIP])
                && $formElement[FE_FILE_UNZIP] != '0'
                && $vars[VAR_FILE_MIME_TYPE] == 'application/zip') {
533
534
535
536
                $flagDoUnzip = true;
            }

            // Do upload
537
            $pathFileName = $this->doUpload($formElement, ($formValues[$column] ?? ''), $sip, $modeUpload);
538
            if ($flagDoUnzip && $pathFileName != '') {
539
540
541
542
543
544
545
546
547
548
549
                if ($formElement[FE_FILE_UNZIP] == '' || $formElement[FE_FILE_UNZIP] == '1') {
                    // Set default dir.
                    $formElement[FE_FILE_UNZIP] = HelperFile::joinPathFilename(dirname($pathFileName), FE_FILE_UNPACK_DIR);
                }

                // Backup STORE_VAR - will be changed in doUnzip()
                $tmpStoreVar = $this->store->getStore(STORE_VAR);
                $this->doUnzip($formElement, $pathFileName);
                // Restore STORE_VAR
                $this->store->setStore($tmpStoreVar, STORE_VAR, true);
            }
550

551
552
            if ($modeUpload == UPLOAD_MODE_DELETEOLD && $pathFileName == '') {
                $pathFileNameTmp = '';  // see '4'
553
554
            } else {
                if (empty($pathFileName)) {
555
                    $pathFileNameTmp = $primaryRecord[$column] ?? ''; // see '3'. Attention: in case of Advanced Upload, $primaryRecord[$column] does not exist.
556
557
558
559
560
                } else {
                    $pathFileNameTmp = $pathFileName; // see '1,2,5'
                }
            }

561
            // Get latest file information
562
            if ($pathFileNameTmp == '') {
563
564
565
566
                // No new upload and no existing: take care to remove previous upload file statistics.
                $this->store->unsetVar(VAR_FILE_MIME_TYPE, STORE_VAR);
                $this->store->unsetVar(VAR_FILE_SIZE, STORE_VAR);
            } else {
567

568
569
570
                $this->store->appendToStore($vars, STORE_VAR);
            }

571
            // If given: fire a sqlBefore query
572
573
574
            if (!$flagDoUnzip) {
                $this->evaluate->parse($formElement[FE_SQL_BEFORE]);
            }
575

576
            // Upload Type: Simple or Advanced
577
578
579
            // If (isset($primaryRecord[$column])) { - see #5048 - isset does not deal correctly with NULL!
            if (array_key_exists($column, $primaryRecord)) {
                // 'Simple Upload': no special action needed, just process the current (maybe modified) value.
580
581
                if ($pathFileName !== false) {
                    $newValues[$column] = $pathFileName;
582
583
584
585
586
587
588
589

                    if (isset($primaryRecord[COLUMN_FILE_SIZE])) {
                        $newValues[COLUMN_FILE_SIZE] = $vars[VAR_FILE_SIZE];
                    }

                    if (isset($primaryRecord[COLUMN_MIME_TYPE])) {
                        $newValues[COLUMN_MIME_TYPE] = $vars[VAR_FILE_MIME_TYPE];
                    }
590
                }
591
592
            } elseif (isset($formElement[FE_IMPORT_TO_TABLE]) && !isset($formElement[FE_SLAVE_ID])) {
                // Excel import on nonexisting column -> no upload
593
594
            } elseif ($flagDoUnzip) {
                // If ZIP and advanced upload: process it not here but via doUnzip.
595
596
            } else {
                // 'Advanced Upload'
597
                $this->doUploadSlave($formElement, $modeUpload);
598
            }
599
600

            // If given: fire a sqlAfter query
601
602
603
            if (!$flagDoUnzip) {
                $this->evaluate->parse($formElement[FE_SQL_AFTER]);
            }
604
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
605

606
607
608
        // Clean up
        HelperFile::chdir($cwd);

609
        // Only used in 'Simple Upload'
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
610
        if (count($newValues) > 0) {
611
            $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
612
        }
613
614
    }

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
    /**
     * Unzip $pathFileName to $formElement[FE_FILE_UNZIP]. Before final extract, fire FE_SQL_VALIDATE.
     * For each file in ZIP:
     * - Fill STORE_VAR with VAR_FILENAME, VAR_FILENAME_ONLY, VAR_FILENAME_BASE, VAR_FILENAME_EXT, VAR_FILE_MIME_TYPE, VAR_FILE_SIZE.
     * - Fire $formElement[FE_SQL_VALIDATE]
     * - Fire FE_SLAVE_ID, FE_SQL_BEFORE, FE_SQL_INSERT, FE_SQL_UPDATE, FE_SQL_DELETE, FE_SQL_AFTER
     *
     * @param array $formElement
     * @param string $pathFileName
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    private function doUnzip(array $formElement, $pathFileName) {

        if (!is_readable($pathFileName)) {
            throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Open ZIP file failed",
                ERROR_MESSAGE_TO_DEVELOPER => "File: " . $pathFileName]),
                ERROR_IO_ZIP_OPEN);
        }

        $zip = new ZipArchive();
        $res = $zip->open($pathFileName);
        if ($res !== true) {
            throw new \UserFormException(json_encode([ERROR_MESSAGE_TO_USER => "Open ZIP file failed" . HelperFile::zipFileErrMsg($res),
                ERROR_MESSAGE_TO_DEVELOPER => "File: " . $pathFileName]), ERROR_IO_ZIP_OPEN);
        }

644
645
646
647
648
649
        // Extract
        if (false === $zip->extractTo($formElement[FE_FILE_UNZIP])) {
            throw new \UserFormException("Failed to extract ZIP.", ERROR_IO_ZIP_OPEN);
        }

        // Do sqlValidate() - to get mime type of zipped items, the archive has already been extracted.
650
651
652
653
654
655
656
657
658
659
660
661
662
        if (!empty($formElement[FE_SQL_VALIDATE])) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $stat = $zip->statIndex($i);

                $itemPathFileName = HelperFile::joinPathFilename($formElement[FE_FILE_UNZIP], $stat['name']);
                $this->store->appendToStore(HelperFile::getFileStat($itemPathFileName), STORE_VAR);
                $this->store->appendToStore(HelperFile::pathinfo($itemPathFileName), STORE_VAR);

                HelperFormElement::sqlValidate($this->evaluate, $formElement);
            }
        }

        // Process
663
664
665
666
        if (!isset($formElement[FE_SLAVE_ID])) {
            $formElement[FE_SLAVE_ID] = '';
        }

667
668
669
670
671
672
673
674
675
676
677
678
679
680
        if (!empty($formElement[FE_SLAVE_ID] . $formElement[FE_SQL_BEFORE] . $formElement[FE_SQL_INSERT] .
            $formElement[FE_SQL_UPDATE] . $formElement[FE_SQL_DELETE] . $formElement[FE_SQL_AFTER])) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $stat = $zip->statIndex($i);

                $itemPathFileName = HelperFile::joinPathFilename($formElement[FE_FILE_UNZIP], $stat['name']);
                $this->store->appendToStore(HelperFile::getFileStat($itemPathFileName), STORE_VAR);
                $this->store->appendToStore(HelperFile::pathinfo($itemPathFileName), STORE_VAR);

                $this->evaluate->parse($formElement[FE_SQL_BEFORE]);
                $this->doUploadSlave($formElement, UPLOAD_MODE_NEW);
                $this->evaluate->parse($formElement[FE_SQL_AFTER]);
            }
        }
681
682
683
684
685

        // Close Zip
        if (false === $zip->close()) {
            throw new \UserFormException("Failed to close ZIP.", ERROR_IO_ZIP_OPEN);
        }
686
687
    }

688
    /**
689
690
     * Process all Upload FormElements for the given $recordId.
     * After processing, &$formValues will be updated with the final filename.
691
     *
Marc Egger's avatar
Marc Egger committed
692
693
     * @throws \CodeException
     * @throws \UserFormException
694
695
696
     */
    public function processAllImageCutFE() {

697
        foreach ($this->feSpecNative as $formElement) {
698
699
700
701
702
703
704
705
706
            // skip non upload formElements
            if ($formElement[FE_TYPE] != FE_TYPE_IMAGE_CUT) {
                continue;
            }

            $this->extractImageDataReplaceFile($formElement);
        }
    }

707
708
709
710
711
712
713
714

    /**
     * Iterates over all FE and checks all 'required' (mode & modeSql) FE.
     * If a required FE is empty, throw an exception.
     * Take care to remove all FE with modeSql='hidden'.
     *
     * Typically, the browser does not allow a submit if a required field is empty.
     *
Marc Egger's avatar
Marc Egger committed
715
716
717
718
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
719
720
721
     */
    public function checkRequiredHidden() {

722
        $formModeGlobal = Support::getFormModeGlobal($this->formSpec[F_MODE_GLOBAL] ?? '');
723
        $reportRequiredFailed = true;
724

725
726
727
728
729
730
        switch ($formModeGlobal) {
            case F_MODE_REQUIRED_OFF:
            case F_MODE_REQUIRED_OFF_BUT_MARK:
                $reportRequiredFailed = false;
                break;
        }
731
732
733

        $clientValues = $this->store::getStore(STORE_FORM);

734
735
        $flagAllRequiredGiven = 1;

736
        foreach ($this->feSpecNative as $key => $formElement) {
737

738
739
740
741
742
            // Do not check retype slave FE.
            if (isset($formElement[FE_RETYPE_SOURCE_NAME])) {
                continue;
            }

743
744
            $this->store->setVar(SYSTEM_FORM_ELEMENT, "Column: " . $formElement[FE_NAME], STORE_SYSTEM);

745
746
747
748
749
            // Normalize FE_MODE
            $mode = Support::handleEscapeSpaceComment($formElement[FE_MODE_SQL]);
            $mode = empty($mode) ? $formElement[FE_MODE] : $this->evaluate->parse($mode);
            $this->feSpecNative[$key][FE_MODE] = $formElement[FE_MODE] = $mode;
            $this->feSpecNative[$key][FE_MODE_SQL] = $formElement[FE_MODE_SQL] = '';
750

751
752
753
            if (isset($formElement[FE_ACCEPT_ZERO_AS_REQUIRED]) && $formElement[FE_ACCEPT_ZERO_AS_REQUIRED] != '0' &&
                isset($clientValues[$formElement[FE_NAME]]) && $clientValues[$formElement[FE_NAME]] == '0') {
                $mode = 'fake'; // The next if() should never be true.
754
755
            }

756
757
758
759
760
            if ($mode == FE_MODE_REQUIRED && empty($clientValues[$formElement[FE_NAME]])) {
                $flagAllRequiredGiven = 0;
                if ($reportRequiredFailed) {
                    throw new \UserFormException("Missing required value: " . $formElement[FE_LABEL], ERROR_REQUIRED_VALUE_EMPTY);
                }
761
762
763
764
765
766
767
            }

            if ($mode == FE_MODE_HIDDEN) {
                // Removing the value from the store, forces that the value won't be stored.
                $this->store::unsetVar($formElement[FE_NAME], STORE_FORM);
            }
        }
768
769
770

        // Save 'allRequiredGiven in STORE_VAR
        $this->store::setVar(VAR_ALL_REQUIRED_GIVEN, $flagAllRequiredGiven, STORE_VAR, true);
771
772
    }

773
774
775
    /**
     *
     * @param array $formElement
Marc Egger's avatar
Marc Egger committed
776
777
     * @throws \CodeException
     * @throws \UserFormException
778
779
780
781
782
     */
    private function extractImageDataReplaceFile(array $formElement) {

        // Take care the necessary target directories exist.
        $cwd = getcwd();
783
        $sitePath = Path::absoluteApp();
784
        if ($cwd === false || $sitePath === false || !HelperFile::chdir($sitePath)) {
Marc Egger's avatar
Marc Egger committed
785
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
786
                json_encode([ERROR_MESSAGE_TO_USER => 'getcwd() failed or SITE_PATH undefined or chdir() failed', ERROR_MESSAGE_TO_DEVELOPER => "getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed."]),
787
                ERROR_IO_CHDIR);
788
789
        }

790
        // Get original pathFileName
791
792
793
        $field = HelperFormElement::AppendFormElementNameImageCut($formElement);
        $pathFileName = $this->store->getVar($field, STORE_SIP);
        if ($pathFileName == '' || !file_exists($pathFileName)) {
Marc Egger's avatar
Marc Egger committed
794
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
795
                json_encode([ERROR_MESSAGE_TO_USER => 'Empty file or file not found', ERROR_MESSAGE_TO_DEVELOPER => 'Empty file or file not found: ' . $pathFileName]),
796
                ERROR_IO_FILE_NOT_FOUND);
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
        }

        // 'data:image/png;base64,AAAFBfj42Pj4...';
        $data = $this->store->getVar($formElement[FE_NAME], STORE_FORM, SANITIZE_ALLOW_ALLBUT);
        // Replace data by pathFileName (that is stored in DB).
        $this->store->setVar($formElement[FE_NAME], $pathFileName, STORE_FORM, true);

        if ($data == '') {
            return; // Nothing to do
        }

        // Split base64 encoded image: 'data:image/png;base64,AAAFBfj42Pj4...'
        list($type, $imageData) = explode(';', $data, 2); // $type= 'data:image/png;', $imageData='base64,AAAFBfj42Pj4...'
        list(, $extension) = explode('/', $type); // $type='png'
        list(, $imageData) = explode(',', $imageData); // $imageData='AAAFBfj42Pj4...'

        // If undefined: set default. BTW: Defined and empty means "no original".
        if (!isset($formElement[FE_IMAGE_CUT_KEEP_ORIGINAL])) {
            $formElement[FE_IMAGE_CUT_KEEP_ORIGINAL] = FE_IMAGE_CUT_ORIGINAL_EXTENSION;
        }
        $extSave = $formElement[FE_IMAGE_CUT_KEEP_ORIGINAL];

        $pathParts = pathinfo($pathFileName);
        // Keep the original file?
        if ($extSave != '') {

            // In case the leading '.' is missing.
            if ($extSave[0] != ".") {
                $extSave = '.' . $extSave;
            }

            // Check if there is already an original - don't create an additional one.
            if (!file_exists($pathFileName . $extSave) &&
                !file_exists($pathParts['dirname'] . $pathParts['filename'] . $extSave)
            ) {
832
                HelperFile::rename($pathFileName, $pathFileName . $extSave);
833
834
835
836
837
838
839
840
            }
        }

        if ($extension != $pathParts['extension']) {
            $pathFileName .= "." . $extension;
        }

        if (false === file_put_contents($pathFileName, base64_decode($imageData))) {
Marc Egger's avatar
Marc Egger committed
841
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
842
                json_encode([ERROR_MESSAGE_TO_USER => 'Write new image failed', ERROR_MESSAGE_TO_DEVELOPER => "Write new image failed: $pathFileName"]),
843
                ERROR_IO_WRITE);
844
845
846
847
848
        }

        $this->store->setVar($formElement[FE_NAME], $pathFileName, STORE_FORM, true);
    }

849
    /**
850
851
852
     * Process upload for the given Formelement. If necessary, delete a previous uploaded file.
     * Calculate the final path/filename and move the file to the new location.
     *
853
     * Check also: Documentation-develop/CODING.md
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
854
     *
Carsten  Rose's avatar
Carsten Rose committed
855
856
857
858
     * @param array $formElement FormElement 'upload'
     * @param string $sipUpload SIP
     * @param Sip $sip
     * @param string $modeUpload UPLOAD_MODE_UNCHANGED | UPLOAD_MODE_NEW | UPLOAD_MODE_DELETEOLD |
Carsten  Rose's avatar
Carsten Rose committed
859
     *                            UPLOAD_MODE_DELETEOLD_NEW
860
     * @return false|string New pathFilename or false on error
Marc Egger's avatar
Marc Egger committed
861
862
     * @throws \CodeException
     * @throws \DbException
863
864
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
865
866
     * @throws \UserFormException
     * @throws \UserReportException
867
868
     * @internal param $recordId
     */
869
870
871
    private function doUpload($formElement, $sipUpload, Sip $sip, &$modeUpload) {
        $flagDelete = false;
        $modeUpload = UPLOAD_MODE_UNCHANGED;
872
        $pathFileName = '';
873

874
        // Status information about upload file
875
876
877
878
879
        $statusUpload = $this->store->getVar($sipUpload, STORE_EXTRA);
        if ($statusUpload === false) {
            return false;
        }

880
        if (isset($formElement[FE_IMPORT_TO_TABLE]) && isset($statusUpload[FILES_TMP_NAME])) {
881
            // Import
882
            $tmpFile = Support::extendFilename($statusUpload[FILES_TMP_NAME], UPLOAD_CACHED);
883
884
            $this->doImport($formElement, $tmpFile);
        }
885

886
887
888
889
890
        // Delete existing old file.
        if (isset($statusUpload[FILES_FLAG_DELETE]) && $statusUpload[FILES_FLAG_DELETE] == '1') {
            $arr = $sip->getVarsFromSip($sipUpload);
            $oldFile = $arr[EXISTING_PATH_FILE_NAME];
            if (file_exists($oldFile)) {
891
                //TODO: it might be possible to delete a file, which is referenced by another record - a check would be nice.
892
                HelperFile::unlink($oldFile, $this->qfqLogFilename);
893
894
895
896
897
898
899
900
901
902
903
            }
            $flagDelete = ($oldFile != '');
        }

        // Set $modeUpload
        if (isset($statusUpload[FILES_TMP_NAME]) && $statusUpload[FILES_TMP_NAME] != '') {
            $modeUpload = $flagDelete ? UPLOAD_MODE_DELETEOLD_NEW : UPLOAD_MODE_NEW;
        } else {
            $modeUpload = $flagDelete ? UPLOAD_MODE_DELETEOLD : UPLOAD_MODE_UNCHANGED;
        }

904
905
        Logger::logMessageWithPrefix(UPLOAD_LOG_PREFIX . ': modeUpload= ' . $modeUpload, $this->qfqLogFilename);

906
        // skip uploading the file, if this is an import without a specified file destination
907
908
        if (!isset($formElement[FE_IMPORT_TO_TABLE]) || isset($formElement[FE_FILE_DESTINATION])) {
            $pathFileName = $this->copyUploadFile($formElement, $statusUpload);
909
910
911
912

            $msg = UPLOAD_LOG_PREFIX . ': ';
            $msg .= ($pathFileName == '') ? 'Remove old upload / no new upload' : 'File "' . $statusUpload[FILES_TMP_NAME] . '" >> "' . $pathFileName . '"';
            Logger::logMessageWithPrefix($msg, $this->qfqLogFilename);
913
914
915
916
917
918
919
920
921
        }

        // Delete current used uniq SIP
        $this->store->setVar($sipUpload, array(), STORE_EXTRA);

        return $pathFileName;
    }

    /**
922
923
     * Excel Import
     *
924
     * @param $formElement
925
     * @param $fileName
Marc Egger's avatar
Marc Egger committed
926
927
928
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
929
930
931
932
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    private function doImport($formElement, $fileName) {
933
        $importNamedSheetsOnly = array();
934

935
        Support::setIfNotSet($formElement, FE_IMPORT_TYPE, FE_IMPORT_TYPE_AUTO);
936

937
938
939
940
        if (!empty($formElement[FE_IMPORT_NAMED_SHEETS_ONLY])) {
            $importNamedSheetsOnly = explode(',', $formElement[FE_IMPORT_NAMED_SHEETS_ONLY]);
        }

Carsten  Rose's avatar
Carsten Rose committed
941
        // Check for keywords which needs an explicit given document type.
942
943
944
945
946
        if ($formElement[FE_IMPORT_TYPE] === FE_IMPORT_TYPE_AUTO) {

            $list = [FE_IMPORT_LIST_SHEET_NAMES, FE_IMPORT_READ_DATA_ONLY, FE_IMPORT_LIST_SHEET_NAMES];
            foreach ($list as $token) {
                if (isset($formElement[$token])) {
Marc Egger's avatar
Marc Egger committed
947
                    throw new \UserFormException('If ' . $token .
948
949
950
951
952
                        ' is given, an explicit document type (like ' . FE_IMPORT_TYPE . '=xlsx) should be set.', ERROR_IMPORT_MISSING_EXPLICIT_TYPE);
                }
            }
        }

953
954
955
956
957
958
959
960
961
962
963
        switch ($formElement[FE_IMPORT_TYPE]) {
            case FE_IMPORT_TYPE_AUTO:
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($fileName);
                break;

            case FE_IMPORT_TYPE_XLS:
            case FE_IMPORT_TYPE_XLSX:
            case FE_IMPORT_TYPE_CSV:
            case FE_IMPORT_TYPE_ODS:
                $inputFileType = ucfirst($formElement[FE_IMPORT_TYPE]);
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
964
965
966
967
968
969
970
971
972
973
974
975
976

                // setReadDataOnly
                if (($formElement[FE_IMPORT_READ_DATA_ONLY] ?? '0') != '0') {
                    $reader->setReadDataOnly(true);
                }

                // setLoadSheetsOnly
                if (!empty ($importNamedSheetsOnly)) {
                    $reader->setLoadSheetsOnly($importNamedSheetsOnly);
                }

                if (($formElement[FE_IMPORT_LIST_SHEET_NAMES] ?? '0') != '0') {
                    $sheetNames = $reader->listWorksheetNames($fileName);
Marc Egger's avatar
Marc Egger committed
977
                    throw new \UserFormException("Worksheets: " . implode(', ', $sheetNames),
978
979
980
                        ERROR_IMPORT_LIST_SHEET_NAMES);
                }

981
982
983
984
                $spreadsheet = $reader->load($fileName);
                break;

            default:
Marc Egger's avatar
Marc Egger committed
985
                throw new \UserFormException("Unknown Excel import type: '" . $formElement[FE_IMPORT_TYPE] . "'.",
986
987
988
989
                    ERROR_UNKNOWN_EXCEL_IMPORT_TYPE);
        }

        $tableName = $formElement[FE_IMPORT_TO_TABLE];
990
        $regions = OnArray::trimArray(explode('|', $formElement[FE_IMPORT_REGION] ?? ''));
991
        $columnNames = OnArray::trimArray(explode(',', $formElement[FE_IMPORT_TO_COLUMNS] ?? ''));
992
993
994
995
        $importMode = $formElement[FE_IMPORT_MODE] ?? FE_IMPORT_MODE_APPEND;

        foreach ($regions as $region) {
            // region: tab, startColumn, startRow, endColumn, endRow
996
            $region = OnArray::trimArray(explode(',', $region));
997
998
999
1000
            $tab = 1;
            if (!empty($region[0])) {
                $tab = $region[0];
            }
For faster browsing, not all history is shown. View entire blame