Save.php 39.5 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
    /**
     * @var null|Store
     */
    private $store = null;
    private $db = null;

    private $evaluate = null;

41
42
    private $qfqLogFilename = '';

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

        $this->qfqLogFilename = $this->store->getVar(SYSTEM_QFQ_LOG, STORE_SYSTEM);

64
65
66
    }

    /**
67
68
     * Starts save process. On succcess, returns forwardmode/page.
     *
69
     * @return int
70
71
     * @throws CodeException
     * @throws DbException
72
     * @throws UserFormException
73
74
     */
    public function process() {
75
        $rc = 0;
76
77
78
79
80

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

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

        return $rc;
90
91
    }

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

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

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

118
119
120
        return $formValues;
    }

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
150
151
152
153
154
     * 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,
    }

    /**
     *
155
     * @param $feName
Carsten  Rose's avatar
Carsten Rose committed
156
     *
157
158
159
160
161
162
163
164
165
166
167
     * @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;
    }

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

183
184
185
        $newValues = array();

        $tableColumns = array_keys($this->store->getStore(STORE_TABLE_COLUMN_TYPES));
186
        $formValues = $this->store->getStore(STORE_FORM);
187
        $formValues = $this->createEmptyTemplateGroupElements($formValues);
188
189
190

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

192
            // Never save a predefined 'id': autoincrement values will be given by database..
193
            if ($column === COLUMN_ID) {
194
                continue;
195
            }
196

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
197
198
199
200
201
            // Skip Upload Elements: those will be processed later.
            if ($this->isColumnUploadField($column)) {
                continue;
            }

202
203
204
205
206
207
208
209
            if ($column === COLUMN_CREATED) {
                $columnCreated = true;
            }

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

210
211
            // Is there a value? Do not forget SIP values. Those do not have necessarily a FormElement.
            if (!isset($formValues[$column])) {
212
                continue;
213
214
            }

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

217
218
219
220
221
222
            // 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);
            }
223
            $newValues[$column] = $formValues[$column];
224

225
226
        }

227
228
229
230
        if ($columnModified && !isset($newValues[COLUMN_MODIFIED])) {
            $newValues[COLUMN_MODIFIED] = date('YmdHis');
        }

231
        if ($recordId == 0) {
232
233
234
            if ($columnCreated && !isset($newValues[COLUMN_CREATED])) {
                $newValues[COLUMN_CREATED] = date('YmdHis');
            }
235
            $rc = $this->insertRecord($this->formSpec[F_TABLE_NAME], $newValues);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
236

237
        } else {
238
            $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
239
240
241
242
            $rc = $recordId;
        }

        return $rc;
243
244
    }

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
245
246
247
248
249
250
    /*
     * Checks if there is a formElement with name '$feName' of type 'upload'
     *
     * @param $feName
     * @return bool
     */
251
252
253
254
    /**
     * @param $feName
     * @return bool
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
255
256
257
258
259
260
    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
261

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
262
263
264
265
266
267
        return false;
    }

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

285
        $sql = "INSERT INTO $tableName ( " . $columnList . " ) VALUES ( " . $paramList . ' )';
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
286
287
288
289
290
291
292
293

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

        return $rc;
    }

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

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

308
        if ($recordId === 0) {
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
309
            throw new CodeException('RecordId=0 - this is not possible for update.', ERROR_RECORDID_0_FORBIDDEN);
310
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
311
312
313
314
315
316
317
318

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

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

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

319
        $sql = substr($sql, 0, strlen($sql) - 2) . " WHERE $primaryKey = ?";
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
320
321
322
323
324
325
326
        $values[] = $recordId;

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

        return $rc;
    }

327
    /**
Carsten  Rose's avatar
Carsten Rose committed
328
329
     * Process all Upload Formelements for the given $recordId. After processing &$formValues will be updated with the
     * final filenames.
330
331
332
333
334
     * @param $recordId
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     * @throws UserReportException
335
336
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
337
     */
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
338
339
340
341
342
343
    public function processAllUploads($recordId) {

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

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

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

352
            $formElement = HelperFormElement::initUploadFormElement($formElement);
353
            if (isset($formElement[FE_FILL_STORE_VAR])) {
354
                $this->store->appendToStore($formElement[FE_FILL_STORE_VAR], STORE_VAR);
355
            }
356

357
358
359
            // Preparation for Log, Debug
            $this->store->setVar(SYSTEM_FORM_ELEMENT, Logger::formatFormElementName($formElement), STORE_SYSTEM);

360
            $column = $formElement[FE_NAME];
361
            $pathFileName = $this->doUpload($formElement, $formValues[$column], $sip, $modeUpload);
362

363
364
365
366
367
368
369
370
            $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]);

