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