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

namespace qfq;

11
12
13
14
15
require_once(__DIR__ . '/store/Store.php');
require_once(__DIR__ . '/store/Sip.php');
require_once(__DIR__ . '/Constants.php');
require_once(__DIR__ . '/Evaluate.php');
require_once(__DIR__ . '/helper/HelperFile.php');
16
require_once(__DIR__ . '/helper/OnArray.php');
17
18
19
20
21
22
//require_once(__DIR__ . '/../qfq/exceptions/UserException.php');
//require_once(__DIR__ . '/../qfq/exceptions/CodeException.php');
//require_once(__DIR__ . '/../qfq/exceptions/DbException.php');
//require_once(__DIR__ . '/../qfq/Evaluate.php');


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

    private $evaluate = null;

    /**
     * @param array $formSpec
     * @param array $feSpecAction
     * @param array $feSpecNative
45
     * @param array $feSpecNativeRaw
46
     * @throws CodeException
47
     * @throws DbException
48
     * @throws UserFormException
49
     * @throws UserReportException
50
     */
51
    public function __construct(array $formSpec, array $feSpecAction, array $feSpecNative, array $feSpecNativeRaw) {
52
53
54
        $this->formSpec = $formSpec;
        $this->feSpecAction = $feSpecAction;
        $this->feSpecNative = $feSpecNative;
55
        $this->feSpecNativeRaw = $feSpecNativeRaw;
56
        $this->store = Store::getInstance();
57
        $this->db = new Database($formSpec[F_DB_INDEX]);
58
59
60
61
        $this->evaluate = new Evaluate($this->store, $this->db);
    }

    /**
62
63
     * Starts save process. On succcess, returns forwardmode/page.
     *
64
     * @return int
65
66
     * @throws CodeException
     * @throws DbException
67
     * @throws UserFormException
68
69
     */
    public function process() {
70
        $rc = 0;
71
72
73
74
75

        if ($this->formSpec['multiMode'] !== 'none') {

            $parentRecords = $this->db->sql($this->formSpec['multiSql']);
            foreach ($parentRecords as $row) {
76
                $this->store->setStore($row, STORE_PARENT_RECORD, true);
77
                $rc = $this->elements($row['_id']);
78
79
            }
        } else {
80
81
            $recordId = $this->store->getVar(SIP_RECORD_ID, STORE_SIP . STORE_ZERO);
            $rc = $this->elements($recordId);
82
        }
83
84

        return $rc;
85
86
    }

87
    /**
Carsten  Rose's avatar
Carsten Rose committed
88
89
     * Create empty FormElements based on templateGroups, for those who not already exist.
     *
90
     * @param array $formValues
Carsten  Rose's avatar
Carsten Rose committed
91
     *
92
     * @return array
93
     * @throws UserFormException
94
95
96
97
98
     */
    private function createEmptyTemplateGroupElements(array $formValues) {

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

99
100
101
102
103
104
105
106
            switch ($formElement[FE_TYPE]) {
//                case FE_TYPE_EXTRA:
                case FE_TYPE_NOTE:
                case FE_TYPE_SUBRECORD:
                    continue 2;
                default:
                    break;
            }
107
            $feName = $formElement[FE_NAME];
108
            if (!isset($formValues[$feName]) && $this->isMemberOfTemplateGroup($formElement)) {
109
110
111
                $formValues[$feName] = $formElement[FE_VALUE];
            }
        }
Carsten  Rose's avatar
Carsten Rose committed
112

113
114
115
        return $formValues;
    }

