Save.php 55.3 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;
Marc Egger's avatar
Marc Egger committed
18
19
use IMATHUZH\Qfq\Core\Helper\Sanitize;
use IMATHUZH\Qfq\Core\Helper\Support;
20
use IMATHUZH\Qfq\Core\Store\FillStoreForm;
Marc Egger's avatar
Marc Egger committed
21
use IMATHUZH\Qfq\Core\Store\Sip;
22
use IMATHUZH\Qfq\Core\Store\Store;
23
use ZipArchive;
24

25
26
27
28
/**
 * Class Save
 * @package qfq
 */
29
30
31
32
33
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
34
    private $feSpecNativeRaw = array(); // copy of all formElement.class='native' of the loaded form
35
36
37
38
39
40

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

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

    /**
     * @var Database
     */
49
50
51
52
    private $db = null;

    private $evaluate = null;

53
54
    private $qfqLogFilename = '';

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

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

76
77
78
        $this->qfqLogFilename = HelperFile::joinPathFilename(
            $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM),
            $this->store->getVar(SYSTEM_QFQ_LOG, STORE_SYSTEM));
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
437
438
439
440
     */
    public function insertRecord($tableName, array $values) {

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

        $paramList = str_repeat('?, ', count($values));
        $paramList = substr($paramList, 0, strlen($paramList) - 2);
        $columnList = '`' . implode('`, `', array_keys($values)) . '`';

441
        $sql = "INSERT INTO `$tableName` ( " . $columnList . " ) VALUES ( " . $paramList . ' )';
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
442
443
444
445
446
447
448
449

        $rc = $this->db->sql($sql, ROW_REGULAR, array_values($values));

        return $rc;
    }

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

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

464
        if ($recordId === 0) {
Marc Egger's avatar
Marc Egger committed
465
            throw new \CodeException('RecordId=0 - this is not possible for update.', ERROR_RECORDID_0_FORBIDDEN);
466
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
467
468
469
470
471
472
473
474

        $sql = 'UPDATE `' . $tableName . '` SET ';

        foreach ($values as $column => $value) {

            $sql .= '`' . $column . '` = ?, ';
        }

475
        $sql = substr($sql, 0, strlen($sql) - 2) . " WHERE $primaryKey = ?";
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
476
477
478
479
480
481
482
        $values[] = $recordId;

        $rc = $this->db->sql($sql, ROW_REGULAR, array_values($values));

        return $rc;
    }

