DataHandler.php 322 KB
Newer Older
1
<?php
2
namespace TYPO3\CMS\Core\DataHandling;
3
4
5
6

/***************************************************************
 *  Copyright notice
 *
7
 *  (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *  A copy is found in the textfile GPL.txt and important notices to the license
 *  from the author is found in LICENSE.txt distributed with these scripts.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
/**
 * Contains the TYPO3 Core Engine
 *
 * Revised for TYPO3 3.9 October 2005 by Kasper Skårhøj
 *
 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
 */
/**
 * This is the TYPO3 Core Engine class for manipulation of the database
 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
 *
 * Dependencies:
 * - $GLOBALS['TCA'] must exist
 * - $GLOBALS['LANG'] must exist
 *
 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
 *
 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
 */
class DataHandler {

	// *********************
	// Public variables you can configure before using the class:
	// *********************
	// Boolean: If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
	/**
	 * @todo Define visibility
	 */
	public $storeLogMessages = TRUE;

	// Boolean: If TRUE, actions are logged to sys_log.
	/**
	 * @todo Define visibility
	 */
	public $enableLogging = TRUE;

	// Boolean: If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
	/**
	 * @todo Define visibility
	 */
	public $reverseOrder = FALSE;

	// Boolean: If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array is similar, it's not saved then.
	/**
	 * @todo Define visibility
	 */
	public $checkSimilar = TRUE;

	// Boolean: If TRUE, incoming values in the data-array have their slashes stripped. ALWAYS SET THIS TO ZERO and supply an unescaped data array instead. This switch may totally disappear in future versions of this class!
	/**
	 * @todo Define visibility
	 */
	public $stripslashes_values = TRUE;

	// Boolean: This will read the record after having updated or inserted it. If anything is not properly submitted an error is written to the log. This feature consumes extra time by selecting records
	/**
	 * @todo Define visibility
	 */
	public $checkStoredRecords = TRUE;

	// Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
	/**
	 * @todo Define visibility
	 */
	public $checkStoredRecords_loose = TRUE;

	// Boolean. If this is set, then a page is deleted by deleting the whole branch under it (user must have deletepermissions to it all). If not set, then the page is deleted ONLY if it has no branch
	/**
	 * @todo Define visibility
	 */
	public $deleteTree = FALSE;

	// Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
	/**
	 * @todo Define visibility
	 */
	public $neverHideAtCopy = FALSE;

	// Boolean: If set, then transformations are NOT performed on the input.
	/**
	 * @todo Define visibility
	 */
	public $dontProcessTransformations = FALSE;

	// Boolean: If set, .vDEFbase values are unset in flexforms.
	/**
	 * @todo Define visibility
	 */
	public $clear_flexFormData_vDEFbase = FALSE;

	// Boolean/Mixed: TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value. FALSE: Will not update anything. "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
	/**
	 * @todo Define visibility
	 */
	public $updateModeL10NdiffData = TRUE;

	// Boolean: If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again! It's meant as the opposite of declaring the record translated.
	/**
	 * @todo Define visibility
	 */
	public $updateModeL10NdiffDataClear = FALSE;

	// Boolean: If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()). YOU MUST KNOW what you do if you use this feature!
	/**
	 * @todo Define visibility
	 */
	public $bypassWorkspaceRestrictions = FALSE;

	// Boolean: If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away. YOU MUST KNOW what you are doing with this feature!
	/**
	 * @todo Define visibility
	 */
	public $bypassFileHandling = FALSE;

	// Boolean: If TRUE, access check, check for deleted etc. for records is bypassed. YOU MUST KNOW what you are doing if you use this feature!
	/**
	 * @todo Define visibility
	 */
	public $bypassAccessCheckForRecords = FALSE;

	// String. Comma-list. This list of tables decides which tables will be copied. If empty then none will. If '*' then all will (that the user has permission to of course)
	/**
	 * @todo Define visibility
	 */
	public $copyWhichTables = '*';