116
    /**
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
     * Check if the current $formElement is member of a templateGroup.
     *
     * @param array $formElement
     * @param int $depth
     * @return bool
     * @throws UserFormException
     */
    private function isMemberOfTemplateGroup(array $formElement, $depth = 0) {
        $depth++;

        if ($depth > 15) {
            throw new UserFormException('FormElement nested too much (in each other - endless?): stop recursion', ERROR_FE_NESTED_TOO_MUCH);
        }

        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,
    }

    /**
     *
150
     * @param $feName
Carsten  Rose's avatar
Carsten Rose committed
151
     *
152
153
154
155
156
157
158
159
160
161
162
     * @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;
    }

163
    /**
Carsten  Rose's avatar
Carsten Rose committed
164
165
     * 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
166
     *
167
     * @param $recordId
Carsten  Rose's avatar
Carsten Rose committed
168
     *
169
     * @return int   record id (in case of insert, it's different from $recordId)
170
171
     * @throws CodeException
     * @throws DbException
172
     * @throws UserFormException
173
174
     */
    public function elements($recordId) {
175
176
        $columnCreated = false;
        $columnModified = false;
Carsten  Rose's avatar
Carsten Rose committed
177

178
179
180
        $newValues = array();

        $tableColumns = array_keys($this->store->getStore(STORE_TABLE_COLUMN_TYPES));
181
        $formValues = $this->store->getStore(STORE_FORM);
182
        $formValues = $this->createEmptyTemplateGroupElements($formValues);
183
184
185

        // Iterate over all table.columns. Built an assoc array $newValues.
        foreach ($tableColumns AS $column) {
186

187
            // Never save a predefined 'id': autoincrement values will be given by database..
188
            if ($column === COLUMN_ID) {
189
                continue;
190
            }
191

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
192
193
194
195
196
            // Skip Upload Elements: those will be processed later.
            if ($this->isColumnUploadField($column)) {
                continue;
            }

197
198
199
200
201
202
203
204
            if ($column === COLUMN_CREATED) {
                $columnCreated = true;
            }

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

205
206
            // Is there a value? Do not forget SIP values. Those do not have necessarily a FormElement.
            if (!isset($formValues[$column])) {
207
                continue;
208
209
            }

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

212
213
214
215
216
217
            // 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);
            }
218
            $newValues[$column] = $formValues[$column];
219

220
221
        }

222
223
224
225
        if ($columnModified && !isset($newValues[COLUMN_MODIFIED])) {
            $newValues[COLUMN_MODIFIED] = date('YmdHis');
        }

226
        if ($recordId == 0) {
227
228
229
            if ($columnCreated && !isset($newValues[COLUMN_CREATED])) {
                $newValues[COLUMN_CREATED] = date('YmdHis');
            }
230
            $rc = $this->insertRecord($this->formSpec[F_TABLE_NAME], $newValues);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
231

232
        } else {
233
            $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
234
235
236
237
            $rc = $recordId;
        }

        return $rc;
238
239
    }

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
240
241
242
243
244
245
    /*
     * Checks if there is a formElement with name '$feName' of type 'upload'
     *
     * @param $feName
     * @return bool
     */
246
247
248
249
    /**
     * @param $feName
     * @return bool
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
250
251
252
253
254
255
    private function isColumnUploadField($feName) {

        foreach ($this->feSpecNative AS $formElement) {
            if ($formElement[FE_NAME] === $feName && $formElement[FE_TYPE] == 'upload')
                return true;
        }
Carsten  Rose's avatar
Carsten Rose committed
256

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
257
258
259
260
261
262
        return false;
    }

    /**
     * Insert new record in table $this->formSpec['tableName'].
     *
263
     * @param $tableName
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
264
     * @param array $values
Carsten  Rose's avatar
Carsten Rose committed
265
     *
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
266
     * @return int  last insert id
267
     * @throws CodeException
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
268
     * @throws DbException
269
     * @throws UserFormException
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
270
271
272
273
274
275
276
277
278
279
     */
    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)) . '`';

280
        $sql = "INSERT INTO $tableName ( " . $columnList . " ) VALUES ( " . $paramList . ' )';
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
281
282
283
284
285
286
287
288

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

        return $rc;
    }

    /**
     * @param string $tableName
Carsten  Rose's avatar
Carsten Rose committed
289
290
     * @param array $values
     * @param int $recordId
291
     * @param string $primaryKey
Carsten  Rose's avatar
Carsten Rose committed
292
     *
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
293
294
295
     * @return bool|int     false if $values is empty, else affectedrows
     * @throws CodeException
     * @throws DbException
Carsten  Rose's avatar
Carsten Rose committed
296
     * @throws UserFormException
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
297
     */
