TYPO3  7.6
version/Classes/Hook/DataHandlerHook.php
Go to the documentation of this file.
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 
24 
30 {
38  protected $notificationEmailInfo = array();
39 
45  protected $remappedIds = array();
46 
47  /****************************
48  ***** Cmdmap Hooks ******
49  ****************************/
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 
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 
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 
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 
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 (
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::isTableWorkspaceEnabled($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  // since TYPO3 CMS 7, version2 is the default and the only option
323  if (!($destRes > 0 || $canMoveRecord && !$destRes)) {
324  $workspaceAccessBlocked['dest1'] = 'Could not insert record from table "' . $table . '" in destination PID "' . $resolvedPid . '" ';
325  } elseif ($destRes == 1 && $WSversion['uid']) {
326  $workspaceAccessBlocked['dest2'] = 'Could not insert other versions in destination PID ';
327  }
328  if (empty($workspaceAccessBlocked)) {
329  // If the move operation is done on a versioned record, which is
330  // NOT new/deleted placeholder and versioningWS is in version 2, then...
331  // since TYPO3 CMS 7, version2 is the default and the only option
332  if ($WSversion['uid'] && !$recIsNewVersion && BackendUtility::isTableWorkspaceEnabled($table)) {
333  $this->moveRecord_wsPlaceholders($table, $uid, $destPid, $WSversion['uid'], $tcemainObj);
334  } else {
335  // moving not needed, just behave like in live workspace
336  $recordWasMoved = false;
337  }
338  } else {
339  $tcemainObj->newlog('Move attempt failed due to workspace restrictions: ' . implode(' // ', $workspaceAccessBlocked), 1);
340  }
341  }
342 
352  protected function moveRecord_processFields(DataHandler $dataHandler, $resolvedPageId, $table, $uid)
353  {
354  $versionedRecord = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $table, $uid);
355  if (empty($versionedRecord)) {
356  return;
357  }
358  foreach ($versionedRecord as $field => $value) {
359  if (empty($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
360  continue;
361  }
363  $dataHandler, $resolvedPageId,
364  $table, $uid, $field, $value,
365  $GLOBALS['TCA'][$table]['columns'][$field]['config']
366  );
367  }
368  }
369 
382  protected function moveRecord_processFieldValue(DataHandler $dataHandler, $resolvedPageId, $table, $uid, $field, $value, array $configuration)
383  {
384  $inlineFieldType = $dataHandler->getInlineFieldType($configuration);
385  $inlineProcessing = (
386  ($inlineFieldType === 'list' || $inlineFieldType === 'field')
387  && BackendUtility::isTableWorkspaceEnabled($configuration['foreign_table'])
388  && (!isset($configuration['behaviour']['disableMovingChildrenWithParent']) || !$configuration['behaviour']['disableMovingChildrenWithParent'])
389  );
390 
391  if ($inlineProcessing) {
392  if ($table === 'pages') {
393  // If the inline elements are related to a page record,
394  // make sure they reside at that page and not at its parent
395  $resolvedPageId = $uid;
396  }
397 
398  $dbAnalysis = $this->createRelationHandlerInstance();
399  $dbAnalysis->start($value, $configuration['foreign_table'], '', $uid, $table, $configuration);
400 
401  // Moving records to a positive destination will insert each
402  // record at the beginning, thus the order is reversed here:
403  foreach ($dbAnalysis->itemArray as $item) {
404  $versionedRecord = BackendUtility::getWorkspaceVersionOfRecord($dataHandler->BE_USER->workspace, $item['table'], $item['id'], 'uid,t3ver_state');
405  if (empty($versionedRecord) || VersionState::cast($versionedRecord['t3ver_state'])->indicatesPlaceholder()) {
406  continue;
407  }
408  $dataHandler->moveRecord($item['table'], $item['id'], $resolvedPageId);
409  }
410  }
411  }
412 
413  /****************************
414  ***** Notifications ******
415  ****************************/
428  protected function notifyStageChange(array $stat, $stageId, $table, $id, $comment, DataHandler $tcemainObj, array $notificationAlternativeRecipients = array())
429  {
430  $workspaceRec = BackendUtility::getRecord('sys_workspace', $stat['uid']);
431  // So, if $id is not set, then $table is taken to be the complete element name!
432  $elementName = $id ? $table . ':' . $id : $table;
433  if (!is_array($workspaceRec)) {
434  return;
435  }
436 
437  // Get the new stage title from workspaces library, if workspaces extension is installed
438  if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
439  $stageService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\StagesService::class);
440  $newStage = $stageService->getStageTitle((int)$stageId);
441  } else {
442  // @todo CONSTANTS SHOULD BE USED - tx_service_workspace_workspaces
443  // @todo use localized labels
444  // Compile label:
445  switch ((int)$stageId) {
446  case 1:
447  $newStage = 'Ready for review';
448  break;
449  case 10:
450  $newStage = 'Ready for publishing';
451  break;
452  case -1:
453  $newStage = 'Element was rejected!';
454  break;
455  case 0:
456  $newStage = 'Rejected element was noticed and edited';
457  break;
458  default:
459  $newStage = 'Unknown state change!?';
460  }
461  }
462  if (empty($notificationAlternativeRecipients)) {
463  // Compile list of recipients:
464  $emails = array();
465  switch ((int)$stat['stagechg_notification']) {
466  case 1:
467  switch ((int)$stageId) {
468  case 1:
469  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']);
470  break;
471  case 10:
472  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], true);
473  break;
474  case -1:
475  // List of elements to reject:
476  $allElements = explode(',', $elementName);
477  // Traverse them, and find the history of each
478  foreach ($allElements as $elRef) {
479  list($eTable, $eUid) = explode(':', $elRef);
480  $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('log_data,tstamp,userid', 'sys_log', 'action=6 and details_nr=30
481  AND tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($eTable, 'sys_log') . '
482  AND recuid=' . (int)$eUid, '', 'uid DESC');
483  // Find all implicated since the last stage-raise from editing to review:
484  foreach ($rows as $dat) {
485  $data = unserialize($dat['log_data']);
486  $emails = $this->getEmailsForStageChangeNotification($dat['userid'], true) + $emails;
487  if ($data['stage'] == 1) {
488  break;
489  }
490  }
491  }
492  break;
493  case 0:
494  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']);
495  break;
496  default:
497  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], true);
498  }
499  break;
500  case 10:
501  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], true);
502  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']) + $emails;
503  $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']) + $emails;
504  break;
505  default:
506  // Do nothing
507  }
508  } else {
509  $emails = $notificationAlternativeRecipients;
510  }
511  // prepare and then send the emails
512  if (!empty($emails)) {
513  // Path to record is found:
514  list($elementTable, $elementUid) = explode(':', $elementName);
515  $elementUid = (int)$elementUid;
516  $elementRecord = BackendUtility::getRecord($elementTable, $elementUid);
517  $recordTitle = BackendUtility::getRecordTitle($elementTable, $elementRecord);
518  if ($elementTable == 'pages') {
519  $pageUid = $elementUid;
520  } else {
521  BackendUtility::fixVersioningPid($elementTable, $elementRecord);
522  $pageUid = ($elementUid = $elementRecord['pid']);
523  }
524  // fetch the TSconfig settings for the email
525  // old way, options are TCEMAIN.notificationEmail_body/subject
526  $TCEmainTSConfig = $tcemainObj->getTCEMAIN_TSconfig($pageUid);
527  // new way, options are
528  // pageTSconfig: tx_version.workspaces.stageNotificationEmail.subject
529  // userTSconfig: page.tx_version.workspaces.stageNotificationEmail.subject
530  $pageTsConfig = BackendUtility::getPagesTSconfig($pageUid);
531  $emailConfig = $pageTsConfig['tx_version.']['workspaces.']['stageNotificationEmail.'];
532  $markers = array(
533  '###RECORD_TITLE###' => $recordTitle,
534  '###RECORD_PATH###' => BackendUtility::getRecordPath($elementUid, '', 20),
535  '###SITE_NAME###' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
536  '###SITE_URL###' => GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir,
537  '###WORKSPACE_TITLE###' => $workspaceRec['title'],
538  '###WORKSPACE_UID###' => $workspaceRec['uid'],
539  '###ELEMENT_NAME###' => $elementName,
540  '###NEXT_STAGE###' => $newStage,
541  '###COMMENT###' => $comment,
542  // See: #30212 - keep both markers for compatibility
543  '###USER_REALNAME###' => $tcemainObj->BE_USER->user['realName'],
544  '###USER_FULLNAME###' => $tcemainObj->BE_USER->user['realName'],
545  '###USER_USERNAME###' => $tcemainObj->BE_USER->user['username']
546  );
547  // add marker for preview links if workspace extension is loaded
548  if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
549  $this->workspaceService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
550  // only generate the link if the marker is in the template - prevents database from getting to much entries
551  if (GeneralUtility::isFirstPartOfStr($emailConfig['message'], 'LLL:')) {
552  $tempEmailMessage = $GLOBALS['LANG']->sL($emailConfig['message']);
553  } else {
554  $tempEmailMessage = $emailConfig['message'];
555  }
556  if (strpos($tempEmailMessage, '###PREVIEW_LINK###') !== false) {
557  $markers['###PREVIEW_LINK###'] = $this->workspaceService->generateWorkspacePreviewLink($elementUid);
558  }
559  unset($tempEmailMessage);
560  $markers['###SPLITTED_PREVIEW_LINK###'] = $this->workspaceService->generateWorkspaceSplittedPreviewLink($elementUid, true);
561  }
562  // Hook for preprocessing of the content for formmails:
563  if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'])) {
564  foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'] as $_classRef) {
565  $_procObj =& GeneralUtility::getUserObj($_classRef);
566  $markers = $_procObj->postModifyMarkers($markers, $this);
567  }
568  }
569  // send an email to each individual user, to ensure the
570  // multilanguage version of the email
571  $emailRecipients = array();
572  // an array of language objects that are needed
573  // for emails with different languages
574  $languageObjects = array(
575  $GLOBALS['LANG']->lang => $GLOBALS['LANG']
576  );
577  // loop through each recipient and send the email
578  foreach ($emails as $recipientData) {
579  // don't send an email twice
580  if (isset($emailRecipients[$recipientData['email']])) {
581  continue;
582  }
583  $emailSubject = $emailConfig['subject'];
584  $emailMessage = $emailConfig['message'];
585  $emailRecipients[$recipientData['email']] = $recipientData['email'];
586  // check if the email needs to be localized
587  // in the users' language
588  if (GeneralUtility::isFirstPartOfStr($emailSubject, 'LLL:') || GeneralUtility::isFirstPartOfStr($emailMessage, 'LLL:')) {
589  $recipientLanguage = $recipientData['lang'] ? $recipientData['lang'] : 'default';
590  if (!isset($languageObjects[$recipientLanguage])) {
591  // a LANG object in this language hasn't been
592  // instantiated yet, so this is done here
594  $languageObject = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
595  $languageObject->init($recipientLanguage);
596  $languageObjects[$recipientLanguage] = $languageObject;
597  } else {
598  $languageObject = $languageObjects[$recipientLanguage];
599  }
600  if (GeneralUtility::isFirstPartOfStr($emailSubject, 'LLL:')) {
601  $emailSubject = $languageObject->sL($emailSubject);
602  }
603  if (GeneralUtility::isFirstPartOfStr($emailMessage, 'LLL:')) {
604  $emailMessage = $languageObject->sL($emailMessage);
605  }
606  }
607  $templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
608  $emailSubject = $templateService->substituteMarkerArray($emailSubject, $markers, '', true, true);
609  $emailMessage = $templateService->substituteMarkerArray($emailMessage, $markers, '', true, true);
610  // Send an email to the recipient
612  $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
613  if (!empty($recipientData['realName'])) {
614  $recipient = array($recipientData['email'] => $recipientData['realName']);
615  } else {
616  $recipient = $recipientData['email'];
617  }
618  $mail->setTo($recipient)
619  ->setSubject($emailSubject)
620  ->setFrom(\TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom())
621  ->setBody($emailMessage);
622  $mail->send();
623  }
624  $emailRecipients = implode(',', $emailRecipients);
625  $tcemainObj->newlog2('Notification email for stage change was sent to "' . $emailRecipients . '"', $table, $id);
626  }
627  }
628 
637  protected function getEmailsForStageChangeNotification($listOfUsers, $noTablePrefix = false)
638  {
639  $users = GeneralUtility::trimExplode(',', $listOfUsers, true);
640  $emails = array();
641  foreach ($users as $userIdent) {
642  if ($noTablePrefix) {
643  $id = (int)$userIdent;
644  } else {
645  list($table, $id) = GeneralUtility::revExplode('_', $userIdent, 2);
646  }
647  if ($table === 'be_users' || $noTablePrefix) {
648  if ($userRecord = BackendUtility::getRecord('be_users', $id, 'uid,email,lang,realName', BackendUtility::BEenableFields('be_users'))) {
649  if (trim($userRecord['email']) !== '') {
650  $emails[$id] = $userRecord;
651  }
652  }
653  }
654  }
655  return $emails;
656  }
657 
658  /****************************
659  ***** Stage Changes ******
660  ****************************/
673  protected function version_setStage($table, $id, $stageId, $comment = '', $notificationEmailInfo = false, DataHandler $tcemainObj, array $notificationAlternativeRecipients = array())
674  {
675  if ($errorCode = $tcemainObj->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
676  $tcemainObj->newlog('Attempt to set stage for record failed: ' . $errorCode, 1);
677  } elseif ($tcemainObj->checkRecordUpdateAccess($table, $id)) {
678  $record = BackendUtility::getRecord($table, $id);
679  $stat = $tcemainObj->BE_USER->checkWorkspace($record['t3ver_wsid']);
680  // check if the usere is allowed to the current stage, so it's also allowed to send to next stage
681  if ($GLOBALS['BE_USER']->workspaceCheckStageForCurrent($record['t3ver_stage'])) {
682  // Set stage of record:
683  $updateData = array(
684  't3ver_stage' => $stageId
685  );
686  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$id, $updateData);
687  $tcemainObj->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id);
688  // TEMPORARY, except 6-30 as action/detail number which is observed elsewhere!
689  $tcemainObj->log($table, $id, 6, 0, 0, 'Stage raised...', 30, array('comment' => $comment, 'stage' => $stageId));
690  if ((int)$stat['stagechg_notification'] > 0) {
692  $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['shared'] = array($stat, $stageId, $comment);
693  $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['elements'][] = $table . ':' . $id;
694  $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['alternativeRecipients'] = $notificationAlternativeRecipients;
695  } else {
696  $this->notifyStageChange($stat, $stageId, $table, $id, $comment, $tcemainObj, $notificationAlternativeRecipients);
697  }
698  }
699  } else {
700  $tcemainObj->newlog('The member user tried to set a stage value "' . $stageId . '" that was not allowed', 1);
701  }
702  } else {
703  $tcemainObj->newlog('Attempt to set stage for record failed because you do not have edit access', 1);
704  }
705  }
706 
707  /*****************************
708  ***** CMD versioning ******
709  *****************************/
720  protected function versionizePages($uid, $label, $versionizeTree, DataHandler $tcemainObj)
721  {
722  $uid = (int)$uid;
723  // returns the branch
724  $brExist = $tcemainObj->doesBranchExist('', $uid, $tcemainObj->pMap['show'], 1);
725  // Checks if we had permissions
726  if ((int)$brExist === -1) {
727  $tcemainObj->newlog('Could not read all subpages to versionize.', 1);
728  return;
729  }
730  // Make list of tables that should come along with a new version of the page:
731  $verTablesArray = array();
732  $allTables = array_keys($GLOBALS['TCA']);
733  foreach ($allTables as $tableName) {
734  if ($tableName != 'pages' && ($versionizeTree > 0 || $GLOBALS['TCA'][$tableName]['ctrl']['versioning_followPages'])) {
735  $verTablesArray[] = $tableName;
736  }
737  }
738  // Remove the possible inline child tables from the tables to be versioniozed automatically:
739  $verTablesArray = array_diff($verTablesArray, $this->getPossibleInlineChildTablesOfParentTable('pages'));
740  // Begin to copy pages if we're allowed to:
741  if ($versionizeTree !== -1) {
742  $tcemainObj->newlog('Versioning type "' . $versionizeTree . '" was not allowed in workspace', 1);
743  return;
744  }
745  // Versionize this page:
746  $theNewRootID = $tcemainObj->versionizeRecord('pages', $uid, $label, false, $versionizeTree);
747  if (!$theNewRootID) {
748  $tcemainObj->newlog('The root version could not be created!', 1);
749  return;
750  }
751  $this->rawCopyPageContent($uid, $theNewRootID, $verTablesArray, $tcemainObj);
752  // If we're going to copy recursively...:
753  if ($versionizeTree > 0) {
754  // Get ALL subpages to copy (read permissions respected - they should NOT be...):
755  $CPtable = $tcemainObj->int_pageTreeInfo(array(), $uid, (int)$versionizeTree, $theNewRootID);
756  // Now copying the subpages
757  foreach ($CPtable as $thePageUid => $thePagePid) {
758  $newPid = $tcemainObj->copyMappingArray['pages'][$thePagePid];
759  if (isset($newPid)) {
760  $theNewRootID = $tcemainObj->copyRecord_raw('pages', $thePageUid, $newPid);
761  $this->rawCopyPageContent($thePageUid, $theNewRootID, $verTablesArray, $tcemainObj);
762  } else {
763  $tcemainObj->newlog('Something went wrong during copying branch (for versioning)', 1);
764  break;
765  }
766  }
767  }
768  }
769 
784  protected function version_swap($table, $id, $swapWith, $swapIntoWS = 0, DataHandler $tcemainObj, $comment = '', $notificationEmailInfo = false, $notificationAlternativeRecipients = array())
785  {
786 
787  // Check prerequisites before start swapping
788 
789  // First, check if we may actually edit the online record
790  if (!$tcemainObj->checkRecordUpdateAccess($table, $id)) {
791  $tcemainObj->newlog('Error: You cannot swap versions for a record you do not have access to edit!', 1);
792  return;
793  }
794  // Select the two versions:
795  $curVersion = BackendUtility::getRecord($table, $id, '*');
796  $swapVersion = BackendUtility::getRecord($table, $swapWith, '*');
797  $movePlh = array();
798  $movePlhID = 0;
799  if (!(is_array($curVersion) && is_array($swapVersion))) {
800  $tcemainObj->newlog('Error: Either online or swap version could not be selected!', 2);
801  return;
802  }
803  if (!$tcemainObj->BE_USER->workspacePublishAccess($swapVersion['t3ver_wsid'])) {
804  $tcemainObj->newlog('User could not publish records from workspace #' . $swapVersion['t3ver_wsid'], 1);
805  return;
806  }
807  $wsAccess = $tcemainObj->BE_USER->checkWorkspace($swapVersion['t3ver_wsid']);
808  if (!($swapVersion['t3ver_wsid'] <= 0 || !($wsAccess['publish_access'] & 1) || (int)$swapVersion['t3ver_stage'] === -10)) {
809  $tcemainObj->newlog('Records in workspace #' . $swapVersion['t3ver_wsid'] . ' can only be published when in "Publish" stage.', 1);
810  return;
811  }
812  if (!($tcemainObj->doesRecordExist($table, $swapWith, 'show') && $tcemainObj->checkRecordUpdateAccess($table, $swapWith))) {
813  $tcemainObj->newlog('You cannot publish a record you do not have edit and show permissions for', 1);
814  return;
815  }
816  if ($swapIntoWS && !$tcemainObj->BE_USER->workspaceSwapAccess()) {
817  $tcemainObj->newlog('Workspace #' . $swapVersion['t3ver_wsid'] . ' does not support swapping.', 1);
818  return;
819  }
820  // Check if the swapWith record really IS a version of the original!
821  if (!(((int)$swapVersion['pid'] == -1 && (int)$curVersion['pid'] >= 0) && (int)$swapVersion['t3ver_oid'] === (int)$id)) {
822  $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);
823  return;
824  }
825  // Lock file name:
826  $lockFileName = PATH_site . 'typo3temp/swap_locking/' . $table . ':' . $id . '.ser';
827  if (@is_file($lockFileName)) {
828  $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);
829  return;
830  }
831 
832  // Now start to swap records by first creating the lock file
833 
834  // Write lock-file:
835  GeneralUtility::writeFileToTypo3tempDir($lockFileName, serialize(array(
836  'tstamp' => $GLOBALS['EXEC_TIME'],
837  'user' => $tcemainObj->BE_USER->user['username'],
838  'curVersion' => $curVersion,
839  'swapVersion' => $swapVersion
840  )));
841  // Find fields to keep
842  $keepFields = $this->getUniqueFields($table);
843  if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
844  $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
845  }
846  // l10n-fields must be kept otherwise the localization
847  // will be lost during the publishing
848  if (!isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
849  $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
850  }
851  // Swap "keepfields"
852  foreach ($keepFields as $fN) {
853  $tmp = $swapVersion[$fN];
854  $swapVersion[$fN] = $curVersion[$fN];
855  $curVersion[$fN] = $tmp;
856  }
857  // Preserve states:
858  $t3ver_state = array();
859  $t3ver_state['swapVersion'] = $swapVersion['t3ver_state'];
860  $t3ver_state['curVersion'] = $curVersion['t3ver_state'];
861  // Modify offline version to become online:
862  $tmp_wsid = $swapVersion['t3ver_wsid'];
863  // Set pid for ONLINE
864  $swapVersion['pid'] = (int)$curVersion['pid'];
865  // We clear this because t3ver_oid only make sense for offline versions
866  // and we want to prevent unintentional misuse of this
867  // value for online records.
868  $swapVersion['t3ver_oid'] = 0;
869  // In case of swapping and the offline record has a state
870  // (like 2 or 4 for deleting or move-pointer) we set the
871  // current workspace ID so the record is not deselected
872  // in the interface by BackendUtility::versioningPlaceholderClause()
873  $swapVersion['t3ver_wsid'] = 0;
874  if ($swapIntoWS) {
875  if ($t3ver_state['swapVersion'] > 0) {
876  $swapVersion['t3ver_wsid'] = $tcemainObj->BE_USER->workspace;
877  } else {
878  $swapVersion['t3ver_wsid'] = (int)$curVersion['t3ver_wsid'];
879  }
880  }
881  $swapVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
882  $swapVersion['t3ver_stage'] = 0;
883  if (!$swapIntoWS) {
884  $swapVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
885  }
886  // Moving element.
888  // && $t3ver_state['swapVersion']==4 // Maybe we don't need this?
889  if ($plhRec = BackendUtility::getMovePlaceholder($table, $id, 't3ver_state,pid,uid' . ($GLOBALS['TCA'][$table]['ctrl']['sortby'] ? ',' . $GLOBALS['TCA'][$table]['ctrl']['sortby'] : ''))) {
890  $movePlhID = $plhRec['uid'];
891  $movePlh['pid'] = $swapVersion['pid'];
892  $swapVersion['pid'] = (int)$plhRec['pid'];
893  $curVersion['t3ver_state'] = (int)$swapVersion['t3ver_state'];
894  $swapVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
895  if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
896  // sortby is a "keepFields" which is why this will work...
897  $movePlh[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']];
898  $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $plhRec[$GLOBALS['TCA'][$table]['ctrl']['sortby']];
899  }
900  }
901  }
902  // Take care of relations in each field (e.g. IRRE):
903  if (is_array($GLOBALS['TCA'][$table]['columns'])) {
904  foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fieldConf) {
905  $this->version_swap_processFields($table, $field, $fieldConf['config'], $curVersion, $swapVersion, $tcemainObj);
906  }
907  }
908  unset($swapVersion['uid']);
909  // Modify online version to become offline:
910  unset($curVersion['uid']);
911  // Set pid for OFFLINE
912  $curVersion['pid'] = -1;
913  $curVersion['t3ver_oid'] = (int)$id;
914  $curVersion['t3ver_wsid'] = $swapIntoWS ? (int)$tmp_wsid : 0;
915  $curVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
916  $curVersion['t3ver_count'] = $curVersion['t3ver_count'] + 1;
917  // Increment lifecycle counter
918  $curVersion['t3ver_stage'] = 0;
919  if (!$swapIntoWS) {
920  $curVersion['t3ver_state'] = (string)new VersionState(VersionState::DEFAULT_STATE);
921  }
922  // Registering and swapping MM relations in current and swap records:
923  $tcemainObj->version_remapMMForVersionSwap($table, $id, $swapWith);
924  // Generating proper history data to prepare logging
925  $tcemainObj->compareFieldArrayWithCurrentAndUnset($table, $id, $swapVersion);
926  $tcemainObj->compareFieldArrayWithCurrentAndUnset($table, $swapWith, $curVersion);
927  // Execute swapping:
928  $sqlErrors = array();
929  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$id, $swapVersion);
930  if ($GLOBALS['TYPO3_DB']->sql_error()) {
931  $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
932  } else {
933  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$swapWith, $curVersion);
934  if ($GLOBALS['TYPO3_DB']->sql_error()) {
935  $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
936  } else {
937  unlink($lockFileName);
938  }
939  }
940  if (!empty($sqlErrors)) {
941  $tcemainObj->newlog('During Swapping: SQL errors happened: ' . implode('; ', $sqlErrors), 2);
942  } else {
943  // Register swapped ids for later remapping:
944  $this->remappedIds[$table][$id] = $swapWith;
945  $this->remappedIds[$table][$swapWith] = $id;
946  // If a moving operation took place...:
947  if ($movePlhID) {
948  // Remove, if normal publishing:
949  if (!$swapIntoWS) {
950  // For delete + completely delete!
951  $tcemainObj->deleteEl($table, $movePlhID, true, true);
952  } else {
953  // Otherwise update the movePlaceholder:
954  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$movePlhID, $movePlh);
955  $tcemainObj->addRemapStackRefIndex($table, $movePlhID);
956  }
957  }
958  // Checking for delete:
959  // Delete only if new/deleted placeholders are there.
960  if (!$swapIntoWS && ((int)$t3ver_state['swapVersion'] === 1 || (int)$t3ver_state['swapVersion'] === 2)) {
961  // Force delete
962  $tcemainObj->deleteEl($table, $id, true);
963  }
964  $tcemainObj->newlog2(($swapIntoWS ? 'Swapping' : 'Publishing') . ' successful for table "' . $table . '" uid ' . $id . '=>' . $swapWith, $table, $id, $swapVersion['pid']);
965  // Update reference index of the live record:
966  $tcemainObj->addRemapStackRefIndex($table, $id);
967  // Set log entry for live record:
968  $propArr = $tcemainObj->getRecordPropertiesFromRow($table, $swapVersion);
969  if ($propArr['_ORIG_pid'] == -1) {
970  $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.offline_record_updated');
971  } else {
972  $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.online_record_updated');
973  }
974  $theLogId = $tcemainObj->log($table, $id, 2, $propArr['pid'], 0, $label, 10, array($propArr['header'], $table . ':' . $id), $propArr['event_pid']);
975  $tcemainObj->setHistory($table, $id, $theLogId);
976  // Update reference index of the offline record:
977  $tcemainObj->addRemapStackRefIndex($table, $swapWith);
978  // Set log entry for offline record:
979  $propArr = $tcemainObj->getRecordPropertiesFromRow($table, $curVersion);
980  if ($propArr['_ORIG_pid'] == -1) {
981  $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.offline_record_updated');
982  } else {
983  $label = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tcemain.xlf:version_swap.online_record_updated');
984  }
985  $theLogId = $tcemainObj->log($table, $swapWith, 2, $propArr['pid'], 0, $label, 10, array($propArr['header'], $table . ':' . $swapWith), $propArr['event_pid']);
986  $tcemainObj->setHistory($table, $swapWith, $theLogId);
987 
988  $stageId = -20; // \TYPO3\CMS\Workspaces\Service\StagesService::STAGE_PUBLISH_EXECUTE_ID;
990  $notificationEmailInfoKey = $wsAccess['uid'] . ':' . $stageId . ':' . $comment;
991  $this->notificationEmailInfo[$notificationEmailInfoKey]['shared'] = array($wsAccess, $stageId, $comment);
992  $this->notificationEmailInfo[$notificationEmailInfoKey]['elements'][] = $table . ':' . $id;
993  $this->notificationEmailInfo[$notificationEmailInfoKey]['alternativeRecipients'] = $notificationAlternativeRecipients;
994  } else {
995  $this->notifyStageChange($wsAccess, $stageId, $table, $id, $comment, $tcemainObj, $notificationAlternativeRecipients);
996  }
997  // Write to log with stageId -20
998  $tcemainObj->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id);
999  $tcemainObj->log($table, $id, 6, 0, 0, 'Published', 30, array('comment' => $comment, 'stage' => $stageId));
1000 
1001  // Clear cache:
1002  $tcemainObj->registerRecordIdForPageCacheClearing($table, $id);
1003  // Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!):
1004  if (!$swapIntoWS && $t3ver_state['curVersion'] > 0) {
1005  // For delete + completely delete!
1006  $tcemainObj->deleteEl($table, $swapWith, true, true);
1007  }
1008 
1009  //Update reference index for live workspace too:
1011  $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
1012  $refIndexObj->setWorkspaceId(0);
1013  $refIndexObj->updateRefIndexTable($table, $id);
1014  $refIndexObj->updateRefIndexTable($table, $swapWith);
1015  }
1016  }
1017 
1026  public function writeRemappedForeignField(\TYPO3\CMS\Core\Database\RelationHandler $dbAnalysis, array $configuration, $parentId)
1027  {
1028  foreach ($dbAnalysis->itemArray as &$item) {
1029  if (isset($this->remappedIds[$item['table']][$item['id']])) {
1030  $item['id'] = $this->remappedIds[$item['table']][$item['id']];
1031  }
1032  }
1033  $dbAnalysis->writeForeignField($configuration, $parentId);
1034  }
1035 
1048  protected function version_swap_processFields($tableName, $fieldName, array $configuration, array $liveData, array $versionData, DataHandler $dataHandler)
1049  {
1050  $inlineType = $dataHandler->getInlineFieldType($configuration);
1051  if ($inlineType !== 'field') {
1052  return;
1053  }
1054  $foreignTable = $configuration['foreign_table'];
1055  // Read relations that point to the current record (e.g. live record):
1056  $liveRelations = $this->createRelationHandlerInstance();
1057  $liveRelations->setWorkspaceId(0);
1058  $liveRelations->start('', $foreignTable, '', $liveData['uid'], $tableName, $configuration);
1059  // Read relations that point to the record to be swapped with e.g. draft record):
1060  $versionRelations = $this->createRelationHandlerInstance();
1061  $versionRelations->setUseLiveReferenceIds(false);
1062  $versionRelations->start('', $foreignTable, '', $versionData['uid'], $tableName, $configuration);
1063  // Update relations for both (workspace/versioning) sites:
1064  if (count($liveRelations->itemArray)) {
1065  $dataHandler->addRemapAction(
1066  $tableName, $liveData['uid'],
1067  array($this, 'updateInlineForeignFieldSorting'),
1068  array($tableName, $liveData['uid'], $foreignTable, $liveRelations->tableArray[$foreignTable], $configuration, $dataHandler->BE_USER->workspace)
1069  );
1070  }
1071  if (count($versionRelations->itemArray)) {
1072  $dataHandler->addRemapAction(
1073  $tableName, $liveData['uid'],
1074  array($this, 'updateInlineForeignFieldSorting'),
1075  array($tableName, $liveData['uid'], $foreignTable, $versionRelations->tableArray[$foreignTable], $configuration, 0)
1076  );
1077  }
1078  }
1079 
1098  public function updateInlineForeignFieldSorting($parentTableName, $parentId, $foreignTableName, $foreignIds, array $configuration, $targetWorkspaceId)
1099  {
1100  $remappedIds = array();
1101  // Use remapped ids (live id <-> version id)
1102  foreach ($foreignIds as $foreignId) {
1103  if (!empty($this->remappedIds[$foreignTableName][$foreignId])) {
1104  $remappedIds[] = $this->remappedIds[$foreignTableName][$foreignId];
1105  } else {
1106  $remappedIds[] = $foreignId;
1107  }
1108  }
1109 
1110  $relationHandler = $this->createRelationHandlerInstance();
1111  $relationHandler->setWorkspaceId($targetWorkspaceId);
1112  $relationHandler->setUseLiveReferenceIds(false);
1113  $relationHandler->start(implode(',', $remappedIds), $foreignTableName);
1114  $relationHandler->processDeletePlaceholder();
1115  $relationHandler->writeForeignField($configuration, $parentId);
1116  }
1117 
1127  protected function version_clearWSID($table, $id, $flush = false, DataHandler $tcemainObj)
1128  {
1129  if ($errorCode = $tcemainObj->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
1130  $tcemainObj->newlog('Attempt to reset workspace for record failed: ' . $errorCode, 1);
1131  return;
1132  }
1133  if (!$tcemainObj->checkRecordUpdateAccess($table, $id)) {
1134  $tcemainObj->newlog('Attempt to reset workspace for record failed because you do not have edit access', 1);
1135  return;
1136  }
1137  $liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, 'uid,t3ver_state');
1138  if (!$liveRec) {
1139  return;
1140  }
1141  // Clear workspace ID:
1142  $updateData = array(
1143  't3ver_wsid' => 0,
1144  't3ver_tstamp' => $GLOBALS['EXEC_TIME']
1145  );
1146  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$id, $updateData);
1147  // Clear workspace ID for live version AND DELETE IT as well because it is a new record!
1148  if (
1149  VersionState::cast($liveRec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER)
1150  || VersionState::cast($liveRec['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
1151  ) {
1152  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$liveRec['uid'], $updateData);
1153  // THIS assumes that the record was placeholder ONLY for ONE record (namely $id)
1154  $tcemainObj->deleteEl($table, $liveRec['uid'], true);
1155  }
1156  // If "deleted" flag is set for the version that got released
1157  // it doesn't make sense to keep that "placeholder" anymore and we delete it completly.
1158  $wsRec = BackendUtility::getRecord($table, $id);
1159  if (
1160  $flush
1161  || (
1162  VersionState::cast($wsRec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER)
1163  || VersionState::cast($wsRec['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
1164  )
1165  ) {
1166  $tcemainObj->deleteEl($table, $id, true, true);
1167  }
1168  // Remove the move-placeholder if found for live record.
1170  if ($plhRec = BackendUtility::getMovePlaceholder($table, $liveRec['uid'], 'uid')) {
1171  $tcemainObj->deleteEl($table, $plhRec['uid'], true, true);
1172  }
1173  }
1174  }
1175 
1176  /*******************************
1177  ***** helper functions ******
1178  *******************************/
1190  protected function rawCopyPageContent($oldPageId, $newPageId, array $copyTablesArray, DataHandler $tcemainObj)
1191  {
1192  if (!$newPageId) {
1193  return;
1194  }
1195  foreach ($copyTablesArray as $table) {
1196  // all records under the page is copied.
1197  if ($table && is_array($GLOBALS['TCA'][$table]) && $table !== 'pages') {
1198  $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid=' . (int)$oldPageId . $tcemainObj->deleteClause($table));
1199  while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
1200  // Check, if this record has already been copied by a parent record as relation:
1201  if (!$tcemainObj->copyMappingArray[$table][$row['uid']]) {
1202  // Copying each of the underlying records (method RAW)
1203  $tcemainObj->copyRecord_raw($table, $row['uid'], $newPageId);
1204  }
1205  }
1206  $GLOBALS['TYPO3_DB']->sql_free_result($mres);
1207  }
1208  }
1209  }
1210 
1219  public function findPageElementsForVersionSwap($table, $id, $offlineId)
1220  {
1221  $rec = BackendUtility::getRecord($table, $offlineId, 't3ver_wsid');
1222  $workspaceId = (int)$rec['t3ver_wsid'];
1223  $elementData = array();
1224  if ($workspaceId === 0) {
1225  return $elementData;
1226  }
1227  // Get page UID for LIVE and workspace
1228  if ($table != 'pages') {
1229  $rec = BackendUtility::getRecord($table, $id, 'pid');
1230  $pageId = $rec['pid'];
1231  $rec = BackendUtility::getRecord('pages', $pageId);
1232  BackendUtility::workspaceOL('pages', $rec, $workspaceId);
1233  $offlinePageId = $rec['_ORIG_uid'];
1234  } else {
1235  $pageId = $id;
1236  $offlinePageId = $offlineId;
1237  }
1238  // Traversing all tables supporting versioning:
1239  foreach ($GLOBALS['TCA'] as $table => $cfg) {
1240  if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1241  $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'));
1242  while (false != ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
1243  $elementData[$table][] = array($row[1], $row[0]);
1244  }
1245  $GLOBALS['TYPO3_DB']->sql_free_result($res);
1246  }
1247  }
1248  if ($offlinePageId && $offlinePageId != $pageId) {
1249  $elementData['pages'][] = array($pageId, $offlinePageId);
1250  }
1251  return $elementData;
1252  }
1253 
1262  public function findPageElementsForVersionStageChange(array $pageIdList, $workspaceId, array &$elementList)
1263  {
1264  if ($workspaceId == 0) {
1265  return;
1266  }
1267  // Traversing all tables supporting versioning:
1268  foreach ($GLOBALS['TCA'] as $table => $cfg) {
1269  if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1270  $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'));
1271  while (false !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
1272  $elementList[$table][] = $row[0];
1273  }
1274  $GLOBALS['TYPO3_DB']->sql_free_result($res);
1275  if (is_array($elementList[$table])) {
1276  // Yes, it is possible to get non-unique array even with DISTINCT above!
1277  // It happens because several UIDs are passed in the array already.
1278  $elementList[$table] = array_unique($elementList[$table]);
1279  }
1280  }
1281  }
1282  }
1283 
1294  public function findPageIdsForVersionStateChange($table, array $idList, $workspaceId, array &$pageIdList, array &$elementList)
1295  {
1296  if ($workspaceId == 0) {
1297  return;
1298  }
1299  $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'));
1300  while (false !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
1301  $pageIdList[] = $row[0];
1302  // Find ws version
1303  // Note: cannot use BackendUtility::getRecordWSOL()
1304  // here because it does not accept workspace id!
1305  $rec = BackendUtility::getRecord('pages', $row[0]);
1306  BackendUtility::workspaceOL('pages', $rec, $workspaceId);
1307  if ($rec['_ORIG_uid']) {
1308  $elementList['pages'][$row[0]] = $rec['_ORIG_uid'];
1309  }
1310  }
1311  $GLOBALS['TYPO3_DB']->sql_free_result($res);
1312  // The line below is necessary even with DISTINCT
1313  // because several elements can be passed by caller
1314  $pageIdList = array_unique($pageIdList);
1315  }
1316 
1323  public function findRealPageIds(array &$idList)
1324  {
1325  foreach ($idList as $key => $id) {
1326  $rec = BackendUtility::getRecord('pages', $id, 't3ver_oid');
1327  if ($rec['t3ver_oid'] > 0) {
1328  $idList[$key] = $rec['t3ver_oid'];
1329  }
1330  }
1331  }
1332 
1347  protected function moveRecord_wsPlaceholders($table, $uid, $destPid, $wsUid, DataHandler $tcemainObj)
1348  {
1349  // If a record gets moved after a record that already has a placeholder record
1350  // then the new placeholder record needs to be after the existing one
1351  $originalRecordDestinationPid = $destPid;
1352  if ($destPid < 0) {
1353  $movePlaceHolder = BackendUtility::getMovePlaceholder($table, abs($destPid), 'uid');
1354  if ($movePlaceHolder !== false) {
1355  $destPid = -$movePlaceHolder['uid'];
1356  }
1357  }
1358  if ($plh = BackendUtility::getMovePlaceholder($table, $uid, 'uid')) {
1359  // If already a placeholder exists, move it:
1360  $tcemainObj->moveRecord_raw($table, $plh['uid'], $destPid);
1361  } else {
1362  // First, we create a placeholder record in the Live workspace that
1363  // represents the position to where the record is eventually moved to.
1364  $newVersion_placeholderFieldArray = array();
1365 
1366  // Use property for move placeholders if set (since TYPO3 CMS 6.2)
1367  if (isset($GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForMovePlaceholders'])) {
1368  $shadowColumnsForMovePlaceholder = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForMovePlaceholders'];
1369  // Fallback to property for new placeholder (existed long time before TYPO3 CMS 6.2)
1370  } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'])) {
1371  $shadowColumnsForMovePlaceholder = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1372  }
1373 
1374  // Set values from the versioned record to the move placeholder
1375  if (!empty($shadowColumnsForMovePlaceholder)) {
1376  $versionedRecord = BackendUtility::getRecord($table, $wsUid);
1377  $shadowColumns = GeneralUtility::trimExplode(',', $shadowColumnsForMovePlaceholder, true);
1378  foreach ($shadowColumns as $shadowColumn) {
1379  if (isset($versionedRecord[$shadowColumn])) {
1380  $newVersion_placeholderFieldArray[$shadowColumn] = $versionedRecord[$shadowColumn];
1381  }
1382  }
1383  }
1384 
1385  if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1386  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1387  }
1388  if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1389  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $tcemainObj->userid;
1390  }
1391  if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
1392  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1393  }
1394  if ($table == 'pages') {
1395  // Copy page access settings from original page to placeholder
1396  $perms_clause = $tcemainObj->BE_USER->getPagePermsClause(1);
1397  $access = BackendUtility::readPageAccess($uid, $perms_clause);
1398  $newVersion_placeholderFieldArray['perms_userid'] = $access['perms_userid'];
1399  $newVersion_placeholderFieldArray['perms_groupid'] = $access['perms_groupid'];
1400  $newVersion_placeholderFieldArray['perms_user'] = $access['perms_user'];
1401  $newVersion_placeholderFieldArray['perms_group'] = $access['perms_group'];
1402  $newVersion_placeholderFieldArray['perms_everybody'] = $access['perms_everybody'];
1403  }
1404  $newVersion_placeholderFieldArray['t3ver_label'] = 'MovePlaceholder #' . $uid;
1405  $newVersion_placeholderFieldArray['t3ver_move_id'] = $uid;
1406  // Setting placeholder state value for temporary record
1407  $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState::MOVE_PLACEHOLDER);
1408  // Setting workspace - only so display of place holders can filter out those from other workspaces.
1409  $newVersion_placeholderFieldArray['t3ver_wsid'] = $tcemainObj->BE_USER->workspace;
1410  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $tcemainObj->getPlaceholderTitleForTableLabel($table, 'MOVE-TO PLACEHOLDER for #' . $uid);
1411  // moving localized records requires to keep localization-settings for the placeholder too
1412  if (isset($GLOBALS['TCA'][$table]['ctrl']['languageField']) && isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'])) {
1413  $l10nParentRec = BackendUtility::getRecord($table, $uid);
1414  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1415  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1416  if (isset($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'])) {
1417  $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']];
1418  }
1419  unset($l10nParentRec);
1420  }
1421  // Initially, create at root level.
1422  $newVersion_placeholderFieldArray['pid'] = 0;
1423  $id = 'NEW_MOVE_PLH';
1424  // Saving placeholder as 'original'
1425  $tcemainObj->insertDB($table, $id, $newVersion_placeholderFieldArray, false);
1426  // Move the new placeholder from temporary root-level to location:
1427  $tcemainObj->moveRecord_raw($table, $tcemainObj->substNEWwithIDs[$id], $destPid);
1428  // Move the workspace-version of the original to be the version of the move-to-placeholder:
1429  // Setting placeholder state value for version (so it can know it is currently a new version...)
1430  $updateFields = array(
1431  't3ver_state' => (string)new VersionState(VersionState::MOVE_POINTER)
1432  );
1433  $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$wsUid, $updateFields);
1434  }
1435  // Check for the localizations of that element and move them as well
1436  $tcemainObj->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
1437  }
1438 
1446  protected function getPossibleInlineChildTablesOfParentTable($parentTable, array $possibleInlineChildren = array())
1447  {
1448  foreach ($GLOBALS['TCA'][$parentTable]['columns'] as $parentField => $parentFieldDefinition) {
1449  if (isset($parentFieldDefinition['config']['type'])) {
1450  $parentFieldConfiguration = $parentFieldDefinition['config'];
1451  if ($parentFieldConfiguration['type'] == 'inline' && isset($parentFieldConfiguration['foreign_table'])) {
1452  if (!in_array($parentFieldConfiguration['foreign_table'], $possibleInlineChildren)) {
1453  $possibleInlineChildren = $this->getPossibleInlineChildTablesOfParentTable($parentFieldConfiguration['foreign_table'], array_merge($possibleInlineChildren, $parentFieldConfiguration['foreign_table']));
1454  }
1455  }
1456  }
1457  }
1458  return $possibleInlineChildren;
1459  }
1460 
1467  public function getCommandMap(DataHandler $tceMain)
1468  {
1470  \TYPO3\CMS\Version\DataHandler\CommandMap::class,
1471  $this,
1472  $tceMain,
1473  $tceMain->cmdmap,
1474  $tceMain->BE_USER->workspace
1475  );
1476  }
1477 
1484  protected function getUniqueFields($table)
1485  {
1486  $listArr = array();
1487  if (empty($GLOBALS['TCA'][$table]['columns'])) {
1488  return $listArr;
1489  }
1490  foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $configArr) {
1491  if ($configArr['config']['type'] === 'input') {
1492  $evalCodesArray = GeneralUtility::trimExplode(',', $configArr['config']['eval'], true);
1493  if (in_array('uniqueInPid', $evalCodesArray) || in_array('unique', $evalCodesArray)) {
1494  $listArr[] = $field;
1495  }
1496  }
1497  }
1498  return $listArr;
1499  }
1500 
1504  protected function createRelationHandlerInstance()
1505  {
1506  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
1507  }
1508 }