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