298
    public function updateRecord($tableName, array $values, $recordId, $primaryKey = F_PRIMARY_KEY_DEFAULT) {
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
299
300
301
302

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

303
        if ($recordId === 0) {
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
304
            throw new CodeException('RecordId=0 - this is not possible for update.', ERROR_RECORDID_0_FORBIDDEN);
305
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
306
307
308
309
310
311
312
313

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

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

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

314
        $sql = substr($sql, 0, strlen($sql) - 2) . " WHERE $primaryKey = ?";
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
315
316
317
318
319
320
321
        $values[] = $recordId;

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

        return $rc;
    }

322
    /**
Carsten  Rose's avatar
Carsten Rose committed
323
324
     * Process all Upload Formelements for the given $recordId. After processing &$formValues will be updated with the
     * final filenames.
325
326
327
328
329
     * @param $recordId
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     * @throws UserReportException
330
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
331
332
333
334
335
336
    public function processAllUploads($recordId) {

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

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

        foreach ($this->feSpecNative AS $formElement) {
            // skip non upload formElements
341
            if ($formElement[FE_TYPE] != FE_TYPE_UPLOAD) {
342
343
344
                continue;
            }

345
            $formElement = HelperFormElement::initUploadFormElement($formElement);
346
            if (isset($formElement[FE_FILL_STORE_VAR])) {
347
                $this->store->appendToStore($formElement[FE_FILL_STORE_VAR], STORE_VAR);
348
            }
349

350
351
352
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($formElement), STORE_SYSTEM);

353
            $column = $formElement[FE_NAME];
354
            $pathFileName = $this->doUpload($formElement, $formValues[$column], $sip, $modeUpload);
355

356
357
358
359
360
361
362
363
            $pathFileNameTmp = empty($pathFileName) ? $primaryRecord[$column] : $pathFileName;
            // Get latest file information
            $vars = HelperFile::getFileStat($pathFileNameTmp);
            $this->store->appendToStore($vars, STORE_VAR);

            // If given: fire a sqlBefore query
            $this->evaluate->parse($formElement[FE_SQL_BEFORE]);

364
            // Upload Type: Simple or Advanced
365
366
367
            // 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.
368
369
                if ($pathFileName !== false) {
                    $newValues[$column] = $pathFileName;
370
371
372
373
374
375
376
377

                    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];
                    }
378
379
380
                }
            } else {
                // 'Advanced Upload'
381
                $this->doUploadSlave($formElement, $modeUpload);
382
            }
383
384
385
386

            // If given: fire a sqlAfter query
            $this->evaluate->parse($formElement[FE_SQL_AFTER]);

387
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
388

389
        // Only used in 'Simple Upload'
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
390
        if (count($newValues) > 0) {
391
            $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
392
        }
393
394
    }

395
    /**
396
397
     * Process all Upload FormElements for the given $recordId.
     * After processing, &$formValues will be updated with the final filename.
398
     *
399
400
     * @throws CodeException
     * @throws UserFormException
401
402
403
404
405
406
407
408
409
410
411
412
413
     */
    public function processAllImageCutFE() {

        foreach ($this->feSpecNative AS $formElement) {
            // skip non upload formElements
            if ($formElement[FE_TYPE] != FE_TYPE_IMAGE_CUT) {
                continue;
            }

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

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434

    /**
     * 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.
     *
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     * @throws UserReportException
     */
    public function checkRequiredHidden() {

        $requiredOff = ($this->store->getVar(F_MODE_GLOBAL, STORE_SIP) == F_MODE_REQUIRED_OFF);

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

        foreach ($this->feSpecNative AS $key => $formElement) {

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

437
438
439
440
441
442
443
            if (empty($formElement[FE_MODE_SQL])) {
                $mode = $formElement[FE_MODE];
            } else {
                $mode = $this->evaluate->parse($formElement[FE_MODE_SQL]);
                $this->feSpecNative[$key][FE_MODE_SQL] = $mode;
            }

444
445
446
447
448
            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.
            }

449
            if (!$requiredOff && $mode == FE_MODE_REQUIRED && empty($clientValues[$formElement[FE_NAME]])) {
450
                throw new UserFormException("Missing required value: " . $formElement[FE_LABEL], ERROR_REQUIRED_VALUE_EMPTY);
451
452
453
454
455
456
457
458
459
            }

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

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
    /**
     *
     * @param array $formElement
     * @throws CodeException
     * @throws UserFormException
     */
    private function extractImageDataReplaceFile(array $formElement) {

        // Take care the necessary target directories exist.
        $cwd = getcwd();
        $sitePath = $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM);
        if ($cwd === false || $sitePath === false || !chdir($sitePath)) {
            throw new UserFormException("getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed.", ERROR_IO_CHDIR);
        }

475
        // Get original pathFileName
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
        $field = HelperFormElement::AppendFormElementNameImageCut($formElement);
        $pathFileName = $this->store->getVar($field, STORE_SIP);
        if ($pathFileName == '' || !file_exists($pathFileName)) {
            throw new UserFormException('Empty file or file not found: ' . $pathFileName, ERROR_IO_FILE_NOT_FOUND);
        }

        // '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)
            ) {
                if (!rename($pathFileName, $pathFileName . $extSave)) {
                    throw new UserFormException("Rename file: '$pathFileName' > '$pathFileName$extSave'", ERROR_IO_RENAME);
                }
            }
        }

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

        if (false === file_put_contents($pathFileName, base64_decode($imageData))) {
            throw new UserFormException("Write new image failed: $pathFileName", ERROR_IO_WRITE);
        }

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

532
    /**
533
534
535
     * 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.
     *
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
536
537
     * Check also: doc/CODING.md
     *
Carsten  Rose's avatar
Carsten Rose committed
538
539
540
541
     * @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
542
543
     *                            UPLOAD_MODE_DELETEOLD_NEW
     *
544
     * @return false|string New pathFilename or false on error
545
     * @throws CodeException
546
     * @throws DbException
547
     * @throws UserFormException
548
549
550
     * @throws UserReportException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
551
552
     * @internal param $recordId
     */
553
554
555
    private function doUpload($formElement, $sipUpload, Sip $sip, &$modeUpload) {
        $flagDelete = false;
        $modeUpload = UPLOAD_MODE_UNCHANGED;
556

557
        // Status information about upload file
558
559
560
561
562
        $statusUpload = $this->store->getVar($sipUpload, STORE_EXTRA);
        if ($statusUpload === false) {
            return false;
        }

563
        if (isset($formElement[FE_IMPORT_TO_TABLE]) && isset($statusUpload[FILES_TMP_NAME])) {
564
            // Import
565
            $tmpFile = Support::extendFilename($statusUpload[FILES_TMP_NAME], UPLOAD_CACHED);
566
567
            $this->doImport($formElement, $tmpFile);
        }
568

569
570
571
572
573
574
575
        // Upload
        // Take care the necessary target directories exist.
        $cwd = getcwd();
        $sitePath = $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM);
        if ($cwd === false || $sitePath === false || !chdir($sitePath)) {
            throw new UserFormException("getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed.", ERROR_IO_CHDIR);
        }
576

577
578
579
580
581
582
583
        // 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)) {
                if (!unlink($oldFile)) {
                    throw new UserFormException('Unlink file failed: ' . $oldFile, ERROR_IO_UNLINK);
584
                }
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
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
            }
            $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;
        }

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

        chdir($cwd);

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

        return $pathFileName;
    }

    /**
     * @param $formElement
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    private function doImport($formElement, $fileName) {
        Support::setIfNotSet($formElement, FE_IMPORT_TYPE, FE_IMPORT_TYPE_AUTO);
        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);
                $spreadsheet = $reader->load($fileName);
                break;

            default:
                throw new UserFormException("Unknown Excel import type: '" . $formElement[FE_IMPORT_TYPE] . "'.",
                    ERROR_UNKNOWN_EXCEL_IMPORT_TYPE);
        }

        $tableName = $formElement[FE_IMPORT_TO_TABLE];
639
640
        $regions = OnArray::trimArray(explode('|', $formElement[FE_IMPORT_REGION] ?? ''));
        $columnNames = OnArray::trimArray(explode(',', $formElement[FE_IMPORT_TO_COLUMNS]));
641
642
643
644
        $importMode = $formElement[FE_IMPORT_MODE] ?? FE_IMPORT_MODE_APPEND;

        foreach ($regions as $region) {
            // region: tab, startColumn, startRow, endColumn, endRow
645
            $region = OnArray::trimArray(explode(',', $region));
646
647
648
649
650
651
652
653
654
655
656
657
658
659
            $tab = 1;
            if (!empty($region[0])) {
                $tab = $region[0];
            }

            try {
                if (is_numeric($tab)) {
                    $worksheet = $spreadsheet->getSheet($tab - 1); // 0-based
                } else {
                    $worksheet = $spreadsheet->getSheetByName($tab);
                    if ($worksheet === null) {
                        throw new \PhpOffice\PhpSpreadsheet\Exception(
                            "No sheet with the name '$tab' could be found."
                        );
660
661
                    }
                }
662
663
664
            } catch (\PhpOffice\PhpSpreadsheet\Exception $e) {
                throw new UserFormException($e->getMessage());
            }
665

666
667
668
669
670
671
672
673
674
            // Set up requested region
            $columnStart = '1';
            $columnEnd = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($worksheet->getHighestColumn());
            $rowStart = 1;
            $rowEnd = $worksheet->getHighestRow();
            if (!empty($region[1])) { // startColumn
                if (!is_numeric($region[1])) $region[1] = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($region[1]);
                if ($region[1] >= $columnStart && $region[1] <= $columnEnd) {
                    $columnStart = $region[1];
675
676
                }
            }
677
678
679
680
681
            if (!empty($region[3])) { // endColumn
                if (!is_numeric($region[3])) $region[3] = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($region[3]);
                if ($region[3] >= $columnStart && $region[3] <= $columnEnd) {
                    $columnEnd = $region[3];
                }
682
            }
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
            if (!empty($region[2]) && $region[2] >= $rowStart && $region[2] <= $rowEnd) {
                $rowStart = $region[2];
            }
            if (!empty($region[4]) && $region[4] >= $rowStart && $region[4] <= $rowEnd) {
                $rowEnd = $region[4];
            }
            // Read the specified region
            $rangeStr = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnStart) . $rowStart . ':' .
                \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnEnd) . $rowEnd;
            $worksheetData = $worksheet->rangeToArray($rangeStr, '', true, false);

            $columnDefinitionArr = [];
            $columnListArr = [];
            for ($column = $columnStart; $column <= $columnEnd; ++$column) {
                if (!empty($columnNames[$column - $columnStart])) {
                    $columnName = $columnNames[$column - $columnStart];
                } else {
                    $columnName = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($column);
701
                }
702
703
                $columnDefinitionArr[] = "`$columnName`   TEXT       NOT NULL  DEFAULT ''";
                $columnListArr[] = "$columnName";
704
705
            }

706
707
708
709
710
711
712
713
714
715
716
717
718
            // SQL time!
            $createTableSql = "CREATE TABLE IF NOT EXISTS `$tableName` (" .
                "`id`        INT(11)    NOT NULL  AUTO_INCREMENT," .
                implode(', ', $columnDefinitionArr) . ',' .
                "`modified`  TIMESTAMP  NOT NULL  DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," .
                "`created`   DATETIME   NOT NULL  DEFAULT CURRENT_TIMESTAMP," .
                "PRIMARY KEY (`id`) )" .
                "ENGINE = InnoDB  DEFAULT CHARSET = utf8 AUTO_INCREMENT = 0;";
            $this->db->sql($createTableSql);

            if ($importMode === FE_IMPORT_MODE_REPLACE) {
                $this->db->sql("TRUNCATE $tableName");
                $importMode = FE_IMPORT_MODE_APPEND;
719
            }
720

721
722
723
724
725
726
727
            // Import the data
            foreach ($worksheetData AS $rowIndex => $row) {
                $columnList = implode(',', $columnListArr);
                $paramPlaceholders = str_repeat('?,', count($worksheetData[0]) - 1) . '?';
                $insertSql = "INSERT INTO `$tableName` ($columnList) VALUES ($paramPlaceholders)";
                $this->db->sql($insertSql, ROW_REGULAR, $row);
            }
728
        }
729
730
731
    }

    /**
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
732
733
734
735
     * Copy uploaded file from temporary location to final location.
     *
     * Check also: doc/CODING.md
     *
736
737
     * @param array $formElement
     * @param array $statusUpload
Carsten  Rose's avatar
Carsten Rose committed
738
     *
739
740
     * @return array|mixed|null|string
     * @throws CodeException
Carsten  Rose's avatar
Carsten Rose committed
741
     * @throws DbException
742
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
743
     * @throws UserReportException
744
745
746
     */
    private function copyUploadFile(array $formElement, array $statusUpload) {
        $pathFileName = '';
747
        $vars = array();
748

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
749
        if (!isset($statusUpload[FILES_TMP_NAME]) || $statusUpload[FILES_TMP_NAME] === '') {
750
751
752
753
            // nothing to upload: e.g. user has deleted a previous uploaded file.
            return '';
        }

754
755
        $srcFile = Support::extendFilename($statusUpload[FILES_TMP_NAME], UPLOAD_CACHED);

756
        if (isset($formElement[FE_FILE_DESTINATION])) {
757

758
            // Provide variable 'filename'. Might be substituted in $formElement[FE_PATH_FILE_NAME].
759
            $origFilename = Sanitize::safeFilename($statusUpload[FILES_NAME]);
760
            $this->store->appendToStore(HelperFile::pathinfo($origFilename), STORE_VAR);
761

762
            $pathFileName = $this->evaluate->parse($formElement[FE_FILE_DESTINATION]);
763
            $pathFileName = Sanitize::safeFilename($pathFileName, false, true); // Dynamically calculated pathFileName might contain invalid characters.
764
765
766

            // Saved in store for later use during 'Advanced Upload'-post processing
            $this->store->setVar(VAR_FILE_DESTINATION, $pathFileName, STORE_VAR);
767
768
        }

769
        if ($pathFileName === '') {
770
            throw new UserFormException("Upload failed, no target '" . FE_FILE_DESTINATION . "' specified.", ERROR_NO_TARGET_PATH_FILE_NAME);
771
772
        }

773
774
        $overwrite = isset($formElement[FE_FILE_REPLACE_MODE]) && $formElement[FE_FILE_REPLACE_MODE] == FE_FILE_REPLACE_MODE_ALWAYS;
        Support::copyFile($srcFile, $pathFileName, $overwrite);
775

776
777
        $this->splitUpload($formElement, $pathFileName);

778
779
        return $pathFileName;
    }
