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