[BUGFIX] Fixed permissions of media field in page properties
[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 if (isset($curValueRec[$field])) {
1639 $curValue = $curValueRec[$field];
1640 }
1641 }
1642
1643 // Getting config for the field
1644 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1645
1646 // Create $recFID only for those types that need it
1647 if (
1648 $tcaFieldConf['type'] === 'flex'
1649 || $tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' || $tcaFieldConf['internal_type'] === 'file_reference')
1650 ) {
1651 $recFID = $table . ':' . $id . ':' . $field;
1652 } else {
1653 $recFID = NULL;
1654 }
1655
1656 // Perform processing:
1657 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1658 return $res;
1659 }
1660
1661 /**
1662 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1663 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1664 *
1665 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1666 * @param string $value The value to set.
1667 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1668 * @param string $table Table name
1669 * @param int $id UID of record
1670 * @param mixed $curValue Current value of the field
1671 * @param string $status 'update' or 'new' flag
1672 * @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.
1673 * @param string $recFID Field identifier [table:uid:field] for flexforms
1674 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1675 * @param array $uploadedFiles
1676 * @param int $tscPID TSconfig PID
1677 * @param array $additionalData Additional data to be forwarded to sub-processors
1678 * @return array Returns the evaluated $value as key "value" in this array.
1679 */
1680 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = NULL) {
1681 // Convert to NULL value if defined in TCA
1682 if ($value === NULL && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1683 $res = array('value' => NULL);
1684 return $res;
1685 }
1686
1687 switch ($tcaFieldConf['type']) {
1688 case 'text':
1689 $res = $this->checkValueForText($value, $tcaFieldConf);
1690 break;
1691 case 'passthrough':
1692 case 'imageManipulation':
1693 case 'user':
1694 $res['value'] = $value;
1695 break;
1696 case 'input':
1697 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1698 break;
1699 case 'check':
1700 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1701 break;
1702 case 'radio':
1703 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1704 break;
1705 case 'group':
1706 case 'select':
1707 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1708 break;
1709 case 'inline':
1710 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1711 break;
1712 case 'flex':
1713 // FlexForms are only allowed for real fields.
1714 if ($field) {
1715 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1716 }
1717 break;
1718 default:
1719 // Do nothing
1720 }
1721 return $res;
1722 }
1723
1724 /**
1725 * Evaluate "text" type values.
1726 *
1727 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1728 * @param string $value The value to set.
1729 * @param array $tcaFieldConf Field configuration from TCA
1730 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1731 * @param string $field Field name
1732 * @return array Modified $res array
1733 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1734 */
1735 public function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
1736 GeneralUtility::logDeprecatedFunction();
1737 return $this->checkValueForText($value, $tcaFieldConf);
1738 }
1739
1740 /**
1741 * Evaluate "text" type values.
1742 *
1743 * @param string $value The value to set.
1744 * @param array $tcaFieldConf Field configuration from TCA
1745 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1746 */
1747 protected function checkValueForText($value, $tcaFieldConf) {
1748 if (!isset($tcaFieldConf['eval']) || $tcaFieldConf['eval'] === '') {
1749 return array('value' => $value);
1750 }
1751 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1752 if ($this->runtimeCache->has($cacheId)) {
1753 $evalCodesArray = $this->runtimeCache->get($cacheId);
1754 } else {
1755 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1756 $this->runtimeCache->set($cacheId, $evalCodesArray);
1757 }
1758 return $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1759 }
1760
1761 /**
1762 * Evaluate "input" type values.
1763 *
1764 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1765 * @param string $value The value to set.
1766 * @param array $tcaFieldConf Field configuration from TCA
1767 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1768 * @param string $field Field name
1769 * @return array Modified $res array
1770 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1771 */
1772 public function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
1773 GeneralUtility::logDeprecatedFunction();
1774 list($table, $id, , , $realPid) = $PP;
1775 return $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1776 }
1777
1778 /**
1779 * Evaluate "input" type values.
1780 *
1781 * @param string $value The value to set.
1782 * @param array $tcaFieldConf Field configuration from TCA
1783 * @param string $table Table name
1784 * @param int $id UID of record
1785 * @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.
1786 * @param string $field Field name
1787 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1788 */
1789 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field) {
1790 // Handle native date/time fields
1791 $isDateOrDateTimeField = FALSE;
1792 $format = '';
1793 $emptyValue = '';
1794 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' || $tcaFieldConf['dbType'] === 'datetime')) {
1795 $isDateOrDateTimeField = TRUE;
1796 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
1797 // Convert the date/time into a timestamp for the sake of the checks
1798 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1799 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1800 // At this point in the processing, the timestamps are still based on UTC
1801 $timeZone = new \DateTimeZone('UTC');
1802 $dateTime = \DateTime::createFromFormat('!' . $format, $value, $timeZone);
1803 $value = $value === $emptyValue ? 0 : $dateTime->getTimestamp();
1804 }
1805 // Secures the string-length to be less than max.
1806 if ((int)$tcaFieldConf['max'] > 0) {
1807 $value = $GLOBALS['LANG']->csConvObj->substr($GLOBALS['LANG']->charSet, $value, 0, (int)$tcaFieldConf['max']);
1808 }
1809 // Checking range of value:
1810 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1811 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1812 $value = $tcaFieldConf['range']['upper'];
1813 }
1814 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1815 $value = $tcaFieldConf['range']['lower'];
1816 }
1817 }
1818
1819 if (empty($tcaFieldConf['eval'])) {
1820 $res = array('value' => $value);
1821 } else {
1822 // Process evaluation settings:
1823 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1824 if ($this->runtimeCache->has($cacheId)) {
1825 $evalCodesArray = $this->runtimeCache->get($cacheId);
1826 } else {
1827 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1828 $this->runtimeCache->set($cacheId, $evalCodesArray);
1829 }
1830
1831 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1832
1833 // Process UNIQUE settings:
1834 // 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...
1835 if ($field && $realPid >= 0 && !empty($res['value'])) {
1836 if (in_array('uniqueInPid', $evalCodesArray, TRUE)) {
1837 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1838 }
1839 if ($res['value'] && in_array('unique', $evalCodesArray, TRUE)) {
1840 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1841 }
1842 }
1843 }
1844
1845 // Handle native date/time fields
1846 if ($isDateOrDateTimeField) {
1847 // Convert the timestamp back to a date/time
1848 $res['value'] = $res['value'] ? date($format, $res['value']) : $emptyValue;
1849 }
1850 return $res;
1851 }
1852
1853 /**
1854 * Evaluates 'check' type values.
1855 *
1856 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1857 * @param string $value The value to set.
1858 * @param array $tcaFieldConf Field configuration from TCA
1859 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1860 * @param string $field Field name
1861 * @return array Modified $res array
1862 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1863 */
1864 public function checkValue_check($res, $value, $tcaFieldConf, $PP, $field = '') {
1865 GeneralUtility::logDeprecatedFunction();
1866 list($table, $id, , , $realPid) = $PP;
1867 return $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1868 }
1869
1870 /**
1871 * Evaluates 'check' type values.
1872 *
1873 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1874 * @param string $value The value to set.
1875 * @param array $tcaFieldConf Field configuration from TCA
1876 * @param string $table Table name
1877 * @param int $id UID of record
1878 * @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.
1879 * @param string $field Field name
1880 * @return array Modified $res array
1881 */
1882 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field) {
1883 $itemC = count($tcaFieldConf['items']);
1884 if (!$itemC) {
1885 $itemC = 1;
1886 }
1887 $maxV = pow(2, $itemC) - 1;
1888 if ($value < 0) {
1889 $value = 0;
1890 }
1891 if ($value > $maxV) {
1892 $value = $maxV;
1893 }
1894 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1895 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1896 $otherRecordsWithSameValue = array();
1897 $maxCheckedRecords = 0;
1898 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, TRUE)) {
1899 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1900 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1901 }
1902 if (in_array('maximumRecordsChecked', $evalCodesArray, TRUE)) {
1903 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1904 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1905 }
1906
1907 // there are more than enough records with value "1" in the DB
1908 // if so, set this value to "0" again
1909 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1910 $value = 0;
1911 if ($this->enableLogging) {
1912 $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));
1913 }
1914 }
1915 }
1916 $res['value'] = $value;
1917 return $res;
1918 }
1919
1920 /**
1921 * Evaluates 'radio' type values.
1922 *
1923 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1924 * @param string $value The value to set.
1925 * @param array $tcaFieldConf Field configuration from TCA
1926 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1927 * @return array Modified $res array
1928 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1929 */
1930 public function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
1931 GeneralUtility::logDeprecatedFunction();
1932 // 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()
1933 return $this->checkValueForRadio($res, $value, $tcaFieldConf, $PP[0], $PP[1], $PP[4], '');
1934 }
1935
1936 /**
1937 * Evaluates 'radio' type values.
1938 *
1939 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1940 * @param string $value The value to set.
1941 * @param array $tcaFieldConf Field configuration from TCA
1942 * @param array $table The table of the record
1943 * @param int $id The id of the record
1944 * @param int $pid The pid of the record
1945 * @param string $field The field to check
1946 * @return array Modified $res array
1947 */
1948 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field) {
1949 if (is_array($tcaFieldConf['items'])) {
1950 foreach ($tcaFieldConf['items'] as $set) {
1951 if ((string)$set[1] === (string)$value) {
1952 $res['value'] = $value;
1953 break;
1954 }
1955 }
1956 }
1957
1958 // if no value was found and an itemsProcFunc is defined, check that for the value
1959 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
1960 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1961 $processedItems = $processingService->getProcessingItems($table, $pid, $field, $this->checkValue_currentRecord,
1962 $tcaFieldConf, $tcaFieldConf['items']);
1963
1964 foreach ($processedItems as $set) {
1965 if ((string)$set[1] === (string)$value) {
1966 $res['value'] = $value;
1967 break;
1968 }
1969 }
1970 }
1971
1972 return $res;
1973 }
1974
1975 /**
1976 * Evaluates 'group' or 'select' type values.
1977 *
1978 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1979 * @param string $value The value to set.
1980 * @param array $tcaFieldConf Field configuration from TCA
1981 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1982 * @param array $uploadedFiles
1983 * @param string $field Field name
1984 * @return array Modified $res array
1985 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1986 */
1987 public function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1988 GeneralUtility::logDeprecatedFunction();
1989 list($table, $id, $curValue, $status, , $recFID) = $PP;
1990 return $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1991 }
1992
1993 /**
1994 * Evaluates 'group' or 'select' type values.
1995 *
1996 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1997 * @param string $value The value to set.
1998 * @param array $tcaFieldConf Field configuration from TCA
1999 * @param string $table Table name
2000 * @param int $id UID of record
2001 * @param mixed $curValue Current value of the field
2002 * @param string $status 'update' or 'new' flag
2003 * @param string $recFID Field identifier [table:uid:field] for flexforms
2004 * @param array $uploadedFiles
2005 * @param string $field Field name
2006 * @return array Modified $res array
2007 */
2008 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field) {
2009 // Detecting if value sent is an array and if so, implode it around a comma:
2010 if (is_array($value)) {
2011 $value = implode(',', $value);
2012 }
2013 // 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.
2014 // Anyway, this should NOT disturb anything else:
2015 $value = $this->convNumEntityToByteValue($value);
2016 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
2017 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
2018 // If multiple is not set, remove duplicates:
2019 if (!$tcaFieldConf['multiple']) {
2020 $valueArray = array_unique($valueArray);
2021 }
2022 // If an exclusive key is found, discard all others:
2023 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
2024 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
2025 foreach ($valueArray as $index => $key) {
2026 if (in_array($key, $exclusiveKeys, TRUE)) {
2027 $valueArray = array($index => $key);
2028 break;
2029 }
2030 }
2031 }
2032 // 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?)
2033 // 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!!
2034 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2035 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
2036 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
2037 $preCount = count($valueArray);
2038 foreach ($valueArray as $index => $key) {
2039 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
2040 unset($valueArray[$index]);
2041 }
2042 }
2043 // 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.
2044 if ($preCount && empty($valueArray)) {
2045 return array();
2046 }
2047 }
2048 // For group types:
2049 if ($tcaFieldConf['type'] == 'group') {
2050 switch ($tcaFieldConf['internal_type']) {
2051 case 'file_reference':
2052
2053 case 'file':
2054 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
2055 break;
2056 case 'db':
2057 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
2058 break;
2059 }
2060 }
2061 // For select types which has a foreign table attached:
2062 $unsetResult = FALSE;
2063 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
2064 // check, if there is a NEW... id in the value, that should be substituted later
2065 if (strpos($value, 'NEW') !== FALSE) {
2066 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
2067 $this->addNewValuesToRemapStackChildIds($valueArray);
2068 $this->remapStack[] = array(
2069 'func' => 'checkValue_group_select_processDBdata',
2070 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
2071 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
2072 'field' => $field
2073 );
2074 $unsetResult = TRUE;
2075 } else {
2076 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
2077 }
2078 }
2079 if (!$unsetResult) {
2080 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2081 $res['value'] = implode(',', $newVal);
2082 } else {
2083 unset($res['value']);
2084 }
2085 return $res;
2086 }
2087
2088 /**
2089 * Applies the filter methods from a column's TCA configuration to a value array.
2090 *
2091 * @param array $tcaFieldConfiguration
2092 * @param array $values
2093 * @return array|mixed
2094 * @throws \RuntimeException
2095 */
2096 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values) {
2097 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
2098 return $values;
2099 }
2100 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2101 if (empty($filter['userFunc'])) {
2102 continue;
2103 }
2104 $parameters = $filter['parameters'] ?: array();
2105 $parameters['values'] = $values;
2106 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2107 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
2108 if (!is_array($values)) {
2109 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
2110 }
2111 }
2112 return $values;
2113 }
2114
2115 /**
2116 * Handling files for group/select function
2117 *
2118 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2119 * @param array $tcaFieldConf Configuration array from TCA of the field
2120 * @param string $curValue Current value of the field
2121 * @param array $uploadedFileArray Array of uploaded files, if any
2122 * @param string $status 'update' or 'new' flag
2123 * @param string $table tablename of record
2124 * @param int $id UID of record
2125 * @param string $recFID Field identifier [table:uid:field] for flexforms
2126 * @return array Modified value array
2127 *
2128 * @throws \RuntimeException
2129 * @see checkValue_group_select()
2130 */
2131 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
2132 // If file handling should NOT be bypassed, do processing:
2133 if (!$this->bypassFileHandling) {
2134 // If any files are uploaded, add them to value array
2135 // Numeric index means that there are multiple files
2136 if (isset($uploadedFileArray[0])) {
2137 $uploadedFiles = $uploadedFileArray;
2138 } else {
2139 // There is only one file
2140 $uploadedFiles = array($uploadedFileArray);
2141 }
2142 foreach ($uploadedFiles as $uploadedFileArray) {
2143 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2144 $valueArray[] = $uploadedFileArray['tmp_name'];
2145 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2146 }
2147 }
2148 // Creating fileFunc object.
2149 if (!$this->fileFunc) {
2150 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
2151 $this->include_filefunctions = 1;
2152 }
2153 // Setting permitted extensions.
2154 $all_files = array();
2155 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
2156 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
2157 $all_files['ftpspace'] = $all_files['webspace'];
2158 $this->fileFunc->init('', $all_files);
2159 }
2160 // If there is an upload folder defined:
2161 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
2162 $currentFilesForHistory = NULL;
2163 // If filehandling should NOT be bypassed, do processing:
2164 if (!$this->bypassFileHandling) {
2165 // For logging..
2166 $propArr = $this->getRecordProperties($table, $id);
2167 // Get destrination path:
2168 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
2169 // If we are updating:
2170 if ($status == 'update') {
2171 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2172 // 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!
2173 // 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_.
2174 // 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.
2175 // Illustration of the problem comes here:
2176 // 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.
2177 // 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.
2178 // 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.
2179 // 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.
2180 if ($this->autoVersioningUpdate === TRUE) {
2181 foreach ($valueArray as $key => $theFile) {
2182 // If it is an already attached file...
2183 if ($theFile === basename($theFile)) {
2184 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2185 }
2186 }
2187 }
2188 // Finding the CURRENT files listed, either from MM or from the current record.
2189 $theFileValues = array();
2190 // If MM relations for the files also!
2191 if ($tcaFieldConf['MM']) {
2192 $dbAnalysis = $this->createRelationHandlerInstance();
2193 /** @var $dbAnalysis RelationHandler */
2194 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2195 foreach ($dbAnalysis->itemArray as $item) {
2196 if ($item['id']) {
2197 $theFileValues[] = $item['id'];
2198 }
2199 }
2200 } else {
2201 $theFileValues = GeneralUtility::trimExplode(',', $curValue, TRUE);
2202 }
2203 $currentFilesForHistory = implode(',', $theFileValues);
2204 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2205 if (!empty($theFileValues)) {
2206 // 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!)
2207 foreach ($valueArray as $key => $theFile) {
2208 if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
2209 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
2210 }
2211 }
2212 // This array contains the filenames in the uploadfolder that should be deleted:
2213 foreach ($theFileValues as $key => $theFile) {
2214 $theFile = trim($theFile);
2215 if (@is_file(($dest . '/' . $theFile))) {
2216 $this->removeFilesStore[] = $dest . '/' . $theFile;
2217 } elseif ($this->enableLogging && $theFile) {
2218 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
2219 }
2220 }
2221 }
2222 }
2223 // Traverse the submitted values:
2224 foreach ($valueArray as $key => $theFile) {
2225 // Init:
2226 $maxSize = (int)$tcaFieldConf['max_size'];
2227 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2228 $theDestFile = '';
2229 // a FAL file was added, now resolve the file object and get the absolute path
2230 // @todo in future versions this needs to be modified to handle FAL objects natively
2231 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2232 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2233 $theFile = $fileObject->getForLocalProcessing(FALSE);
2234 }
2235 // NEW FILES? If the value contains '/' it indicates, that the file
2236 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2237 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
2238 // Check various things before copying file:
2239 // File and destination must exist
2240 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
2241 // Finding size.
2242 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2243 $fileSize = $uploadedFileArray['size'];
2244 } else {
2245 $fileSize = filesize($theFile);
2246 }
2247 // Check file size:
2248 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2249 // Prepare filename:
2250 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2251 $fI = GeneralUtility::split_fileref($theEndFileName);
2252 // Check for allowed extension:
2253 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2254 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2255 // If we have a unique destination filename, then write the file:
2256 if ($theDestFile) {
2257 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2258 // Hook for post-processing the upload action
2259 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2260 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2261 $hookObject = GeneralUtility::getUserObj($classRef);
2262 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2263 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\DataHandling\\DataHandlerProcessUploadHookInterface', 1279962349);
2264 }
2265 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2266 }
2267 }
2268 $this->copiedFileMap[$theFile] = $theDestFile;
2269 clearstatcache();
2270 if ($this->enableLogging && !@is_file($theDestFile)) {
2271 $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']);
2272 }
2273 } elseif ($this->enableLogging) {
2274 $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']);
2275 }
2276 } elseif ($this->enableLogging) {
2277 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2278 }
2279 } elseif ($this->enableLogging) {
2280 $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']);
2281 }
2282 } elseif ($this->enableLogging) {
2283 $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']);
2284 }
2285 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2286 if (@is_file($theDestFile)) {
2287 $info = GeneralUtility::split_fileref($theDestFile);
2288 // The value is set to the new filename
2289 $valueArray[$key] = $info['file'];
2290 } else {
2291 // The value is set to the new filename
2292 unset($valueArray[$key]);
2293 }
2294 }
2295 }
2296 }
2297 // 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!
2298 if ($tcaFieldConf['MM']) {
2299 /** @var $dbAnalysis RelationHandler */
2300 $dbAnalysis = $this->createRelationHandlerInstance();
2301 // Dummy
2302 $dbAnalysis->tableArray['files'] = array();
2303 foreach ($valueArray as $key => $theFile) {
2304 // Explode files
2305 $dbAnalysis->itemArray[]['id'] = $theFile;
2306 }
2307 if ($status == 'update') {
2308 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2309 $newFiles = implode(',', $dbAnalysis->getValueArray());
2310 list(, , $recFieldName) = explode(':', $recFID);
2311 if ($currentFilesForHistory != $newFiles) {
2312 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2313 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2314 } else {
2315 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2316 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2317 }
2318 } else {
2319 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
2320 }
2321 $valueArray = $dbAnalysis->countItems();
2322 }
2323 } else {
2324 if (!empty($valueArray)) {
2325 // If filehandling should NOT be bypassed, do processing:
2326 if (!$this->bypassFileHandling) {
2327 // For logging..
2328 $propArr = $this->getRecordProperties($table, $id);
2329 foreach ($valueArray as &$theFile) {
2330 // FAL handling: it's a UID, thus it is resolved to the absolute path
2331 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2332 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2333 $theFile = $fileObject->getForLocalProcessing(FALSE);
2334 }
2335 if ($this->alternativeFilePath[$theFile]) {
2336 // If alternative File Path is set for the file, then it was an import
2337 // don't import the file if it already exists
2338 if (@is_file((PATH_site . $this->alternativeFilePath[$theFile]))) {
2339 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
2340 } elseif (@is_file($theFile)) {
2341 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
2342 if (!@is_dir($dest)) {
2343 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
2344 }
2345 // Init:
2346 $maxSize = (int)$tcaFieldConf['max_size'];
2347 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2348 $theDestFile = '';
2349 $fileSize = filesize($theFile);
2350 // Check file size:
2351 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2352 // Prepare filename:
2353 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2354 $fI = GeneralUtility::split_fileref($theEndFileName);
2355 // Check for allowed extension:
2356 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2357 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
2358 // Write the file:
2359 if ($theDestFile) {
2360 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2361 $this->copiedFileMap[$theFile] = $theDestFile;
2362 clearstatcache();
2363 if ($this->enableLogging && !@is_file($theDestFile)) {
2364 $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']);
2365 }
2366 } elseif ($this->enableLogging) {
2367 $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']);
2368 }
2369 } elseif ($this->enableLogging) {
2370 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2371 }
2372 } elseif ($this->enableLogging) {
2373 $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']);
2374 }
2375 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2376 if (@is_file($theDestFile)) {
2377 // The value is set to the new filename
2378 $theFile = $theDestFile;
2379 } else {
2380 // The value is set to the new filename
2381 unset($theFile);
2382 }
2383 }
2384 }
2385 if (!empty($theFile)) {
2386 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2387 if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
2388 $theFile = PathUtility::stripPathSitePrefix($theFile);
2389 }
2390 }
2391 }
2392 unset($theFile);
2393 }
2394 }
2395 }
2396 return $valueArray;
2397 }
2398
2399 /**
2400 * Evaluates 'flex' type values.
2401 *
2402 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2403 * @param string|array $value The value to set.
2404 * @param array $tcaFieldConf Field configuration from TCA
2405 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2406 * @param array $uploadedFiles Uploaded files for the field
2407 * @param string $field Field name
2408 * @return array Modified $res array
2409 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
2410 */
2411 public function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
2412 GeneralUtility::logDeprecatedFunction();
2413 list($table, $id, $curValue, $status, $realPid, $recFID, $tscPID) = $PP;
2414 $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
2415 }
2416
2417 /**
2418 * Evaluates 'flex' type values.
2419 *
2420 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2421 * @param string|array $value The value to set.
2422 * @param array $tcaFieldConf Field configuration from TCA
2423 * @param string $table Table name
2424 * @param int $id UID of record
2425 * @param mixed $curValue Current value of the field
2426 * @param string $status 'update' or 'new' flag
2427 * @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.
2428 * @param string $recFID Field identifier [table:uid:field] for flexforms
2429 * @param int $tscPID TSconfig PID
2430 * @param array $uploadedFiles Uploaded files for the field
2431 * @param string $field Field name
2432 * @return array Modified $res array
2433 */
2434 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field) {
2435
2436 if (is_array($value)) {
2437 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2438 // 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
2439 // 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.
2440 // Only active when larger than zero.
2441 $newRecordPidValue = $status == 'new' ? $realPid : 0;
2442 // Get current value array:
2443 $dataStructArray = BackendUtility::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, $field, TRUE, $newRecordPidValue);
2444 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : array();
2445 if (!is_array($currentValueArray)) {
2446 $currentValueArray = array();
2447 }
2448 if (is_array($currentValueArray['meta']['currentLangId'])) {
2449 unset($currentValueArray['meta']['currentLangId']);
2450 }
2451 // Remove all old meta for languages...
2452 // Evaluation of input values:
2453 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID));
2454 // Create XML from input value:
2455 $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
2456
2457 // 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
2458 // (provided that the current value was already stored IN the charset that the new value is converted to).
2459 $arrValue = GeneralUtility::xml2array($xmlValue);
2460
2461 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2462 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2463 $hookObject = GeneralUtility::getUserObj($classRef);
2464 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2465 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2466 }
2467 }
2468 }
2469
2470 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2471 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, TRUE);
2472
2473 // Action commands (sorting order and removals of elements) for flexform sections,
2474 // see FormEngine for the use of this GP parameter
2475 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2476 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2477 $arrValue = GeneralUtility::xml2array($xmlValue);
2478 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2479 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
2480 }
2481 // Create the value XML:
2482 $res['value'] = '';
2483 $res['value'] .= $xmlValue;
2484 } else {
2485 // Passthrough...:
2486 $res['value'] = $value;
2487 }
2488
2489 return $res;
2490 }
2491
2492 /**
2493 * Converts an array to FlexForm XML
2494 *
2495 * @param array $array Array with FlexForm data
2496 * @param bool $addPrologue If set, the XML prologue is returned as well.
2497 * @return string Input array converted to XML
2498 */
2499 public function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
2500 /** @var $flexObj FlexFormTools */
2501 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2502 return $flexObj->flexArray2Xml($array, $addPrologue);
2503 }
2504
2505 /**
2506 * Actions for flex form element (move, delete)
2507 * allows to remove and move flexform sections
2508 *
2509 * @param array $valueArray by reference
2510 * @param array $actionCMDs
2511 */
2512 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
2513 if (!is_array($valueArray) || !is_array($actionCMDs)) {
2514 return;
2515 }
2516
2517 foreach ($actionCMDs as $key => $value) {
2518 if ($key == '_ACTION') {
2519 // First, check if there are "commands":
2520 if (current($actionCMDs[$key]) === '') {
2521 continue;
2522 }
2523
2524 asort($actionCMDs[$key]);
2525 $newValueArray = array();
2526 foreach ($actionCMDs[$key] as $idx => $order) {
2527 if (substr($idx, 0, 3) == 'ID-') {
2528 $idx = $this->newIndexMap[$idx];
2529 }
2530 // 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.
2531 if ($order != 'DELETE') {
2532 $newValueArray[$idx] = $valueArray[$idx];
2533 }
2534 unset($valueArray[$idx]);
2535 }
2536 $valueArray = $valueArray + $newValueArray;
2537 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2538 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2539 }
2540 }
2541 }
2542
2543 /**
2544 * Evaluates 'inline' type values.
2545 * (partly copied from the select_group function on this issue)
2546 *
2547 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2548 * @param string $value The value to set.
2549 * @param array $tcaFieldConf Field configuration from TCA
2550 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2551 * @param string $field Field name
2552 * @param array $additionalData Additional data to be forwarded to sub-processors
2553 * @return array Modified $res array
2554 */
2555 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = NULL) {
2556 list($table, $id, , $status) = $PP;
2557 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2558 }
2559
2560 /**
2561 * Evaluates 'inline' type values.
2562 * (partly copied from the select_group function on this issue)
2563 *
2564 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2565 * @param string $value The value to set.
2566 * @param array $tcaFieldConf Field configuration from TCA
2567 * @param string $table Table name
2568 * @param int $id UID of record
2569 * @param string $status 'update' or 'new' flag
2570 * @param string $field Field name
2571 * @param array $additionalData Additional data to be forwarded to sub-processors
2572 * @return array Modified $res array
2573 */
2574 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = NULL) {
2575 if (!$tcaFieldConf['foreign_table']) {
2576 // Fatal error, inline fields should always have a foreign_table defined
2577 return FALSE;
2578 }
2579 // When values are sent they come as comma-separated values which are exploded by this function:
2580 $valueArray = GeneralUtility::trimExplode(',', $value);
2581 // Remove duplicates: (should not be needed)
2582 $valueArray = array_unique($valueArray);
2583 // Example for received data:
2584 // $value = 45,NEW4555fdf59d154,12,123
2585 // We need to decide whether we use the stack or can save the relation directly.
2586 if (strpos($value, 'NEW') !== FALSE || !MathUtility::canBeInterpretedAsInteger($id)) {
2587 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
2588 $this->addNewValuesToRemapStackChildIds($valueArray);
2589 $this->remapStack[] = array(
2590 'func' => 'checkValue_inline_processDBdata',
2591 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData),
2592 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
2593 'additionalData' => $additionalData,
2594 'field' => $field,
2595 );
2596 unset($res['value']);
2597 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2598 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2599 }
2600 return $res;
2601 }
2602
2603 /**
2604 * Checks if a fields has more items than defined via TCA in maxitems.
2605 * If there are more items than allowd, the item list is truncated to the defined number.
2606 *
2607 * @param array $tcaFieldConf Field configuration from TCA
2608 * @param array $valueArray Current value array of items
2609 * @return array The truncated value array of items
2610 */
2611 public function checkValue_checkMax($tcaFieldConf, $valueArray) {
2612 // 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...
2613 $valueArrayC = count($valueArray);
2614 // 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.
2615 $maxI = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 1;
2616 if ($valueArrayC > $maxI) {
2617 $valueArrayC = $maxI;
2618 }
2619 // Checking for not too many elements
2620 // Dumping array to list
2621 $newVal = array();
2622 foreach ($valueArray as $nextVal) {
2623 if ($valueArrayC == 0) {
2624 break;
2625 }
2626 $valueArrayC--;
2627 $newVal[] = $nextVal;
2628 }
2629 return $newVal;
2630 }
2631
2632 /*********************************************
2633 *
2634 * Helper functions for evaluation functions.
2635 *
2636 ********************************************/
2637 /**
2638 * Gets a unique value for $table/$id/$field based on $value
2639 *
2640 * @param string $table Table name
2641 * @param string $field Field name for which $value must be unique
2642 * @param string $value Value string.
2643 * @param int $id UID to filter out in the lookup (the record itself...)
2644 * @param int $newPid If set, the value will be unique for this PID
2645 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2646 */
2647 public function getUnique($table, $field, $value, $id, $newPid = 0) {
2648 // Initialize:
2649 $whereAdd = '';
2650 $newValue = '';
2651 if ((int)$newPid) {
2652 $whereAdd .= ' AND pid=' . (int)$newPid;
2653 } else {
2654 $whereAdd .= ' AND pid>=0';
2655 }
2656 // "AND pid>=0" for versioning
2657 $whereAdd .= $this->deleteClause($table);
2658 // If the field is configured in TCA, proceed:
2659 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2660 // Look for a record which might already have the value:
2661 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($value, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2662 $counter = 0;
2663 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2664 while ($this->databaseConnection->sql_num_rows($res)) {
2665 $newValue = $value . $counter;
2666 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($newValue, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2667 $counter++;
2668 if ($counter > 100) {
2669 break;
2670 }
2671 }
2672 $this->databaseConnection->sql_free_result($res);
2673 // If the new value is there:
2674 $value = $newValue !== '' ? $newValue : $value;
2675 }
2676 return $value;
2677 }
2678
2679 /**
2680 * gets all records that have the same value in a field
2681 * excluding the given uid
2682 *
2683 * @param string $tableName Table name
2684 * @param int $uid UID to filter out in the lookup (the record itself...)
2685 * @param string $fieldName Field name for which $value must be unique
2686 * @param string $value Value string.
2687 * @param int $pageId If set, the value will be unique for this PID
2688 * @return array
2689 */
2690 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0) {
2691 $result = array();
2692 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2693
2694 $uid = (int)$uid;
2695 $pageId = (int)$pageId;
2696 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ? 'pid = ' . $pageId : 'pid >= 0');
2697 $result = BackendUtility::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2698 }
2699 return $result;
2700 }
2701
2702 /**
2703 * @param string $value The field value to be evaluated
2704 * @param array $evalArray Array of evaluations to traverse.
2705 * @param string $is_in The "is_in" value of the field configuration from TCA
2706 * @return array
2707 */
2708 public function checkValue_text_Eval($value, $evalArray, $is_in) {
2709 $res = array();
2710 $set = TRUE;
2711 foreach ($evalArray as $func) {
2712 switch ($func) {
2713 case 'trim':
2714 $value = trim($value);
2715 break;
2716 case 'required':
2717 if (!$value) {
2718 $set = FALSE;
2719 }
2720 break;
2721 default:
2722 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2723 if (class_exists($func)) {
2724 $evalObj = GeneralUtility::makeInstance($func);
2725 if (method_exists($evalObj, 'evaluateFieldValue')) {
2726 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2727 }
2728 }
2729 }
2730 }
2731 }
2732 if ($set) {
2733 $res['value'] = $value;
2734 }
2735 return $res;
2736 }
2737
2738 /**
2739 * Evaluation of 'input'-type values based on 'eval' list
2740 *
2741 * @param string $value Value to evaluate
2742 * @param array $evalArray Array of evaluations to traverse.
2743 * @param string $is_in Is-in string for 'is_in' evaluation
2744 * @return array Modified $value in key 'value' or empty array
2745 */
2746 public function checkValue_input_Eval($value, $evalArray, $is_in) {
2747 $res = array();
2748 $set = TRUE;
2749 foreach ($evalArray as $func) {
2750 switch ($func) {
2751 case 'int':
2752 case 'year':
2753 case 'time':
2754 case 'timesec':
2755 $value = (int)$value;
2756 break;
2757 case 'date':
2758 case 'datetime':
2759 $value = (int)$value;
2760 if ($value > 0 && !$this->dontProcessTransformations) {
2761 $value -= date('Z', $value);
2762 }
2763 break;
2764 case 'double2':
2765 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2766 $negative = $value[0] === '-';
2767 $value = strtr($value, array(',' => '.', '-' => ''));
2768 if (strpos($value, '.') === FALSE) {
2769 $value .= '.0';
2770 }
2771 $valueArray = explode('.', $value);
2772 $dec = array_pop($valueArray);
2773 $value = join('', $valueArray) . '.' . $dec;
2774 if ($negative) {
2775 $value *= -1;
2776 }
2777 $value = number_format($value, 2, '.', '');
2778 break;
2779 case 'md5':
2780 if (strlen($value) != 32) {
2781 $set = FALSE;
2782 }
2783 break;
2784 case 'trim':
2785 $value = trim($value);
2786 break;
2787 case 'upper':
2788 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toUpper');
2789 break;
2790 case 'lower':
2791 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toLower');
2792 break;
2793 case 'required':
2794 if (!isset($value) || $value === '') {
2795 $set = FALSE;
2796 }
2797 break;
2798 case 'is_in':
2799 $c = strlen($value);
2800 if ($c) {
2801 $newVal = '';
2802 for ($a = 0; $a < $c; $a++) {
2803 $char = substr($value, $a, 1);
2804 if (strpos($is_in, $char) !== FALSE) {
<