371
            // Upload Type: Simple or Advanced
372
373
374
            // 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.
375
376
                if ($pathFileName !== false) {
                    $newValues[$column] = $pathFileName;
377
378
379
380
381
382
383
384

                    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];
                    }
385
                }
386
387
            } elseif (isset($formElement[FE_IMPORT_TO_TABLE]) && !isset($formElement[FE_SLAVE_ID])) {
                // Excel import on nonexisting column -> no upload
388
389
            } else {
                // 'Advanced Upload'
390
                $this->doUploadSlave($formElement, $modeUpload);
391
            }
392
393
394
395

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

396
        }
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
397

398
        // Only used in 'Simple Upload'
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
399
        if (count($newValues) > 0) {
400
            $this->updateRecord($this->formSpec[F_TABLE_NAME], $newValues, $recordId, $this->formSpec[F_PRIMARY_KEY]);
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
401
        }
402
403
    }

404
    /**
405
406
     * Process all Upload FormElements for the given $recordId.
     * After processing, &$formValues will be updated with the final filename.
407
     *
408
409
     * @throws CodeException
     * @throws UserFormException
410
411
412
413
414
415
416
417
418
419
420
421
422
     */
    public function processAllImageCutFE() {

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

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

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443

    /**
     * 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) {

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

446
447
448
449
450
451
452
            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;
            }

453
454
455
            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.
456
457
            }

458
            if (!$requiredOff && $mode == FE_MODE_REQUIRED && empty($clientValues[$formElement[FE_NAME]])) {
459
                throw new UserFormException("Missing required value: " . $formElement[FE_LABEL], ERROR_REQUIRED_VALUE_EMPTY);
460
461
462
463
464
465
466
467
468
            }

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

469
470
471
472
473
474
475
476
477
478
479
    /**
     *
     * @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);
480
        if ($cwd === false || $sitePath === false || !HelperFile::chdir($sitePath)) {
481
482
483
            throw new UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'getcwd() failed or SITE_PATH undefined or chdir() failed', ERROR_MESSAGE_SUPPORT => "getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed."]),
                ERROR_IO_CHDIR);
484
485
        }

486
        // Get original pathFileName
487
488
489
        $field = HelperFormElement::AppendFormElementNameImageCut($formElement);
        $pathFileName = $this->store->getVar($field, STORE_SIP);
        if ($pathFileName == '' || !file_exists($pathFileName)) {
490
491
492
            throw new UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'Empty file or file not found', ERROR_MESSAGE_SUPPORT => 'Empty file or file not found: ' . $pathFileName]),
                ERROR_IO_FILE_NOT_FOUND);
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
        }

        // '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)
            ) {
528
                HelperFile::rename($pathFileName, $pathFileName . $extSave);
529
530
531
532
533
534
535
536
            }
        }

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

        if (false === file_put_contents($pathFileName, base64_decode($imageData))) {
537
538
539
            throw new UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'Write new image failed', ERROR_MESSAGE_SUPPORT => "Write new image failed: $pathFileName"]),
                ERROR_IO_WRITE);
540
541
542
543
544
        }

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

545
    /**
546
547
548
     * 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
549
550
     * Check also: doc/CODING.md
     *
Carsten  Rose's avatar
Carsten Rose committed
551
552
553
554
     * @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
555
556
     *                            UPLOAD_MODE_DELETEOLD_NEW
     *
557
     * @return false|string New pathFilename or false on error
558
     * @throws CodeException
559
     * @throws DbException
560
     * @throws UserFormException
561
562
563
     * @throws UserReportException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
564
565
     * @internal param $recordId
     */
566
567
568
    private function doUpload($formElement, $sipUpload, Sip $sip, &$modeUpload) {
        $flagDelete = false;
        $modeUpload = UPLOAD_MODE_UNCHANGED;
569

570
        // Status information about upload file
571
572
573
574
575
        $statusUpload = $this->store->getVar($sipUpload, STORE_EXTRA);
        if ($statusUpload === false) {
            return false;
        }

576
        if (isset($formElement[FE_IMPORT_TO_TABLE]) && isset($statusUpload[FILES_TMP_NAME])) {
577
            // Import
578
            $tmpFile = Support::extendFilename($statusUpload[FILES_TMP_NAME], UPLOAD_CACHED);
579
580
            $this->doImport($formElement, $tmpFile);
        }
581

582
        // Upload - Take care the necessary target directories exist.
583
584
        $cwd = getcwd();
        $sitePath = $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM);
585
        if ($cwd === false || $sitePath === false || !HelperFile::chdir($sitePath)) {
586
587
588
            throw new UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'getcwd() failed or SITE_PATH undefined or chdir() failed', ERROR_MESSAGE_SUPPORT => "getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed."]),
                ERROR_IO_CHDIR);