483
    /**
Carsten  Rose's avatar
Carsten Rose committed
484
485
     * Process all Upload Formelements for the given $recordId. After processing &$formValues will be updated with the
     * final filenames.
486
487
488
489
490
491
492
493
     *
     * Constellation: # FILE OLD   FILE NEW     FILESIZE
     *                1 none       none
     *                2 none       new
     *                3 exist      no change
     *                4 delete     none
     *                5 delete     new
     *
494
     * @param $recordId
Marc Egger's avatar
Marc Egger committed
495
496
497
498
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
499
500
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
501
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
502
503
504
505
    public function processAllUploads($recordId) {

        $sip = new Sip(false);
        $newValues = array();
506
507

        $flagDoUnzip = false;
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
508
509

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

512
513
514
515
516
517
518
519
520
521
        // Upload - Take care the necessary target directories exist.
        $cwd = getcwd();
        $sitePath = $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM);
        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) {
522
            // skip non upload formElements
523
            if ($formElement[FE_TYPE] != FE_TYPE_UPLOAD) {
524
525
526
                continue;
            }

527
528
529
530
            // 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);

531
            $formElement = HelperFormElement::initUploadFormElement($formElement);
532
            if (isset($formElement[FE_FILL_STORE_VAR])) {
533
                $formElement[FE_FILL_STORE_VAR] = $this->evaluate->parse($formElement[FE_FILL_STORE_VAR], ROW_EXPECT_0_1);
534
                $this->store->appendToStore($formElement[FE_FILL_STORE_VAR], STORE_VAR);
535
            }
536

537
            $column = $formElement[FE_NAME];
538
539
540
541

            $statusUpload = $this->store->getVar($formValues[$column] ?? '', STORE_EXTRA);
            // Get file stats
            $vars = array();
542
543
            $vars[VAR_FILE_SIZE] = $statusUpload[FILES_SIZE] ?? '';
            $vars[VAR_FILE_MIME_TYPE] = $statusUpload[FILES_TYPE] ?? '';
544
545

            // Check for 'unzip'.
546
547
548
            if (isset($formElement[FE_FILE_UNZIP])
                && $formElement[FE_FILE_UNZIP] != '0'
                && $vars[VAR_FILE_MIME_TYPE] == 'application/zip') {
549
550
551
552
                $flagDoUnzip = true;
            }

            // Do upload
553
            $pathFileName = $this->doUpload($formElement, ($formValues[$column] ?? ''), $sip, $modeUpload);
554
            if ($flagDoUnzip && $pathFileName != '') {
555
556
557
558
559
560
561
562
563
564
565
                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);
            }
566

567
568
            if ($modeUpload == UPLOAD_MODE_DELETEOLD && $pathFileName == '') {
                $pathFileNameTmp = '';  // see '4'
569
570
            } else {
                if (empty($pathFileName)) {
571
                    $pathFileNameTmp = $primaryRecord[$column] ?? ''; // see '3'. Attention: in case of Advanced Upload, $primaryRecord[$column] does not exist.
572
573
574
575
576
                } else {
                    $pathFileNameTmp = $pathFileName; // see '1,2,5'
                }
            }

577
            // Get latest file information
578
            if ($pathFileNameTmp == '') {
579
580
581
582
                // 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 {
583

584
585
586
                $this->store->appendToStore($vars, STORE_VAR);
            }

587
            // If given: fire a sqlBefore query
588
589
590
            if (!$flagDoUnzip) {
                $this->evaluate->parse($formElement[FE_SQL_BEFORE]);
            }
591

592
            // Upload Type: Simple or Advanced
593
594
595
            // 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.
596
597
                if ($pathFileName !== false) {
                    $newValues[$column] = $pathFileName;
598
599
600
601
602
603
604
605

                    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];
                    }
606
                }
607
608
            } elseif (isset($formElement[FE_IMPORT_TO_TABLE]) && !isset($formElement[FE_SLAVE_ID])) {
                // Excel import on nonexisting column -> no upload
609
610
            } elseif ($flagDoUnzip) {
                // If ZIP and advanced upload: process it not here but via doUnzip.
611
612
            } else {
                // 'Advanced Upload'
613
                $this->doUploadSlave($formElement, $modeUpload);
614
            }
615
616

            // If given: fire a sqlAfter query
617
618
619
            if (!$flagDoUnzip) {
                $this->evaluate->parse($formElement[FE_SQL_AFTER]);
            }
620
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
621

622
623
624
        // Clean up
        HelperFile::chdir($cwd);

625
        // Only used in 'Simple Upload'
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
626
        if (count($newValues) > 0) {
627
            $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
628
        }
629
630
    }

631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
    /**
     * 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);
        }

660
661
662
663
664
665
        // 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.
666
667
668
669
670
671
672
673
674
675
676
677
678
        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
679
680
681
682
        if (!isset($formElement[FE_SLAVE_ID])) {
            $formElement[FE_SLAVE_ID] = '';
        }

683
684
685
686
687
688
689
690
691
692
693
694
695
696
        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]);
            }
        }
697
698
699
700
701

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

704
    /**
705
706
     * Process all Upload FormElements for the given $recordId.
     * After processing, &$formValues will be updated with the final filename.
707
     *
Marc Egger's avatar
Marc Egger committed
708
709
     * @throws \CodeException
     * @throws \UserFormException
710
711
712
     */
    public function processAllImageCutFE() {

713
        foreach ($this->feSpecNative as $formElement) {
714
715
716
717
718
719
720
721
722
            // skip non upload formElements
            if ($formElement[FE_TYPE] != FE_TYPE_IMAGE_CUT) {
                continue;
            }

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

723
724
725
726
727
728
729
730

    /**
     * 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
731
732
733
734
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
735
736
737
     */
    public function checkRequiredHidden() {

738
        $formModeGlobal = Support::getFormModeGlobal($this->formSpec[F_MODE_GLOBAL] ?? '');
739
        $reportRequiredFailed = true;
740

741
742
743
744
745
746
        switch ($formModeGlobal) {
            case F_MODE_REQUIRED_OFF:
            case F_MODE_REQUIRED_OFF_BUT_MARK:
                $reportRequiredFailed = false;
                break;
        }
747
748
749

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

750
751
        $flagAllRequiredGiven = 1;

752
        foreach ($this->feSpecNative as $key => $formElement) {
753

754
755
756
757
758
            // Do not check retype slave FE.
            if (isset($formElement[FE_RETYPE_SOURCE_NAME])) {
                continue;
            }

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

761
762
763
764
765
            // 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] = '';
766

767
768
769
            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.
770
771
            }

772
773
774
775
776
            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);
                }
777
778
779
780
781
782
783
            }

            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);
            }
        }
784
785
786

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

789
790
791
    /**
     *
     * @param array $formElement
Marc Egger's avatar
Marc Egger committed
792
793
     * @throws \CodeException
     * @throws \UserFormException
794
795
796
797
798
799
     */
    private function extractImageDataReplaceFile(array $formElement) {

        // Take care the necessary target directories exist.
        $cwd = getcwd();
        $sitePath = $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM);
800
        if ($cwd === false || $sitePath === false || !HelperFile::chdir($sitePath)) {
Marc Egger's avatar
Marc Egger committed
801
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
802
                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."]),
803
                ERROR_IO_CHDIR);
804
805
        }

806
        // Get original pathFileName
