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