	// Integer. If 0 then branch is NOT copied. If 1 then pages on the 1st level is copied. If 2 then pages on the second level is copied ... and so on
	/**
	 * @todo Define visibility
	 */
	public $copyTree = 0;

	// Array [table][fields]=value: New records are created with default values and you can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
	/**
	 * @todo Define visibility
	 */
	public $defaultValues = array();

	// Array [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to override the incoming data. You must set this externally. You must make sure the fields in this array are also found in the table, because it's not checked. All columns can be set by this array!
	/**
	 * @todo Define visibility
	 */
	public $overrideValues = array();

	// Array [filename]=alternative_filename: Use this array to force another name onto a file. Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field, then 'my_file.txt' will be used as the name instead.
	/**
	 * @todo Define visibility
	 */
	public $alternativeFileName = array();

	// Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
	/**
	 * @todo Define visibility
	 */
	public $alternativeFilePath = array();

	// If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated. You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1. Then an empty checkbox will disable the field.
	/**
	 * @todo Define visibility
	 */
	public $data_disableFields = array();

	// Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete). The option is used for import of T3D files when synchronizing between two mirrored servers. As a security measure this feature is available only for Admin Users (for now)
	/**
	 * @todo Define visibility
	 */
	public $suggestedInsertUids = array();

	// Object. Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.
	/**
	 * @todo Define visibility
	 */
	public $callBackObj;

	// *********************
	// Internal variables (mapping arrays) which can be used (read-only) from outside
	// *********************
	// Contains mapping of auto-versionized records.
	/**
	 * @todo Define visibility
	 */
	public $autoVersionIdMap = array();

	// 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
	/**
	 * @todo Define visibility
	 */
	public $substNEWwithIDs = array();

	// Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
	/**
	 * @todo Define visibility
	 */
	public $substNEWwithIDs_table = array();

	// Holds the tables and there the ids of newly created child records from IRRE
	/**
	 * @todo Define visibility
	 */
	public $newRelatedIDs = array();

	// This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
	/**
	 * @todo Define visibility
	 */
	public $copyMappingArray_merged = array();

	// A map between input file name and final destination for files being attached to records.
	/**
	 * @todo Define visibility
	 */
	public $copiedFileMap = array();

	// Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
	/**
	 * @todo Define visibility
	 */
	public $RTEmagic_copyIndex = array();

	// Errors are collected in this variable.
	/**
	 * @todo Define visibility
	 */
	public $errorLog = array();

	// *********************
	// Internal Variables, do not touch.
	// *********************
	// Variables set in init() function:
	/**
	 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
	 *
	 * @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
	 * @todo Define visibility
	 */
	public $BE_USER;

	// Will be set to uid of be_user executing this script
	/**
	 * @todo Define visibility
	 */
	public $userid;

	// Will be set to username of be_user executing this script
	/**
	 * @todo Define visibility
	 */
	public $username;

	// Will be set if user is admin
	/**
	 * @todo Define visibility
	 */
	public $admin;

	// Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
	/**
	 * @todo Define visibility
	 */
	public $defaultPermissions = array(
		'user' => 'show,edit,delete,new,editcontent',
		'group' => 'show,edit,new,editcontent',
		'everybody' => ''
	);

	// 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.
	/**
	 * @todo Define visibility
	 */
	public $exclude_array;

299
300
301
302
303
304
305
306
	/**
	 * Data submitted from the form view, used to control behaviours,
	 * e.g. this is used to activate/deactive fields and thus store NULL values
	 *
	 * @var array
	 */
	protected $control = array();

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
	// Set with incoming data array
	/**
	 * @todo Define visibility
	 */
	public $datamap = array();

	// Set with incoming cmd array
	/**
	 * @todo Define visibility
	 */
	public $cmdmap = array();

	// Internal static:
	// Permission mapping
	/**
	 * @todo Define visibility
	 */
	public $pMap = array(
		'show' => 1,
		// 1st bit
		'edit' => 2,
		// 2nd bit
		'delete' => 4,
		// 3rd bit
		'new' => 8,
		// 4th bit
		'editcontent' => 16
	);

	// Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
	/**
	 * @todo Define visibility
	 */
	public $sortIntervals = 256;

	// Internal caching arrays
	// Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
	/**
	 * @todo Define visibility
	 */
	public $recUpdateAccessCache = array();

	// User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
	/**
	 * @todo Define visibility
	 */
	public $recInsertAccessCache = array();

	// Caching array for check of whether records are in a webmount
	/**
	 * @todo Define visibility
	 */
	public $isRecordInWebMount_Cache = array();

	// Caching array for page ids in webmounts
	/**
	 * @todo Define visibility
	 */
	public $isInWebMount_Cache = array();

	// Caching for collecting TSconfig for page ids
	/**
	 * @todo Define visibility
	 */
	public $cachedTSconfig = array();

	// Used for caching page records in pageInfo()
	/**
	 * @todo Define visibility
	 */
	public $pageCache = array();

	// Array caching workspace access for BE_USER
	/**
	 * @todo Define visibility
	 */
	public $checkWorkspaceCache = array();

	// Other arrays:
	// For accumulation of MM relations that must be written after new records are created.
	/**
	 * @todo Define visibility
	 */
	public $dbAnalysisStore = array();

	// For accumulation of files which must be deleted after processing of all input content
	/**
	 * @todo Define visibility
	 */
	public $removeFilesStore = array();

	// Uploaded files, set by process_uploads()
	/**
	 * @todo Define visibility
	 */
	public $uploadedFileArray = array();

	// Used for tracking references that might need correction after operations
	/**
	 * @todo Define visibility
	 */
	public $registerDBList = array();

	// Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
	/**
	 * @todo Define visibility
	 */
	public $registerDBPids = array();

	// Used by the copy action to track the ids of new pages so subpages are correctly inserted! THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE! Read from copyMappingArray_merged instead which is accumulating this information.
	/**
	 * @todo Define visibility
	 */
	public $copyMappingArray = array();

	// array used for remapping uids and values at the end of process_datamap
	/**
	 * @todo Define visibility
	 */
	public $remapStack = array();

	// array used for remapping uids and values at the end of process_datamap (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
	/**
	 * @todo Define visibility
	 */
	public $remapStackRecords = array();

	// array used for checking whether new children need to be remapped
	protected $remapStackChildIds = array();

	// array used for executing addition actions after remapping happened (sett processRemapStack())
	protected $remapStackActions = array();

	// array used for executing post-processing on the reference index
	protected $remapStackRefIndex = array();

	// array used for additional calls to $this->updateRefIndex
	/**
	 * @todo Define visibility
	 */
	public $updateRefIndexStack = array();

	// tells, that this TCEmain was called from tx_impext - this variable is set by tx_impexp
	/**
	 * @todo Define visibility
	 */
	public $callFromImpExp = FALSE;

	// Array for new flexform index mapping
	/**
	 * @todo Define visibility
	 */
	public $newIndexMap = array();

	// Various
	/**
	 * basicFileFunctions object
	 * For "singleTon" file-manipulation object
	 *
	 * @var \TYPO3\CMS\Core\Utility\File\BasicFileUtility
	 * @todo Define visibility
	 */
	public $fileFunc;

	// Set to "currentRecord" during checking of values.
	/**
	 * @todo Define visibility
	 */
	public $checkValue_currentRecord = array();

	// A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.
	/**
	 * @todo Define visibility
	 */
	public $autoVersioningUpdate = FALSE;

	// Disable delete clause
	protected $disableDeleteClause = FALSE;

	protected $checkModifyAccessListHookObjects;

	protected $version_remapMMForVersionSwap_reg;

