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