589
        }
590

591
592
593
594
595
        // 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)) {
596
                //TODO: it might be possible to delete a file, which is referenced by another record - a check would be nice.
597
                HelperFile::unlink($oldFile, $this->qfqLogFilename);
598
599
600
601
602
603
604
605
606
607
608
            }
            $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;
        }

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

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

            $msg = UPLOAD_LOG_PREFIX . ': ';
            $msg .= ($pathFileName == '') ? 'Remove old upload / no new upload' : 'File "' . $statusUpload[FILES_TMP_NAME] . '" >> "' . $pathFileName . '"';
            Logger::logMessageWithPrefix($msg, $this->qfqLogFilename);
618
619
        }

620
        HelperFile::chdir($cwd);
621
622
623
624
625
626
627
628
629

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

        return $pathFileName;
    }

    /**
     * @param $formElement
630
     * @param $fileName
631
632
633
634
635
636
637
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    private function doImport($formElement, $fileName) {
638

639
        Support::setIfNotSet($formElement, FE_IMPORT_TYPE, FE_IMPORT_TYPE_AUTO);
640

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
        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];
661
662
        $regions = OnArray::trimArray(explode('|', $formElement[FE_IMPORT_REGION] ?? ''));
        $columnNames = OnArray::trimArray(explode(',', $formElement[FE_IMPORT_TO_COLUMNS]));
663
664
665
666
        $importMode = $formElement[FE_IMPORT_MODE] ?? FE_IMPORT_MODE_APPEND;

        foreach ($regions as $region) {
            // region: tab, startColumn, startRow, endColumn, endRow
667
            $region = OnArray::trimArray(explode(',', $region));
668
669
670
671
672
673
674
675
676
677
678
679
680
681
            $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."
                        );
682
683
                    }
                }
684
685
686
            } catch (\PhpOffice\PhpSpreadsheet\Exception $e) {
                throw new UserFormException($e->getMessage());
            }
687

688
689
690
691
692
693
694
695
696
            // 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];
697
698
                }
            }
699
700
701
702
703
            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];
                }
704
            }
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
            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);
723
                }
724
725
                $columnDefinitionArr[] = "`$columnName`   TEXT       NOT NULL  DEFAULT ''";
                $columnListArr[] = "$columnName";
726
727
            }

728
729
730
731
732
733
734
735
736
737
738
739
740
            // 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;
741
            }
742

743
744
745
746
747
748
749
            // 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);
            }
750
        }
751
752
753
    }

    /**
Carsten  Rose's avatar
Upload:    
Carsten Rose committed
754
755
756
757
     * Copy uploaded file from temporary location to final location.
     *
     * Check also: doc/CODING.md
     *
758
759
760
761
     * @param array $formElement
     * @param array $statusUpload
     * @return array|mixed|null|string
     * @throws CodeException
Carsten  Rose's avatar
Carsten Rose committed
762
     * @throws DbException
763
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
764
     * @throws UserReportException
765
766
767
768
     */
    private function copyUploadFile(array $formElement, array $statusUpload) {
        $pathFileName = '';

Carsten  Rose's avatar
Upload:    
Carsten Rose committed
769
        if (!isset($statusUpload[FILES_TMP_NAME]) || $statusUpload[FILES_TMP_NAME] === '') {
770
771
772
773
            // nothing to upload: e.g. user has deleted a previous uploaded file.
            return '';
        }

774
775
        $srcFile = Support::extendFilename($statusUpload[FILES_TMP_NAME], UPLOAD_CACHED);

776
        if (isset($formElement[FE_FILE_DESTINATION])) {
777

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

782
            $pathFileName = $this->evaluate->parse($formElement[FE_FILE_DESTINATION]);
783
            $pathFileName = Sanitize::safeFilename($pathFileName, false, true); // Dynamically calculated pathFileName might contain invalid characters.
784
785
786

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

789
        if ($pathFileName === '') {
790
            throw new UserFormException("Upload failed, no target '" . FE_FILE_DESTINATION . "' specified.", ERROR_NO_TARGET_PATH_FILE_NAME);
791
792
        }

793
794
795
796
797
798
799
        // If given, get chmodDir. Needs to be prefixed with a 0 (=octal) - it should not be quoted! Symbolic mode is not allowed. E.g.: 0660, or 01777
        if (empty($formElement[FE_FILE_CHMOD_DIR])) {
            $chmodDir = false;
        } else {
            $chmodDir = octdec($formElement[FE_FILE_CHMOD_DIR]);
        }

800
        $overwrite = isset($formElement[FE_FILE_REPLACE_MODE]) && $formElement[FE_FILE_REPLACE_MODE] == FE_FILE_REPLACE_MODE_ALWAYS;
801
        Support::moveFile($srcFile, $pathFileName, $overwrite, $chmodDir);
802

803
        // get chmodFile
804
805
        if (empty($formElement[FE_FILE_CHMOD_FILE])) {
            $chmodFile = false;
806
        } else {
807
            $chmodFile = octdec($formElement[FE_FILE_CHMOD_FILE]);
808
809
        }

810
        $this->autoOrient($formElement, $pathFileName);
811
        HelperFile::chmod($pathFileName, $chmodFile);
812

813
        $this->splitUpload($formElement, $pathFileName, $chmodFile, $statusUpload);
814

815
816
        return $pathFileName;
    }
817

818
819
    /**
     * If fe['autoOrient'] is given and the MimeType corresponds to fe['autoOrientMimeType']: the given {{pathFileName:V}} will be converted.
820
     * ImageMagick 'convert' seems to do a better job than GraficsMagick (Orientation is stable even if multiple times applied).
821
822
823
824
825
826
827
828
     *
     * @param array $formElement
     * @param $pathFileName
     * @throws CodeException
     * @throws DbException
     * @throws UserFormException
     * @throws UserReportException
     */
829
    private function autoOrient(array $formElement, $pathFileName) {
830
831

        // 'autoOrient' wished?
832
        if (!isset($formElement[FE_FILE_AUTO_ORIENT]) || $formElement[FE_FILE_AUTO_ORIENT] == '0') {
833
834
835
836
            return; // No
        }

        // Upload has matching MimeType?
837
        $mimeTypeList = empty($formElement[FE_FILE_AUTO_ORIENT_MIME_TYPE]) ? 'image/jpeg,image/png,image/tiff' : $formElement[FE_FILE_AUTO_ORIENT_MIME_TYPE];
838
        if (!HelperFile::checkFileType($pathFileName, $pathFileName, $mimeTypeList)) {
839
840
841
842
843
844
845
846
            return;
        }

        // Get 'autoOrient' command
        $cmd = empty($formElement[FE_FILE_AUTO_ORIENT_CMD]) ? FE_FILE_AUTO_ORIENT_CMD_DEFAULT : $formElement[FE_FILE_AUTO_ORIENT_CMD];
        $cmd = $this->evaluate->parse($cmd);

        // Do 'autoOrient' command
847
848
849
850
        $output = Support::qfqExec($cmd, $rc);
        if ($rc != 0) {
            throw new UserFormException(json_encode([ERROR_MESSAGE_TO_USER => 'copy failed', ERROR_MESSAGE_SUPPORT => "[cmd=$cmd]$output"]), ERROR_IO_COPY);
        }
851
852
    }

853
    /**
Carsten  Rose's avatar
Carsten Rose committed
854
855
856
857
858
859
860
     * 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.
     *
861
     * @param array $formElement
862
863
     * @param string $pathFileName
     * @param int $chmod
864
     * @param array $statusUpload
865
866
     * @throws CodeException
     * @throws DbException
867
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
868
     * @throws UserReportException
869
     */
870
    private function splitUpload(array $formElement, $pathFileName, $chmod, array $statusUpload) {
871

872
        if (empty($formElement[FE_FILE_SPLIT]) || $statusUpload[FILES_TYPE] != MIME_TYPE_SPLIT_CAPABLE) {
873
874
875
876
            return;
        }

        $fileDestinationSplit = $this->evaluate->parse($formElement[FE_FILE_DESTINATION_SPLIT]);
877
        $fileSplitType = $this->evaluate->parse($formElement[FE_FILE_SPLIT]);
878
        $fileSplitTypeOptions = $this->evaluate->parse($formElement[FE_FILE_SPLIT_OPTIONS]);
879
880
881
882
883
884
        $fileSplitTableName = $this->evaluate->parse($formElement[FE_FILE_SPLIT_TABLE_NAME]);

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

885
886
887
        if ($fileDestinationSplit == '') {
            $ext = ($fileSplitType == FE_FILE_SPLIT_SVG) ? '.%02d.svg' : '.jpg';
            $fileDestinationSplit = $pathFileName . '.split/split' . $ext;
888
889
        }

Carsten  Rose's avatar
Carsten Rose committed
890
        HelperFile::mkDirParent($fileDestinationSplit);
891
892
893
894
895
896
897

        // Save CWD
        $cwd = getcwd();

        // Create temporary directory
        $tempDir = Support::createTempDir();
        $newSrc = $tempDir . DIRECTORY_SEPARATOR . QFQ_TEMP_SOURCE;
898
        HelperFile::copy($pathFileName, $newSrc);
899

900
        HelperFile::chdir($tempDir);
901
902
903
904
905
906
907
908
909
910

        // 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'];

911
912
913
914
915
        switch ($fileSplitType) {
            case FE_FILE_SPLIT_SVG:
                $cmd = 'pdf2svg "' . $newSrc . '" "' . $fileNameDest . '" all';
                break;
            case FE_FILE_SPLIT_JPEG:
916
917
918
919
                if ($fileSplitTypeOptions == '') {
                    $fileSplitTypeOptions = FE_FILE_SPLIT_OPTIONS_JPEG;
                }
                $cmd = "convert $fileSplitTypeOptions '$newSrc' '$fileNameDest'";
920
921
922
923
924
                break;
            default:
                throw new UserFormException("Unknown 'fileSplit' type: " . $formElement[FE_FILE_SPLIT], ERROR_UNKNOWN_TOKEN);
        }

925
        // Split PDF
926
927
        $output = Support::qfqExec($cmd, $rc);
        if ($rc != 0) {
928
929
            throw new UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'pdf2svg failed', ERROR_MESSAGE_SUPPORT => "[$cwd][cmd=$cmd]$output"]),
930
                ERROR_PDF2SVG);