	/**
	 * The outer most instance of t3lib_TCEmain
	 * (t3lib_TCEmain instantiates itself on versioning and localization)
	 *
494
	 * @var \TYPO3\CMS\Core\DataHandling\DataHandler
495
496
497
	 */
	protected $outerMostInstance = NULL;

498
499
500
501
502
503
504
	/**
	 * @param array $control
	 */
	public function setControl(array $control) {
		$this->control = $control;
	}

505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
	/**
	 * Initializing.
	 * For details, see 'TYPO3 Core API' document.
	 * This function does not start the processing of data, but merely initializes the object
	 *
	 * @param array $data Data to be modified or inserted in the database
	 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
	 * @param object $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
	 * @return void
	 */
	public function start($data, $cmd, $altUserObject = '') {
		// Initializing BE_USER
		$this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
		$this->userid = $this->BE_USER->user['uid'];
		$this->username = $this->BE_USER->user['username'];
		$this->admin = $this->BE_USER->user['admin'];
		if ($this->BE_USER->uc['recursiveDelete']) {
			$this->deleteTree = 1;
		}
		if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData === TRUE) {
			$this->updateModeL10NdiffData = FALSE;
		}
		// Initializing default permissions for pages
		$defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
		if (isset($defaultPermissions['user'])) {
			$this->defaultPermissions['user'] = $defaultPermissions['user'];
		}
		if (isset($defaultPermissions['group'])) {
			$this->defaultPermissions['group'] = $defaultPermissions['group'];
		}
		if (isset($defaultPermissions['everybody'])) {
			$this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];
		}
		// generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
		$this->exclude_array = $this->admin ? array() : $this->getExcludeListArray();
		// Setting the data and cmd arrays
		if (is_array($data)) {
			reset($data);
			$this->datamap = $data;
		}
		if (is_array($cmd)) {
			reset($cmd);
			$this->cmdmap = $cmd;
		}
	}

	/**
	 * Function that can mirror input values in datamap-array to other uid numbers.
	 * 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]
	 *
	 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
	 * @return void
	 * @todo Define visibility
	 */
	public function setMirror($mirror) {
		if (is_array($mirror)) {
			foreach ($mirror as $table => $uid_array) {
				if (isset($this->datamap[$table])) {
					foreach ($uid_array as $id => $uidList) {
						if (isset($this->datamap[$table][$id])) {
							$theIdsInArray = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $uidList, 1);
							foreach ($theIdsInArray as $copyToUid) {
								$this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
							}
						}
					}
				}
			}
		}
	}

	/**
	 * Initializes default values coming from User TSconfig
	 *
	 * @param array $userTS User TSconfig array
	 * @return void
	 * @todo Define visibility
	 */
	public function setDefaultsFromUserTS($userTS) {
		if (is_array($userTS)) {
			foreach ($userTS as $k => $v) {
				$k = substr($k, 0, -1);
587
				if ($k && is_array($v) && isset($GLOBALS['TCA'][$k])) {
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
					if (is_array($this->defaultValues[$k])) {
						$this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
					} else {
						$this->defaultValues[$k] = $v;
					}
				}
			}
		}
	}

	/**
	 * Processing of uploaded files.
	 * 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.
	 *
	 * @param array $postFiles $_FILES array
	 * @return void
	 * @todo Define visibility
	 */
	public function process_uploads($postFiles) {
		if (is_array($postFiles)) {
			// Editing frozen:
			if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
				$this->newlog('All editing in this workspace has been frozen!', 1);
				return FALSE;
			}
			$subA = reset($postFiles);
			if (is_array($subA)) {
615
				if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
					// Initialize the uploadedFilesArray:
					$this->uploadedFileArray = array();
					// For each entry:
					foreach ($subA as $key => $values) {
						$this->process_uploads_traverseArray($this->uploadedFileArray, $values, $key);
					}
				} else {
					$this->uploadedFileArray = $subA;
				}
			}
		}
	}

	/**
	 * Traverse the upload array if needed to rearrange values.
	 *
	 * @param array $outputArr $this->uploadedFileArray passed by reference
	 * @param array $inputArr Input array  ($_FILES parts)
	 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
	 * @return void
	 * @access private
	 * @see process_uploads()
	 * @todo Define visibility
	 */
	public function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet) {
		if (is_array($inputArr)) {
			foreach ($inputArr as $key => $value) {
				$this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
			}
		} else {
			$outputArr[$keyToSet] = $inputArr;
		}
	}

	/*********************************************
	 *
	 * HOOKS
	 *
	 *********************************************/
	/**
	 * Hook: processDatamap_afterDatabaseOperations
	 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
	 *
	 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
	 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
	 *
	 * @param object $hookObjectsArr (reference) Array with hook objects
	 * @param string $status (reference) Status of the current operation, 'new' or 'update
	 * @param string $table (refrence) The table currently processing data for
	 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
	 * @param array $fieldArray (reference) The field array of a record
	 * @return void
	 * @todo Define visibility
	 */
	public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
		// Process hook directly:
		if (!isset($this->remapStackRecords[$table][$id])) {
			foreach ($hookObjectsArr as $hookObj) {
				if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
					$hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
				}
			}
		} else {
			$this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
				'status' => $status,
				'fieldArray' => $fieldArray,
				'hookObjectsArr' => $hookObjectsArr
			);
		}
	}

	/**
	 * Gets the 'checkModifyAccessList' hook objects.
	 * The first call initializes the accordant objects.
	 *
	 * @return array The 'checkModifyAccessList' hook objects (if any)
	 */
	protected function getCheckModifyAccessListHookObjects() {
		if (!isset($this->checkModifyAccessListHookObjects)) {
			$this->checkModifyAccessListHookObjects = array();
			if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
				foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
					$hookObject = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classData);
					if (!$hookObject instanceof \TYPO3\CMS\Core\DataHandling\DataHandlerCheckModifyAccessListHookInterface) {
						throw new \UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_checkModifyAccessListHook', 1251892472);
					}
					$this->checkModifyAccessListHookObjects[] = $hookObject;
				}
			}
		}
		return $this->checkModifyAccessListHookObjects;
	}

	/*********************************************
	 *
	 * PROCESSING DATA
	 *
	 *********************************************/
	/**
	 * Processing the data-array
	 * Call this function to process the data-array set by start()
	 *
	 * @return void
	 */
	public function process_datamap() {
721
722
		$this->controlActiveElements();

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
		// Keep versionized(!) relations here locally:
		$registerDBList = array();
		$this->registerElementsToBeDeleted();
		$this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
		// Editing frozen:
		if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
			$this->newlog('All editing in this workspace has been frozen!', 1);
			return FALSE;
		}
		// First prepare user defined objects (if any) for hooks which extend this function:
		$hookObjectsArr = array();
		if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
			foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
				$hookObject = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef);
				if (method_exists($hookObject, 'processDatamap_beforeStart')) {
					$hookObject->processDatamap_beforeStart($this);
				}
				$hookObjectsArr[] = $hookObject;
			}
		}
		// 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.
		$orderOfTables = array();
		// Set pages first.
		if (isset($this->datamap['pages'])) {
			$orderOfTables[] = 'pages';
		}
		$orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
		// Process the tables...
		foreach ($orderOfTables as $table) {
			// Check if
			//	   - table is set in $GLOBALS['TCA'],
			//	   - table is NOT readOnly
			//	   - the table is set with content in the data-array (if not, there's nothing to process...)
			//	   - permissions for tableaccess OK
			$modifyAccessList = $this->checkModifyAccessList($table);
			if (!$modifyAccessList) {
				$id = 0;
				$this->log($table, $id, 2, 0, 1, 'Attempt to modify table \'%s\' without permission', 1, array($table));
			}
762
			if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList) {
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
				if ($this->reverseOrder) {
					$this->datamap[$table] = array_reverse($this->datamap[$table], 1);
				}
				// For each record from the table, do:
				// $id is the record uid, may be a string if new records...
				// $incomingFieldArray is the array of fields
				foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
					if (is_array($incomingFieldArray)) {
						// Handle native date/time fields
						$dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
						foreach ($GLOBALS['TCA'][$table]['columns'] as $column => $config) {
							if (isset($incomingFieldArray[$column])) {
								if (isset($config['config']['dbType']) && \TYPO3\CMS\Core\Utility\GeneralUtility::inList('date,datetime', $config['config']['dbType'])) {
									$emptyValue = $dateTimeFormats[$config['config']['dbType']]['empty'];
									$format = $dateTimeFormats[$config['config']['dbType']]['format'];
									$incomingFieldArray[$column] = $incomingFieldArray[$column] ? date($format, $incomingFieldArray[$column]) : $emptyValue;
								}
							}
						}
						// Hook: processDatamap_preProcessFieldArray
						foreach ($hookObjectsArr as $hookObj) {
							if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
								$hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
							}
						}
						// ******************************
						// Checking access to the record
						// ******************************
						$createNewVersion = FALSE;
						$recordAccess = FALSE;
						$old_pid_value = '';
						$this->autoVersioningUpdate = FALSE;
						// Is it a new record? (Then Id is a string)
						if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($id)) {
							// Get a fieldArray with default values
							$fieldArray = $this->newFieldArray($table);
							// A pid must be set for new records.
							if (isset($incomingFieldArray['pid'])) {
								// $value = the pid
								$pid_value = $incomingFieldArray['pid'];
								// Checking and finding numerical pid, it may be a string-reference to another value
								$OK = 1;
								// If a NEW... id
								if (strstr($pid_value, 'NEW')) {
									if (substr($pid_value, 0, 1) == '-') {
										$negFlag = -1;
										$pid_value = substr($pid_value, 1);
									} else {
										$negFlag = 1;
									}
									// Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
									if (isset($this->substNEWwithIDs[$pid_value])) {
										if ($negFlag === 1) {
											$old_pid_value = $this->substNEWwithIDs[$pid_value];
										}
										$pid_value = intval($negFlag * $this->substNEWwithIDs[$pid_value]);
									} else {
										$OK = 0;
									}
								}
								$pid_value = intval($pid_value);
								// The $pid_value is now the numerical pid at this point
								if ($OK) {
									$sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
									// Points to a page on which to insert the element, possibly in the top of the page
									if ($pid_value >= 0) {
										// If this table is sorted we better find the top sorting number
										if ($sortRow) {
											$fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
										}
										// The numerical pid is inserted in the data array
										$fieldArray['pid'] = $pid_value;
									} else {
										// points to another record before ifself
										// If this table is sorted we better find the top sorting number
										if ($sortRow) {
											// Because $pid_value is < 0, getSortNumber returns an array
											$tempArray = $this->getSortNumber($table, 0, $pid_value);
											$fieldArray['pid'] = $tempArray['pid'];
											$fieldArray[$sortRow] = $tempArray['sortNumber'];
										} else {
											// Here we fetch the PID of the record that we point to...
											$tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
											$fieldArray['pid'] = $tempdata['pid'];
										}
									}
								}
							}
							$theRealPid = $fieldArray['pid'];
							// Now, check if we may insert records on this pid.
							if ($theRealPid >= 0) {
								// Checks if records can be inserted on this $pid.
								$recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
								if ($recordAccess) {
									$this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
									$recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, TRUE);
									if (!$recordAccess) {
860
										$this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', 1);
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
									} elseif (!$this->bypassWorkspaceRestrictions) {
										// Workspace related processing:
										// If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
										if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
											if ($res < 0) {
												$recordAccess = FALSE;
												$this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
											}
										} else {
											// So, if no live records were allowed, we have to create a new version of this record:
											if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
												$createNewVersion = TRUE;
											} else {
												$recordAccess = FALSE;
												$this->newlog('Record could not be created in this workspace in this branch', 1);
											}
										}
									}
								}
							} else {
								debug('Internal ERROR: pid should not be less than zero!');
							}
							// Yes new record, change $record_status to 'insert'
							$status = 'new';
						} else {
							// Nope... $id is a number
							$fieldArray = array();
							$recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
							if (!$recordAccess) {
								$propArr = $this->getRecordProperties($table, $id);
891
								$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']);
892
893
894
895
896
							} else {
								// Next check of the record permissions (internals)
								$recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
								if (!$recordAccess) {
									$propArr = $this->getRecordProperties($table, $id);
897
									$this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', 1);
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
								} else {
									// Here we fetch the PID of the record that we point to...
									$tempdata = $this->recordInfo($table, $id, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : ''));
									$theRealPid = $tempdata['pid'];
									// Use the new id of the versionized record we're trying to write to:
									// (This record is a child record of a parent and has already been versionized.)
									if ($this->autoVersionIdMap[$table][$id]) {
										// For the reason that creating a new version of this record, automatically
										// created related child records (e.g. "IRRE"), update the accordant field:
										$this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
										// Use the new id of the copied/versionized record:
										$id = $this->autoVersionIdMap[$table][$id];
										$recordAccess = TRUE;
										$this->autoVersioningUpdate = TRUE;
									} elseif (!$this->bypassWorkspaceRestrictions && ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata))) {
										$recordAccess = FALSE;
										// Versioning is required and it must be offline version!
										// Check if there already is a workspace version
										$WSversion = \TYPO3\CMS\Backend\Utility\BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
										if ($WSversion) {
											$id = $WSversion['uid'];
											$recordAccess = TRUE;
										} elseif ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
921
922
											$tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
											/** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
											$tce->stripslashes_values = 0;
											// Setting up command for creating a new version of the record:
											$cmd = array();
											$cmd[$table][$id]['version'] = array(
												'action' => 'new',
												'treeLevels' => -1,
												// Default is to create a version of the individual records... element versioning that is.
												'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
											);
											$tce->start(array(), $cmd);
											$tce->process_cmdmap();
											$this->errorLog = array_merge($this->errorLog, $tce->errorLog);
											// If copying was successful, share the new uids (also of related children):
											if ($tce->copyMappingArray[$table][$id]) {
												foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
													foreach ($origIdArray as $origId => $newId) {
														$this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
														$this->autoVersionIdMap[$origTable][$origId] = $newId;
													}
												}
												$this->RTEmagic_copyIndex = \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule($this->RTEmagic_copyIndex, $tce->RTEmagic_copyIndex);
												// See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
												// Update registerDBList, that holds the copied relations to child records:
												$registerDBList = array_merge($registerDBList, $tce->registerDBList);
												// For the reason that creating a new version of this record, automatically
												// created related child records (e.g. "IRRE"), update the accordant field:
												$this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
												// Use the new id of the copied/versionized record:
												$id = $this->autoVersionIdMap[$table][$id];
												$recordAccess = TRUE;
												$this->autoVersioningUpdate = TRUE;
											} else {
955
												$this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', 1);
956
957
											}
										} else {
958
											$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);
959
960
961
962
963
964
965
966
967
968
969
970
										}
									}
								}
							}
							// The default is 'update'
							$status = 'update';
						}
						// If access was granted above, proceed to create or update record:
						if ($recordAccess) {
							// Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
							list($tscPID) = \TYPO3\CMS\Backend\Utility\BackendUtility::getTSCpid($table, $id, $old_pid_value ? $old_pid_value : $fieldArray['pid']);
							$TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
971
							if ($status == 'new' && $table == 'pages' && is_array($TSConfig['permissions.'])) {
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
								$fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
							}
							if ($createNewVersion) {
								$newVersion_placeholderFieldArray = $fieldArray;
							}
							// Processing of all fields in incomingFieldArray and setting them in $fieldArray
							$fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
							// NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
							// Forcing some values unto field array:
							// NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
							$fieldArray = $this->overrideFieldArray($table, $fieldArray);
							if ($createNewVersion) {
								$newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
							}
							// Setting system fields
							if ($status == 'new') {
								if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
									$fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
									if ($createNewVersion) {
										$newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
									}
								}
								if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
									$fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
									if ($createNewVersion) {
										$newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
									}
								}
							} elseif ($this->checkSimilar) {