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