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