931
        }
932

933
934
935
936
937
938
939
        // Array of created file names.
        if (false === ($files = scandir('.'))) {
            throw new UserFormException(
                json_encode([ERROR_MESSAGE_TO_USER => 'Splitted files not found', ERROR_MESSAGE_SUPPORT => "[cwd=$cwd] scandir(.)" . HelperFile::errorGetLastAsString()]),
                ERROR_PDF2JPEG);
        }

940
941
942
943
944
        $xId = $this->store->getVar(COLUMN_ID, STORE_RECORD);

        // Clean optional existing old split records and files from further uploads.
        $this->db->deleteSplitFileAndRecord($xId, $fileSplitTableName);

945
946
        // IM 'convert' will produce files <file>-1.jpg <file>-10.jpg ... - bring them in natural sort order
        natsort($files);
947
948
949

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

        // 1) Move split files to final location. 2) Created records to reference each split file.
953
954
955
956
957
958
959
960
961
962
963
964
        foreach ($files as $file) {

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

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

965
966
            Support::moveFile($file, Support::joinPath($cwd, $fileDestination), true);
            HelperFile::chmod($fileDestination, $chmod);
967
968

            // Insert records.
969
            $this->db->sql($sql, ROW_REGULAR, [$fileSplitTableName, $xId, $fileDestination]);
970
971
972
        }

        // Pop directory
