[BUGFIX] Prevent catchable error during workspace publishing
[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 if (isset($fieldConf['config']) && is_array($fieldConf['config'])) {
897 $this->version_swap_processFields($table, $field, $fieldConf['config'], $curVersion, $swapVersion, $dataHandler);
898 }
899 }
900 }
901 unset($swapVersion['uid']);
902 // Modify online version to become offline:
903 unset($curVersion['uid']);
904 // Set pid for OFFLINE
905 $curVersion['pid'] = -1;
906 $curVersion['t3ver_oid'] = (int)$id;
907 $curVersion['t3ver_wsid'] = $swapIntoWS ? (int)$tmp_wsid : 0;
908 $curVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
909 $curVersion['t3ver_count'] = $curVersion['t3ver_count'] + 1;
910 // Increment lifecycle counter
911 $curVersion['t3ver_stage'] = 0;
912 if (!$swapIntoWS) {
913 $curVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
914 }
915 // Registering and swapping MM relations in current and swap records:
916 $dataHandler->version_remapMMForVersionSwap($table, $id, $swapWith);
917 // Generating proper history data to prepare logging
918 $dataHandler->compareFieldArrayWithCurrentAndUnset($table, $id, $swapVersion);
919 $dataHandler->compareFieldArrayWithCurrentAndUnset($table, $swapWith, $curVersion);
920
921 // Execute swapping:
922 $sqlErrors = [];
923 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
924
925 $platform = $connection->getDatabasePlatform();
926 $tableDetails = null;
927 if ($platform instanceof SQLServerPlatform) {
928 // mssql needs to set proper PARAM_LOB and others to update fields
929 $tableDetails = $connection->getSchemaManager()->listTableDetails($table);
930 }
931
932 try {
933 $types = [];
934
935 if ($platform instanceof SQLServerPlatform) {
936 foreach ($curVersion as $columnName => $columnValue) {
937 $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
938 }
939 }
940
941 $connection->update(
942 $table,
943 $swapVersion,
944 ['uid' => (int)$id],
945 $types
946 );
947 } catch (DBALException $e) {
948 $sqlErrors[] = $e->getPrevious()->getMessage();
949 }
950
951 if (empty($sqlErrors)) {
952 try {
953 $types = [];
954 if ($platform instanceof SQLServerPlatform) {
955 foreach ($curVersion as $columnName => $columnValue) {
956 $types[$columnName] = $tableDetails->getColumn($columnName)->getType()->getBindingType();
957 }
958 }
959
960 $connection->update(
961 $table,
962 $curVersion,
963 ['uid' => (int)$swapWith],
964 $types
965 );
966 unlink($lockFileName);
967 } catch (DBALException $e) {
968 $sqlErrors[] = $e->getPrevious()->getMessage();
969 }
970 }
971
972 if (!empty($sqlErrors)) {
973 $dataHandler->newlog('During Swapping: SQL errors happened: ' . implode('; ', $sqlErrors), 2);
974 } else {
975 // Register swapped ids for later remapping:
976 $this->remappedIds[$table][$id] = $swapWith;
977 $this->remappedIds[$table][$swapWith] = $id;
978 // If a moving operation took place...:
979 if ($movePlhID) {
980 // Remove, if normal publishing:
981 if (!$swapIntoWS) {
982 // For delete + completely delete!
983 $dataHandler->deleteEl($table, $movePlhID, true, true);
984 } else {
985 // Otherwise update the movePlaceholder:
986 GeneralUtility::makeInstance(ConnectionPool::class)
987 ->getConnectionForTable($table)
988 ->update(
989 $table,
990 $movePlh,
991 ['uid' => (int)$movePlhID]
992 );
993 $dataHandler->addRemapStackRefIndex($table, $movePlhID);
994 }
995 }
996 // Checking for delete:
997 // Delete only if new/deleted placeholders are there.
998 if (!$swapIntoWS && ((int)$t3ver_state['swapVersion'] === 1 || (int)$t3ver_state['swapVersion'] === 2)) {
999 // Force delete
1000 $dataHandler->deleteEl($table, $id, true);
1001 }
1002 $dataHandler->newlog2(($swapIntoWS ? 'Swapping' : 'Publishing') . ' successful for table "' . $table . '" uid ' . $id . '=>' . $swapWith, $table, $id, $swapVersion['pid']);
1003 // Update reference index of the live record:
1004 $dataHandler->addRemapStackRefIndex($table, $id);
1005 // Set log entry for live record:
1006 $propArr = $dataHandler->getRecordPropertiesFromRow($table, $swapVersion);
1007 if ($propArr['_ORIG_pid'] == -1) {
1008 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.offline_record_updated');
1009 } else {
1010 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.online_record_updated');
1011 }
1012 $theLogId = $dataHandler->log($table, $id, 2, $propArr['pid'], 0, $label, 10, [$propArr['header'], $table . ':' . $id], $propArr['event_pid']);
1013 $dataHandler->setHistory($table, $id, $theLogId);
1014 // Update reference index of the offline record:
1015 $dataHandler->addRemapStackRefIndex($table, $swapWith);
1016 // Set log entry for offline record:
1017 $propArr = $dataHandler->getRecordPropertiesFromRow($table, $curVersion);
1018 if ($propArr['_ORIG_pid'] == -1) {
1019 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.offline_record_updated');
1020 } else {
1021 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_tcemain.xlf:version_swap.online_record_updated');
1022 }
1023 $theLogId = $dataHandler->log($table, $swapWith, 2, $propArr['pid'], 0, $label, 10, [$propArr['header'], $table . ':' . $swapWith], $propArr['event_pid']);
1024 $dataHandler->setHistory($table, $swapWith, $theLogId);
1025
1026 $stageId = -20; // \TYPO3\CMS\Workspaces\Service\StagesService::STAGE_PUBLISH_EXECUTE_ID;
1027 if ($notificationEmailInfo) {
1028 $notificationEmailInfoKey = $wsAccess['uid'] . ':' . $stageId . ':' . $comment;
1029 $this->notificationEmailInfo[$notificationEmailInfoKey]['shared'] = [$wsAccess, $stageId, $comment];
1030 $this->notificationEmailInfo[$notificationEmailInfoKey]['elements'][] = $table . ':' . $id;
1031 $this->notificationEmailInfo[$notificationEmailInfoKey]['alternativeRecipients'] = $notificationAlternativeRecipients;
1032 } else {
1033 $this->notifyStageChange($wsAccess, $stageId, $table, $id, $comment, $dataHandler, $notificationAlternativeRecipients);
1034 }
1035 // Write to log with stageId -20
1036 $dataHandler->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id);
1037 $dataHandler->log($table, $id, 6, 0, 0, 'Published', 30, ['comment' => $comment, 'stage' => $stageId]);
1038
1039 // Clear cache:
1040 $dataHandler->registerRecordIdForPageCacheClearing($table, $id);
1041 // Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!):
1042 if (!$swapIntoWS && $t3ver_state['curVersion'] > 0) {
1043 // For delete + completely delete!
1044 $dataHandler->deleteEl($table, $swapWith, true, true);
1045 }
1046
1047 //Update reference index for live workspace too:
1048 /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */
1049 $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
1050 $refIndexObj->setWorkspaceId(0);
1051 $refIndexObj->updateRefIndexTable($table, $id);
1052 $refIndexObj->updateRefIndexTable($table, $swapWith);
1053 }
1054 }
1055
1056 /**
1057 * Writes remapped foreign field (IRRE).
1058 *
1059 * @param \TYPO3\CMS\Core\Database\RelationHandler $dbAnalysis Instance that holds the sorting order of child records
1060 * @param array $configuration The TCA field configuration
1061 * @param int $parentId The uid of the parent record
1062 */
1063 public function writeRemappedForeignField(\TYPO3\CMS\Core\Database\RelationHandler $dbAnalysis, array $configuration, $parentId)
1064 {
1065 foreach ($dbAnalysis->itemArray as &$item) {
1066 if (isset($this->remappedIds[$item['table']][$item['id']])) {
1067 $item['id'] = $this->remappedIds[$item['table']][$item['id']];
1068 }
1069 }
1070 $dbAnalysis->writeForeignField($configuration, $parentId);
1071 }
1072
1073 /**
1074 * Processes fields of a record for the publishing/swapping process.
1075 * Basically this takes care of IRRE (type "inline") child references.
1076 *
1077 * @param string $tableName Table name
1078 * @param string $fieldName: Field name
1079 * @param array $configuration TCA field configuration
1080 * @param array $liveData: Live record data
1081 * @param array $versionData: Version record data
1082 * @param DataHandler $dataHandler Calling data-handler object
1083 */
1084 protected function version_swap_processFields($tableName, $fieldName, array $configuration, array $liveData, array $versionData, DataHandler $dataHandler)
1085 {
1086 $inlineType = $dataHandler->getInlineFieldType($configuration);
1087 if ($inlineType !== 'field') {
1088 return;
1089 }
1090 $foreignTable = $configuration['foreign_table'];
1091 // Read relations that point to the current record (e.g. live record):
1092 $liveRelations = $this->createRelationHandlerInstance();
1093 $liveRelations->setWorkspaceId(0);
1094 $liveRelations->start('', $foreignTable, '', $liveData['uid'], $tableName, $configuration);
1095 // Read relations that point to the record to be swapped with e.g. draft record):
1096 $versionRelations = $this->createRelationHandlerInstance();
1097 $versionRelations->setUseLiveReferenceIds(false);
1098 $versionRelations->start('', $foreignTable, '', $versionData['uid'], $tableName, $configuration);
1099 // Update relations for both (workspace/versioning) sites:
1100 if (count($liveRelations->itemArray)) {
1101 $dataHandler->addRemapAction(
1102 $tableName,
1103 $liveData['uid'],
1104 [$this, 'updateInlineForeignFieldSorting'],
1105 [$tableName, $liveData['uid'], $foreignTable, $liveRelations->tableArray[$foreignTable], $configuration, $dataHandler->BE_USER->workspace]
1106 );
1107 }
1108 if (count($versionRelations->itemArray)) {
1109 $dataHandler->addRemapAction(
1110 $tableName,
1111 $liveData['uid'],
1112 [$this, 'updateInlineForeignFieldSorting'],
1113 [$tableName, $liveData['uid'], $foreignTable, $versionRelations->tableArray[$foreignTable], $configuration, 0]
1114 );
1115 }
1116 }
1117
1118 /**
1119 * Updates foreign field sorting values of versioned and live
1120 * parents after(!) the whole structure has been published.
1121 *
1122 * This method is used as callback function in
1123 * DataHandlerHook::version_swap_procBasedOnFieldType().
1124 * Sorting fields ("sortby") are not modified during the
1125 * workspace publishing/swapping process directly.
1126 *
1127 * @param string $parentTableName
1128 * @param string $parentId
1129 * @param string $foreignTableName
1130 * @param int[] $foreignIds
1131 * @param array $configuration
1132 * @param int $targetWorkspaceId
1133 * @internal
1134 */
1135 public function updateInlineForeignFieldSorting($parentTableName, $parentId, $foreignTableName, $foreignIds, array $configuration, $targetWorkspaceId)
1136 {
1137 $remappedIds = [];
1138 // Use remapped ids (live id <-> version id)
1139 foreach ($foreignIds as $foreignId) {
1140 if (!empty($this->remappedIds[$foreignTableName][$foreignId])) {
1141 $remappedIds[] = $this->remappedIds[$foreignTableName][$foreignId];
1142 } else {
1143 $remappedIds[] = $foreignId;
1144 }
1145 }
1146
1147 $relationHandler = $this->createRelationHandlerInstance();
1148 $relationHandler->setWorkspaceId($targetWorkspaceId);
1149 $relationHandler->setUseLiveReferenceIds(false);
1150 $relationHandler->start(implode(',', $remappedIds), $foreignTableName);
1151 $relationHandler->processDeletePlaceholder();
1152 $relationHandler->writeForeignField($configuration, $parentId);
1153 }
1154
1155 /**
1156 * Release version from this workspace (and into "Live" workspace but as an offline version).
1157 *
1158 * @param string $table Table name
1159 * @param int $id Record UID
1160 * @param bool $flush If set, will completely delete element
1161 * @param DataHandler $dataHandler DataHandler object
1162 */
1163 protected function version_clearWSID($table, $id, $flush = false, DataHandler $dataHandler)
1164 {
1165 if ($errorCode = $dataHandler->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
1166 $dataHandler->newlog('Attempt to reset workspace for record failed: ' . $errorCode, 1);
1167 return;
1168 }
1169 if (!$dataHandler->checkRecordUpdateAccess($table, $id)) {
1170 $dataHandler->newlog('Attempt to reset workspace for record failed because you do not have edit access', 1);
1171 return;
1172 }
1173 $liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, 'uid,t3ver_state');
1174 if (!$liveRec) {
1175 return;
1176 }
1177 // Clear workspace ID:
1178 $updateData = [
1179 't3ver_wsid' => 0,
1180 't3ver_tstamp' => $GLOBALS['EXEC_TIME']
1181 ];
1182 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
1183 $connection->update(
1184 $table,
1185 $updateData,
1186 ['uid' => (int)$id]
1187 );
1188
1189 // Clear workspace ID for live version AND DELETE IT as well because it is a new record!
1190 if (
1191 VersionState::cast($liveRec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER)
1192 || VersionState::cast($liveRec['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
1193 ) {
1194 $connection->update(
1195 $table,
1196 $updateData,
1197 ['uid' => (int)$liveRec['uid']]
1198 );
1199
1200 // THIS assumes that the record was placeholder ONLY for ONE record (namely $id)
1201 $dataHandler->deleteEl($table, $liveRec['uid'], true);
1202 }
1203 // If "deleted" flag is set for the version that got released
1204 // it doesn't make sense to keep that "placeholder" anymore and we delete it completly.
1205 $wsRec = BackendUtility::getRecord($table, $id);
1206 if (
1207 $flush
1208 || (
1209 VersionState::cast($wsRec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER)
1210 || VersionState::cast($wsRec['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
1211 )
1212 ) {
1213 $dataHandler->deleteEl($table, $id, true, true);
1214 }
1215 // Remove the move-placeholder if found for live record.
1216 if (BackendUtility::isTableWorkspaceEnabled($table)) {
1217 if ($plhRec = BackendUtility::getMovePlaceholder($table, $liveRec['uid'], 'uid')) {
1218 $dataHandler->deleteEl($table, $plhRec['uid'], true, true);
1219 }
1220 }
1221 }
1222
1223 /*******************************
1224 ***** helper functions ******
1225 *******************************/
1226
1227 /**
1228 * Finds all elements for swapping versions in workspace
1229 *
1230 * @param string $table Table name of the original element to swap
1231 * @param int $id UID of the original element to swap (online)
1232 * @param int $offlineId As above but offline
1233 * @return array Element data. Key is table name, values are array with first element as online UID, second - offline UID
1234 */
1235 public function findPageElementsForVersionSwap($table, $id, $offlineId)
1236 {
1237 $rec = BackendUtility::getRecord($table, $offlineId, 't3ver_wsid');
1238 $workspaceId = (int)$rec['t3ver_wsid'];
1239 $elementData = [];
1240 if ($workspaceId === 0) {
1241 return $elementData;
1242 }
1243 // Get page UID for LIVE and workspace
1244 if ($table !== 'pages') {
1245 $rec = BackendUtility::getRecord($table, $id, 'pid');
1246 $pageId = $rec['pid'];
1247 $rec = BackendUtility::getRecord('pages', $pageId);
1248 BackendUtility::workspaceOL('pages', $rec, $workspaceId);
1249 $offlinePageId = $rec['_ORIG_uid'];
1250 } else {
1251 $pageId = $id;
1252 $offlinePageId = $offlineId;
1253 }
1254 // Traversing all tables supporting versioning:
1255 foreach ($GLOBALS['TCA'] as $table => $cfg) {
1256 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1257 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1258 ->getQueryBuilderForTable($table);
1259
1260 $queryBuilder->getRestrictions()
1261 ->removeAll()
1262 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1263
1264 $statement = $queryBuilder
1265 ->select('A.uid AS offlineUid', 'B.uid AS uid')
1266 ->from($table, 'A')
1267 ->from($table, 'B')
1268 ->where(
1269 $queryBuilder->expr()->eq(
1270 'A.pid',
1271 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1272 ),
1273 $queryBuilder->expr()->eq(
1274 'B.pid',
1275 $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
1276 ),
1277 $queryBuilder->expr()->eq(
1278 'A.t3ver_wsid',
1279 $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
1280 ),
1281 $queryBuilder->expr()->eq('A.t3ver_oid', $queryBuilder->quoteIdentifier('B.uid'))
1282 )
1283 ->execute();
1284
1285 while ($row = $statement->fetch()) {
1286 $elementData[$table][] = [$row['uid'], $row['offlineUid']];
1287 }
1288 }
1289 }
1290 if ($offlinePageId && $offlinePageId != $pageId) {
1291 $elementData['pages'][] = [$pageId, $offlinePageId];
1292 }
1293
1294 return $elementData;
1295 }
1296
1297 /**
1298 * Searches for all elements from all tables on the given pages in the same workspace.
1299 *
1300 * @param array $pageIdList List of PIDs to search
1301 * @param int $workspaceId Workspace ID
1302 * @param array $elementList List of found elements. Key is table name, value is array of element UIDs
1303 */
1304 public function findPageElementsForVersionStageChange(array $pageIdList, $workspaceId, array &$elementList)
1305 {
1306 if ($workspaceId == 0) {
1307 return;
1308 }
1309 // Traversing all tables supporting versioning:
1310 foreach ($GLOBALS['TCA'] as $table => $cfg) {
1311 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1312 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1313 ->getQueryBuilderForTable($table);
1314
1315 $queryBuilder->getRestrictions()
1316 ->removeAll()
1317 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1318
1319 $statement = $queryBuilder
1320 ->select('A.uid')
1321 ->from($table, 'A')
1322 ->from($table, 'B')
1323 ->where(
1324 $queryBuilder->expr()->eq(
1325 'A.pid',
1326 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1327 ),
1328 $queryBuilder->expr()->in(
1329 'B.pid',
1330 $queryBuilder->createNamedParameter($pageIdList, Connection::PARAM_INT_ARRAY)
1331 ),
1332 $queryBuilder->expr()->eq(
1333 'A.t3ver_wsid',
1334 $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
1335 ),
1336 $queryBuilder->expr()->eq('A.t3ver_oid', $queryBuilder->quoteIdentifier('B.uid'))
1337 )
1338 ->groupBy('A.uid')
1339 ->execute();
1340
1341 while ($row = $statement->fetch()) {
1342 $elementList[$table][] = $row['uid'];
1343 }
1344 if (is_array($elementList[$table])) {
1345 // Yes, it is possible to get non-unique array even with DISTINCT above!
1346 // It happens because several UIDs are passed in the array already.
1347 $elementList[$table] = array_unique($elementList[$table]);
1348 }
1349 }
1350 }
1351 }
1352
1353 /**
1354 * Finds page UIDs for the element from table <code>$table</code> with UIDs from <code>$idList</code>
1355 *
1356 * @param string $table Table to search
1357 * @param array $idList List of records' UIDs
1358 * @param int $workspaceId Workspace ID. We need this parameter because user can be in LIVE but he still can publisg DRAFT from ws module!
1359 * @param array $pageIdList List of found page UIDs
1360 * @param array $elementList List of found element UIDs. Key is table name, value is list of UIDs
1361 */
1362 public function findPageIdsForVersionStateChange($table, array $idList, $workspaceId, array &$pageIdList, array &$elementList)
1363 {
1364 if ($workspaceId == 0) {
1365 return;
1366 }
1367
1368 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1369 ->getQueryBuilderForTable($table);
1370 $queryBuilder->getRestrictions()
1371 ->removeAll()
1372 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1373
1374 $statement = $queryBuilder
1375 ->select('B.pid')
1376 ->from($table, 'A')
1377 ->from($table, 'B')
1378 ->where(
1379 $queryBuilder->expr()->eq(
1380 'A.pid',
1381 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1382 ),
1383 $queryBuilder->expr()->eq(
1384 'A.t3ver_wsid',
1385 $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
1386 ),
1387 $queryBuilder->expr()->in(
1388 'A.uid',
1389 $queryBuilder->createNamedParameter($idList, Connection::PARAM_INT_ARRAY)
1390 ),
1391 $queryBuilder->expr()->eq('A.t3ver_oid', $queryBuilder->quoteIdentifier('B.uid'))
1392 )
1393 ->groupBy('B.pid')
1394 ->execute();
1395
1396 while ($row = $statement->fetch()) {
1397 $pageIdList[] = $row['pid'];
1398 // Find ws version
1399 // Note: cannot use BackendUtility::getRecordWSOL()
1400 // here because it does not accept workspace id!
1401 $rec = BackendUtility::getRecord('pages', $row[0]);
1402 BackendUtility::workspaceOL('pages', $rec, $workspaceId);
1403 if ($rec['_ORIG_uid']) {
1404 $elementList['pages'][$row[0]] = $rec['_ORIG_uid'];
1405 }
1406 }
1407 // The line below is necessary even with DISTINCT
1408 // because several elements can be passed by caller
1409 $pageIdList = array_unique($pageIdList);
1410 }
1411
1412 /**
1413 * Finds real page IDs for state change.
1414 *
1415 * @param array $idList List of page UIDs, possibly versioned
1416 */
1417 public function findRealPageIds(array &$idList)
1418 {
1419 foreach ($idList as $key => $id) {
1420 $rec = BackendUtility::getRecord('pages', $id, 't3ver_oid');
1421 if ($rec['t3ver_oid'] > 0) {
1422 $idList[$key] = $rec['t3ver_oid'];
1423 }
1424 }
1425 }
1426
1427 /**
1428 * Creates a move placeholder for workspaces.
1429 * USE ONLY INTERNALLY
1430 * Moving placeholder: Can be done because the system sees it as a placeholder for NEW elements like t3ver_state=VersionState::NEW_PLACEHOLDER
1431 * Moving original: Will either create the placeholder if it doesn't exist or move existing placeholder in workspace.
1432 *
1433 * @param string $table Table name to move
1434 * @param int $uid Record uid to move (online record)
1435 * @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
1436 * @param int $wsUid UID of offline version of online record
1437 * @param DataHandler $dataHandler DataHandler object
1438 * @see moveRecord()
1439 */
1440 protected function moveRecord_wsPlaceholders($table, $uid, $destPid, $wsUid, DataHandler $dataHandler)
1441 {
1442 // If a record gets moved after a record that already has a placeholder record
1443 // then the new placeholder record needs to be after the existing one
1444 $originalRecordDestinationPid = $destPid;
1445 if ($destPid < 0) {
1446 $movePlaceHolder = BackendUtility::getMovePlaceholder($table, abs($destPid), 'uid');
1447 if ($movePlaceHolder !== false) {
1448 $destPid = -$movePlaceHolder['uid'];
1449 }
1450 }
1451 if ($plh = BackendUtility::getMovePlaceholder($table, $uid, 'uid')) {
1452 // If already a placeholder exists, move it:
1453 $dataHandler->moveRecord_raw($table, $plh['uid'], $destPid);
1454 } else {
1455 // First, we create a placeholder record in the Live workspace that
1456 // represents the position to where the record is eventually moved to.
1457 $newVersion_placeholderFieldArray = [];
1458
1459 // Use property for move placeholders if set (since TYPO3 CMS 6.2)
1460 if (isset($GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForMovePlaceholders'])) {
1461 $shadowColumnsForMovePlaceholder = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForMovePlaceholders'];
1462 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'])) {
1463 // Fallback to property for new placeholder (existed long time before TYPO3 CMS 6.2)
1464 $shadowColumnsForMovePlaceholder = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1465 }
1466
1467 // Set values from the versioned record to the move placeholder
1468 if (!empty($shadowColumnsForMovePlaceholder)) {
1469 $versionedRecord = BackendUtility::getRecord($table, $wsUid);
1470 $shadowColumns = GeneralUtility::trimExplode(',', $shadowColumnsForMovePlaceholder, true);
1471 foreach ($shadowColumns as $shadowColumn) {
1472 if (isset($versionedRecord[$shadowColumn])) {
1473 $newVersion_placeholderFieldArray[$shadowColumn] = $versionedRecord[$shadowColumn];
1474 }
1475 }
1476 }
1477
1478 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1479 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1480 }
1481 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1482 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $dataHandler->userid;
1483 }
1484 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
1485 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1486 }
1487 if ($table === 'pages') {
1488 // Copy page access settings from original page to placeholder
1489 $perms_clause = $dataHandler->BE_USER->getPagePermsClause(1);
1490 $access = BackendUtility::readPageAccess($uid, $perms_clause);
1491 $newVersion_placeholderFieldArray['perms_userid'] = $access['perms_userid'];
1492 $newVersion_placeholderFieldArray['perms_groupid'] = $access['perms_groupid'];
1493 $newVersion_placeholderFieldArray['perms_user'] = $access['perms_user'];
1494 $newVersion_placeholderFieldArray['perms_group'] = $access['perms_group'];
1495 $newVersion_placeholderFieldArray['perms_everybody'] = $access['perms_everybody'];
1496 }
1497 $newVersion_placeholderFieldArray['t3ver_label'] = 'MovePlaceholder #' . $uid;
1498 $newVersion_placeholderFieldArray['t3ver_move_id'] = $uid;
1499 // Setting placeholder state value for temporary record
1500 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState::MOVE_PLACEHOLDER);
1501 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1502 $newVersion_placeholderFieldArray['t3ver_wsid'] = $dataHandler->BE_USER->workspace;
1503 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $dataHandler->getPlaceholderTitleForTableLabel($table, 'MOVE-TO PLACEHOLDER for #' . $uid);
1504 // moving localized records requires to keep localization-settings for the placeholder too
1505 if (isset($GLOBALS['TCA'][$table]['ctrl']['languageField']) && isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
1506 $l10nParentRec = BackendUtility::getRecord($table, $uid);
1507 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1508 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1509 if (isset($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])) {
1510 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']];
1511 }
1512 unset($l10nParentRec);
1513 }
1514 // Initially, create at root level.
1515 $newVersion_placeholderFieldArray['pid'] = 0;
1516 $id = 'NEW_MOVE_PLH';
1517 // Saving placeholder as 'original'
1518 $dataHandler->insertDB($table, $id, $newVersion_placeholderFieldArray, false);
1519 // Move the new placeholder from temporary root-level to location:
1520 $dataHandler->moveRecord_raw($table, $dataHandler->substNEWwithIDs[$id], $destPid);
1521 // Move the workspace-version of the original to be the version of the move-to-placeholder:
1522 // Setting placeholder state value for version (so it can know it is currently a new version...)
1523 $updateFields = [
1524 't3ver_state' => (string)new VersionState(VersionState::MOVE_POINTER)
1525 ];
1526
1527 GeneralUtility::makeInstance(ConnectionPool::class)
1528 ->getConnectionForTable($table)
1529 ->update(
1530 $table,
1531 $updateFields,
1532 ['uid' => (int)$wsUid]
1533 );
1534 }
1535 // Check for the localizations of that element and move them as well
1536 $dataHandler->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
1537 }
1538
1539 /**
1540 * Gets an instance of the command map helper.
1541 *
1542 * @param DataHandler $dataHandler DataHandler object
1543 * @return \TYPO3\CMS\Version\DataHandler\CommandMap
1544 */
1545 public function getCommandMap(DataHandler $dataHandler)
1546 {
1547 return GeneralUtility::makeInstance(
1548 \TYPO3\CMS\Version\DataHandler\CommandMap::class,
1549 $this,
1550 $dataHandler,
1551 $dataHandler->cmdmap,
1552 $dataHandler->BE_USER->workspace
1553 );
1554 }
1555
1556 /**
1557 * Returns all fieldnames from a table which have the unique evaluation type set.
1558 *
1559 * @param string $table Table name
1560 * @return array Array of fieldnames
1561 */
1562 protected function getUniqueFields($table)
1563 {
1564 $listArr = [];
1565 if (empty($GLOBALS['TCA'][$table]['columns'])) {
1566 return $listArr;
1567 }
1568 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $configArr) {
1569 if ($configArr['config']['type'] === 'input') {
1570 $evalCodesArray = GeneralUtility::trimExplode(',', $configArr['config']['eval'], true);
1571 if (in_array('uniqueInPid', $evalCodesArray) || in_array('unique', $evalCodesArray)) {
1572 $listArr[] = $field;
1573 }
1574 }
1575 }
1576 return $listArr;
1577 }
1578
1579 /**
1580 * @return \TYPO3\CMS\Core\Database\RelationHandler
1581 */
1582 protected function createRelationHandlerInstance()
1583 {
1584 return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
1585 }
1586
1587 /**
1588 * @return LanguageService
1589 */
1590 protected function getLanguageService()
1591 {
1592 return $GLOBALS['LANG'];
1593 }
1594 }