780

781
    /**
Carsten  Rose's avatar
Carsten Rose committed
782
783
784
785
786
787
788
     * Check's if the file $pathFileName should be splitted in one file per page. If no: do nothing and return.
     * The only possible split target file format is 'svg': fileSplit=svg.
     * The splitted files will be saved under fileDestinationSplit=some/path/to/file.%02d.svg. A printf style token,
     * like '%02d', is needed to create distinguished filename's. See 'man pdf2svg' for further details.
     * For every created file, a record in table 'Split' is created (see splitSvg() ), storing the pathFileName of the
     * current page/file.
     *
789
790
     * @param array $formElement
     * @param $pathFileName
791
792
     * @throws CodeException
     * @throws DbException
793
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
794
     * @throws UserReportException
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
     */
    private function splitUpload(array $formElement, $pathFileName) {

        if (empty($formElement[FE_FILE_SPLIT]) || empty($formElement[FE_FILE_DESTINATION_SPLIT])) {
            return;
        }

        $fileDestinationSplit = $this->evaluate->parse($formElement[FE_FILE_DESTINATION_SPLIT]);
        $fileSplit = $this->evaluate->parse($formElement[FE_FILE_SPLIT]);
        $fileSplitTableName = $this->evaluate->parse($formElement[FE_FILE_SPLIT_TABLE_NAME]);

        if (empty($fileSplitTableName)) {
            $fileSplitTableName = $this->formSpec[F_TABLE_NAME];
        }

        // Filetype testen: nur Dateien splitten die man auch wirklich entpacken kann
        switch ($fileSplit) {
            case FE_FILE_SPLIT_SVG:
                $this->splitSvg($pathFileName, $fileDestinationSplit, $fileSplitTableName);
                break;
            default:
                throw new UserFormException("Unknown 'fileSplit' type: " . $formElement[FE_FILE_SPLIT], ERROR_UNKNOWN_TOKEN);
        }
    }

    /**
Carsten  Rose's avatar
Carsten Rose committed
821
822
823
     * Split's the PDF file $pathFileNameSrc in several SVG-file, one per page.
     * For every created file, a record in table 'Split' is created, storing the pathFileName to the individual file.
     *
824
825
     * @param $pathFileNameSrc
     * @param $fileDestinationSplit
826
     * @param $fileSplitTableName
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     */
    private function splitSvg($pathFileNameSrc, $fileDestinationSplit, $fileSplitTableName) {

        Support::mkDirParent($fileDestinationSplit);

        // Save CWD
        $cwd = getcwd();

        // Create temporary directory
        $tempDir = Support::createTempDir();
        $newSrc = $tempDir . DIRECTORY_SEPARATOR . QFQ_TEMP_SOURCE;
        $rc = copy($pathFileNameSrc, $newSrc);

        $rc = chdir($tempDir);

        // Split destination.
        $pathParts = pathinfo($fileDestinationSplit);
        if (empty($pathParts['filename']) || empty($pathParts['basename'])) {
            throw new UserFormException('Missing filename in ' . FE_FILE_DESTINATION_SPLIT, ERROR_MISSING_FILE_NAME);
        }

        // Extract filename from destination directory.
        $fileNameDest = $pathParts['basename'];

        // Split PDF
        $rc = exec('pdf2svg "' . $newSrc . '" "' . $fileNameDest . '" all');

        // Array of created filenames.
        $files = scandir('.');

        // Create DB records according to the extracted filenames.
        $tableName = TABLE_NAME_SPLIT;
        $sql = "INSERT INTO $tableName (`tableName`, `xId`, `pathFilename`, `created`) VALUES (?,?,?, NOW())";

        foreach ($files as $file) {

            if ($file == '.' || $file == '..' || $file == QFQ_TEMP_SOURCE) {
                continue;
            }

            if (!empty($pathParts['dirname'])) {
                $fileDestination = $pathParts['dirname'] . '/' . $file;
            } else {
                $fileDestination = $file;
            }

            $rc = rename($file, Support::joinPath($cwd, $fileDestination));

            // Insert records.
            $this->db->sql($sql, ROW_REGULAR, [$fileSplitTableName, $this->store->getVar(COLUMN_ID, STORE_RECORD), $fileDestination]);
        }

        // Pop directory
        $rc = chdir($cwd);

        // Remove duplicated source
        $rc = unlink($newSrc);
        // Remove empty directory
        $rc = rmdir($tempDir);
    }

