[BUGFIX] Skip swapping/publishing of deleted records
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / DataHandling / DataHandler.php
1 <?php
2 namespace TYPO3\CMS\Core\DataHandling;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
19 use TYPO3\CMS\Core\Cache\CacheManager;
20 use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
21 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
22 use TYPO3\CMS\Core\Database\DatabaseConnection;
23 use TYPO3\CMS\Core\Database\ReferenceIndex;
24 use TYPO3\CMS\Core\Database\RelationHandler;
25 use TYPO3\CMS\Core\Html\RteHtmlParser;
26 use TYPO3\CMS\Core\Messaging\FlashMessage;
27 use TYPO3\CMS\Core\Messaging\FlashMessageService;
28 use TYPO3\CMS\Core\Resource\ResourceFactory;
29 use TYPO3\CMS\Core\Type\Bitmask\Permission;
30 use TYPO3\CMS\Core\Utility\ArrayUtility;
31 use TYPO3\CMS\Core\Utility\File\BasicFileUtility;
32 use TYPO3\CMS\Core\Utility\GeneralUtility;
33 use TYPO3\CMS\Core\Utility\MathUtility;
34 use TYPO3\CMS\Core\Utility\PathUtility;
35 use TYPO3\CMS\Core\Utility\StringUtility;
36 use TYPO3\CMS\Core\Versioning\VersionState;
37
38 /**
39 * The main data handler class which takes care of correctly updating and inserting records.
40 * This class was formerly known as TCEmain.
41 *
42 * This is the TYPO3 Core Engine class for manipulation of the database
43 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
44 *
45 * Dependencies:
46 * - $GLOBALS['TCA'] must exist
47 * - $GLOBALS['LANG'] must exist
48 *
49 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
50 */
51 class DataHandler
52 {
53 // *********************
54 // Public variables you can configure before using the class:
55 // *********************
56 /**
57 * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
58 * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
59 *
60 * @var bool
61 */
62 public $storeLogMessages = true;
63
64 /**
65 * If TRUE, actions are logged to sys_log.
66 *
67 * @var bool
68 */
69 public $enableLogging = true;
70
71 /**
72 * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
73 * bunch of records.
74 *
75 * @var bool
76 */
77 public $reverseOrder = false;
78
79 /**
80 * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
81 * is similar, it's not saved then.
82 *
83 * @var bool
84 */
85 public $checkSimilar = true;
86
87 /**
88 * If TRUE, incoming values in the data-array have their slashes stripped. ALWAYS SET THIS TO ZERO and supply an
89 * unescaped data array instead. This switch may totally disappear in future versions of this class!
90 *
91 * @var bool
92 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
93 */
94 public $stripslashes_values = true;
95
96 /**
97 * This will read the record after having updated or inserted it. If anything is not properly submitted an error
98 * is written to the log. This feature consumes extra time by selecting records
99 *
100 * @var bool
101 */
102 public $checkStoredRecords = true;
103
104 /**
105 * If set, values '' and 0 will equal each other when the stored records are checked.
106 *
107 * @var bool
108 */
109 public $checkStoredRecords_loose = true;
110
111 /**
112 * If this is set, then a page is deleted by deleting the whole branch under it (user must have
113 * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
114 *
115 * @var bool
116 */
117 public $deleteTree = false;
118
119 /**
120 * If set, then the 'hideAtCopy' flag for tables will be ignored.
121 *
122 * @var bool
123 */
124 public $neverHideAtCopy = false;
125
126 /**
127 * If set, then the TCE class has been instantiated during an import action of a T3D
128 *
129 * @var bool
130 */
131 public $isImporting = false;
132
133 /**
134 * If set, then transformations are NOT performed on the input.
135 *
136 * @var bool
137 */
138 public $dontProcessTransformations = false;
139
140 /**
141 * If set, .vDEFbase values are unset in flexforms.
142 *
143 * @var bool
144 * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
145 */
146 public $clear_flexFormData_vDEFbase = false;
147
148 /**
149 * TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value.
150 * FALSE: Will not update anything.
151 * "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
152 *
153 * @var bool|string
154 */
155 public $updateModeL10NdiffData = true;
156
157 /**
158 * If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again!
159 * It's meant as the opposite of declaring the record translated.
160 *
161 * @var bool
162 */
163 public $updateModeL10NdiffDataClear = false;
164
165 /**
166 * If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()).
167 * YOU MUST KNOW what you do if you use this feature!
168 *
169 * @var bool
170 */
171 public $bypassWorkspaceRestrictions = false;
172
173 /**
174 * If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away.
175 * YOU MUST KNOW what you are doing with this feature!
176 *
177 * @var bool
178 */
179 public $bypassFileHandling = false;
180
181 /**
182 * If TRUE, access check, check for deleted etc. for records is bypassed.
183 * YOU MUST KNOW what you are doing if you use this feature!
184 *
185 * @var bool
186 */
187 public $bypassAccessCheckForRecords = false;
188
189 /**
190 * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
191 * If '*' then all will (that the user has permission to of course)
192 *
193 * @var string
194 */
195 public $copyWhichTables = '*';
196
197 /**
198 * If 0 then branch is NOT copied.
199 * If 1 then pages on the 1st level is copied.
200 * If 2 then pages on the second level is copied ... and so on
201 *
202 * @var int
203 */
204 public $copyTree = 0;
205
206 /**
207 * [table][fields]=value: New records are created with default values and you can set this array on the
208 * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
209 * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
210 * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
211 *
212 * @var array
213 */
214 public $defaultValues = [];
215
216 /**
217 * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
218 * override the incoming data. You must set this externally. You must make sure the fields in this array are also
219 * found in the table, because it's not checked. All columns can be set by this array!
220 *
221 * @var array
222 */
223 public $overrideValues = [];
224
225 /**
226 * [filename]=alternative_filename: Use this array to force another name onto a file.
227 * Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field,
228 * then 'my_file.txt' will be used as the name instead.
229 *
230 * @var array
231 */
232 public $alternativeFileName = [];
233
234 /**
235 * Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
236 *
237 * @var array
238 */
239 public $alternativeFilePath = [];
240
241 /**
242 * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
243 * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
244 * Then an empty checkbox will disable the field.
245 *
246 * @var array
247 */
248 public $data_disableFields = [];
249
250 /**
251 * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
252 * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
253 * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
254 * The option is used for import of T3D files when synchronizing between two mirrored servers.
255 * As a security measure this feature is available only for Admin Users (for now)
256 *
257 * @var array
258 */
259 public $suggestedInsertUids = [];
260
261 /**
262 * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
263 * iteration functions inside DataHandler for traversing a FlexForm structure.
264 *
265 * @var object
266 */
267 public $callBackObj;
268
269 // *********************
270 // Internal variables (mapping arrays) which can be used (read-only) from outside
271 // *********************
272 /**
273 * Contains mapping of auto-versionized records.
274 *
275 * @var array
276 */
277 public $autoVersionIdMap = [];
278
279 /**
280 * When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
281 *
282 * @var array
283 */
284 public $substNEWwithIDs = [];
285
286 /**
287 * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
288 *
289 * @var array
290 */
291 public $substNEWwithIDs_table = [];
292
293 /**
294 * Holds the tables and there the ids of newly created child records from IRRE
295 *
296 * @var array
297 */
298 public $newRelatedIDs = [];
299
300 /**
301 * This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
302 *
303 * @var array
304 */
305 public $copyMappingArray_merged = [];
306
307 /**
308 * Per-table array with UIDs that have been deleted.
309 *
310 * @var array
311 */
312 protected $deletedRecords = [];
313
314 /**
315 * A map between input file name and final destination for files being attached to records.
316 *
317 * @var array
318 */
319 public $copiedFileMap = [];
320
321 /**
322 * Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
323 *
324 * @var array
325 */
326 public $RTEmagic_copyIndex = [];
327
328 /**
329 * Errors are collected in this variable.
330 *
331 * @var array
332 */
333 public $errorLog = [];
334
335 /**
336 * Fields from the pages-table for which changes will trigger a pagetree refresh
337 *
338 * @var array
339 */
340 public $pagetreeRefreshFieldsFromPages = ['pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid'];
341
342 /**
343 * Indicates whether the pagetree needs a refresh because of important changes
344 *
345 * @var bool
346 */
347 public $pagetreeNeedsRefresh = false;
348
349 // *********************
350 // Internal Variables, do not touch.
351 // *********************
352
353 // Variables set in init() function:
354
355 /**
356 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
357 *
358 * @var BackendUserAuthentication
359 */
360 public $BE_USER;
361
362 /**
363 * Will be set to uid of be_user executing this script
364 *
365 * @var int
366 */
367 public $userid;
368
369 /**
370 * Will be set to username of be_user executing this script
371 *
372 * @var string
373 */
374 public $username;
375
376 /**
377 * Will be set if user is admin
378 *
379 * @var bool
380 */
381 public $admin;
382
383 /**
384 * Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
385 *
386 * @var array
387 */
388 public $defaultPermissions = [
389 'user' => 'show,edit,delete,new,editcontent',
390 'group' => 'show,edit,new,editcontent',
391 'everybody' => ''
392 ];
393
394 /**
395 * The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
396 *
397 * @var array
398 */
399 protected $excludedTablesAndFields = [];
400
401 /**
402 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
403 * @var int
404 */
405 public $include_filefunctions;
406
407 /**
408 * Data submitted from the form view, used to control behaviours,
409 * e.g. this is used to activate/deactivate fields and thus store NULL values
410 *
411 * @var array
412 */
413 protected $control = [];
414
415 /**
416 * Set with incoming data array
417 *
418 * @var array
419 */
420 public $datamap = [];
421
422 /**
423 * Set with incoming cmd array
424 *
425 * @var array
426 */
427 public $cmdmap = [];
428
429 /**
430 * List of changed old record ids to new records ids
431 *
432 * @var array
433 */
434 protected $mmHistoryRecords = [];
435
436 /**
437 * List of changed old record ids to new records ids
438 *
439 * @var array
440 */
441 protected $historyRecords = [];
442
443 // Internal static:
444 /**
445 * Permission mapping
446 *
447 * @var array
448 */
449 public $pMap = [
450 'show' => 1,
451 // 1st bit
452 'edit' => 2,
453 // 2nd bit
454 'delete' => 4,
455 // 3rd bit
456 'new' => 8,
457 // 4th bit
458 'editcontent' => 16
459 ];
460
461 /**
462 * Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
463 *
464 * @var int
465 */
466 public $sortIntervals = 256;
467
468 // Internal caching arrays
469 /**
470 * Used by function checkRecordUpdateAccess() to store whether a record is updatable or not.
471 *
472 * @var array
473 */
474 public $recUpdateAccessCache = [];
475
476 /**
477 * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
478 *
479 * @var array
480 */
481 public $recInsertAccessCache = [];
482
483 /**
484 * Caching array for check of whether records are in a webmount
485 *
486 * @var array
487 */
488 public $isRecordInWebMount_Cache = [];
489
490 /**
491 * Caching array for page ids in webmounts
492 *
493 * @var array
494 */
495 public $isInWebMount_Cache = [];
496
497 /**
498 * Caching for collecting TSconfig for page ids
499 *
500 * @var array
501 */
502 public $cachedTSconfig = [];
503
504 /**
505 * Used for caching page records in pageInfo()
506 *
507 * @var array
508 */
509 public $pageCache = [];
510
511 /**
512 * Array caching workspace access for BE_USER
513 *
514 * @var array
515 */
516 public $checkWorkspaceCache = [];
517
518 // Other arrays:
519 /**
520 * For accumulation of MM relations that must be written after new records are created.
521 *
522 * @var array
523 */
524 public $dbAnalysisStore = [];
525
526 /**
527 * For accumulation of files which must be deleted after processing of all input content
528 *
529 * @var array
530 */
531 public $removeFilesStore = [];
532
533 /**
534 * Uploaded files, set by process_uploads()
535 *
536 * @var array
537 */
538 public $uploadedFileArray = [];
539
540 /**
541 * Used for tracking references that might need correction after operations
542 *
543 * @var array
544 */
545 public $registerDBList = [];
546
547 /**
548 * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
549 *
550 * @var array
551 */
552 public $registerDBPids = [];
553
554 /**
555 * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
556 * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
557 * Read from copyMappingArray_merged instead which is accumulating this information.
558 *
559 * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
560 * are only available after an action has been completed.
561 *
562 * @var array
563 */
564 public $copyMappingArray = [];
565
566 /**
567 * Array used for remapping uids and values at the end of process_datamap
568 *
569 * @var array
570 */
571 public $remapStack = [];
572
573 /**
574 * Array used for remapping uids and values at the end of process_datamap
575 * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
576 *
577 * @var array
578 */
579 public $remapStackRecords = [];
580
581 /**
582 * Array used for checking whether new children need to be remapped
583 *
584 * @var array
585 */
586 protected $remapStackChildIds = [];
587
588 /**
589 * Array used for executing addition actions after remapping happened (set processRemapStack())
590 *
591 * @var array
592 */
593 protected $remapStackActions = [];
594
595 /**
596 * Array used for executing post-processing on the reference index
597 *
598 * @var array
599 */
600 protected $remapStackRefIndex = [];
601
602 /**
603 * Array used for additional calls to $this->updateRefIndex
604 *
605 * @var array
606 */
607 public $updateRefIndexStack = [];
608
609 /**
610 * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
611 * This variable is set by \TYPO3\CMS\Impext\ImportExport
612 *
613 * @var array
614 */
615 public $callFromImpExp = false;
616
617 /**
618 * Array for new flexform index mapping
619 *
620 * @var array
621 */
622 public $newIndexMap = [];
623
624 // Various
625 /**
626 * basicFileFunctions object
627 * For "singleton" file-manipulation object
628 *
629 * @var BasicFileUtility
630 */
631 public $fileFunc;
632
633 /**
634 * Set to "currentRecord" during checking of values.
635 *
636 * @var array
637 */
638 public $checkValue_currentRecord = [];
639
640 /**
641 * A signal flag used to tell file processing that auto versioning has happened and hence certain action should be applied.
642 *
643 * @var bool
644 */
645 public $autoVersioningUpdate = false;
646
647 /**
648 * Disable delete clause
649 *
650 * @var bool
651 */
652 protected $disableDeleteClause = false;
653
654 /**
655 * @var array
656 */
657 protected $checkModifyAccessListHookObjects;
658
659 /**
660 * @var array
661 */
662 protected $version_remapMMForVersionSwap_reg;
663
664 /**
665 * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
666 * This object instantiates itself on versioning and localization ...
667 *
668 * @var \TYPO3\CMS\Core\DataHandling\DataHandler
669 */
670 protected $outerMostInstance = null;
671
672 /**
673 * Internal cache for collecting records that should trigger cache clearing
674 *
675 * @var array
676 */
677 protected static $recordsToClearCacheFor = [];
678
679 /**
680 * Internal cache for pids of records which were deleted. It's not possible
681 * to retrieve the parent folder/page at a later stage
682 *
683 * @var array
684 */
685 protected static $recordPidsForDeletedRecords = [];
686
687 /**
688 * Database layer. Identical to $GLOBALS['TYPO3_DB']
689 *
690 * @var DatabaseConnection
691 */
692 protected $databaseConnection;
693
694 /**
695 * Runtime Cache to store and retrieve data computed for a single request
696 *
697 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
698 */
699 protected $runtimeCache = null;
700
701 /**
702 * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
703 *
704 * @var string
705 */
706 protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';
707
708 /**
709 *
710 */
711 public function __construct()
712 {
713 $this->databaseConnection = $GLOBALS['TYPO3_DB'];
714 $this->runtimeCache = $this->getRuntimeCache();
715 }
716
717 /**
718 * @param array $control
719 */
720 public function setControl(array $control)
721 {
722 $this->control = $control;
723 }
724
725 /**
726 * Initializing.
727 * For details, see 'TYPO3 Core API' document.
728 * This function does not start the processing of data, but merely initializes the object
729 *
730 * @param array $data Data to be modified or inserted in the database
731 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
732 * @param BackendUserAuthentication|NULL $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
733 * @return void
734 */
735 public function start($data, $cmd, $altUserObject = null)
736 {
737 // Initializing BE_USER
738 $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
739 $this->userid = $this->BE_USER->user['uid'];
740 $this->username = $this->BE_USER->user['username'];
741 $this->admin = $this->BE_USER->user['admin'];
742 if ($this->BE_USER->uc['recursiveDelete']) {
743 $this->deleteTree = 1;
744 }
745 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData === true) {
746 $this->updateModeL10NdiffData = false;
747 }
748 // Initializing default permissions for pages
749 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
750 if (isset($defaultPermissions['user'])) {
751 $this->defaultPermissions['user'] = $defaultPermissions['user'];
752 }
753 if (isset($defaultPermissions['group'])) {
754 $this->defaultPermissions['group'] = $defaultPermissions['group'];
755 }
756 if (isset($defaultPermissions['everybody'])) {
757 $this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];
758 }
759 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
760 if (!$this->admin) {
761 $this->excludedTablesAndFields = array_flip($this->getExcludeListArray());
762 }
763 // Setting the data and cmd arrays
764 if (is_array($data)) {
765 reset($data);
766 $this->datamap = $data;
767 }
768 if (is_array($cmd)) {
769 reset($cmd);
770 $this->cmdmap = $cmd;
771 }
772 }
773
774 /**
775 * Function that can mirror input values in datamap-array to other uid numbers.
776 * Example: $mirror[table][11] = '22,33' will look for content in $this->datamap[table][11] and copy it to $this->datamap[table][22] and $this->datamap[table][33]
777 *
778 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
779 * @return void
780 */
781 public function setMirror($mirror)
782 {
783 if (!is_array($mirror)) {
784 return;
785 }
786
787 foreach ($mirror as $table => $uid_array) {
788 if (!isset($this->datamap[$table])) {
789 continue;
790 }
791
792 foreach ($uid_array as $id => $uidList) {
793 if (!isset($this->datamap[$table][$id])) {
794 continue;
795 }
796
797 $theIdsInArray = GeneralUtility::trimExplode(',', $uidList, true);
798 foreach ($theIdsInArray as $copyToUid) {
799 $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
800 }
801 }
802 }
803 }
804
805 /**
806 * Initializes default values coming from User TSconfig
807 *
808 * @param array $userTS User TSconfig array
809 * @return void
810 */
811 public function setDefaultsFromUserTS($userTS)
812 {
813 if (!is_array($userTS)) {
814 return;
815 }
816
817 foreach ($userTS as $k => $v) {
818 $k = substr($k, 0, -1);
819 if (!$k || !is_array($v) || !isset($GLOBALS['TCA'][$k])) {
820 continue;
821 }
822
823 if (is_array($this->defaultValues[$k])) {
824 $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
825 } else {
826 $this->defaultValues[$k] = $v;
827 }
828 }
829 }
830
831 /**
832 * Processing of uploaded files.
833 * It turns out that some versions of PHP arranges submitted data for files different if sent in an array. This function will unify this so the internal array $this->uploadedFileArray will always contain files arranged in the same structure.
834 *
835 * @param array $postFiles $_FILES array
836 * @return void
837 */
838 public function process_uploads($postFiles)
839 {
840 if (!is_array($postFiles)) {
841 return;
842 }
843
844 // Editing frozen:
845 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
846 if ($this->enableLogging) {
847 $this->newlog('All editing in this workspace has been frozen!', 1);
848 }
849 return;
850 }
851 $subA = reset($postFiles);
852 if (is_array($subA)) {
853 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
854 // Initialize the uploadedFilesArray:
855 $this->uploadedFileArray = [];
856 // For each entry:
857 foreach ($subA as $key => $values) {
858 $this->process_uploads_traverseArray($this->uploadedFileArray, $values, $key);
859 }
860 } else {
861 $this->uploadedFileArray = $subA;
862 }
863 }
864 }
865
866 /**
867 * Traverse the upload array if needed to rearrange values.
868 *
869 * @param array $outputArr $this->uploadedFileArray passed by reference
870 * @param array $inputArr Input array ($_FILES parts)
871 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
872 * @return void
873 * @access private
874 * @see process_uploads()
875 */
876 public function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet)
877 {
878 if (is_array($inputArr)) {
879 foreach ($inputArr as $key => $value) {
880 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
881 }
882 } else {
883 $outputArr[$keyToSet] = $inputArr;
884 }
885 }
886
887 /*********************************************
888 *
889 * HOOKS
890 *
891 *********************************************/
892 /**
893 * Hook: processDatamap_afterDatabaseOperations
894 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
895 *
896 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
897 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
898 *
899 * @param array $hookObjectsArr (reference) Array with hook objects
900 * @param string $status (reference) Status of the current operation, 'new' or 'update
901 * @param string $table (reference) The table currently processing data for
902 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
903 * @param array $fieldArray (reference) The field array of a record
904 * @return void
905 */
906 public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
907 {
908 // Process hook directly:
909 if (!isset($this->remapStackRecords[$table][$id])) {
910 foreach ($hookObjectsArr as $hookObj) {
911 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
912 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
913 }
914 }
915 } else {
916 $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = [
917 'status' => $status,
918 'fieldArray' => $fieldArray,
919 'hookObjectsArr' => $hookObjectsArr
920 ];
921 }
922 }
923
924 /**
925 * Gets the 'checkModifyAccessList' hook objects.
926 * The first call initializes the accordant objects.
927 *
928 * @return array The 'checkModifyAccessList' hook objects (if any)
929 * @throws \UnexpectedValueException
930 */
931 protected function getCheckModifyAccessListHookObjects()
932 {
933 if (!isset($this->checkModifyAccessListHookObjects)) {
934 $this->checkModifyAccessListHookObjects = [];
935 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
936 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
937 $hookObject = GeneralUtility::getUserObj($classData);
938 if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface) {
939 throw new \UnexpectedValueException($classData . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface::class, 1251892472);
940 }
941 $this->checkModifyAccessListHookObjects[] = $hookObject;
942 }
943 }
944 }
945 return $this->checkModifyAccessListHookObjects;
946 }
947
948 /*********************************************
949 *
950 * PROCESSING DATA
951 *
952 *********************************************/
953 /**
954 * Processing the data-array
955 * Call this function to process the data-array set by start()
956 *
957 * @return void|FALSE
958 */
959 public function process_datamap()
960 {
961 $this->controlActiveElements();
962
963 // Keep versionized(!) relations here locally:
964 $registerDBList = [];
965 $this->registerElementsToBeDeleted();
966 $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
967 // Editing frozen:
968 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
969 if ($this->enableLogging) {
970 $this->newlog('All editing in this workspace has been frozen!', 1);
971 }
972 return false;
973 }
974 // First prepare user defined objects (if any) for hooks which extend this function:
975 $hookObjectsArr = [];
976 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
977 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
978 $hookObject = GeneralUtility::getUserObj($classRef);
979 if (method_exists($hookObject, 'processDatamap_beforeStart')) {
980 $hookObject->processDatamap_beforeStart($this);
981 }
982 $hookObjectsArr[] = $hookObject;
983 }
984 }
985 // Organize tables so that the pages-table is always processed first. This is required if you want to make sure that content pointing to a new page will be created.
986 $orderOfTables = [];
987 // Set pages first.
988 if (isset($this->datamap['pages'])) {
989 $orderOfTables[] = 'pages';
990 }
991 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
992 // Process the tables...
993 foreach ($orderOfTables as $table) {
994 // Check if
995 // - table is set in $GLOBALS['TCA'],
996 // - table is NOT readOnly
997 // - the table is set with content in the data-array (if not, there's nothing to process...)
998 // - permissions for tableaccess OK
999 $modifyAccessList = $this->checkModifyAccessList($table);
1000 if ($this->enableLogging && !$modifyAccessList) {
1001 $this->log($table, 0, 2, 0, 1, 'Attempt to modify table \'%s\' without permission', 1, [$table]);
1002 }
1003 if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->datamap[$table]) || !$modifyAccessList) {
1004 continue;
1005 }
1006
1007 if ($this->reverseOrder) {
1008 $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
1009 }
1010 // For each record from the table, do:
1011 // $id is the record uid, may be a string if new records...
1012 // $incomingFieldArray is the array of fields
1013 foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
1014 if (!is_array($incomingFieldArray)) {
1015 continue;
1016 }
1017 $theRealPid = null;
1018
1019 // Handle native date/time fields
1020 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
1021 foreach ($GLOBALS['TCA'][$table]['columns'] as $column => $config) {
1022 if (isset($incomingFieldArray[$column])) {
1023 if (isset($config['config']['dbType']) && ($config['config']['dbType'] === 'date' || $config['config']['dbType'] === 'datetime')) {
1024 $emptyValue = $dateTimeFormats[$config['config']['dbType']]['empty'];
1025 $format = $dateTimeFormats[$config['config']['dbType']]['format'];
1026 $incomingFieldArray[$column] = $incomingFieldArray[$column] ? gmdate($format, $incomingFieldArray[$column]) : $emptyValue;
1027 }
1028 }
1029 }
1030 // Hook: processDatamap_preProcessFieldArray
1031 foreach ($hookObjectsArr as $hookObj) {
1032 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
1033 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
1034 }
1035 }
1036 // ******************************
1037 // Checking access to the record
1038 // ******************************
1039 $createNewVersion = false;
1040 $recordAccess = false;
1041 $old_pid_value = '';
1042 $this->autoVersioningUpdate = false;
1043 // Is it a new record? (Then Id is a string)
1044 if (!MathUtility::canBeInterpretedAsInteger($id)) {
1045 // Get a fieldArray with default values
1046 $fieldArray = $this->newFieldArray($table);
1047 // A pid must be set for new records.
1048 if (isset($incomingFieldArray['pid'])) {
1049 // $value = the pid
1050 $pid_value = $incomingFieldArray['pid'];
1051 // Checking and finding numerical pid, it may be a string-reference to another value
1052 $OK = 1;
1053 // If a NEW... id
1054 if (strstr($pid_value, 'NEW')) {
1055 if ($pid_value[0] === '-') {
1056 $negFlag = -1;
1057 $pid_value = substr($pid_value, 1);
1058 } else {
1059 $negFlag = 1;
1060 }
1061 // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
1062 if (isset($this->substNEWwithIDs[$pid_value])) {
1063 if ($negFlag === 1) {
1064 $old_pid_value = $this->substNEWwithIDs[$pid_value];
1065 }
1066 $pid_value = (int)($negFlag * $this->substNEWwithIDs[$pid_value]);
1067 } else {
1068 $OK = 0;
1069 }
1070 }
1071 $pid_value = (int)$pid_value;
1072 // The $pid_value is now the numerical pid at this point
1073 if ($OK) {
1074 $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
1075 // Points to a page on which to insert the element, possibly in the top of the page
1076 if ($pid_value >= 0) {
1077 // If this table is sorted we better find the top sorting number
1078 if ($sortRow) {
1079 $fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
1080 }
1081 // The numerical pid is inserted in the data array
1082 $fieldArray['pid'] = $pid_value;
1083 } else {
1084 // points to another record before ifself
1085 // If this table is sorted we better find the top sorting number
1086 if ($sortRow) {
1087 // Because $pid_value is < 0, getSortNumber returns an array
1088 $tempArray = $this->getSortNumber($table, 0, $pid_value);
1089 $fieldArray['pid'] = $tempArray['pid'];
1090 $fieldArray[$sortRow] = $tempArray['sortNumber'];
1091 } else {
1092 // Here we fetch the PID of the record that we point to...
1093 $tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
1094 $fieldArray['pid'] = $tempdata['pid'];
1095 }
1096 }
1097 }
1098 }
1099 $theRealPid = $fieldArray['pid'];
1100 // Now, check if we may insert records on this pid.
1101 if ($theRealPid >= 0) {
1102 // Checks if records can be inserted on this $pid.
1103 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
1104 if ($recordAccess) {
1105 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
1106 $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
1107 if (!$recordAccess) {
1108 if ($this->enableLogging) {
1109 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', 1);
1110 }
1111 } elseif (!$this->bypassWorkspaceRestrictions) {
1112 // Workspace related processing:
1113 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
1114 if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
1115 if ($res < 0) {
1116 $recordAccess = false;
1117 if ($this->enableLogging) {
1118 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
1119 }
1120 }
1121 } else {
1122 // So, if no live records were allowed, we have to create a new version of this record:
1123 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1124 $createNewVersion = true;
1125 } else {
1126 $recordAccess = false;
1127 if ($this->enableLogging) {
1128 $this->newlog('Record could not be created in this workspace in this branch', 1);
1129 }
1130 }
1131 }
1132 }
1133 }
1134 } else {
1135 debug('Internal ERROR: pid should not be less than zero!');
1136 }
1137 // Yes new record, change $record_status to 'insert'
1138 $status = 'new';
1139 } else {
1140 // Nope... $id is a number
1141 $fieldArray = [];
1142 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
1143 if (!$recordAccess) {
1144 if ($this->enableLogging) {
1145 $propArr = $this->getRecordProperties($table, $id);
1146 $this->log($table, $id, 2, 0, 1, 'Attempt to modify record \'%s\' (%s) without permission. Or non-existing page.', 2, [$propArr['header'], $table . ':' . $id], $propArr['event_pid']);
1147 }
1148 continue;
1149 }
1150 // Next check of the record permissions (internals)
1151 $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
1152 if (!$recordAccess) {
1153 if ($this->enableLogging) {
1154 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', 1);
1155 }
1156 } else {
1157 // Here we fetch the PID of the record that we point to...
1158 $tempdata = $this->recordInfo($table, $id, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : ''));
1159 $theRealPid = $tempdata['pid'];
1160 // Use the new id of the versionized record we're trying to write to:
1161 // (This record is a child record of a parent and has already been versionized.)
1162 if ($this->autoVersionIdMap[$table][$id]) {
1163 // For the reason that creating a new version of this record, automatically
1164 // created related child records (e.g. "IRRE"), update the accordant field:
1165 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1166 // Use the new id of the copied/versionized record:
1167 $id = $this->autoVersionIdMap[$table][$id];
1168 $recordAccess = true;
1169 $this->autoVersioningUpdate = true;
1170 } elseif (!$this->bypassWorkspaceRestrictions && ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata))) {
1171 $recordAccess = false;
1172 // Versioning is required and it must be offline version!
1173 // Check if there already is a workspace version
1174 $WSversion = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
1175 if ($WSversion) {
1176 $id = $WSversion['uid'];
1177 $recordAccess = true;
1178 } elseif ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1179 // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1180 $this->pagetreeNeedsRefresh = true;
1181
1182 /** @var $tce DataHandler */
1183 $tce = GeneralUtility::makeInstance(__CLASS__);
1184 $tce->stripslashes_values = false;
1185 $tce->enableLogging = $this->enableLogging;
1186 // Setting up command for creating a new version of the record:
1187 $cmd = [];
1188 $cmd[$table][$id]['version'] = [
1189 'action' => 'new',
1190 'treeLevels' => -1,
1191 // Default is to create a version of the individual records... element versioning that is.
1192 'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
1193 ];
1194 $tce->start([], $cmd);
1195 $tce->process_cmdmap();
1196 $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
1197 // If copying was successful, share the new uids (also of related children):
1198 if ($tce->copyMappingArray[$table][$id]) {
1199 foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
1200 foreach ($origIdArray as $origId => $newId) {
1201 $this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
1202 $this->autoVersionIdMap[$origTable][$origId] = $newId;
1203 }
1204 }
1205 ArrayUtility::mergeRecursiveWithOverrule($this->RTEmagic_copyIndex, $tce->RTEmagic_copyIndex);
1206 // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
1207 // Update registerDBList, that holds the copied relations to child records:
1208 $registerDBList = array_merge($registerDBList, $tce->registerDBList);
1209 // For the reason that creating a new version of this record, automatically
1210 // created related child records (e.g. "IRRE"), update the accordant field:
1211 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1212 // Use the new id of the copied/versionized record:
1213 $id = $this->autoVersionIdMap[$table][$id];
1214 $recordAccess = true;
1215 $this->autoVersioningUpdate = true;
1216 } elseif ($this->enableLogging) {
1217 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', 1);
1218 }
1219 } elseif ($this->enableLogging) {
1220 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version not allowed in workspace!', 1);
1221 }
1222 }
1223 }
1224 // The default is 'update'
1225 $status = 'update';
1226 }
1227 // If access was granted above, proceed to create or update record:
1228 if (!$recordAccess) {
1229 continue;
1230 }
1231
1232 // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1233 list($tscPID) = BackendUtility::getTSCpid($table, $id, $old_pid_value ? $old_pid_value : $fieldArray['pid']);
1234 if ($status === 'new' && $table === 'pages') {
1235 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
1236 if (isset($TSConfig['permissions.']) && is_array($TSConfig['permissions.'])) {
1237 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
1238 }
1239 }
1240 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1241 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1242 $newVersion_placeholderFieldArray = [];
1243 if ($createNewVersion) {
1244 // create a placeholder array with already processed field content
1245 $newVersion_placeholderFieldArray = $fieldArray;
1246 }
1247 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
1248 // Forcing some values unto field array:
1249 // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1250 $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1251 if ($createNewVersion) {
1252 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
1253 }
1254 // Setting system fields
1255 if ($status == 'new') {
1256 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1257 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1258 if ($createNewVersion) {
1259 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1260 }
1261 }
1262 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1263 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1264 if ($createNewVersion) {
1265 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1266 }
1267 }
1268 } elseif ($this->checkSimilar) {
1269 // Removing fields which are equal to the current value:
1270 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1271 }
1272 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1273 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1274 if ($createNewVersion) {
1275 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1276 }
1277 }
1278 // Set stage to "Editing" to make sure we restart the workflow
1279 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1280 $fieldArray['t3ver_stage'] = 0;
1281 }
1282 // Hook: processDatamap_postProcessFieldArray
1283 foreach ($hookObjectsArr as $hookObj) {
1284 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1285 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1286 }
1287 }
1288 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1289 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
1290 if (is_array($fieldArray)) {
1291 if ($status == 'new') {
1292 if ($table === 'pages') {
1293 // for new pages always a refresh is needed
1294 $this->pagetreeNeedsRefresh = true;
1295 }
1296
1297 // This creates a new version of the record with online placeholder and offline version
1298 if ($createNewVersion) {
1299 // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1300 $this->pagetreeNeedsRefresh = true;
1301
1302 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
1303 // Setting placeholder state value for temporary record
1304 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER);
1305 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1306 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1307 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $this->getPlaceholderTitleForTableLabel($table);
1308 // Saving placeholder as 'original'
1309 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, false);
1310 // For the actual new offline version, set versioning values to point to placeholder:
1311 $fieldArray['pid'] = -1;
1312 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
1313 $fieldArray['t3ver_id'] = 1;
1314 // Setting placeholder state value for version (so it can know it is currently a new version...)
1315 $fieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER_VERSION);
1316 $fieldArray['t3ver_label'] = 'First draft version';
1317 $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1318 // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
1319 $phShadowId = $this->insertDB($table, $id, $fieldArray, true, 0, true);
1320 if ($phShadowId) {
1321 // Processes fields of the placeholder record:
1322 $this->triggerRemapAction($table, $id, [$this, 'placeholderShadowing'], [$table, $phShadowId]);
1323 // Hold auto-versionized ids of placeholders:
1324 $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
1325 }
1326 } else {
1327 $this->insertDB($table, $id, $fieldArray, false, $incomingFieldArray['uid']);
1328 }
1329 } else {
1330 if ($table === 'pages') {
1331 // only a certain number of fields needs to be checked for updates
1332 // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1333 $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages, array_keys($fieldArray));
1334 if (!empty($fieldsToCheck)) {
1335 $this->pagetreeNeedsRefresh = true;
1336 }
1337 }
1338 $this->updateDB($table, $id, $fieldArray);
1339 $this->placeholderShadowing($table, $id);
1340 }
1341 }
1342 // Hook: processDatamap_afterDatabaseOperations
1343 // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1344 // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1345 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1346 }
1347 }
1348 // Process the stack of relations to remap/correct
1349 $this->processRemapStack();
1350 $this->dbAnalysisStoreExec();
1351 $this->removeRegisteredFiles();
1352 // Hook: processDatamap_afterAllOperations
1353 // Note: When this hook gets called, all operations on the submitted data have been finished.
1354 foreach ($hookObjectsArr as $hookObj) {
1355 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1356 $hookObj->processDatamap_afterAllOperations($this);
1357 }
1358 }
1359 if ($this->isOuterMostInstance()) {
1360 $this->processClearCacheQueue();
1361 $this->resetElementsToBeDeleted();
1362 }
1363 }
1364
1365 /**
1366 * Fix shadowing of data in case we are editing an offline version of a live "New" placeholder record:
1367 *
1368 * @param string $table Table name
1369 * @param int $id Record uid
1370 * @return void
1371 */
1372 public function placeholderShadowing($table, $id)
1373 {
1374 if ($liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, '*')) {
1375 if (VersionState::cast($liveRec['t3ver_state'])->indicatesPlaceholder()) {
1376 $justStoredRecord = BackendUtility::getRecord($table, $id);
1377 $newRecord = [];
1378 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1379 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1380 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1381 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
1382 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1383 $shadowColumns = array_unique(GeneralUtility::trimExplode(',', $shadowCols, true));
1384 foreach ($shadowColumns as $fieldName) {
1385 if ((string)$justStoredRecord[$fieldName] !== (string)$liveRec[$fieldName] && isset($GLOBALS['TCA'][$table]['columns'][$fieldName]) && $fieldName !== 'uid' && $fieldName !== 'pid') {
1386 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
1387 }
1388 }
1389 if (!empty($newRecord)) {
1390 if ($this->enableLogging) {
1391 $this->newlog2('Shadowing done on fields <i>' . implode(',', array_keys($newRecord)) . '</i> in placeholder record ' . $table . ':' . $liveRec['uid'] . ' (offline version UID=' . $id . ')', $table, $liveRec['uid'], $liveRec['pid']);
1392 }
1393 $this->updateDB($table, $liveRec['uid'], $newRecord);
1394 }
1395 }
1396 }
1397 }
1398
1399 /**
1400 * Create a placeholder title for the label field that does match the field requirements
1401 *
1402 * @param string $table The table name
1403 * @param string $placeholderContent Placeholder content to be used
1404 * @return string placeholder value
1405 */
1406 public function getPlaceholderTitleForTableLabel($table, $placeholderContent = null)
1407 {
1408 if ($placeholderContent === null) {
1409 $placeholderContent = 'PLACEHOLDER';
1410 }
1411
1412 $labelPlaceholder = '[' . $placeholderContent . ', WS#' . $this->BE_USER->workspace . ']';
1413 $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1414 if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1415 return $labelPlaceholder;
1416 }
1417 $evalCodesArray = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], true);
1418 $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '');
1419 return isset($transformedLabel['value']) ? $transformedLabel['value'] : $labelPlaceholder;
1420 }
1421
1422 /**
1423 * Filling in the field array
1424 * $this->excludedTablesAndFields is used to filter fields if needed.
1425 *
1426 * @param string $table Table name
1427 * @param int $id Record ID
1428 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1429 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1430 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1431 * @param string $status Is 'new' or 'update'
1432 * @param int $tscPID TSconfig PID
1433 * @return array Field Array
1434 */
1435 public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1436 {
1437 // Initialize:
1438 $originalLanguageRecord = null;
1439 $originalLanguage_diffStorage = null;
1440 $diffStorageFlag = false;
1441 // Setting 'currentRecord' and 'checkValueRecord':
1442 if (strstr($id, 'NEW')) {
1443 // Must have the 'current' array - not the values after processing below...
1444 $currentRecord = ($checkValueRecord = $fieldArray);
1445 // IF $incomingFieldArray is an array, overlay it.
1446 // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
1447 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1448 ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1449 }
1450 } else {
1451 // We must use the current values as basis for this!
1452 $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1453 // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
1454 BackendUtility::fixVersioningPid($table, $currentRecord);
1455 // Get original language record if available:
1456 if (is_array($currentRecord) && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
1457 $lookUpTable = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] ?: $table;
1458 $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1459 BackendUtility::workspaceOL($lookUpTable, $originalLanguageRecord);
1460 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1461 }
1462 }
1463 $this->checkValue_currentRecord = $checkValueRecord;
1464 // In the following all incoming value-fields are tested:
1465 // - Are the user allowed to change the field?
1466 // - Is the field uid/pid (which are already set)
1467 // - perms-fields for pages-table, then do special things...
1468 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1469 // If everything is OK, the field is entered into $fieldArray[]
1470 foreach ($incomingFieldArray as $field => $fieldValue) {
1471 if (isset($this->excludedTablesAndFields[$table . '-' . $field]) || $this->data_disableFields[$table][$id][$field]) {
1472 continue;
1473 }
1474
1475 // The field must be editable.
1476 // Checking if a value for language can be changed:
1477 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER->checkLanguageAccess($fieldValue);
1478 if ($languageDeny) {
1479 continue;
1480 }
1481
1482 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
1483 // @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1484 if ($this->stripslashes_values) {
1485 GeneralUtility::deprecationLog(
1486 'The option stripslash_values is typically set to FALSE as data should be properly prepared before sending to DataHandler. Do not rely on DataHandler removing extra slashes. The option will be removed in TYPO3 CMS 8.'
1487 );
1488 if (is_array($fieldValue)) {
1489 GeneralUtility::stripSlashesOnArray($fieldValue);
1490 } else {
1491 $fieldValue = stripslashes($fieldValue);
1492 }
1493 }
1494 switch ($field) {
1495 case 'uid':
1496 case 'pid':
1497 // Nothing happens, already set
1498 break;
1499 case 'perms_userid':
1500 case 'perms_groupid':
1501 case 'perms_user':
1502 case 'perms_group':
1503 case 'perms_everybody':
1504 // Permissions can be edited by the owner or the administrator
1505 if ($table == 'pages' && ($this->admin || $status == 'new' || $this->pageInfo($id, 'perms_userid') == $this->userid)) {
1506 $value = (int)$fieldValue;
1507 switch ($field) {
1508 case 'perms_userid':
1509 $fieldArray[$field] = $value;
1510 break;
1511 case 'perms_groupid':
1512 $fieldArray[$field] = $value;
1513 break;
1514 default:
1515 if ($value >= 0 && $value < pow(2, 5)) {
1516 $fieldArray[$field] = $value;
1517 }
1518 }
1519 }
1520 break;
1521 case 't3ver_oid':
1522 case 't3ver_id':
1523 case 't3ver_wsid':
1524 case 't3ver_state':
1525 case 't3ver_count':
1526 case 't3ver_stage':
1527 case 't3ver_tstamp':
1528 // t3ver_label is not here because it CAN be edited as a regular field!
1529 break;
1530 default:
1531 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1532 // Evaluating the value
1533 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
1534 if (array_key_exists('value', $res)) {
1535 $fieldArray[$field] = $res['value'];
1536 }
1537 // Add the value of the original record to the diff-storage content:
1538 if ($this->updateModeL10NdiffData && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1539 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
1540 $diffStorageFlag = true;
1541 }
1542 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1543 // When a copy or version is made of a record, a search is made for any RTEmagic* images in fields having the "images" soft reference parser applied.
1544 // That should be TRUE for RTE fields. If any are found they are duplicated to new names and the file reference in the bodytext is updated accordingly.
1545 // However, with auto-versioning the submitted content of the field will just overwrite the corrected values. This leaves a) lost RTEmagic files and b) creates a double reference to the old files.
1546 // The only solution I can come up with is detecting when auto versioning happens, then see if any RTEmagic images was copied and if so make a stupid string-replace of the content !
1547 if ($this->autoVersioningUpdate === true) {
1548 if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
1549 foreach ($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1550 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1551 }
1552 }
1553 }
1554 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1555 // Allow value for original UID to pass by...
1556 $fieldArray[$field] = $fieldValue;
1557 }
1558 }
1559 }
1560 // Add diff-storage information:
1561 if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
1562 // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
1563 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1564 }
1565 // Checking for RTE-transformations of fields:
1566 $types_fieldConfig = BackendUtility::getTCAtypes($table, $this->checkValue_currentRecord);
1567 $theTypeString = null;
1568 if (is_array($types_fieldConfig)) {
1569 foreach ($types_fieldConfig as $vconf) {
1570 // RTE transformations:
1571 if ($this->dontProcessTransformations || !isset($fieldArray[$vconf['field']])) {
1572 continue;
1573 }
1574
1575 // Look for transformation flag:
1576 if ((string)$incomingFieldArray['_TRANSFORM_' . $vconf['field']] === 'RTE') {
1577 if ($theTypeString === null) {
1578 $theTypeString = BackendUtility::getTCAtypeValue($table, $this->checkValue_currentRecord);
1579 }
1580 $RTEsetup = $this->BE_USER->getTSConfig('RTE', BackendUtility::getPagesTSconfig($tscPID));
1581 $thisConfig = BackendUtility::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1582 $fieldArray[$vconf['field']] = $this->transformRichtextContentToDatabase(
1583 $fieldArray[$vconf['field']], $table, $vconf['field'], $vconf['spec'], $thisConfig, $this->checkValue_currentRecord['pid']
1584 );
1585 }
1586 }
1587 }
1588 // Return fieldArray
1589 return $fieldArray;
1590 }
1591
1592 /**
1593 * Performs transformation of content from richtext element to database.
1594 *
1595 * @param string $value Value to transform.
1596 * @param string $table The table name
1597 * @param string $field The field name
1598 * @param array $defaultExtras Default extras configuration of this field - typically "richtext:rte_transform[mode=ts_css]"
1599 * @param array $thisConfig Configuration for RTEs; A mix between TSconfig and others. Configuration for additional transformation information
1600 * @param int $pid PID value of record (true parent page id)
1601 * @return string Transformed content
1602 */
1603 protected function transformRichtextContentToDatabase($value, $table, $field, $defaultExtras, $thisConfig, $pid)
1604 {
1605 if ($defaultExtras['rte_transform']) {
1606 $parameters = BackendUtility::getSpecConfParametersFromArray($defaultExtras['rte_transform']['parameters']);
1607 // There must be a mode set for transformation, this is typically 'ts_css'
1608 if ($parameters['mode']) {
1609 // Initialize transformation:
1610 $parseHTML = GeneralUtility::makeInstance(RteHtmlParser::class);
1611 $parseHTML->init($table . ':' . $field, $pid);
1612 $parseHTML->setRelPath('');
1613 // Perform transformation:
1614 $value = $parseHTML->RTE_transform($value, $defaultExtras, 'db', $thisConfig);
1615 }
1616 }
1617 return $value;
1618 }
1619
1620 /*********************************************
1621 *
1622 * Evaluation of input values
1623 *
1624 ********************************************/
1625 /**
1626 * Evaluates a value according to $table/$field settings.
1627 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1628 * NOTICE: Calling this function expects this: 1) That the data is saved! (files are copied and so on) 2) That files registered for deletion IS deleted at the end (with ->removeRegisteredFiles() )
1629 *
1630 * @param string $table Table name
1631 * @param string $field Field name
1632 * @param string $value Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
1633 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1634 * @param string $status 'update' or 'new' flag
1635 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1636 * @param int $tscPID TSconfig PID
1637 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1638 */
1639 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID)
1640 {
1641 // Result array
1642 $res = [];
1643
1644 // Processing special case of field pages.doktype
1645 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1646 // If the user may not use this specific doktype, we issue a warning
1647 if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1648 if ($this->enableLogging) {
1649 $propArr = $this->getRecordProperties($table, $id);
1650 $this->log($table, $id, 5, 0, 1, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, [$propArr['header']], $propArr['event_pid']);
1651 }
1652 return $res;
1653 }
1654 if ($status == 'update') {
1655 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1656 $onlyAllowedTables = isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']) ? $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1657 if ($onlyAllowedTables) {
1658 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1659 if ($theWrongTables) {
1660 if ($this->enableLogging) {
1661 $propArr = $this->getRecordProperties($table, $id);
1662 $this->log($table, $id, 5, 0, 1, '\'doktype\' of page \'%s\' could not be changed because the page contains records from disallowed tables; %s', 2, [$propArr['header'], $theWrongTables], $propArr['event_pid']);
1663 }
1664 return $res;
1665 }
1666 }
1667 }
1668 }
1669
1670 $curValue = null;
1671 if ((int)$id !== 0) {
1672 // Get current value:
1673 $curValueRec = $this->recordInfo($table, $id, $field);
1674 // isset() won't work here, since values can be NULL
1675 if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1676 $curValue = $curValueRec[$field];
1677 }
1678 }
1679
1680 // Getting config for the field
1681 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1682
1683 // Create $recFID only for those types that need it
1684 if (
1685 $tcaFieldConf['type'] === 'flex'
1686 || $tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' || $tcaFieldConf['internal_type'] === 'file_reference')
1687 ) {
1688 $recFID = $table . ':' . $id . ':' . $field;
1689 } else {
1690 $recFID = null;
1691 }
1692
1693 // Perform processing:
1694 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1695 return $res;
1696 }
1697
1698 /**
1699 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1700 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1701 *
1702 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1703 * @param string $value The value to set.
1704 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1705 * @param string $table Table name
1706 * @param int $id UID of record
1707 * @param mixed $curValue Current value of the field
1708 * @param string $status 'update' or 'new' flag
1709 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1710 * @param string $recFID Field identifier [table:uid:field] for flexforms
1711 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1712 * @param array $uploadedFiles
1713 * @param int $tscPID TSconfig PID
1714 * @param array $additionalData Additional data to be forwarded to sub-processors
1715 * @return array Returns the evaluated $value as key "value" in this array.
1716 */
1717 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1718 {
1719 // Convert to NULL value if defined in TCA
1720 if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1721 $res = ['value' => null];
1722 return $res;
1723 }
1724
1725 switch ($tcaFieldConf['type']) {
1726 case 'text':
1727 $res = $this->checkValueForText($value, $tcaFieldConf);
1728 break;
1729 case 'passthrough':
1730 case 'imageManipulation':
1731 case 'user':
1732 $res['value'] = $value;
1733 break;
1734 case 'input':
1735 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1736 break;
1737 case 'check':
1738 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1739 break;
1740 case 'radio':
1741 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1742 break;
1743 case 'group':
1744 case 'select':
1745 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1746 break;
1747 case 'inline':
1748 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1749 break;
1750 case 'flex':
1751 // FlexForms are only allowed for real fields.
1752 if ($field) {
1753 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1754 }
1755 break;
1756 default:
1757 // Do nothing
1758 }
1759 return $res;
1760 }
1761
1762 /**
1763 * Evaluate "text" type values.
1764 *
1765 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1766 * @param string $value The value to set.
1767 * @param array $tcaFieldConf Field configuration from TCA
1768 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1769 * @param string $field Field name
1770 * @return array Modified $res array
1771 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1772 */
1773 public function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '')
1774 {
1775 GeneralUtility::logDeprecatedFunction();
1776 return $this->checkValueForText($value, $tcaFieldConf);
1777 }
1778
1779 /**
1780 * Evaluate "text" type values.
1781 *
1782 * @param string $value The value to set.
1783 * @param array $tcaFieldConf Field configuration from TCA
1784 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1785 */
1786 protected function checkValueForText($value, $tcaFieldConf)
1787 {
1788 if (!isset($tcaFieldConf['eval']) || $tcaFieldConf['eval'] === '') {
1789 return ['value' => $value];
1790 }
1791 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1792 if ($this->runtimeCache->has($cacheId)) {
1793 $evalCodesArray = $this->runtimeCache->get($cacheId);
1794 } else {
1795 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1796 $this->runtimeCache->set($cacheId, $evalCodesArray);
1797 }
1798 return $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1799 }
1800
1801 /**
1802 * Evaluate "input" type values.
1803 *
1804 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1805 * @param string $value The value to set.
1806 * @param array $tcaFieldConf Field configuration from TCA
1807 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1808 * @param string $field Field name
1809 * @return array Modified $res array
1810 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1811 */
1812 public function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '')
1813 {
1814 GeneralUtility::logDeprecatedFunction();
1815 list($table, $id, , , $realPid) = $PP;
1816 return $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1817 }
1818
1819 /**
1820 * Evaluate "input" type values.
1821 *
1822 * @param string $value The value to set.
1823 * @param array $tcaFieldConf Field configuration from TCA
1824 * @param string $table Table name
1825 * @param int $id UID of record
1826 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1827 * @param string $field Field name
1828 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1829 */
1830 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1831 {
1832 // Handle native date/time fields
1833 $isDateOrDateTimeField = false;
1834 $format = '';
1835 $emptyValue = '';
1836 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' || $tcaFieldConf['dbType'] === 'datetime')) {
1837 $isDateOrDateTimeField = true;
1838 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
1839 // Convert the date/time into a timestamp for the sake of the checks
1840 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1841 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1842 // At this point in the processing, the timestamps are still based on UTC
1843 $timeZone = new \DateTimeZone('UTC');
1844 $dateTime = \DateTime::createFromFormat('!' . $format, $value, $timeZone);
1845 $value = $value === $emptyValue ? 0 : $dateTime->getTimestamp();
1846 }
1847 // Secures the string-length to be less than max.
1848 if ((int)$tcaFieldConf['max'] > 0) {
1849 $value = $GLOBALS['LANG']->csConvObj->substr($GLOBALS['LANG']->charSet, (string)$value, 0, (int)$tcaFieldConf['max']);
1850 }
1851 // Checking range of value:
1852 // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1853 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1854 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1855 $value = $tcaFieldConf['range']['upper'];
1856 }
1857 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1858 $value = $tcaFieldConf['range']['lower'];
1859 }
1860 }
1861
1862 if (empty($tcaFieldConf['eval'])) {
1863 $res = ['value' => $value];
1864 } else {
1865 // Process evaluation settings:
1866 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1867 if ($this->runtimeCache->has($cacheId)) {
1868 $evalCodesArray = $this->runtimeCache->get($cacheId);
1869 } else {
1870 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1871 $this->runtimeCache->set($cacheId, $evalCodesArray);
1872 }
1873
1874 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1875
1876 // Process UNIQUE settings:
1877 // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
1878 if ($field && $realPid >= 0 && !empty($res['value'])) {
1879 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1880 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1881 }
1882 if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1883 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1884 }
1885 }
1886 }
1887
1888 // Handle native date/time fields
1889 if ($isDateOrDateTimeField) {
1890 // Convert the timestamp back to a date/time
1891 $res['value'] = $res['value'] ? date($format, $res['value']) : $emptyValue;
1892 }
1893 return $res;
1894 }
1895
1896 /**
1897 * Evaluates 'check' type values.
1898 *
1899 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1900 * @param string $value The value to set.
1901 * @param array $tcaFieldConf Field configuration from TCA
1902 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1903 * @param string $field Field name
1904 * @return array Modified $res array
1905 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1906 */
1907 public function checkValue_check($res, $value, $tcaFieldConf, $PP, $field = '')
1908 {
1909 GeneralUtility::logDeprecatedFunction();
1910 list($table, $id, , , $realPid) = $PP;
1911 return $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1912 }
1913
1914 /**
1915 * Evaluates 'check' type values.
1916 *
1917 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1918 * @param string $value The value to set.
1919 * @param array $tcaFieldConf Field configuration from TCA
1920 * @param string $table Table name
1921 * @param int $id UID of record
1922 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1923 * @param string $field Field name
1924 * @return array Modified $res array
1925 */
1926 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
1927 {
1928 $items = $tcaFieldConf['items'];
1929 if ($tcaFieldConf['itemsProcFunc']) {
1930 /** @var ItemProcessingService $processingService */
1931 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1932 $items = $processingService->getProcessingItems($table, $realPid, $field,
1933 $this->checkValue_currentRecord,
1934 $tcaFieldConf, $tcaFieldConf['items']);
1935 }
1936
1937 $itemC = count($items);
1938 if (!$itemC) {
1939 $itemC = 1;
1940 }
1941 $maxV = pow(2, $itemC) - 1;
1942 if ($value < 0) {
1943 // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
1944 $value = 0;
1945 }
1946 if ($value > $maxV) {
1947 // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
1948 // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
1949 // @todo: are permanently removed from the value.
1950 // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
1951 // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
1952 $value = $value & $maxV;
1953 }
1954 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1955 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1956 $otherRecordsWithSameValue = [];
1957 $maxCheckedRecords = 0;
1958 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
1959 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1960 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1961 }
1962 if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
1963 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1964 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1965 }
1966
1967 // there are more than enough records with value "1" in the DB
1968 // if so, set this value to "0" again
1969 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1970 $value = 0;
1971 if ($this->enableLogging) {
1972 $this->log($table, $id, 5, 0, 1, 'Could not activate checkbox for field "%s". A total of %s record(s) can have this checkbox activated. Uncheck other records first in order to activate the checkbox of this record.', -1, [$GLOBALS['LANG']->sL(BackendUtility::getItemLabel($table, $field)), $maxCheckedRecords]);
1973 }
1974 }
1975 }
1976 $res['value'] = $value;
1977 return $res;
1978 }
1979
1980 /**
1981 * Evaluates 'radio' type values.
1982 *
1983 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1984 * @param string $value The value to set.
1985 * @param array $tcaFieldConf Field configuration from TCA
1986 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1987 * @return array Modified $res array
1988 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1989 */
1990 public function checkValue_radio($res, $value, $tcaFieldConf, $PP)
1991 {
1992 GeneralUtility::logDeprecatedFunction();
1993 // TODO find a way to get the field name; it should not be set in $recFID as this is only created for some record types, see checkValue()
1994 return $this->checkValueForRadio($res, $value, $tcaFieldConf, $PP[0], $PP[1], $PP[4], '');
1995 }
1996
1997 /**
1998 * Evaluates 'radio' type values.
1999 *
2000 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2001 * @param string $value The value to set.
2002 * @param array $tcaFieldConf Field configuration from TCA
2003 * @param array $table The table of the record
2004 * @param int $id The id of the record
2005 * @param int $pid The pid of the record
2006 * @param string $field The field to check
2007 * @return array Modified $res array
2008 */
2009 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
2010 {
2011 if (is_array($tcaFieldConf['items'])) {
2012 foreach ($tcaFieldConf['items'] as $set) {
2013 if ((string)$set[1] === (string)$value) {
2014 $res['value'] = $value;
2015 break;
2016 }
2017 }
2018 }
2019
2020 // if no value was found and an itemsProcFunc is defined, check that for the value
2021 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
2022 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
2023 $processedItems = $processingService->getProcessingItems($table, $pid, $field, $this->checkValue_currentRecord,
2024 $tcaFieldConf, $tcaFieldConf['items']);
2025
2026 foreach ($processedItems as $set) {
2027 if ((string)$set[1] === (string)$value) {
2028 $res['value'] = $value;
2029 break;
2030 }
2031 }
2032 }
2033
2034 return $res;
2035 }
2036
2037 /**
2038 * Evaluates 'group' or 'select' type values.
2039 *
2040 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2041 * @param string $value The value to set.
2042 * @param array $tcaFieldConf Field configuration from TCA
2043 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2044 * @param array $uploadedFiles
2045 * @param string $field Field name
2046 * @return array Modified $res array
2047 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
2048 */
2049 public function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field)
2050 {
2051 GeneralUtility::logDeprecatedFunction();
2052 list($table, $id, $curValue, $status, , $recFID) = $PP;
2053 return $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
2054 }
2055
2056 /**
2057 * Evaluates 'group' or 'select' type values.
2058 *
2059 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2060 * @param string $value The value to set.
2061 * @param array $tcaFieldConf Field configuration from TCA
2062 * @param string $table Table name
2063 * @param int $id UID of record
2064 * @param mixed $curValue Current value of the field
2065 * @param string $status 'update' or 'new' flag
2066 * @param string $recFID Field identifier [table:uid:field] for flexforms
2067 * @param array $uploadedFiles
2068 * @param string $field Field name
2069 * @return array Modified $res array
2070 */
2071 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field)
2072 {
2073 // Detecting if value sent is an array and if so, implode it around a comma:
2074 if (is_array($value)) {
2075 $value = implode(',', $value);
2076 }
2077 // This converts all occurrences of '&#123;' to the byte 123 in the string - this is needed in very rare cases where file names with special characters (e.g. ???, umlaut) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
2078 // Anyway, this should NOT disturb anything else:
2079 $value = $this->convNumEntityToByteValue($value);
2080 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
2081 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
2082 // If multiple is not set, remove duplicates:
2083 if (!$tcaFieldConf['multiple']) {
2084 $valueArray = array_unique($valueArray);
2085 }
2086 // If an exclusive key is found, discard all others:
2087 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
2088 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
2089 foreach ($valueArray as $index => $key) {
2090 if (in_array($key, $exclusiveKeys, true)) {
2091 $valueArray = [$index => $key];
2092 break;
2093 }
2094 }
2095 }
2096 // This could be a good spot for parsing the array through a validation-function which checks if the values are correct (except that database references are not in their final form - but that is the point, isn't it?)
2097 // NOTE!!! Must check max-items of files before the later check because that check would just leave out file names if there are too many!!
2098 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2099 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
2100 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
2101 $preCount = count($valueArray);
2102 foreach ($valueArray as $index => $key) {
2103 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
2104 unset($valueArray[$index]);
2105 }
2106 }
2107 // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
2108 if ($preCount && empty($valueArray)) {
2109 return [];
2110 }
2111 }
2112 // For group types:
2113 if ($tcaFieldConf['type'] == 'group') {
2114 switch ($tcaFieldConf['internal_type']) {
2115 case 'file_reference':
2116 case 'file':
2117 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
2118 break;
2119 }
2120 }
2121 // For select types which has a foreign table attached:
2122 $unsetResult = false;
2123 if (
2124 $tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db'
2125 || $tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] || isset($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages')
2126 ) {
2127 // check, if there is a NEW... id in the value, that should be substituted later
2128 if (strpos($value, 'NEW') !== false) {
2129 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2130 $this->addNewValuesToRemapStackChildIds($valueArray);
2131 $this->remapStack[] = [
2132 'func' => 'checkValue_group_select_processDBdata',
2133 'args' => [$valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field],
2134 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5],
2135 'field' => $field
2136 ];
2137 $unsetResult = true;
2138 } else {
2139 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2140 }
2141 }
2142 if (!$unsetResult) {
2143 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2144 $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2145 } else {
2146 unset($res['value']);
2147 }
2148 return $res;
2149 }
2150
2151 /**
2152 * Applies the filter methods from a column's TCA configuration to a value array.
2153 *
2154 * @param array $tcaFieldConfiguration
2155 * @param array $values
2156 * @return array|mixed
2157 * @throws \RuntimeException
2158 */
2159 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2160 {
2161 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
2162 return $values;
2163 }
2164 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2165 if (empty($filter['userFunc'])) {
2166 continue;
2167 }
2168 $parameters = $filter['parameters'] ?: [];
2169 $parameters['values'] = $values;
2170 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2171 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
2172 if (!is_array($values)) {
2173 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
2174 }
2175 }
2176 return $values;
2177 }
2178
2179 /**
2180 * Handling files for group/select function
2181 *
2182 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2183 * @param array $tcaFieldConf Configuration array from TCA of the field
2184 * @param string $curValue Current value of the field
2185 * @param array $uploadedFileArray Array of uploaded files, if any
2186 * @param string $status 'update' or 'new' flag
2187 * @param string $table tablename of record
2188 * @param int $id UID of record
2189 * @param string $recFID Field identifier [table:uid:field] for flexforms
2190 * @return array Modified value array
2191 *
2192 * @throws \RuntimeException
2193 * @see checkValue_group_select()
2194 */
2195 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
2196 {
2197 // If file handling should NOT be bypassed, do processing:
2198 if (!$this->bypassFileHandling) {
2199 // If any files are uploaded, add them to value array
2200 // Numeric index means that there are multiple files
2201 if (isset($uploadedFileArray[0])) {
2202 $uploadedFiles = $uploadedFileArray;
2203 } else {
2204 // There is only one file
2205 $uploadedFiles = [$uploadedFileArray];
2206 }
2207 foreach ($uploadedFiles as $uploadedFileArray) {
2208 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2209 $valueArray[] = $uploadedFileArray['tmp_name'];
2210 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2211 }
2212 }
2213 // Creating fileFunc object.
2214 if (!$this->fileFunc) {
2215 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
2216 $this->include_filefunctions = 1;
2217 }
2218 // Setting permitted extensions.
2219 $all_files = [];
2220 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
2221 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
2222 $all_files['ftpspace'] = $all_files['webspace'];
2223 $this->fileFunc->init('', $all_files);
2224 }
2225 // If there is an upload folder defined:
2226 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
2227 $currentFilesForHistory = null;
2228 // If filehandling should NOT be bypassed, do processing:
2229 if (!$this->bypassFileHandling) {
2230 // For logging..
2231 $propArr = $this->getRecordProperties($table, $id);
2232 // Get destrination path:
2233 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
2234 // If we are updating:
2235 if ($status == 'update') {
2236 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2237 // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
2238 // The only solution I could come up with (except removing support for managing files when autoversioning) was to convert all relative files to absolute names so they are copied again (and existing files deleted). This should keep references intact but means that some files are copied, then deleted after being copied _again_.
2239 // Actually, the same problem applies to database references in case auto-versioning would include sub-records since in such a case references are remapped - and they would be overridden due to the same principle then.
2240 // Illustration of the problem comes here:
2241 // We have a record 123 with a file logo.gif. We open and edit the files header in a workspace. So a new version is automatically made.
2242 // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
2243 // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
2244 // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
2245 if ($this->autoVersioningUpdate === true) {
2246 foreach ($valueArray as $key => $theFile) {
2247 // If it is an already attached file...
2248 if ($theFile === basename($theFile)) {
2249 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2250 }
2251 }
2252 }
2253 // Finding the CURRENT files listed, either from MM or from the current record.
2254 $theFileValues = [];
2255 // If MM relations for the files also!
2256 if ($tcaFieldConf['MM']) {
2257 $dbAnalysis = $this->createRelationHandlerInstance();
2258 /** @var $dbAnalysis RelationHandler */
2259 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2260 foreach ($dbAnalysis->itemArray as $item) {
2261 if ($item['id']) {
2262 $theFileValues[] = $item['id'];
2263 }
2264 }
2265 } else {
2266 $theFileValues = GeneralUtility::trimExplode(',', $curValue, true);
2267 }
2268 $currentFilesForHistory = implode(',', $theFileValues);
2269 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2270 if (!empty($theFileValues)) {
2271 // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
2272 foreach ($valueArray as $key => $theFile) {
2273 if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
2274 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
2275 }
2276 }
2277 // This array contains the filenames in the uploadfolder that should be deleted:
2278 foreach ($theFileValues as $key => $theFile) {
2279 $theFile = trim($theFile);
2280 if (@is_file(($dest . '/' . $theFile))) {
2281 $this->removeFilesStore[] = $dest . '/' . $theFile;
2282 } elseif ($this->enableLogging && $theFile) {
2283 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, [$dest . '/' . $theFile, $recFID], $propArr['event_pid']);
2284 }
2285 }
2286 }
2287 }
2288 // Traverse the submitted values:
2289 foreach ($valueArray as $key => $theFile) {
2290 // Init:
2291 $maxSize = (int)$tcaFieldConf['max_size'];
2292 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2293 $theDestFile = '';
2294 // a FAL file was added, now resolve the file object and get the absolute path
2295 // @todo in future versions this needs to be modified to handle FAL objects natively
2296 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2297 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2298 $theFile = $fileObject->getForLocalProcessing(false);
2299 }
2300 // NEW FILES? If the value contains '/' it indicates, that the file
2301 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2302 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
2303 // Check various things before copying file:
2304 // File and destination must exist
2305 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
2306 // Finding size.
2307 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2308 $fileSize = $uploadedFileArray['size'];
2309 } else {
2310 $fileSize = filesize($theFile);
2311 }
2312 // Check file size:
2313 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2314 // Prepare filename:
2315 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2316 $fI = GeneralUtility::split_fileref($theEndFileName);
2317 // Check for allowed extension:
2318 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2319 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2320 // If we have a unique destination filename, then write the file:
2321 if ($theDestFile) {
2322 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2323 // Hook for post-processing the upload action
2324 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2325 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2326 $hookObject = GeneralUtility::getUserObj($classRef);
2327 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2328 throw new \UnexpectedValueException($classRef . ' must implement interface ' . DataHandlerProcessUploadHookInterface::class, 1279962349);
2329 }
2330 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2331 }
2332 }
2333 $this->copiedFileMap[$theFile] = $theDestFile;
2334 clearstatcache();
2335 if ($this->enableLogging && !@is_file($theDestFile)) {
2336 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, [$theFile, dirname($theDestFile), $recFID], $propArr['event_pid']);
2337 }
2338 } elseif ($this->enableLogging) {
2339 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2340 }
2341 } elseif ($this->enableLogging) {
2342 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2343 }
2344 } elseif ($this->enableLogging) {
2345 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, [GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID], $propArr['event_pid']);
2346 }
2347 } elseif ($this->enableLogging) {
2348 $this->log($table, $id, 5, 0, 1, 'The destination (%s) or the source file (%s) does not exist. (%s)', 14, [$dest, $theFile, $recFID], $propArr['event_pid']);
2349 }
2350 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2351 if (@is_file($theDestFile)) {
2352 $info = GeneralUtility::split_fileref($theDestFile);
2353 // The value is set to the new filename
2354 $valueArray[$key] = $info['file'];
2355 } else {
2356 // The value is set to the new filename
2357 unset($valueArray[$key]);
2358 }
2359 }
2360 }
2361 }
2362 // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
2363 if ($tcaFieldConf['MM']) {
2364 /** @var $dbAnalysis RelationHandler */
2365 $dbAnalysis = $this->createRelationHandlerInstance();
2366 // Dummy
2367 $dbAnalysis->tableArray['files'] = [];
2368 foreach ($valueArray as $key => $theFile) {
2369 // Explode files
2370 $dbAnalysis->itemArray[]['id'] = $theFile;
2371 }
2372 if ($status == 'update') {
2373 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2374 $newFiles = implode(',', $dbAnalysis->getValueArray());
2375 list(, , $recFieldName) = explode(':', $recFID);
2376 if ($currentFilesForHistory != $newFiles) {
2377 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2378 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2379 } else {
2380 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2381 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2382 }
2383 } else {
2384 $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, 0];
2385 }
2386 $valueArray = $dbAnalysis->countItems();
2387 }
2388 } else {
2389 if (!empty($valueArray)) {
2390 // If filehandling should NOT be bypassed, do processing:
2391 if (!$this->bypassFileHandling) {
2392 // For logging..
2393 $propArr = $this->getRecordProperties($table, $id);
2394 foreach ($valueArray as &$theFile) {
2395 // FAL handling: it's a UID, thus it is resolved to the absolute path
2396 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2397 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2398 $theFile = $fileObject->getForLocalProcessing(false);
2399 }
2400 if ($this->alternativeFilePath[$theFile]) {
2401 // If alternative File Path is set for the file, then it was an import
2402 // don't import the file if it already exists
2403 if (@is_file((PATH_site . $this->alternativeFilePath[$theFile]))) {
2404 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
2405 } elseif (@is_file($theFile)) {
2406 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
2407 if (!@is_dir($dest)) {
2408 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
2409 }
2410 // Init:
2411 $maxSize = (int)$tcaFieldConf['max_size'];
2412 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2413 $theDestFile = '';
2414 $fileSize = filesize($theFile);
2415 // Check file size:
2416 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2417 // Prepare filename:
2418 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2419 $fI = GeneralUtility::split_fileref($theEndFileName);
2420 // Check for allowed extension:
2421 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2422 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
2423 // Write the file:
2424 if ($theDestFile) {
2425 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2426 $this->copiedFileMap[$theFile] = $theDestFile;
2427 clearstatcache();
2428 if ($this->enableLogging && !@is_file($theDestFile)) {
2429 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, [$theFile, dirname($theDestFile), $recFID], $propArr['event_pid']);
2430 }
2431 } elseif ($this->enableLogging) {
2432 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2433 }
2434 } elseif ($this->enableLogging) {
2435 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2436 }
2437 } elseif ($this->enableLogging) {
2438 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, [GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID], $propArr['event_pid']);
2439 }
2440 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2441 if (@is_file($theDestFile)) {
2442 // The value is set to the new filename
2443 $theFile = $theDestFile;
2444 } else {
2445 // The value is set to the new filename
2446 unset($theFile);
2447 }
2448 }
2449 }
2450 if (!empty($theFile)) {
2451 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2452 if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
2453 $theFile = PathUtility::stripPathSitePrefix($theFile);
2454 }
2455 }
2456 }
2457 unset($theFile);
2458 }
2459 }
2460 }
2461 return $valueArray;
2462 }
2463
2464 /**
2465 * Evaluates 'flex' type values.
2466 *
2467 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2468 * @param string|array $value The value to set.
2469 * @param array $tcaFieldConf Field configuration from TCA
2470 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2471 * @param array $uploadedFiles Uploaded files for the field
2472 * @param string $field Field name
2473 * @return array Modified $res array
2474 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
2475 */
2476 public function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field)
2477 {
2478 GeneralUtility::logDeprecatedFunction();
2479 list($table, $id, $curValue, $status, $realPid, $recFID, $tscPID) = $PP;
2480 $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
2481 }
2482
2483 /**
2484 * Evaluates 'flex' type values.
2485 *
2486 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2487 * @param string|array $value The value to set.
2488 * @param array $tcaFieldConf Field configuration from TCA
2489 * @param string $table Table name
2490 * @param int $id UID of record
2491 * @param mixed $curValue Current value of the field
2492 * @param string $status 'update' or 'new' flag
2493 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
2494 * @param string $recFID Field identifier [table:uid:field] for flexforms
2495 * @param int $tscPID TSconfig PID
2496 * @param array $uploadedFiles Uploaded files for the field
2497 * @param string $field Field name
2498 * @return array Modified $res array
2499 */
2500 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2501 {
2502 if (is_array($value)) {
2503 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2504 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord does not have a uid or pid for that
2505 // sake, the BackendUtility::getFlexFormDS() function returns no good DS. For new records we do know the expected PID so therefore we send that with this special parameter.
2506 // Only active when larger than zero.
2507 $newRecordPidValue = $status == 'new' ? $realPid : 0;
2508 // Get current value array:
2509 $dataStructArray = BackendUtility::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, $field, true, $newRecordPidValue);
2510 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : [];
2511 if (!is_array($currentValueArray)) {
2512 $currentValueArray = [];
2513 }
2514 if (isset($currentValueArray['meta']['currentLangId'])) {
2515 // @deprecated call since TYPO3 7, will be removed with TYPO3 8
2516 unset($currentValueArray['meta']['currentLangId']);
2517 }
2518 // Remove all old meta for languages...
2519 // Evaluation of input values:
2520 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, [$table, $id, $curValue, $status, $realPid, $recFID, $tscPID]);
2521 // Create XML from input value:
2522 $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2523
2524 // Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same
2525 // (provided that the current value was already stored IN the charset that the new value is converted to).
2526 $arrValue = GeneralUtility::xml2array($xmlValue);
2527
2528 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2529 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2530 $hookObject = GeneralUtility::getUserObj($classRef);
2531 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2532 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2533 }
2534 }
2535 }
2536
2537 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2538 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2539
2540 // Action commands (sorting order and removals of elements) for flexform sections,
2541 // see FormEngine for the use of this GP parameter
2542 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2543 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2544 $arrValue = GeneralUtility::xml2array($xmlValue);
2545 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2546 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2547 }
2548 // Create the value XML:
2549 $res['value'] = '';
2550 $res['value'] .= $xmlValue;
2551 } else {
2552 // Passthrough...:
2553 $res['value'] = $value;
2554 }
2555
2556 return $res;
2557 }
2558
2559 /**
2560 * Converts an array to FlexForm XML
2561 *
2562 * @param array $array Array with FlexForm data
2563 * @param bool $addPrologue If set, the XML prologue is returned as well.
2564 * @return string Input array converted to XML
2565 */
2566 public function checkValue_flexArray2Xml($array, $addPrologue = false)
2567 {
2568 /** @var $flexObj FlexFormTools */
2569 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2570 return $flexObj->flexArray2Xml($array, $addPrologue);
2571 }
2572
2573 /**
2574 * Actions for flex form element (move, delete)
2575 * allows to remove and move flexform sections
2576 *
2577 * @param array $valueArray by reference
2578 * @param array $actionCMDs
2579 */
2580 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2581 {
2582 if (!is_array($valueArray) || !is_array($actionCMDs)) {
2583 return;
2584 }
2585
2586 foreach ($actionCMDs as $key => $value) {
2587 if ($key == '_ACTION') {
2588 // First, check if there are "commands":
2589 if (current($actionCMDs[$key]) === '') {
2590 continue;
2591 }
2592
2593 asort($actionCMDs[$key]);
2594 $newValueArray = [];
2595 foreach ($actionCMDs[$key] as $idx => $order) {
2596 if (substr($idx, 0, 3) == 'ID-') {
2597 $idx = $this->newIndexMap[$idx];
2598 }
2599 // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost files unless we act on this delete operation by traversing and deleting files that were referred to.
2600 if ($order != 'DELETE') {
2601 $newValueArray[$idx] = $valueArray[$idx];
2602 }
2603 unset($valueArray[$idx]);
2604 }
2605 $valueArray = $valueArray + $newValueArray;
2606 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2607 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2608 }
2609 }
2610 }
2611
2612 /**
2613 * Evaluates 'inline' type values.
2614 * (partly copied from the select_group function on this issue)
2615 *
2616 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2617 * @param string $value The value to set.
2618 * @param array $tcaFieldConf Field configuration from TCA
2619 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2620 * @param string $field Field name
2621 * @param array $additionalData Additional data to be forwarded to sub-processors
2622 * @return array Modified $res array
2623 */
2624 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2625 {
2626 list($table, $id, , $status) = $PP;
2627 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2628 }
2629
2630 /**
2631 * Evaluates 'inline' type values.
2632 * (partly copied from the select_group function on this issue)
2633 *
2634 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2635 * @param string $value The value to set.
2636 * @param array $tcaFieldConf Field configuration from TCA
2637 * @param string $table Table name
2638 * @param int $id UID of record
2639 * @param string $status 'update' or 'new' flag
2640 * @param string $field Field name
2641 * @param array $additionalData Additional data to be forwarded to sub-processors
2642 * @return array Modified $res array
2643 */
2644 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2645 {
2646 if (!$tcaFieldConf['foreign_table']) {
2647 // Fatal error, inline fields should always have a foreign_table defined
2648 return false;
2649 }
2650 // When values are sent they come as comma-separated values which are exploded by this function:
2651 $valueArray = GeneralUtility::trimExplode(',', $value);
2652 // Remove duplicates: (should not be needed)
2653 $valueArray = array_unique($valueArray);
2654 // Example for received data:
2655 // $value = 45,NEW4555fdf59d154,12,123
2656 // We need to decide whether we use the stack or can save the relation directly.
2657 if (strpos($value, 'NEW') !== false || !MathUtility::canBeInterpretedAsInteger($id)) {
2658 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2659 $this->addNewValuesToRemapStackChildIds($valueArray);
2660 $this->remapStack[] = [
2661 'func' => 'checkValue_inline_processDBdata',
2662 'args' => [$valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData],
2663 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4],
2664 'additionalData' => $additionalData,
2665 'field' => $field,
2666 ];
2667 unset($res['value']);
2668 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2669 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2670 }
2671 return $res;
2672 }
2673
2674 /**
2675 * Checks if a fields has more items than defined via TCA in maxitems.
2676 * If there are more items than allowd, the item list is truncated to the defined number.
2677 *
2678 * @param array $tcaFieldConf Field configuration from TCA
2679 * @param array $valueArray Current value array of items
2680 * @return array The truncated value array of items
2681 */
2682 public function checkValue_checkMax($tcaFieldConf, $valueArray)
2683 {
2684 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2685 $valueArrayC = count($valueArray);
2686 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
2687 $maxI = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 1;
2688 if ($valueArrayC > $maxI) {
2689 $valueArrayC = $maxI;
2690 }
2691 // Checking for not too many elements
2692 // Dumping array to list
2693 $newVal = [];
2694 foreach ($valueArray as $nextVal) {
2695 if ($valueArrayC == 0) {
2696 break;
2697 }
2698 $valueArrayC--;
2699 $newVal[] = $nextVal;
2700 }
2701 return $newVal;
2702 }
2703
2704 /*********************************************
2705 *
2706 * Helper functions for evaluation functions.
2707 *
2708 ********************************************/
2709 /**
2710 * Gets a unique value for $table/$id/$field based on $value
2711 *
2712 * @param string $table Table name
2713 * @param string $field Field name for which $value must be unique
2714 * @param string $value Value string.
2715 * @param int $id UID to filter out in the lookup (the record itself...)
2716 * @param int $newPid If set, the value will be unique for this PID
2717 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2718 */
2719 public function getUnique($table, $field, $value, $id, $newPid = 0)
2720 {
2721 // Initialize:
2722 $whereAdd = '';
2723 $newValue = '';
2724 if ((int)$newPid) {
2725 $whereAdd .= ' AND pid=' . (int)$newPid;
2726 } else {
2727 $whereAdd .= ' AND pid>=0';
2728 }
2729 // "AND pid>=0" for versioning
2730 $whereAdd .= $this->deleteClause($table);
2731 // If the field is configured in TCA, proceed:
2732 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2733 // Look for a record which might already have the value:
2734 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($value, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2735 $counter = 0;
2736 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2737 while ($this->databaseConnection->sql_num_rows($res)) {
2738 $newValue = $value . $counter;
2739 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($newValue, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2740 $counter++;
2741 if ($counter > 100) {
2742 break;
2743 }
2744 }
2745 $this->databaseConnection->sql_free_result($res);
2746 // If the new value is there:
2747 $value = $newValue !== '' ? $newValue : $value;
2748 }
2749 return $value;
2750 }
2751
2752 /**
2753 * gets all records that have the same value in a field
2754 * excluding the given uid
2755 *
2756 * @param string $tableName Table name
2757 * @param int $uid UID to filter out in the lookup (the record itself...)
2758 * @param string $fieldName Field name for which $value must be unique
2759 * @param string $value Value string.
2760 * @param int $pageId If set, the value will be unique for this PID
2761 * @return array
2762 */
2763 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2764 {
2765 $result = [];
2766 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2767 $uid = (int)$uid;
2768 $pageId = (int)$pageId;
2769 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ? 'pid = ' . $pageId : 'pid >= 0');
2770 $result = BackendUtility::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2771 }
2772 return $result;
2773 }
2774
2775 /**
2776 * @param string $value The field value to be evaluated
2777 * @param array $evalArray Array of evaluations to traverse.
2778 * @param string $is_in The "is_in" value of the field configuration from TCA
2779 * @return array
2780 */
2781 public function checkValue_text_Eval($value, $evalArray, $is_in)
2782 {
2783 $res = [];
2784 $set = true;
2785 foreach ($evalArray as $func) {
2786 switch ($func) {
2787 case 'trim':
2788 $value = trim($value);
2789 break;
2790 case 'required':
2791 if (!$value) {
2792 $set = false;
2793 }
2794 break;
2795 default:
2796 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2797 if (class_exists($func)) {
2798 $evalObj = GeneralUtility::makeInstance($func);
2799 if (method_exists($evalObj, 'evaluateFieldValue')) {
2800 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2801 }
2802 }
2803 }
2804 }
2805 }
2806 if ($set) {
2807 $res['value'] = $value;
2808 }
2809 return $res;
2810 }
2811
2812 /**
2813 * Evaluation of 'input'-type values based on 'eval' list
2814 *
2815 * @param string $value Value to evaluate
2816 * @param array $evalArray Array of evaluations to traverse.
2817 * @param string $is_in Is-in string for 'is_in' evaluation
2818 * @return array Modified $value in key 'value' or empty array
2819 */
2820 public function checkValue_input_Eval($value, $evalArray, $is_in)
2821 {
2822 $res = [];
2823 $set = true;
2824 foreach ($evalArray as $func) {
2825 switch ($func) {
2826 case 'int':
2827 case 'year':
2828 case 'time':
2829 case 'timesec':
2830 $value = (int)$value;
2831 break;
2832 case 'date':
2833 case 'datetime':
2834 $value = (int)$value;
2835 if ($value !== 0 && !$this->dontProcessTransformations) {
2836 $value -= date('Z', $value);
2837 }
2838 break;
2839 case 'double2':
2840 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2841 $negative = $value[0] === '-';
2842 $value = strtr($value, [',' => '.', '-' => '']);
2843 if (strpos($value, '.') === false) {
2844 $value .= '.0';
2845 }
2846 $valueArray = explode('.', $value);
2847 $dec = array_pop($valueArray);
2848 $value = join('', $valueArray) . '.' . $dec;
2849 if ($negative) {
2850 $value *= -1;
2851 }
2852 $value = number_format($value, 2, '.', '');
2853 break;
2854 case 'md5':
2855 if (strlen($value) != 32) {
2856 $set = false;
2857 }
2858 break;
2859 case 'trim':
2860 $value = trim($value);
2861 break;
2862 case 'upper':
2863 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toUpper');
2864 break;
2865 case 'lower':
2866 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toLower');
2867 break;
2868 case 'required':
2869 if (!isset($value) || $value === '') {
2870 $set = false;
2871 }
2872 break;
2873 case 'is_in':
2874 $c = strlen($value);
2875 if ($c) {
2876 $newVal = '';
2877 for ($a = 0; $a < $c; $a++) {
2878 $char = substr($value, $a, 1);
2879 if (strpos($is_in, $char) !== false) {
2880 $newVal .= $char;
2881 }
2882 }
2883 $value = $newVal;
2884 }
2885 break;
2886 case 'nospace':
2887 $value = str_replace(' ', '', $value);
2888 break;
2889 case 'alpha':
2890 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2891 break;
2892 case 'num':
2893 $value = preg_replace('/[^0-9]/', '', $value);
2894 break;
2895 case 'alphanum':
2896 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2897 break;
2898 case 'alphanum_x':
2899 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2900 break;
2901 case 'domainname':
2902 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2903 $value = GeneralUtility::idnaEncode($value);
2904 }
2905 break;
2906 case 'email':
2907 if ((string)$value !== '') {
2908 $this->checkValue_input_ValidateEmail($value, $set);
2909 }
2910 break;
2911 default:
2912 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2913 if (class_exists($func)) {
2914 $evalObj = GeneralUtility::makeInstance($func);
2915 if (method_exists($evalObj, 'evaluateFieldValue')) {
2916 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2917 }
2918 }
2919 }
2920 }
2921 }
2922 if ($set) {
2923 $res['value'] = $value;
2924 }
2925 return $res;
2926 }