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