891
    /**
892
     * Create/update or delete the slave record.
893
894
     *
     * @param array $fe
895
     * @param $modeUpload
896
897
     * @return int
     * @throws CodeException
Carsten  Rose's avatar
Carsten Rose committed
898
     * @throws DbException
899
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
900
     * @throws UserReportException
901
     */
902
    private function doUploadSlave(array $fe, $modeUpload) {
903
904
        $sql = '';
        $flagUpdateSlaveId = false;
905
        $flagSlaveDeleted = false;
906

907
        if (!isset($fe[FE_SLAVE_ID])) {
908
909
910
            throw new UserFormException("Missing 'slaveId'-definition", ERROR_MISSING_SLAVE_ID_DEFINITION);
        }

911
        // Get the slaveId
912
        $slaveId = Support::falseEmptyToZero($this->evaluate->parse($fe[FE_SLAVE_ID]));
913
914
915
        // Store the slaveId: it's used and replaced in the update statement.
        $this->store->setVar(VAR_SLAVE_ID, $slaveId, STORE_VAR, true);

916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
        $mode = ($slaveId == '0') ? 'I' : 'U'; // I=Insert, U=Update
        $mode .= ($modeUpload == UPLOAD_MODE_NEW || $modeUpload == UPLOAD_MODE_DELETEOLD_NEW) ? 'N' : ''; // N=New File, '' if no new file.
        $mode .= ($modeUpload == UPLOAD_MODE_DELETEOLD) ? 'D' : ''; // Delete slave record only if there is no new and not 'unchanged'.
        switch ($mode) {
            case 'IN':
                $sql = $fe[FE_SQL_INSERT];
                $flagUpdateSlaveId = true;
                break;
            case 'UN':
                $sql = $fe[FE_SQL_UPDATE];
                break;
            case 'I':
            case 'U':
                $sql = ''; // no old file and no new file.
                break;
            case 'UD':
                $sql = $fe[FE_SQL_DELETE];
                $flagSlaveDeleted = true;
                break;
            default:
                throw new CodeException('Unknown mode: ' . $mode, ERROR_UNKNOWN_MODE);
937
938
939
        }

        $rc = $this->evaluate->parse($sql);
940
941
942
943
944
        // Check if the slave record has been deleted: if yes, set slaveId=0
        if ($flagSlaveDeleted && $rc > 0) {
            $rc = 0;
            $flagUpdateSlaveId = true;
        }
945
946
947
948
949
950
951
952
953

        if ($flagUpdateSlaveId) {
            // Store the slaveId: it's used and replaced in the update statement.
            $this->store->setVar(VAR_SLAVE_ID, $rc, STORE_VAR, true);
            $slaveId = $rc;
        }

        return $slaveId;
    }
954
}