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