807
808
809
        $field = HelperFormElement::AppendFormElementNameImageCut($formElement);
        $pathFileName = $this->store->getVar($field, STORE_SIP);
        if ($pathFileName == '' || !file_exists($pathFileName)) {
Marc Egger's avatar
Marc Egger committed
810
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
811
                json_encode([ERROR_MESSAGE_TO_USER => 'Empty file or file not found', ERROR_MESSAGE_TO_DEVELOPER => 'Empty file or file not found: ' . $pathFileName]),
812
                ERROR_IO_FILE_NOT_FOUND);
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
        }

        // '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)
            ) {
848
                HelperFile::rename($pathFileName, $pathFileName . $extSave);
849
850
851
852
853
854
855
856
            }
        }

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

        if (false === file_put_contents($pathFileName, base64_decode($imageData))) {
Marc Egger's avatar
Marc Egger committed
857
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
858
                json_encode([ERROR_MESSAGE_TO_USER => 'Write new image failed', ERROR_MESSAGE_TO_DEVELOPER => "Write new image failed: $pathFileName"]),
859
                ERROR_IO_WRITE);
860
861
862
863
864
        }

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

865
    /**
866
867
868
     * 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.
     *
869
     * Check also: Documentation-develop/CODING.md
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
870
     *
Carsten  Rose's avatar
Carsten Rose committed
871
872
873
874
     * @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
875
     *                            UPLOAD_MODE_DELETEOLD_NEW
876
     * @return false|string New pathFilename or false on error
Marc Egger's avatar
Marc Egger committed
877
878
     * @throws \CodeException
     * @throws \DbException
879
880
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
881
882
     * @throws \UserFormException
     * @throws \UserReportException
883
884
     * @internal param $recordId
     */
885
886
887
    private function doUpload($formElement, $sipUpload, Sip $sip, &$modeUpload) {
        $flagDelete = false;
        $modeUpload = UPLOAD_MODE_UNCHANGED;
888
        $pathFileName = '';
889

890
        // Status information about upload file
891
892
893
894
895
        $statusUpload = $this->store->getVar($sipUpload, STORE_EXTRA);
        if ($statusUpload === false) {
            return false;
        }

896
        if (isset($formElement[FE_IMPORT_TO_TABLE]) && isset($statusUpload[FILES_TMP_NAME])) {
897
            // Import
898
            $tmpFile = Support::extendFilename($statusUpload[FILES_TMP_NAME], UPLOAD_CACHED);
899
900
            $this->doImport($formElement, $tmpFile);
        }
901

902
903
904
905
906
        // 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)) {
907
                //TODO: it might be possible to delete a file, which is referenced by another record - a check would be nice.
908
                HelperFile::unlink($oldFile, $this->qfqLogFilename);
909
910
911
912
913
914
915
916
917
918
919
            }
            $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;
        }

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

922
        // skip uploading the file, if this is an import without a specified file destination
923
924
        if (!isset($formElement[FE_IMPORT_TO_TABLE]) || isset($formElement[FE_FILE_DESTINATION])) {
            $pathFileName = $this->copyUploadFile($formElement, $statusUpload);
925
926
927
928

            $msg = UPLOAD_LOG_PREFIX . ': ';
            $msg .= ($pathFileName == '') ? 'Remove old upload / no new upload' : 'File "' . $statusUpload[FILES_TMP_NAME] . '" >> "' . $pathFileName . '"';
            Logger::logMessageWithPrefix($msg, $this->qfqLogFilename);
929
930
931
932
933
934
935
936
937
        }

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

        return $pathFileName;
    }

    /**
938
939
     * Excel Import
     *
940
     * @param $formElement
941
     * @param $fileName
Marc Egger's avatar
Marc Egger committed
942
943
944
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
945
946
947
948
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    private function doImport($formElement, $fileName) {
949
        $importNamedSheetsOnly = array();
950

951
        Support::setIfNotSet($formElement, FE_IMPORT_TYPE, FE_IMPORT_TYPE_AUTO);
952

953
954
955
956
        if (!empty($formElement[FE_IMPORT_NAMED_SHEETS_ONLY])) {
            $importNamedSheetsOnly = explode(',', $formElement[FE_IMPORT_NAMED_SHEETS_ONLY]);
        }

Carsten  Rose's avatar
Carsten Rose committed
957
        // Check for keywords which needs an explicit given document type.
958
959
960
961
962
        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
963
                    throw new \UserFormException('If ' . $token .
964
965
966
967
968
                        ' is given, an explicit document type (like ' . FE_IMPORT_TYPE . '=xlsx) should be set.', ERROR_IMPORT_MISSING_EXPLICIT_TYPE);
                }
            }
        }

969
970
971
972
973
974
975
976
977
978
979
        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);
980
981
982
983
984
985
986
987
988
989
990
991
992

                // 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
993
                    throw new \UserFormException("Worksheets: " . implode(', ', $sheetNames),
994
995
996
                        ERROR_IMPORT_LIST_SHEET_NAMES);
                }

997
998
999
1000
                $spreadsheet = $reader->load($fileName);
                break;

            default: