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