265dac1eaa4c04d058a60c76690ca69c4a2d2533
[Packages/TYPO3.CMS.git] / typo3 / sysext / version / Classes / Hook / DataHandlerHook.php
1 <?php
2 namespace TYPO3\CMS\Version\Hook;
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 Doctrine\DBAL\DBALException;
18 use Doctrine\DBAL\Platforms\SQLServerPlatform;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Core\Database\Connection;
21 use TYPO3\CMS\Core\Database\ConnectionPool;
22 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
23 use TYPO3\CMS\Core\Database\ReferenceIndex;
24 use TYPO3\CMS\Core\DataHandling\DataHandler;
25 use TYPO3\CMS\Core\Service\MarkerBasedTemplateService;
26 use TYPO3\CMS\Core\Utility\ArrayUtility;
27 use TYPO3\CMS\Core\Utility\GeneralUtility;
28 use TYPO3\CMS\Core\Versioning\VersionState;
29 use TYPO3\CMS\Lang\LanguageService;
30
31 /**
32 * Contains some parts for staging, versioning and workspaces
33 * to interact with the TYPO3 Core Engine
34 */
35 class DataHandlerHook
36 {
37 /**
38 * For accumulating information about workspace stages raised
39 * on elements so a single mail is sent as notification.
40 * previously called "accumulateForNotifEmail" in DataHandler
41 *
42 * @var array
43 */
44 protected $notificationEmailInfo = [];
45
46 /**
47 * Contains remapped IDs.
48 *
49 * @var array
50 */
51 protected $remappedIds = [];
52
53 /**
54 * @var \TYPO3\CMS\Workspaces\Service\WorkspaceService
55 */
56 protected $workspaceService;
57
58 /****************************
59 ***** Cmdmap Hooks ******
60 ****************************/
61 /**
62 * hook that is called before any cmd of the commandmap is executed
63 *
64 * @param DataHandler $dataHandler reference to the main DataHandler object
65 */
66 public function processCmdmap_beforeStart(DataHandler $dataHandler)
67 {
68 // Reset notification array
69 $this->notificationEmailInfo = [];
70 // Resolve dependencies of version/workspaces actions:
71 $dataHandler->cmdmap = $this->getCommandMap($dataHandler)->process()->get();
72 }
73
74 /**
75 * hook that is called when no prepared command was found
76 *
77 * @param string $command the command to be executed
78 * @param string $table the table of the record
79 * @param int $id the ID of the record
80 * @param mixed $value the value containing the data
81 * @param bool $commandIsProcessed can be set so that other hooks or
82 * @param DataHandler $dataHandler reference to the main DataHandler object
83 */
84 public function processCmdmap($command, $table, $id, $value, &$commandIsProcessed, DataHandler $dataHandler)
85 {
86 // custom command "version"
87 if ($command === 'version') {
88 $commandIsProcessed = true;
89 $action = (string)$value['action'];
90 $comment = !empty($value['comment']) ? $value['comment'] : '';
91 $notificationAlternativeRecipients = (isset($value['notificationAlternativeRecipients'])) && is_array($value['notificationAlternativeRecipients']) ? $value['notificationAlternativeRecipients'] : [];
92 switch ($action) {
93 case 'new':
94 $dataHandler->versionizeRecord($table, $id, $value['label']);
95 break;
96 case 'swap':
97 $this->version_swap(
98 $table,
99 $id,
100 $value['swapWith'],
101 $value['swapIntoWS'],
102 $dataHandler,
103 $comment,
104 true,
105 $notificationAlternativeRecipients
106 );
107 break;
108 case 'clearWSID':
109 $this->version_clearWSID($table, $id, false, $dataHandler);
110 break;
111 case 'flush':
112 $this->version_clearWSID($table, $id, true, $dataHandler);
113 break;
114 case 'setStage':
115 $elementIds = GeneralUtility::trimExplode(',', $id, true);
116 foreach ($elementIds as $elementId) {
117 $this->version_setStage(
118 $table,
119 $elementId,
120 $value['stageId'],
121 $comment,
122 true,
123 $dataHandler,
124 $notificationAlternativeRecipients
125 );
126 }
127 break;
128 default:
129 // Do nothing
130 }
131 }
132 }
133
134 /**
135 * hook that is called AFTER all commands of the commandmap was
136 * executed
137 *
138 * @param DataHandler $dataHandler reference to the main DataHandler object
139 */
140 public function processCmdmap_afterFinish(DataHandler $dataHandler)
141 {
142 // Empty accumulation array:
143 foreach ($this->notificationEmailInfo as $notifItem) {
144 $this->notifyStageChange($notifItem['shared'][0], $notifItem['shared'][1], implode(', ', $notifItem['elements']), 0, $notifItem['shared'][2], $dataHandler, $notifItem['alternativeRecipients']);
145 }
146 // Reset notification array
147 $this->notificationEmailInfo = [];
148 // Reset remapped IDs
149 $this->remappedIds = [];
150 }
151
152 /**
153 * hook that is called when an element shall get deleted
154 *
155 * @param string $table the table of the record
156 * @param int $id the ID of the record
157 * @param array $record The accordant database record
158 * @param bool $recordWasDeleted can be set so that other hooks or
159 * @param DataHandler $dataHandler reference to the main DataHandler object
160 */
161 public function processCmdmap_deleteAction($table, $id, array $record, &$recordWasDeleted, DataHandler $dataHandler)
162 {
163 // only process the hook if it wasn't processed
164 // by someone else before
165 if ($recordWasDeleted) {
166 return;
167 }
168 $recordWasDeleted = true;
169 // For Live version, try if there is a workspace version because if so, rather "delete" that instead
170 // Look, if record is an offline version, then delete directly:
171 if ($record['pid'] != -1) {
172 if ($wsVersion = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $table, $id)) {
173 $record = $wsVersion;
174 $id = $record['uid'];
175 }
176 }
177 $recordVersionState = VersionState::cast($record['t3ver_state']);
178 // Look, if record is an offline version, then delete directly:
179 if ($record['pid'] == -1) {
180 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
181 // In Live workspace, delete any. In other workspaces there must be match.
182 if ($dataHandler->BE_USER->workspace == 0 || (int)$record['t3ver_wsid'] == $dataHandler->BE_USER->workspace) {
183 $liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, 'uid,t3ver_state');
184 // Processing can be skipped if a delete placeholder shall be swapped/published
185 // during the current request. Thus it will be deleted later on...
186 $liveRecordVersionState = VersionState::cast($liveRec['t3ver_state']);
187 if ($recordVersionState->equals(VersionState::DELETE_PLACEHOLDER) && !empty($liveRec['uid'])
188 && !empty($dataHandler->cmdmap[$table][$liveRec['uid']]['version']['action'])
189 && !empty($dataHandler->cmdmap[$table][$liveRec['uid']]['version']['swapWith'])
190 && $dataHandler->cmdmap[$table][$liveRec['uid']]['version']['action'] === 'swap'
191 && $dataHandler->cmdmap[$table][$liveRec['uid']]['version']['swapWith'] == $id
192 ) {
193 return null;
194 }
195
196 if ($record['t3ver_wsid'] > 0 && $recordVersionState->equals(VersionState::DEFAULT_STATE)) {
197 // Change normal versioned record to delete placeholder
198 // Happens when an edited record is deleted
199 GeneralUtility::makeInstance(ConnectionPool::class)
200 ->getConnectionForTable($table)
201 ->update(
202 $table,
203 [
204 't3ver_label' => 'DELETED!',
205 't3ver_state' => 2,
206 ],
207 ['uid' => $id]
208 );
209
210 // Delete localization overlays:
211 $dataHandler->deleteL10nOverlayRecords($table, $id);
212 } elseif ($record['t3ver_wsid'] == 0 || !$liveRecordVersionState->indicatesPlaceholder()) {
213 // Delete those in WS 0 + if their live records state was not "Placeholder".
214 $dataHandler->deleteEl($table, $id);
215 // Delete move-placeholder if current version record is a move-to-pointer
216 if ($recordVersionState->equals(VersionState::MOVE_POINTER)) {
217 $movePlaceholder = BackendUtility::getMovePlaceholder($table, $liveRec['uid'], 'uid', $record['t3ver_wsid']);
218 if (!empty($movePlaceholder)) {
219 $dataHandler->deleteEl($table, $movePlaceholder['uid']);
220 }
221 }
222 } else {
223 // If live record was placeholder (new/deleted), rather clear
224 // it from workspace (because it clears both version and placeholder).
225 $this->version_clearWSID($table, $id, false, $dataHandler);
226 }
227 } else {
228 $dataHandler->newlog('Tried to delete record from another workspace', 1);
229 }
230 } else {
231 $dataHandler->newlog('Versioning not enabled for record with PID = -1!', 2);
232 }
233 } elseif ($res = $dataHandler->BE_USER->workspaceAllowLiveRecordsInPID($record['pid'], $table)) {
234 // Look, if record is "online" or in a versionized branch, then delete directly.
235 if ($res > 0) {
236 $dataHandler->deleteEl($table, $id);
237 } else {
238 $dataHandler->newlog('Stage of root point did not allow for deletion', 1);
239 }
240 } elseif ($recordVersionState->equals(VersionState::MOVE_PLACEHOLDER)) {
241 // Placeholders for moving operations are deletable directly.
242 // Get record which its a placeholder for and reset the t3ver_state of that:
243 if ($wsRec = BackendUtility::getWorkspaceVersionOfRecord($record['t3ver_wsid'], $table, $record['t3ver_move_id'], 'uid')) {
244 // Clear the state flag of the workspace version of the record
245 // Setting placeholder state value for version (so it can know it is currently a new version...)
246
247 GeneralUtility::makeInstance(ConnectionPool::class)
248 ->getConnectionForTable($table)
249 ->update(
250 $table,
251 [
252 't3ver_state' => (string)new VersionState(VersionState::DEFAULT_STATE)
253 ],
254 ['uid' => (int)$wsRec['uid']]
255 );
256 }
257 $dataHandler->deleteEl($table, $id);
258 } else {
259 // Otherwise, try to delete by versioning:
260 $copyMappingArray = $dataHandler->copyMappingArray;
261 $dataHandler->versionizeRecord($table, $id, 'DELETED!', true);
262 // Determine newly created versions:
263 // (remove placeholders are copied and modified, thus they appear in the copyMappingArray)
264 $versionizedElements = ArrayUtility::arrayDiffAssocRecursive($dataHandler->copyMappingArray, $copyMappingArray);
265 // Delete localization overlays:
266 foreach ($versionizedElements as $versionizedTableName => $versionizedOriginalIds) {
267 foreach ($versionizedOriginalIds as $versionizedOriginalId => $_) {
268 $dataHandler->deleteL10nOverlayRecords($versionizedTableName, $versionizedOriginalId);
269 }
270 }
271 }
272 }
273
274 /**
275 * Hook for \TYPO3\CMS\Core\DataHandling\DataHandler::moveRecord that cares about
276 * moving records that are *not* in the live workspace
277 *
278 * @param string $table the table of the record
279 * @param int $uid the ID of the record
280 * @param int $destPid Position to move to: $destPid: >=0 then it points to
281 * @param array $propArr Record properties, like header and pid (includes workspace overlay)
282 * @param array $moveRec Record properties, like header and pid (without workspace overlay)
283 * @param int $resolvedPid The final page ID of the record
284 * @param bool $recordWasMoved can be set so that other hooks or
285 * @param DataHandler $dataHandler
286 */
287 public function moveRecord($table, $uid, $destPid, array $propArr, array $moveRec, $resolvedPid, &$recordWasMoved, DataHandler $dataHandler)
288 {
289 // Only do something in Draft workspace
290 if ($dataHandler->BE_USER->workspace === 0) {
291 return;
292 }
293 if ($destPid < 0) {
294 // Fetch move placeholder, since it might point to a new page in the current workspace
295 $movePlaceHolder = BackendUtility::getMovePlaceholder($table, abs($destPid), 'uid,pid');
296 if ($movePlaceHolder !== false) {
297 $resolvedPid = $movePlaceHolder['pid'];
298 }
299 }
300 $recordWasMoved = true;
301 $moveRecVersionState = VersionState::cast($moveRec['t3ver_state']);
302 // Get workspace version of the source record, if any:
303 $WSversion = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');
304 // Handle move-placeholders if the current record is not one already
305 if (
306 BackendUtility::isTableWorkspaceEnabled($table)
307 && !$moveRecVersionState->equals(VersionState::MOVE_PLACEHOLDER)
308 ) {
309 // Create version of record first, if it does not exist
310 if (empty($WSversion['uid'])) {
311 $dataHandler->versionizeRecord($table, $uid, 'MovePointer');
312 $WSversion = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');
313 $this->moveRecord_processFields($dataHandler, $resolvedPid, $table, $uid);
314 } elseif ($dataHandler->isRecordCopied($table, $uid) && (int)$dataHandler->copyMappingArray[$table][$uid] === (int)$WSversion['uid']) {
315 // If the record has been versioned before (e.g. cascaded parent-child structure), create only the move-placeholders
316 $this->moveRecord_processFields($dataHandler, $resolvedPid, $table, $uid);
317 }
318 }
319 // Check workspace permissions:
320 $workspaceAccessBlocked = [];
321 // Element was in "New/Deleted/Moved" so it can be moved...
322 $recIsNewVersion = $moveRecVersionState->indicatesPlaceholder();
323 $destRes = $dataHandler->BE_USER->workspaceAllowLiveRecordsInPID($resolvedPid, $table);
324 $canMoveRecord = ($recIsNewVersion || BackendUtility::isTableWorkspaceEnabled($table));
325 // Workspace source check:
326 if (!$recIsNewVersion) {
327 $errorCode = $dataHandler->BE_USER->workspaceCannotEditRecord($table, $WSversion['uid'] ? $WSversion['uid'] : $uid);
328 if ($errorCode) {
329 $workspaceAccessBlocked['src1'] = 'Record could not be edited in workspace: ' . $errorCode . ' ';
330 } elseif (!$canMoveRecord && $dataHandler->BE_USER->workspaceAllowLiveRecordsInPID($moveRec['pid'], $table) <= 0) {
331 $workspaceAccessBlocked['src2'] = 'Could not remove record from table "' . $table . '" from its page "' . $moveRec['pid'] . '" ';
332 }
333 }
334 // Workspace destination check:
335 // All records can be inserted if $destRes is greater than zero.
336 // Only new versions can be inserted if $destRes is FALSE.
337 // NO RECORDS can be inserted if $destRes is negative which indicates a stage
338 // not allowed for use. If "versioningWS" is version 2, moving can take place of versions.
339 // since TYPO3 CMS 7, version2 is the default and the only option
340 if (!($destRes > 0 || $canMoveRecord && !$destRes)) {
341 $workspaceAccessBlocked['dest1'] = 'Could not insert record from table "' . $table . '" in destination PID "' . $resolvedPid . '" ';
342 } elseif ($destRes == 1 && $WSversion['uid']) {
343 $workspaceAccessBlocked['dest2'] = 'Could not insert other versions in destination PID ';
344 }
345 if (empty($workspaceAccessBlocked)) {
346 // If the move operation is done on a versioned record, which is
347 // NOT new/deleted placeholder and versioningWS is in version 2, then...
348 // since TYPO3 CMS 7, version2 is the default and the only option
349 if ($WSversion['uid'] && !$recIsNewVersion && BackendUtility::isTableWorkspaceEnabled($table)) {
350 $this->moveRecord_wsPlaceholders($table, $uid, $destPid, $WSversion['uid'], $dataHandler);
351 } else {
352 // moving not needed, just behave like in live workspace
353 $recordWasMoved = false;
354 }
355 } else {
356 $dataHandler->newlog('Move attempt failed due to workspace restrictions: ' . implode(' // ', $workspaceAccessBlocked), 1);
357 }
358 }
359
360 /**
361 * Processes fields of a moved record and follows references.
362 *
363 * @param DataHandler $dataHandler Calling DataHandler instance
364 * @param int $resolvedPageId Resolved real destination page id
365 * @param string $table Name of parent table
366 * @param int $uid UID of the parent record
367 */
368 protected function moveRecord_processFields(DataHandler $dataHandler, $resolvedPageId, $table, $uid)
369 {
370 $versionedRecord = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $table, $uid);
371 if (empty($versionedRecord)) {
372 return;
373 }
374 foreach ($versionedRecord as $field => $value) {
375 if (empty($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
376 continue;
377 }
378 $this->moveRecord_processFieldValue(
379 $dataHandler,
380 $resolvedPageId,
381 $table,
382 $uid,
383 $field,
384 $value,
385 $GLOBALS['TCA'][$table]['columns'][$field]['config']
386 );
387 }
388 }
389
390 /**
391 * Processes a single field of a moved record and follows references.
392 *
393 * @param DataHandler $dataHandler Calling DataHandler instance
394 * @param int $resolvedPageId Resolved real destination page id
395 * @param string $table Name of parent table
396 * @param int $uid UID of the parent record
397 * @param string $field Name of the field of the parent record
398 * @param string $value Value of the field of the parent record
399 * @param array $configuration TCA field configuration of the parent record
400 */
401 protected function moveRecord_processFieldValue(DataHandler $dataHandler, $resolvedPageId, $table, $uid, $field, $value, array $configuration)
402 {
403 $inlineFieldType = $dataHandler->getInlineFieldType($configuration);
404 $inlineProcessing = (
405 ($inlineFieldType === 'list' || $inlineFieldType === 'field')
406 && BackendUtility::isTableWorkspaceEnabled($configuration['foreign_table'])
407 && (!isset($configuration['behaviour']['disableMovingChildrenWithParent']) || !$configuration['behaviour']['disableMovingChildrenWithParent'])
408 );
409
410 if ($inlineProcessing) {
411 if ($table === 'pages') {
412 // If the inline elements are related to a page record,
413 // make sure they reside at that page and not at its parent
414 $resolvedPageId = $uid;
415 }
416
417 $dbAnalysis = $this->createRelationHandlerInstance();
418 $dbAnalysis->start($value, $configuration['foreign_table'], '', $uid, $table, $configuration);
419
420 // Moving records to a positive destination will insert each
421 // record at the beginning, thus the order is reversed here:
422 foreach ($dbAnalysis->itemArray as $item) {
423 $versionedRecord = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $item['table'], $item['id'], 'uid,t3ver_state');
424 if (empty($versionedRecord) || VersionState::cast($versionedRecord['t3ver_state'])->indicatesPlaceholder()) {
425 continue;
426 }
427 $dataHandler->moveRecord($item['table'], $item['id'], $resolvedPageId);
428 }
429 }
430 }
431
432 /****************************
433 ***** Notifications ******
434 ****************************/
435 /**
436 * Send an email notification to users in workspace
437 *
438 * @param array $stat Workspace access array from \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::checkWorkspace()
439 * @param int $stageId New Stage number: 0 = editing, 1= just ready for review, 10 = ready for publication, -1 = rejected!
440 * @param string $table Table name of element (or list of element names if $id is zero)
441 * @param int $id Record uid of element (if zero, then $table is used as reference to element(s) alone)
442 * @param string $comment User comment sent along with action
443 * @param DataHandler $dataHandler DataHandler object
444 * @param array $notificationAlternativeRecipients List of recipients to notify instead of be_users selected by sys_workspace, list is generated by workspace extension module
445 */
446 protected function notifyStageChange(array $stat, $stageId, $table, $id, $comment, DataHandler $dataHandler, array $notificationAlternativeRecipients = [])
447 {
448 $workspaceRec = BackendUtility::getRecord('sys_workspace', $stat['uid']);
449 // So, if $id is not set, then $table is taken to be the complete element name!
450 $elementName = $id ? $table . ':' . $id : $table;
451 if (!is_array($workspaceRec)) {
452 return;
453 }
454
455 // Get the new stage title from workspaces library, if workspaces extension is installed
456 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
457 $stageService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\StagesService::class);
458 $newStage = $stageService->getStageTitle((int)$stageId);
459 } else {
460 // @todo CONSTANTS SHOULD BE USED - tx_service_workspace_workspaces
461 // @todo use localized labels
462 // Compile label:
463 switch ((int)$stageId) {
464 case 1:
465 $newStage = 'Ready for review';
466 break;
467 case 10:
468 $newStage = 'Ready for publishing';
469 break;
470 case -1:
471 $newStage = 'Element was rejected!';
472 break;
473 case 0:
474 $newStage = 'Rejected element was noticed and edited';
475 break;
476 default:
477 $newStage = 'Unknown state change!?';
478 }
479 }
480 if (empty($notificationAlternativeRecipients)) {
481 // Compile list of recipients:
482 $emails = [];
483 switch ((int)$stat['stagechg_notification']) {
484 case 1:
485 switch ((int)$stageId) {
486 case 1:
487 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']);
488 break;
489 case 10:
490 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], true);
491 break;
492 case -1:
493 // List of elements to reject:
494 $allElements = explode(',', $elementName);
495 // Traverse them, and find the history of each
496 foreach ($allElements as $elRef) {
497 list($eTable, $eUid) = explode(':', $elRef);
498
499 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
500 ->getQueryBuilderForTable('sys_log');
501
502 $queryBuilder->getRestrictions()->removeAll();
503
504 $result = $queryBuilder
505 ->select('log_data', 'tstamp', 'userid')
506 ->from('sys_log')
507 ->where(
508 $queryBuilder->expr()->eq(
509 'action',
510 $queryBuilder->createNamedParameter(6, \PDO::PARAM_INT)
511 ),
512 $queryBuilder->expr()->eq(
513 'details_nr',
514 $queryBuilder->createNamedParameter(30, \PDO::PARAM_INT)
515 ),
516 $queryBuilder->expr()->eq(
517 'tablename',
518 $queryBuilder->createNamedParameter($eTable, \PDO::PARAM_STR)
519 ),
520 $queryBuilder->expr()->eq(
521 'recuid',
522 $queryBuilder->createNamedParameter($eUid, \PDO::PARAM_INT)
523 )
524 )
525 ->orderBy('uid', 'DESC')
526 ->execute();
527
528 // Find all implicated since the last stage-raise from editing to review:
529 while ($dat = $result->fetch()) {
530 $data = unserialize($dat['log_data']);
531 $emails = $this->getEmailsForStageChangeNotification($dat['userid'], true) + $emails;
532 if ($data['stage'] == 1) {
533 break;
534 }
535 }
536 }
537 break;
538 case 0:
539 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']);
540 break;
541 default:
542 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], true);
543 }
544 break;
545 case 10:
546 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], true);
547 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']) + $emails;
548 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']) + $emails;
549 break;
550 default:
551 // Do nothing
552 }
553 } else {
554 $emails = $notificationAlternativeRecipients;
555 }
556 // prepare and then send the emails
557 if (!empty($emails)) {
558 // Path to record is found:
559 list($elementTable, $elementUid) = explode(':', $elementName);
560 $elementUid = (int)$elementUid;
561 $elementRecord = BackendUtility::getRecord($elementTable, $elementUid);
562 $recordTitle = BackendUtility::getRecordTitle($elementTable, $elementRecord);
563 if ($elementTable === 'pages') {
564 $pageUid = $elementUid;
565 } else {
566 BackendUtility::fixVersioningPid($elementTable, $elementRecord);
567 $pageUid = ($elementUid = $elementRecord['pid']);
568 }
569
570 // new way, options are
571 // pageTSconfig: tx_version.workspaces.stageNotificationEmail.subject
572 // userTSconfig: page.tx_version.workspaces.stageNotificationEmail.subject
573 $pageTsConfig = BackendUtility::getPagesTSconfig($pageUid);
574 $emailConfig = $pageTsConfig['tx_version.']['workspaces.']['stageNotificationEmail.'];
575 $markers = [
576 '###RECORD_TITLE###' => $recordTitle,
577 '###RECORD_PATH###' => BackendUtility::getRecordPath($elementUid, '', 20),
578 '###SITE_NAME###' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
579 '###SITE_URL###' => GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir,
580 '###WORKSPACE_TITLE###' => $workspaceRec['title'],
581 '###WORKSPACE_UID###' => $workspaceRec['uid'],
582 '###ELEMENT_NAME###' => $elementName,
583 '###NEXT_STAGE###' => $newStage,
584 '###COMMENT###' => $comment,
585 // See: #30212 - keep both markers for compatibility
586 '###USER_REALNAME###' => $dataHandler->BE_USER->user['realName'],
587 '###USER_FULLNAME###' => $dataHandler->BE_USER->user['realName'],
588 '###USER_USERNAME###' => $dataHandler->BE_USER->user['username']
589 ];
590 // add marker for preview links if workspace extension is loaded
591 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
592 $this->workspaceService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
593 // only generate the link if the marker is in the template - prevents database from getting to much entries
594 if (GeneralUtility::isFirstPartOfStr($emailConfig['message'], 'LLL:')) {
595 $tempEmailMessage = $this->getLanguageService()->sL($emailConfig['message']);
596 } else {
597 $tempEmailMessage = $emailConfig['message'];
598 }
599 if (strpos($tempEmailMessage, '###PREVIEW_LINK###') !== false) {
600 $markers['###PREVIEW_LINK###'] = $this->workspaceService->generateWorkspacePreviewLink($elementUid);
601 }
602 unset($tempEmailMessage);
603 $markers['###SPLITTED_PREVIEW_LINK###'] = $this->workspaceService->generateWorkspaceSplittedPreviewLink($elementUid, true);
604 }
605 // Hook for preprocessing of the content for formmails:
606 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'])) {
607 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'] as $_classRef) {
608 $_procObj =& GeneralUtility::getUserObj($_classRef);
609 $markers = $_procObj->postModifyMarkers($markers, $this);
610 }
611 }
612 // send an email to each individual user, to ensure the
613 // multilanguage version of the email
614 $emailRecipients = [];
615 // an array of language objects that are needed
616 // for emails with different languages
617 $languageObjects = [
618 $this->getLanguageService()->lang => $this->getLanguageService()
619 ];
620 // loop through each recipient and send the email
621 foreach ($emails as $recipientData) {
622 // don't send an email twice
623 if (isset($emailRecipients[$recipientData['email']])) {
624 continue;
625 }
626 $emailSubject = $emailConfig['subject'];
627 $emailMessage = $emailConfig['message'];
628 $emailRecipients[$recipientData['email']] = $recipientData['email'];
629 // check if the email needs to be localized
630 // in the users' language
631 if (GeneralUtility::isFirstPartOfStr($emailSubject, 'LLL:') || GeneralUtility::isFirstPartOfStr($emailMessage, 'LLL:')) {
632 $recipientLanguage = $recipientData['lang'] ? $recipientData['lang'] : 'default';
633 if (!isset($languageObjects[$recipientLanguage])) {
634 // a LANG object in this language hasn't been
635 // instantiated yet, so this is done here
636 /** @var $languageObject \TYPO3\CMS\Lang\LanguageService */
637 $languageObject = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
638 $languageObject->init($recipientLanguage);
639 $languageObjects[$recipientLanguage] = $languageObject;
640 } else {
641 $languageObject = $languageObjects[$recipientLanguage];
642 }
643 if (GeneralUtility::isFirstPartOfStr($emailSubject, 'LLL:')) {
644 $emailSubject = $languageObject->sL($emailSubject);
645 }
646 if (GeneralUtility::isFirstPartOfStr($emailMessage, 'LLL:')) {
647 $emailMessage = $languageObject->sL($emailMessage);
648 }
649 }
650 $templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
651 $emailSubject = $templateService->substituteMarkerArray($emailSubject, $markers, '', true, true);
652 $emailMessage = $templateService->substituteMarkerArray($emailMessage, $markers, '', true, true);
653 // Send an email to the recipient
654 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
655 $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
656 if (!empty($recipientData['realName'])) {
657 $recipient = [$recipientData['email'] => $recipientData['realName']];
658 } else {
659 $recipient = $recipientData['email'];
660 }
661 $mail->setTo($recipient)
662 ->setSubject($emailSubject)
663 ->setBody($emailMessage);
664 $mail->send();
665 }
666 $emailRecipients = implode(',', $emailRecipients);
667 $dataHandler->newlog2('Notification email for stage change was sent to "' . $emailRecipients . '"', $table, $id);
668 }
669 }
670
671 /**
672 * Return be_users that should be notified on stage change from input list.
673 * previously called notifyStageChange_getEmails() in DataHandler
674 *
675 * @param string $listOfUsers List of backend users, on the form "be_users_10,be_users_2" or "10,2" in case noTablePrefix is set.
676 * @param bool $noTablePrefix If set, the input list are integers and not strings.
677 * @return array Array of emails
678 */
679 protected function getEmailsForStageChangeNotification($listOfUsers, $noTablePrefix = false)
680 {
681 $users = GeneralUtility::trimExplode(',', $listOfUsers, true);
682 $emails = [];
683 foreach ($users as $userIdent) {
684 if ($noTablePrefix) {
685 $id = (int)$userIdent;
686 } else {
687 list($table, $id) = GeneralUtility::revExplode('_', $userIdent, 2);
688 }
689 if ($table === 'be_users' || $noTablePrefix) {
690 if ($userRecord = BackendUtility::getRecord('be_users', $id, 'uid,email,lang,realName', BackendUtility::BEenableFields('be_users'))) {
691 if (trim($userRecord['email']) !== '') {
692 $emails[$id] = $userRecord;
693 }
694 }
695 }
696 }
697 return $emails;
698 }
699
700 /****************************
701 ***** Stage Changes ******
702 ****************************/
703 /**
704 * Setting stage of record
705 *
706 * @param string $table Table name
707 * @param int $integer Record UID
708 * @param int $stageId Stage ID to set
709 * @param string $comment Comment that goes into log
710 * @param bool $notificationEmailInfo Accumulate state changes in memory for compiled notification email?
711 * @param DataHandler $dataHandler DataHandler object
712 * @param array $notificationAlternativeRecipients comma separated list of recipients to notify instead of normal be_users
713 */
714 protected function version_setStage($table, $id, $stageId, $comment = '', $notificationEmailInfo = false, DataHandler $dataHandler, array $notificationAlternativeRecipients = [])
715 {
716 if ($errorCode = $dataHandler->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
717 $dataHandler->newlog('Attempt to set stage for record failed: ' . $errorCode, 1);
718 } elseif ($dataHandler->checkRecordUpdateAccess($table, $id)) {
719 $record = BackendUtility::getRecord($table, $id);
720 $stat = $dataHandler->BE_USER->checkWorkspace($record['t3ver_wsid']);
721 // check if the usere is allowed to the current stage, so it's also allowed to send to next stage
722 if ($dataHandler->BE_USER->workspaceCheckStageForCurrent($record['t3ver_stage'])) {
723 // Set stage of record:
724 GeneralUtility::makeInstance(ConnectionPool::class)
725 ->getConnectionForTable($table)
726 ->update(
727 $table,
728 [
729 't3ver_stage' => $stageId,
730 ],
731 ['uid' => (int)$id]
732 );
733 $dataHandler->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id);
734 // TEMPORARY, except 6-30 as action/detail number which is observed elsewhere!
735 $dataHandler->log($table, $id, 6, 0, 0, 'Stage raised...', 30, ['comment' => $comment, 'stage' => $stageId]);
736 if ((int)$stat['stagechg_notification'] > 0) {
737 if ($notificationEmailInfo) {
738 $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['shared'] = [$stat, $stageId, $comment];
739 $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['elements'][] = $table . ':' . $id;
740 $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['alternativeRecipients'] = $notificationAlternativeRecipients;
741 } else {
742 $this->notifyStageChange($stat, $stageId, $table, $id, $comment, $dataHandler, $notificationAlternativeRecipients);
743 }
744 }
745 } else {
746 $dataHandler->newlog('The member user tried to set a stage value "' . $stageId . '" that was not allowed', 1);
747 }
748 } else {
749 $dataHandler->newlog('Attempt to set stage for record failed because you do not have edit access', 1);
750 }
751 }
752
753 /*****************************
754 ***** CMD versioning ******
755 *****************************/
756
757 /**
758 * Swapping versions of a record
759 * Version from archive (future/past, called "swap version") will get the uid of the "t3ver_oid", the official element with uid = "t3ver_oid" will get the new versions old uid. PIDs are swapped also
760 *
761 * @param string $table Table name
762 * @param int $id UID of the online record to swap
763 * @param int $swapWith UID of the archived version to swap with!
764 * @param bool $swapIntoWS If set, swaps online into workspace instead of publishing out of workspace.
765 * @param DataHandler $dataHandler DataHandler object
766 * @param string $comment Notification comment
767 * @param bool $notificationEmailInfo Accumulate state changes in memory for compiled notification email?
768 * @param array $notificationAlternativeRecipients comma separated list of recipients to notificate instead of normal be_users
769 */
770 protected function version_swap($table, $id, $swapWith, $swapIntoWS = 0, DataHandler $dataHandler, $comment = '', $notificationEmailInfo = false, $notificationAlternativeRecipients = [])
771 {
772
773 // Check prerequisites before start swapping
774
775 // Skip records that have been deleted during the current execution
776 if ($dataHandler->hasDeletedRecord($table, $id)) {
777 return;
778 }
779
780 // First, check if we may actually edit the online record
781 if (!$dataHandler->checkRecordUpdateAccess($table, $id)) {
782 $dataHandler->newlog('Error: You cannot swap versions for a record you do not have access to edit!', 1);
783 return;
784 }
785 // Select the two versions:
786 $curVersion = BackendUtility::getRecord($table, $id, '*');
787 $swapVersion = BackendUtility::getRecord($table, $swapWith, '*');
788 $movePlh = [];
789 $movePlhID = 0;
790 if (!(is_array($curVersion) && is_array($swapVersion))) {
791 $dataHandler->newlog('Error: Either online or swap version could not be selected!', 2);
792 return;
793 }
794 if (!$dataHandler->BE_USER->workspacePublishAccess($swapVersion['t3ver_wsid'])) {
795 $dataHandler->newlog('User could not publish records from workspace #' . $swapVersion['t3ver_wsid'], 1);
796 return;
797 }
798 $wsAccess = $dataHandler->BE_USER->checkWorkspace($swapVersion['t3ver_wsid']);
799 if (!($swapVersion['t3ver_wsid'] <= 0 || !($wsAccess['publish_access'] & 1) || (int)$swapVersion['t3ver_stage'] === -10)) {
800 $dataHandler->newlog('Records in workspace #' . $swapVersion['t3ver_wsid'] . ' can only be published when in "Publish" stage.', 1);
801 return;
802 }
803 if (!($dataHandler->doesRecordExist($table, $swapWith, 'show') && $dataHandler->checkRecordUpdateAccess($table, $swapWith))) {
804 $dataHandler->newlog('You cannot publish a record you do not have edit and show permissions for', 1);
805 return;
806 }
807 if ($swapIntoWS && !$dataHandler->BE_USER->workspaceSwapAccess()) {
808 $dataHandler->newlog('Workspace #' . $swapVersion['t3ver_wsid'] . ' does not support swapping.', 1);
809 return;
810 }
811 // Check if the swapWith record really IS a version of the original!
812 if (!(((int)$swapVersion['pid'] == -1 && (int)$curVersion['pid'] >= 0) && (int)$swapVersion['t3ver_oid'] === (int)$id)) {
813 $dataHandler->newlog('In swap version, either pid was not -1 or the t3ver_oid didn\'t match the id of the online version as it must!', 2);
814 return;
815 }
816 // Lock file name:
817 $lockFileName = PATH_site . 'typo3temp/var/swap_locking/' . $table . '_' . $id . '.ser';
818 if (@is_file($lockFileName)) {
819 $dataHandler->newlog('A swapping lock file was present. Either another swap process is already running or a previous swap process failed. Ask your administrator to handle the situation.', 2);
820 return;
821 }
822
823 // Now start to swap records by first creating the lock file
824
825 // Write lock-file:
826 GeneralUtility::writeFileToTypo3tempDir($lockFileName, serialize([
827 'tstamp' => $GLOBALS['EXEC_TIME'],
828 'user' => $dataHandler->BE_USER->user['username'],
829 'curVersion' => $curVersion,
830 'swapVersion' => $swapVersion
831 ]));
832 // Find fields to keep
833 $keepFields = $this->getUniqueFields($table);
834 if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
835 $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
836 }
837 // l10n-fields must be kept otherwise the localization
838 // will be lost during the publishing
839 if ($table !== 'pages_language_overlay' && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
840 $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
841 }
842 // Swap "keepfields"
843 foreach ($keepFields as $fN) {
844 $tmp = $swapVersion[$fN];
845 $swapVersion[$fN] = $curVersion[$fN];
846 $curVersion[$fN] = $tmp;
847 }
848 // Preserve states:
849 $t3ver_state = [];
850 $t3ver_state['swapVersion'] = $swapVersion['t3ver_state'];
851 $t3ver_state['curVersion'] = $curVersion['t3ver_state'];
852 // Modify offline version to become online:
853 $tmp_wsid = $swapVersion['t3ver_wsid'];
854 // Set pid for ONLINE
855 $swapVersion['pid'] = (int)$curVersion['pid'];
856 // We clear this because t3ver_oid only make sense for offline versions
857 // and we want to prevent unintentional misuse of this
858 // value for online records.
859 $swapVersion['t3ver_oid'] = 0;
860 // In case of swapping and the offline record has a state
861 // (like 2 or 4 for deleting or move-pointer) we set the
862 // current workspace ID so the record is not deselected
863 // in the interface by BackendUtility::versioningPlaceholderClause()
864 $swapVersion['t3ver_wsid'] = 0;
865 if ($swapIntoWS) {
866 if ($t3ver_state['swapVersion'] > 0) {
867 $swapVersion['t3ver_wsid'] = $dataHandler->BE_USER->workspace;
868 } else {
869 $swapVersion['t3ver_wsid'] = (int)$curVersion['t3ver_wsid'];
870 }
871 }
872 $swapVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
873 $swapVersion['t3ver_stage'] = 0;
874 if (!$swapIntoWS) {
875 $swapVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
876 }
877 // Moving element.
878 if (BackendUtility::isTableWorkspaceEnabled($table)) {
879 // && $t3ver_state['swapVersion']==4 // Maybe we don't need this?
880 if ($plhRec = BackendUtility::getMovePlaceholder($table, $id, 't3ver_state,pid,uid' . ($GLOBALS['TCA'][$table]['ctrl']['sortby'] ? ',' . $GLOBALS['TCA'][$table]['ctrl']['sortby'] : ''))) {
881 $movePlhID = $plhRec['uid'];
882 $movePlh['pid'] = $swapVersion['pid'];
883 $swapVersion['pid'] = (int)$plhRec['pid'];
884 $curVersion['t3ver_state'] = (int)$swapVersion['t3ver_state'];
885 $swapVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
886 if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
887 // sortby is a "keepFields" which is why this will work...
888 $movePlh[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']];
889 $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $plhRec[$GLOBALS['TCA'][$table]['ctrl']['sortby']];
890 }
891 }
892 }
893 // Take care of relations in each field (e.g. IRRE):
894 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
895 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fieldConf) {
896 $this->version_swap_processFields($table, $field, $fieldConf['config'], $curVersion, $swapVersion, $dataHandler);
897 }
898 }
899 unset($swapVersion['uid']);
900 // Modify online version to become offline:
901 unset($curVersion['uid']);
902 // Set pid for OFFLINE
903 $curVersion['pid'] = -1;
904 $curVersion['t3ver_oid'] = (int)$id;
905 $curVersion['t3ver_wsid'] = $swapIntoWS ? (int)$tmp_wsid : 0;
906 $curVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
907 $curVersion['t3ver_count'] = $curVersion['t3ver_count'] + 1;
908 // Increment lifecycle counter
909 $curVersion['t3ver_stage'] = 0;
910 if (!$swapIntoWS) {
911 $curVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
912 }
913 // Registering and swapping MM relations in current and swap records:
914 $dataHandler->version_remapMMForVersionSwap($table, $id, $swapWith);
915 // Generating proper history data to prepare logging
916 $dataHandler->compareFieldArrayWithCurrentAndUnset($table, $id, $swapVersion);
917 $dataHandler->compareFieldArrayWithCurrentAndUnset($table, $swapWith, $curVersion);
918
919 // Execute swapping:
920 $sqlErrors = [];
921 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
922
923 $platform = $connection->getDatabasePlatform();
924 $tableDetails = null;
925 if ($platform instanceof SQLServerPlatform) {
926 // mssql needs to set proper PARAM_LOB and others to update fields
927 $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
928 }
929
930 try {
931 $types = [];
932
933 if ($platform instanceof SQLServerPlatform) {
934 foreach ($curVersion as $columnName => $columnValue) {
935 $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
936 }
937 }
938
939 $connection->update(
940 $table,
941 $swapVersion,
942 ['uid' => (int)$id],
943 $types
944 );
945 } catch (DBALException $e) {
946 $sqlErrors[] = $e->getPrevious()->getMessage();
947 }
948
949 if (empty($sqlErrors)) {
950 try {
951 $types = [];
952 if ($platform instanceof SQLServerPlatform) {
953 foreach ($curVersion as $columnName => $columnValue) {
954 $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
955 }
956 }
957
958 $connection->update(
959 $table,
960 $curVersion,
961 ['uid' => (int)$swapWith],
962 $types
963 );
964 unlink($lockFileName);
965 } catch (DBALException $e) {
966 $sqlErrors[] = $e->getPrevious()->getMessage();
967 }
968 }
969
970 if (!empty($sqlErrors)) {
971 $dataHandler->newlog('During Swapping: SQL errors happened: ' . implode('; ', $sqlErrors), 2);
972 } else {
973 // Register swapped ids for later remapping:
974 $this->remappedIds[$table][$id] = $swapWith;
975 $this->remappedIds[$table][$swapWith] = $id;
976 // If a moving operation took place...:
977 if ($movePlhID) {
978 // Remove, if normal publishing:
979 if (!$swapIntoWS) {
980 // For delete + completely delete!
981 $dataHandler->deleteEl($table, $movePlhID, true, true);
982 } else {
983 // Otherwise update the movePlaceholder:
984 GeneralUtility::makeInstance(ConnectionPool::class)
985 ->getConnectionForTable($table)
986 ->update(
987 $table,
988 $movePlh,
989 ['uid' => (int)$movePlhID]
990 );
991 $dataHandler->addRemapStackRefIndex($table, $movePlhID);
992 }
993 }
994 // Checking for delete:
995 // Delete only if new/deleted placeholders are there.
996 if (!$swapIntoWS && ((int)$t3ver_state['swapVersion'] === 1 || (int)$t3ver_state['swapVersion'] === 2)) {
997 // Force delete
998 $dataHandler->deleteEl($table, $id, true);
999 }
1000 $dataHandler->newlog2(($swapIntoWS ? 'Swapping' : 'Publishing') . ' successful for table "' . $table . '" uid ' . $id . '=>' . $swapWith, $table, $id, $swapVersion['pid']);
1001 // Update reference index of the live record:
1002 $dataHandler->addRemapStackRefIndex($table, $id);
1003 // Set log entry for live record:
1004 $propArr = $dataHandler->getRecordPropertiesFromRow($table, $swapVersion);
1005 if ($propArr['_ORIG_pid'] == -1) {
1006 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.offline_record_updated');
1007 } else {
1008 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.online_record_updated');
1009 }
1010 $theLogId = $dataHandler->log($table, $id, 2, $propArr['pid'], 0, $label, 10, [$propArr['header'], $table . ':' . $id], $propArr['event_pid']);
1011 $dataHandler->setHistory($table, $id, $theLogId);
1012 // Update reference index of the offline record:
1013 $dataHandler->addRemapStackRefIndex($table, $swapWith);
1014 // Set log entry for offline record:
1015 $propArr = $dataHandler->getRecordPropertiesFromRow($table, $curVersion);
1016 if ($propArr['_ORIG_pid'] == -1) {
1017 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.offline_record_updated');
1018 } else {
1019 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.online_record_updated');
1020 }
1021 $theLogId = $dataHandler->log($table, $swapWith, 2, $propArr['pid'], 0, $label, 10, [$propArr['header'], $table . ':' . $swapWith], $propArr['event_pid']);
1022 $dataHandler->setHistory($table, $swapWith, $theLogId);
1023
1024 $stageId = -20; // \TYPO3\CMS\Workspaces\Service\StagesService::STAGE_PUBLISH_EXECUTE_ID;
1025 if ($notificationEmailInfo) {
1026 $notificationEmailInfoKey = $wsAccess['uid'] . ':' . $stageId . ':' . $comment;
1027 $this->notificationEmailInfo[$notificationEmailInfoKey]['shared'] = [$wsAccess, $stageId, $comment];
1028 $this->notificationEmailInfo[$notificationEmailInfoKey]['elements'][] = $table . ':' . $id;
1029 $this->notificationEmailInfo[$notificationEmailInfoKey]['alternativeRecipients'] = $notificationAlternativeRecipients;
1030 } else {
1031 $this->notifyStageChange($wsAccess, $stageId, $table, $id, $comment, $dataHandler, $notificationAlternativeRecipients);
1032 }
1033 // Write to log with stageId -20
1034 $dataHandler->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id);
1035 $dataHandler->log($table, $id, 6, 0, 0, 'Published', 30, ['comment' => $comment, 'stage' => $stageId]);
1036
1037 // Clear cache:
1038 $dataHandler->registerRecordIdForPageCacheClearing($table, $id);
1039 // Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!):
1040 if (!$swapIntoWS && $t3ver_state['curVersion'] > 0) {
1041 // For delete + completely delete!
1042 $dataHandler->deleteEl($table, $swapWith, true, true);
1043 }
1044
1045 //Update reference index for live workspace too:
1046 /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */
1047 $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
1048 $refIndexObj->setWorkspaceId(0);
1049 $refIndexObj->updateRefIndexTable($table, $id);
1050 $refIndexObj->updateRefIndexTable($table, $swapWith);
1051 }
1052 }
1053
1054 /**
1055 * Writes remapped foreign field (IRRE).
1056 *
1057 * @param \TYPO3\CMS\Core\Database\RelationHandler $dbAnalysis Instance that holds the sorting order of child records
1058 * @param array $configuration The TCA field configuration
1059 * @param int $parentId The uid of the parent record
1060 */
1061 public function writeRemappedForeignField(\TYPO3\CMS\Core\Database\RelationHandler $dbAnalysis, array $configuration, $parentId)
1062 {
1063 foreach ($dbAnalysis->itemArray as &$item) {
1064 if (isset($this->remappedIds[$item['table']][$item['id']])) {
1065 $item['id'] = $this->remappedIds[$item['table']][$item['id']];
1066 }
1067 }
1068 $dbAnalysis->writeForeignField($configuration, $parentId);
1069 }
1070
1071 /**
1072 * Processes fields of a record for the publishing/swapping process.
1073 * Basically this takes care of IRRE (type "inline") child references.
1074 *
1075 * @param string $tableName Table name
1076 * @param string $fieldName: Field name
1077 * @param array $configuration TCA field configuration
1078 * @param array $liveData: Live record data
1079 * @param array $versionData: Version record data
1080 * @param DataHandler $dataHandler Calling data-handler object
1081 */
1082 protected function version_swap_processFields($tableName, $fieldName, array $configuration, array $liveData, array $versionData, DataHandler $dataHandler)
1083 {
1084 $inlineType = $dataHandler->getInlineFieldType($configuration);
1085 if ($inlineType !== 'field') {
1086 return;
1087 }
1088 $foreignTable = $configuration['foreign_table'];
1089 // Read relations that point to the current record (e.g. live record):
1090 $liveRelations = $this->createRelationHandlerInstance();
1091 $liveRelations->setWorkspaceId(0);
1092 $liveRelations->start('', $foreignTable, '', $liveData['uid'], $tableName, $configuration);
1093 // Read relations that point to the record to be swapped with e.g. draft record):
1094 $versionRelations = $this->createRelationHandlerInstance();
1095 $versionRelations->setUseLiveReferenceIds(false);
1096 $versionRelations->start('', $foreignTable, '', $versionData['uid'], $tableName, $configuration);
1097 // Update relations for both (workspace/versioning) sites:
1098 if (count($liveRelations->itemArray)) {
1099 $dataHandler->addRemapAction(
1100 $tableName,
1101 $liveData['uid'],
1102 [$this, 'updateInlineForeignFieldSorting'],
1103 [$tableName, $liveData['uid'], $foreignTable, $liveRelations->tableArray[$foreignTable], $configuration, $dataHandler->BE_USER->workspace]
1104 );
1105 }
1106 if (count($versionRelations->itemArray)) {
1107 $dataHandler->addRemapAction(
1108 $tableName,
1109 $liveData['uid'],
1110 [$this, 'updateInlineForeignFieldSorting'],
1111 [$tableName, $liveData['uid'], $foreignTable, $versionRelations->tableArray[$foreignTable], $configuration, 0]
1112 );
1113 }
1114 }
1115
1116 /**
1117 * Updates foreign field sorting values of versioned and live
1118 * parents after(!) the whole structure has been published.
1119 *
1120 * This method is used as callback function in
1121 * DataHandlerHook::version_swap_procBasedOnFieldType().
1122 * Sorting fields ("sortby") are not modified during the
1123 * workspace publishing/swapping process directly.
1124 *
1125 * @param string $parentTableName
1126 * @param string $parentId
1127 * @param string $foreignTableName
1128 * @param int[] $foreignIds
1129 * @param array $configuration
1130 * @param int $targetWorkspaceId
1131 * @internal
1132 */
1133 public function updateInlineForeignFieldSorting($parentTableName, $parentId, $foreignTableName, $foreignIds, array $configuration, $targetWorkspaceId)
1134 {
1135 $remappedIds = [];
1136 // Use remapped ids (live id <-> version id)
1137 foreach ($foreignIds as $foreignId) {
1138 if (!empty($this->remappedIds[$foreignTableName][$foreignId])) {
1139 $remappedIds[] = $this->remappedIds[$foreignTableName][$foreignId];
1140 } else {
1141 $remappedIds[] = $foreignId;
1142 }
1143 }
1144
1145 $relationHandler = $this->createRelationHandlerInstance();
1146 $relationHandler->setWorkspaceId($targetWorkspaceId);
1147 $relationHandler->setUseLiveReferenceIds(false);
1148 $relationHandler->start(implode(',', $remappedIds), $foreignTableName);
1149 $relationHandler->processDeletePlaceholder();
1150 $relationHandler->writeForeignField($configuration, $parentId);
1151 }
1152
1153 /**
1154 * Release version from this workspace (and into "Live" workspace but as an offline version).
1155 *
1156 * @param string $table Table name
1157 * @param int $id Record UID
1158 * @param bool $flush If set, will completely delete element
1159 * @param DataHandler $dataHandler DataHandler object
1160 */
1161 protected function version_clearWSID($table, $id, $flush = false, DataHandler $dataHandler)
1162 {
1163 if ($errorCode = $dataHandler->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
1164 $dataHandler->newlog('Attempt to reset workspace for record failed: ' . $errorCode, 1);
1165 return;
1166 }
1167 if (!$dataHandler->checkRecordUpdateAccess($table, $id)) {
1168 $dataHandler->newlog('Attempt to reset workspace for record failed because you do not have edit access', 1);
1169 return;
1170 }
1171 $liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, 'uid,t3ver_state');
1172 if (!$liveRec) {
1173 return;
1174 }
1175 // Clear workspace ID:
1176 $updateData = [
1177 't3ver_wsid' => 0,
1178 't3ver_tstamp' => $GLOBALS['EXEC_TIME']
1179 ];
1180 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
1181 $connection->update(
1182 $table,
1183 $updateData,
1184 ['uid' => (int)$id]
1185 );
1186
1187 // Clear workspace ID for live version AND DELETE IT as well because it is a new record!
1188 if (
1189 VersionState::cast($liveRec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER)
1190 || VersionState::cast($liveRec['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
1191 ) {
1192 $connection->update(
1193 $table,
1194 $updateData,
1195 ['uid' => (int)$liveRec['uid']]
1196 );
1197
1198 // THIS assumes that the record was placeholder ONLY for ONE record (namely $id)
1199 $dataHandler->deleteEl($table, $liveRec['uid'], true);
1200 }
1201 // If "deleted" flag is set for the version that got released
1202 // it doesn't make sense to keep that "placeholder" anymore and we delete it completly.
1203 $wsRec = BackendUtility::getRecord($table, $id);
1204 if (
1205 $flush
1206 || (
1207 VersionState::cast($wsRec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER)
1208 || VersionState::cast($wsRec['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
1209 )
1210 ) {
1211 $dataHandler->deleteEl($table, $id, true, true);
1212 }
1213 // Remove the move-placeholder if found for live record.
1214 if (BackendUtility::isTableWorkspaceEnabled($table)) {
1215 if ($plhRec = BackendUtility::getMovePlaceholder($table, $liveRec['uid'], 'uid')) {
1216 $dataHandler->deleteEl($table, $plhRec['uid'], true, true);
1217 }
1218 }
1219 }
1220
1221 /*******************************
1222 ***** helper functions ******
1223 *******************************/
1224
1225 /**
1226 * Finds all elements for swapping versions in workspace
1227 *
1228 * @param string $table Table name of the original element to swap
1229 * @param int $id UID of the original element to swap (online)
1230 * @param int $offlineId As above but offline
1231 * @return array Element data. Key is table name, values are array with first element as online UID, second - offline UID
1232 */
1233 public function findPageElementsForVersionSwap($table, $id, $offlineId)
1234 {
1235 $rec = BackendUtility::getRecord($table, $offlineId, 't3ver_wsid');
1236 $workspaceId = (int)$rec['t3ver_wsid'];
1237 $elementData = [];
1238 if ($workspaceId === 0) {
1239 return $elementData;
1240 }
1241 // Get page UID for LIVE and workspace
1242 if ($table !== 'pages') {
1243 $rec = BackendUtility::getRecord($table, $id, 'pid');
1244 $pageId = $rec['pid'];
1245 $rec = BackendUtility::getRecord('pages', $pageId);
1246 BackendUtility::workspaceOL('pages', $rec, $workspaceId);
1247 $offlinePageId = $rec['_ORIG_uid'];
1248 } else {
1249 $pageId = $id;
1250 $offlinePageId = $offlineId;
1251 }
1252 // Traversing all tables supporting versioning:
1253 foreach ($GLOBALS['TCA'] as $table => $cfg) {
1254 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1255 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1256 ->getQueryBuilderForTable($table);
1257
1258 $queryBuilder->getRestrictions()
1259 ->removeAll()
1260 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1261
1262 $statement = $queryBuilder
1263 ->select('A.uid AS offlineUid', 'B.uid AS uid')
1264 ->from($table, 'A')
1265 ->from($table, 'B')
1266 ->where(
1267 $queryBuilder->expr()->eq(
1268 'A.pid',
1269 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1270 ),
1271 $queryBuilder->expr()->eq(
1272 'B.pid',
1273 $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
1274 ),
1275 $queryBuilder->expr()->eq(
1276 'A.t3ver_wsid',
1277 $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
1278 ),
1279 $queryBuilder->expr()->eq('A.t3ver_oid', $queryBuilder->quoteIdentifier('B.uid'))
1280 )
1281 ->execute();
1282
1283 while ($row = $statement->fetch()) {
1284 $elementData[$table][] = [$row['uid'], $row['offlineUid']];
1285 }
1286 }
1287 }
1288 if ($offlinePageId && $offlinePageId != $pageId) {
1289 $elementData['pages'][] = [$pageId, $offlinePageId];
1290 }
1291
1292 return $elementData;
1293 }
1294
1295 /**
1296 * Searches for all elements from all tables on the given pages in the same workspace.
1297 *
1298 * @param array $pageIdList List of PIDs to search
1299 * @param int $workspaceId Workspace ID
1300 * @param array $elementList List of found elements. Key is table name, value is array of element UIDs
1301 */
1302 public function findPageElementsForVersionStageChange(array $pageIdList, $workspaceId, array &$elementList)
1303 {
1304 if ($workspaceId == 0) {
1305 return;
1306 }
1307 // Traversing all tables supporting versioning:
1308 foreach ($GLOBALS['TCA'] as $table => $cfg) {
1309 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1310 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1311 ->getQueryBuilderForTable($table);
1312
1313 $queryBuilder->getRestrictions()
1314 ->removeAll()
1315 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1316
1317 $statement = $queryBuilder
1318 ->select('A.uid')
1319 ->from($table, 'A')
1320 ->from($table, 'B')
1321 ->where(
1322 $queryBuilder->expr()->eq(
1323 'A.pid',
1324 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1325 ),
1326 $queryBuilder->expr()->in(
1327 'B.pid',
1328 $queryBuilder->createNamedParameter($pageIdList, Connection::PARAM_INT_ARRAY)
1329 ),
1330 $queryBuilder->expr()->eq(
1331 'A.t3ver_wsid',
1332 $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
1333 ),
1334 $queryBuilder->expr()->eq('A.t3ver_oid', $queryBuilder->quoteIdentifier('B.uid'))
1335 )
1336 ->groupBy('A.uid')
1337 ->execute();
1338
1339 while ($row = $statement->fetch()) {
1340 $elementList[$table][] = $row['uid'];
1341 }
1342 if (is_array($elementList[$table])) {
1343 // Yes, it is possible to get non-unique array even with DISTINCT above!
1344 // It happens because several UIDs are passed in the array already.
1345 $elementList[$table] = array_unique($elementList[$table]);
1346 }
1347 }
1348 }
1349 }
1350
1351 /**
1352 * Finds page UIDs for the element from table <code>$table</code> with UIDs from <code>$idList</code>
1353 *
1354 * @param string $table Table to search
1355 * @param array $idList List of records' UIDs
1356 * @param int $workspaceId Workspace ID. We need this parameter because user can be in LIVE but he still can publisg DRAFT from ws module!
1357 * @param array $pageIdList List of found page UIDs
1358 * @param array $elementList List of found element UIDs. Key is table name, value is list of UIDs
1359 */
1360 public function findPageIdsForVersionStateChange($table, array $idList, $workspaceId, array &$pageIdList, array &$elementList)
1361 {
1362 if ($workspaceId == 0) {
1363 return;
1364 }
1365
1366 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1367 ->getQueryBuilderForTable($table);
1368 $queryBuilder->getRestrictions()
1369 ->removeAll()
1370 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1371
1372 $statement = $queryBuilder
1373 ->select('B.pid')
1374 ->from($table, 'A')
1375 ->from($table, 'B')
1376 ->where(
1377 $queryBuilder->expr()->eq(
1378 'A.pid',
1379 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1380 ),
1381 $queryBuilder->expr()->eq(
1382 'A.t3ver_wsid',
1383 $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
1384 ),
1385 $queryBuilder->expr()->in(
1386 'A.uid',
1387 $queryBuilder->createNamedParameter($idList, Connection::PARAM_INT_ARRAY)
1388 ),
1389 $queryBuilder->expr()->eq('A.t3ver_oid', $queryBuilder->quoteIdentifier('B.uid'))
1390 )
1391 ->groupBy('B.pid')
1392 ->execute();
1393
1394 while ($row = $statement->fetch()) {
1395 $pageIdList[] = $row['pid'];
1396 // Find ws version
1397 // Note: cannot use BackendUtility::getRecordWSOL()
1398 // here because it does not accept workspace id!
1399 $rec = BackendUtility::getRecord('pages', $row[0]);
1400 BackendUtility::workspaceOL('pages', $rec, $workspaceId);
1401 if ($rec['_ORIG_uid']) {
1402 $elementList['pages'][$row[0]] = $rec['_ORIG_uid'];
1403 }
1404 }
1405 // The line below is necessary even with DISTINCT
1406 // because several elements can be passed by caller
1407 $pageIdList = array_unique($pageIdList);
1408 }
1409
1410 /**
1411 * Finds real page IDs for state change.
1412 *
1413 * @param array $idList List of page UIDs, possibly versioned
1414 */
1415 public function findRealPageIds(array &$idList)
1416 {
1417 foreach ($idList as $key => $id) {
1418 $rec = BackendUtility::getRecord('pages', $id, 't3ver_oid');
1419 if ($rec['t3ver_oid'] > 0) {
1420 $idList[$key] = $rec['t3ver_oid'];
1421 }
1422 }
1423 }
1424
1425 /**
1426 * Creates a move placeholder for workspaces.
1427 * USE ONLY INTERNALLY
1428 * Moving placeholder: Can be done because the system sees it as a placeholder for NEW elements like t3ver_state=VersionState::NEW_PLACEHOLDER
1429 * Moving original: Will either create the placeholder if it doesn't exist or move existing placeholder in workspace.
1430 *
1431 * @param string $table Table name to move
1432 * @param int $uid Record uid to move (online record)
1433 * @param int $destPid Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
1434 * @param int $wsUid UID of offline version of online record
1435 * @param DataHandler $dataHandler DataHandler object
1436 * @see moveRecord()
1437 */
1438 protected function moveRecord_wsPlaceholders($table, $uid, $destPid, $wsUid, DataHandler $dataHandler)
1439 {
1440 // If a record gets moved after a record that already has a placeholder record
1441 // then the new placeholder record needs to be after the existing one
1442 $originalRecordDestinationPid = $destPid;
1443 if ($destPid < 0) {
1444 $movePlaceHolder = BackendUtility::getMovePlaceholder($table, abs($destPid), 'uid');
1445 if ($movePlaceHolder !== false) {
1446 $destPid = -$movePlaceHolder['uid'];
1447 }
1448 }
1449 if ($plh = BackendUtility::getMovePlaceholder($table, $uid, 'uid')) {
1450 // If already a placeholder exists, move it:
1451 $dataHandler->moveRecord_raw($table, $plh['uid'], $destPid);
1452 } else {
1453 // First, we create a placeholder record in the Live workspace that
1454 // represents the position to where the record is eventually moved to.
1455 $newVersion_placeholderFieldArray = [];
1456
1457 // Use property for move placeholders if set (since TYPO3 CMS 6.2)
1458 if (isset($GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForMovePlaceholders'])) {
1459 $shadowColumnsForMovePlaceholder = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForMovePlaceholders'];
1460 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'])) {
1461 // Fallback to property for new placeholder (existed long time before TYPO3 CMS 6.2)
1462 $shadowColumnsForMovePlaceholder = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1463 }
1464
1465 // Set values from the versioned record to the move placeholder
1466 if (!empty($shadowColumnsForMovePlaceholder)) {
1467 $versionedRecord = BackendUtility::getRecord($table, $wsUid);
1468 $shadowColumns = GeneralUtility::trimExplode(',', $shadowColumnsForMovePlaceholder, true);
1469 foreach ($shadowColumns as $shadowColumn) {
1470 if (isset($versionedRecord[$shadowColumn])) {
1471 $newVersion_placeholderFieldArray[$shadowColumn] = $versionedRecord[$shadowColumn];
1472 }
1473 }
1474 }
1475
1476 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1477 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1478 }
1479 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1480 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $dataHandler->userid;
1481 }
1482 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
1483 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1484 }
1485 if ($table === 'pages') {
1486 // Copy page access settings from original page to placeholder
1487 $perms_clause = $dataHandler->BE_USER->getPagePermsClause(1);
1488 $access = BackendUtility::readPageAccess($uid, $perms_clause);
1489 $newVersion_placeholderFieldArray['perms_userid'] = $access['perms_userid'];
1490 $newVersion_placeholderFieldArray['perms_groupid'] = $access['perms_groupid'];
1491 $newVersion_placeholderFieldArray['perms_user'] = $access['perms_user'];
1492 $newVersion_placeholderFieldArray['perms_group'] = $access['perms_group'];
1493 $newVersion_placeholderFieldArray['perms_everybody'] = $access['perms_everybody'];
1494 }
1495 $newVersion_placeholderFieldArray['t3ver_label'] = 'MovePlaceholder #' . $uid;
1496 $newVersion_placeholderFieldArray['t3ver_move_id'] = $uid;
1497 // Setting placeholder state value for temporary record
1498 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState::MOVE_PLACEHOLDER);
1499 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1500 $newVersion_placeholderFieldArray['t3ver_wsid'] = $dataHandler->BE_USER->workspace;
1501 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $dataHandler->getPlaceholderTitleForTableLabel($table, 'MOVE-TO PLACEHOLDER for #' . $uid);
1502 // moving localized records requires to keep localization-settings for the placeholder too
1503 if (isset($GLOBALS['TCA'][$table]['ctrl']['languageField']) && isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
1504 $l10nParentRec = BackendUtility::getRecord($table, $uid);
1505 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1506 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1507 if (isset($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])) {
1508 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']];
1509 }
1510 unset($l10nParentRec);
1511 }
1512 // Initially, create at root level.
1513 $newVersion_placeholderFieldArray['pid'] = 0;
1514 $id = 'NEW_MOVE_PLH';
1515 // Saving placeholder as 'original'
1516 $dataHandler->insertDB($table, $id, $newVersion_placeholderFieldArray, false);
1517 // Move the new placeholder from temporary root-level to location:
1518 $dataHandler->moveRecord_raw($table, $dataHandler->substNEWwithIDs[$id], $destPid);
1519 // Move the workspace-version of the original to be the version of the move-to-placeholder:
1520 // Setting placeholder state value for version (so it can know it is currently a new version...)
1521 $updateFields = [
1522 't3ver_state' => (string)new VersionState(VersionState::MOVE_POINTER)
1523 ];
1524
1525 GeneralUtility::makeInstance(ConnectionPool::class)
1526 ->getConnectionForTable($table)
1527 ->update(
1528 $table,
1529 $updateFields,
1530 ['uid' => (int)$wsUid]
1531 );
1532 }
1533 // Check for the localizations of that element and move them as well
1534 $dataHandler->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
1535 }
1536
1537 /**
1538 * Gets an instance of the command map helper.
1539 *
1540 * @param DataHandler $dataHandler DataHandler object
1541 * @return \TYPO3\CMS\Version\DataHandler\CommandMap
1542 */
1543 public function getCommandMap(DataHandler $dataHandler)
1544 {
1545 return GeneralUtility::makeInstance(
1546 \TYPO3\CMS\Version\DataHandler\CommandMap::class,
1547 $this,
1548 $dataHandler,
1549 $dataHandler->cmdmap,
1550 $dataHandler->BE_USER->workspace
1551 );
1552 }
1553
1554 /**
1555 * Returns all fieldnames from a table which have the unique evaluation type set.
1556 *
1557 * @param string $table Table name
1558 * @return array Array of fieldnames
1559 */
1560 protected function getUniqueFields($table)
1561 {
1562 $listArr = [];
1563 if (empty($GLOBALS['TCA'][$table]['columns'])) {
1564 return $listArr;
1565 }
1566 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $configArr) {
1567 if ($configArr['config']['type'] === 'input') {
1568 $evalCodesArray = GeneralUtility::trimExplode(',', $configArr['config']['eval'], true);
1569 if (in_array('uniqueInPid', $evalCodesArray) || in_array('unique', $evalCodesArray)) {
1570 $listArr[] = $field;
1571 }
1572 }
1573 }
1574 return $listArr;
1575 }
1576
1577 /**
1578 * @return \TYPO3\CMS\Core\Database\RelationHandler
1579 */
1580 protected function createRelationHandlerInstance()
1581 {
1582 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
1583 }
1584
1585 /**
1586 * @return LanguageService
1587 */
1588 protected function getLanguageService()
1589 {
1590 return $GLOBALS['LANG'];
1591 }
1592 }