973
        HelperFile::chdir($cwd);
974
975

        // Remove duplicated source
976
977
        HelperFile::unlink($newSrc);

978
        // Remove empty directory
979
        HelperFile::rmdir($tempDir);
980
981
    }

982
    /**
983
     * Create/update or delete the slave record.
984
985
     *
     * @param array $fe
986
     * @param $modeUpload
987
988
     * @return int
     * @throws CodeException
Carsten  Rose's avatar
Carsten Rose committed
989
     * @throws DbException
990
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
991
     * @throws UserReportException
992
     */
993
    private function doUploadSlave(array $fe, $modeUpload) {
994
995
        $sql = '';
        $flagUpdateSlaveId = false;
996
        $flagSlaveDeleted = false;
997

998
        if (!isset($fe[FE_SLAVE_ID])) {
999
1000
1001
            throw new UserFormException("Missing 'slaveId'-definition", ERROR_MISSING_SLAVE_ID_DEFINITION);
        }

1002
        // Get the slaveId
1003
        $slaveId = Support::falseEmptyToZero($this->evaluate->parse($fe[FE_SLAVE_ID]));
1004
1005
1006
        // Store the slaveId: it's used and replaced in the update statement.
        $this->store->setVar(VAR_SLAVE_ID, $slaveId, STORE_VAR, true);

1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
        $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);
1028
1029
1030
        }

        $rc = $this->evaluate->parse($sql);
1031
1032
1033
1034
1035
        // Check if the slave record has been deleted: if yes, set slaveId=0
        if ($flagSlaveDeleted && $rc > 0) {
            $rc = 0;
            $flagUpdateSlaveId = true;
        }
1036
1037
1038
1039
1040
1041
1042
1043
1044

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