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