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