d6c0ea8c340943d1baf4b116ebf01779d8e15d4c
[Packages/TYPO3.CMS.git] / typo3 / sysext / workspaces / Classes / Service / WorkspaceService.php
1 <?php
2 namespace TYPO3\CMS\Workspaces\Service;
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\Utility\GeneralUtility;
19 use TYPO3\CMS\Core\Versioning\VersionState;
20
21 /**
22 * Workspace service
23 *
24 * @author Workspaces Team (http://forge.typo3.org/projects/show/typo3v4-workspaces)
25 */
26 class WorkspaceService implements \TYPO3\CMS\Core\SingletonInterface {
27
28 /**
29 * @var array
30 */
31 protected $pageCache = array();
32
33 const TABLE_WORKSPACE = 'sys_workspace';
34 const SELECT_ALL_WORKSPACES = -98;
35 const LIVE_WORKSPACE_ID = 0;
36 /**
37 * retrieves the available workspaces from the database and checks whether
38 * they're available to the current BE user
39 *
40 * @return array array of worspaces available to the current user
41 */
42 public function getAvailableWorkspaces() {
43 $availableWorkspaces = array();
44 // add default workspaces
45 if ($GLOBALS['BE_USER']->checkWorkspace(array('uid' => (string)self::LIVE_WORKSPACE_ID))) {
46 $availableWorkspaces[self::LIVE_WORKSPACE_ID] = self::getWorkspaceTitle(self::LIVE_WORKSPACE_ID);
47 }
48 // add custom workspaces (selecting all, filtering by BE_USER check):
49 $customWorkspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid, title, adminusers, members', 'sys_workspace', 'pid = 0' . BackendUtility::deleteClause('sys_workspace'), '', 'title');
50 if (count($customWorkspaces)) {
51 foreach ($customWorkspaces as $workspace) {
52 if ($GLOBALS['BE_USER']->checkWorkspace($workspace)) {
53 $availableWorkspaces[$workspace['uid']] = $workspace['title'];
54 }
55 }
56 }
57 return $availableWorkspaces;
58 }
59
60 /**
61 * Gets the current workspace ID.
62 *
63 * @return int The current workspace ID
64 */
65 public function getCurrentWorkspace() {
66 $workspaceId = $GLOBALS['BE_USER']->workspace;
67 $activeId = $GLOBALS['BE_USER']->getSessionData('tx_workspace_activeWorkspace');
68
69 // Avoid invalid workspace settings
70 if ($activeId !== NULL && $activeId !== self::SELECT_ALL_WORKSPACES) {
71 $availableWorkspaces = $this->getAvailableWorkspaces();
72 if (!isset($availableWorkspaces[$activeId])) {
73 $activeId = NULL;
74 }
75 }
76
77 if ($activeId !== NULL) {
78 $workspaceId = $activeId;
79 }
80
81 return $workspaceId;
82 }
83
84 /**
85 * Find the title for the requested workspace.
86 *
87 * @param int $wsId
88 * @return string
89 * @throws \InvalidArgumentException
90 */
91 static public function getWorkspaceTitle($wsId) {
92 $title = FALSE;
93 switch ($wsId) {
94 case self::LIVE_WORKSPACE_ID:
95 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:shortcut_onlineWS');
96 break;
97 default:
98 $labelField = $GLOBALS['TCA']['sys_workspace']['ctrl']['label'];
99 $wsRecord = BackendUtility::getRecord('sys_workspace', $wsId, 'uid,' . $labelField);
100 if (is_array($wsRecord)) {
101 $title = $wsRecord[$labelField];
102 }
103 }
104 if ($title === FALSE) {
105 throw new \InvalidArgumentException('No such workspace defined');
106 }
107 return $title;
108 }
109
110 /**
111 * Building tcemain CMD-array for swapping all versions in a workspace.
112 *
113 * @param int Real workspace ID, cannot be ONLINE (zero).
114 * @param bool If set, then the currently online versions are swapped into the workspace in exchange for the offline versions. Otherwise the workspace is emptied.
115 * @param int $pageId The page id
116 * @param int $language Select specific language only
117 * @return array Command array for tcemain
118 */
119 public function getCmdArrayForPublishWS($wsid, $doSwap, $pageId = 0, $language = NULL) {
120 $wsid = (int)$wsid;
121 $cmd = array();
122 if ($wsid >= -1 && $wsid !== 0) {
123 // Define stage to select:
124 $stage = -99;
125 if ($wsid > 0) {
126 $workspaceRec = BackendUtility::getRecord('sys_workspace', $wsid);
127 if ($workspaceRec['publish_access'] & 1) {
128 $stage = \TYPO3\CMS\Workspaces\Service\StagesService::STAGE_PUBLISH_ID;
129 }
130 }
131 // Select all versions to swap:
132 $versions = $this->selectVersionsInWorkspace($wsid, 0, $stage, $pageId ?: -1, 0, 'tables_modify', $language);
133 // Traverse the selection to build CMD array:
134 foreach ($versions as $table => $records) {
135 foreach ($records as $rec) {
136 // Build the cmd Array:
137 $cmd[$table][$rec['t3ver_oid']]['version'] = array('action' => 'swap', 'swapWith' => $rec['uid'], 'swapIntoWS' => $doSwap ? 1 : 0);
138 }
139 }
140 }
141 return $cmd;
142 }
143
144 /**
145 * Building tcemain CMD-array for releasing all versions in a workspace.
146 *
147 * @param int Real workspace ID, cannot be ONLINE (zero).
148 * @param bool Run Flush (TRUE) or ClearWSID (FALSE) command
149 * @param int $pageId The page id
150 * @param int $language Select specific language only
151 * @return array Command array for tcemain
152 */
153 public function getCmdArrayForFlushWS($wsid, $flush = TRUE, $pageId = 0, $language = NULL) {
154 $wsid = (int)$wsid;
155 $cmd = array();
156 if ($wsid >= -1 && $wsid !== 0) {
157 // Define stage to select:
158 $stage = -99;
159 // Select all versions to swap:
160 $versions = $this->selectVersionsInWorkspace($wsid, 0, $stage, $pageId ?: -1, 0, 'tables_modify', $language);
161 // Traverse the selection to build CMD array:
162 foreach ($versions as $table => $records) {
163 foreach ($records as $rec) {
164 // Build the cmd Array:
165 $cmd[$table][$rec['uid']]['version'] = array('action' => $flush ? 'flush' : 'clearWSID');
166 }
167 }
168 }
169 return $cmd;
170 }
171
172 /**
173 * Select all records from workspace pending for publishing
174 * Used from backend to display workspace overview
175 * User for auto-publishing for selecting versions for publication
176 *
177 * @param int Workspace ID. If -99, will select ALL versions from ANY workspace. If -98 will select all but ONLINE. >=-1 will select from the actual workspace
178 * @param int Lifecycle filter: 1 = select all drafts (never-published), 2 = select all published one or more times (archive/multiple), anything else selects all.
179 * @param int Stage filter: -99 means no filtering, otherwise it will be used to select only elements with that stage. For publishing, that would be "10
180 * @param int Page id: Live page for which to find versions in workspace!
181 * @param int Recursion Level - select versions recursive - parameter is only relevant if $pageId != -1
182 * @param string How to collect records for "listing" or "modify" these tables. Support the permissions of each type of record, see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::check.
183 * @param int $language Select specific language only
184 * @return array Array of all records uids etc. First key is table name, second key incremental integer. Records are associative arrays with uid and t3ver_oidfields. The pid of the online record is found as "livepid" the pid of the offline record is found in "wspid
185 */
186 public function selectVersionsInWorkspace($wsid, $filter = 0, $stage = -99, $pageId = -1, $recursionLevel = 0, $selectionType = 'tables_select', $language = NULL) {
187 $wsid = (int)$wsid;
188 $filter = (int)$filter;
189 $output = array();
190 // Contains either nothing or a list with live-uids
191 if ($pageId != -1 && $recursionLevel > 0) {
192 $pageList = $this->getTreeUids($pageId, $wsid, $recursionLevel);
193 } elseif ($pageId != -1) {
194 $pageList = $pageId;
195 } else {
196 $pageList = '';
197 // check if person may only see a "virtual" page-root
198 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
199 $mountPoints = array_unique($mountPoints);
200 if (!in_array(0, $mountPoints)) {
201 $tempPageIds = array();
202 foreach ($mountPoints as $mountPoint) {
203 $tempPageIds[] = $this->getTreeUids($mountPoint, $wsid, $recursionLevel);
204 }
205 $pageList = implode(',', $tempPageIds);
206 }
207 }
208 // Traversing all tables supporting versioning:
209 foreach ($GLOBALS['TCA'] as $table => $cfg) {
210 // we do not collect records from tables without permissions on them.
211 if (!$GLOBALS['BE_USER']->check($selectionType, $table)) {
212 continue;
213 }
214 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
215 $recs = $this->selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage, $language);
216 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] === 2) {
217 $moveRecs = $this->getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage);
218 $recs = array_merge($recs, $moveRecs);
219 }
220 $recs = $this->filterPermittedElements($recs, $table);
221 if (count($recs)) {
222 $output[$table] = $recs;
223 }
224 }
225 }
226 return $output;
227 }
228
229 /**
230 * Find all versionized elements except moved records.
231 *
232 * @param string $table
233 * @param string $pageList
234 * @param int $wsid
235 * @param int $filter
236 * @param int $stage
237 * @param int $language
238 * @return array
239 */
240 protected function selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage, $language = NULL) {
241 $isTableLocalizable = BackendUtility::isTableLocalizable($table);
242 $languageParentField = '';
243 // If table is not localizable, but localized reocrds shall
244 // be collected, an empty result array needs to be returned:
245 if ($isTableLocalizable === FALSE && $language > 0) {
246 return array();
247 } elseif ($isTableLocalizable) {
248 $languageParentField = 'A.' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . ', ';
249 }
250 $fields = 'A.uid, A.t3ver_oid, A.t3ver_stage, ' . $languageParentField . 'B.pid AS wspid, B.pid AS livepid';
251 if ($isTableLocalizable) {
252 $fields .= ', A.' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
253 }
254 $from = $table . ' A,' . $table . ' B';
255 // Table A is the offline version and pid=-1 defines offline
256 $where = 'A.pid=-1 AND A.t3ver_state!=' . new VersionState(VersionState::MOVE_POINTER);
257 if ($pageList) {
258 $pidField = $table === 'pages' ? 'uid' : 'pid';
259 $pidConstraint = strstr($pageList, ',') ? ' IN (' . $pageList . ')' : '=' . $pageList;
260 $where .= ' AND B.' . $pidField . $pidConstraint;
261 }
262 if ($isTableLocalizable && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($language)) {
263 $where .= ' AND A.' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '=' . $language;
264 }
265 // For "real" workspace numbers, select by that.
266 // If = -98, select all that are NOT online (zero).
267 // Anything else below -1 will not select on the wsid and therefore select all!
268 if ($wsid > self::SELECT_ALL_WORKSPACES) {
269 $where .= ' AND A.t3ver_wsid=' . $wsid;
270 } elseif ($wsid === self::SELECT_ALL_WORKSPACES) {
271 $where .= ' AND A.t3ver_wsid!=0';
272 }
273 // lifecycle filter:
274 // 1 = select all drafts (never-published),
275 // 2 = select all published one or more times (archive/multiple)
276 if ($filter === 1 || $filter === 2) {
277 $where .= ' AND A.t3ver_count ' . ($filter === 1 ? '= 0' : '> 0');
278 }
279 if ($stage != -99) {
280 $where .= ' AND A.t3ver_stage=' . (int)$stage;
281 }
282 // Table B (online) must have PID >= 0 to signify being online.
283 $where .= ' AND B.pid>=0';
284 // ... and finally the join between the two tables.
285 $where .= ' AND A.t3ver_oid=B.uid';
286 $where .= BackendUtility::deleteClause($table, 'A');
287 $where .= BackendUtility::deleteClause($table, 'B');
288 // Select all records from this table in the database from the workspace
289 // This joins the online version with the offline version as tables A and B
290 // Order by UID, mostly to have a sorting in the backend overview module which doesn't "jump around" when swapping.
291 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'B.uid');
292 return is_array($res) ? $res : array();
293 }
294
295 /**
296 * Find all moved records at their new position.
297 *
298 * @param string $table
299 * @param string $pageList
300 * @param int $wsid
301 * @param int $filter
302 * @param int $stage
303 * @return array
304 */
305 protected function getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage) {
306 // Aliases:
307 // A - moveTo placeholder
308 // B - online record
309 // C - moveFrom placeholder
310 $fields = 'A.pid AS wspid, B.uid AS t3ver_oid, C.uid AS uid, B.pid AS livepid';
311 $from = $table . ' A, ' . $table . ' B,' . $table . ' C';
312 $where = 'A.t3ver_state=' . new VersionState(VersionState::MOVE_PLACEHOLDER) . ' AND B.pid>0 AND B.t3ver_state='
313 . new VersionState(VersionState::DEFAULT_STATE) . ' AND B.t3ver_wsid=0 AND C.pid=-1 AND C.t3ver_state='
314 . new VersionState(VersionState::MOVE_POINTER);
315 if ($wsid > self::SELECT_ALL_WORKSPACES) {
316 $where .= ' AND A.t3ver_wsid=' . $wsid . ' AND C.t3ver_wsid=' . $wsid;
317 } elseif ($wsid === self::SELECT_ALL_WORKSPACES) {
318 $where .= ' AND A.t3ver_wsid!=0 AND C.t3ver_wsid!=0 ';
319 }
320 // lifecycle filter:
321 // 1 = select all drafts (never-published),
322 // 2 = select all published one or more times (archive/multiple)
323 if ($filter === 1 || $filter === 2) {
324 $where .= ' AND C.t3ver_count ' . ($filter === 1 ? '= 0' : '> 0');
325 }
326 if ($stage != -99) {
327 $where .= ' AND C.t3ver_stage=' . (int)$stage;
328 }
329 if ($pageList) {
330 $pidField = $table === 'pages' ? 'B.uid' : 'A.pid';
331 $pidConstraint = strstr($pageList, ',') ? ' IN (' . $pageList . ')' : '=' . $pageList;
332 $where .= ' AND ' . $pidField . $pidConstraint;
333 }
334 $where .= ' AND A.t3ver_move_id = B.uid AND B.uid = C.t3ver_oid';
335 $where .= BackendUtility::deleteClause($table, 'A');
336 $where .= BackendUtility::deleteClause($table, 'B');
337 $where .= BackendUtility::deleteClause($table, 'C');
338 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'A.uid');
339 return is_array($res) ? $res : array();
340 }
341
342 /**
343 * Find all page uids recursive starting from a specific page
344 *
345 * @param int $pageId
346 * @param int $wsid
347 * @param int $recursionLevel
348 * @return string Comma sep. uid list
349 */
350 protected function getTreeUids($pageId, $wsid, $recursionLevel) {
351 // Reusing existing functionality with the drawback that
352 // mount points are not covered yet
353 $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
354 /** @var $searchObj \TYPO3\CMS\Core\Database\QueryView */
355 $searchObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\QueryView::class);
356 if ($pageId > 0) {
357 $pageList = $searchObj->getTreeList($pageId, $recursionLevel, 0, $perms_clause);
358 } else {
359 $mountPoints = $GLOBALS['BE_USER']->uc['pageTree_temporaryMountPoint'];
360 if (!is_array($mountPoints) || empty($mountPoints)) {
361 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
362 $mountPoints = array_unique($mountPoints);
363 }
364 $newList = array();
365 foreach ($mountPoints as $mountPoint) {
366 $newList[] = $searchObj->getTreeList($mountPoint, $recursionLevel, 0, $perms_clause);
367 }
368 $pageList = implode(',', $newList);
369 }
370 unset($searchObj);
371 if ((int)$GLOBALS['TCA']['pages']['ctrl']['versioningWS'] === 2 && $pageList) {
372 // Remove the "subbranch" if a page was moved away
373 $movedAwayPages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid, pid, t3ver_move_id', 'pages', 't3ver_move_id IN (' . $pageList . ') AND t3ver_wsid=' . (int)$wsid . BackendUtility::deleteClause('pages'), '', 'uid', '', 't3ver_move_id');
374 $pageIds = GeneralUtility::intExplode(',', $pageList, TRUE);
375 // move all pages away
376 $newList = array_diff($pageIds, array_keys($movedAwayPages));
377 // keep current page in the list
378 $newList[] = $pageId;
379 // move back in if still connected to the "remaining" pages
380 do {
381 $changed = FALSE;
382 foreach ($movedAwayPages as $uid => $rec) {
383 if (in_array($rec['pid'], $newList) && !in_array($uid, $newList)) {
384 $newList[] = $uid;
385 $changed = TRUE;
386 }
387 }
388 } while ($changed);
389 $pageList = implode(',', $newList);
390 // In case moving pages is enabled we need to replace all move-to pointer with their origin
391 $pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid, t3ver_move_id', 'pages', 'uid IN (' . $pageList . ')' . BackendUtility::deleteClause('pages'), '', 'uid', '', 'uid');
392 $newList = array();
393 $pageIds = GeneralUtility::intExplode(',', $pageList, TRUE);
394 if (!in_array($pageId, $pageIds)) {
395 $pageIds[] = $pageId;
396 }
397 foreach ($pageIds as $pageId) {
398 if ((int)$pages[$pageId]['t3ver_move_id'] > 0) {
399 $newList[] = (int)$pages[$pageId]['t3ver_move_id'];
400 } else {
401 $newList[] = $pageId;
402 }
403 }
404 $pageList = implode(',', $newList);
405 }
406 return $pageList;
407 }
408
409 /**
410 * Remove all records which are not permitted for the user
411 *
412 * @param array $recs
413 * @param string $table
414 * @return array
415 */
416 protected function filterPermittedElements($recs, $table) {
417 $checkField = $table == 'pages' ? 'uid' : 'wspid';
418 $permittedElements = array();
419 if (is_array($recs)) {
420 foreach ($recs as $rec) {
421 $page = BackendUtility::getRecord('pages', $rec[$checkField], 'uid,pid,perms_userid,perms_user,perms_groupid,perms_group,perms_everybody');
422 if ($GLOBALS['BE_USER']->doesUserHaveAccess($page, 1) && $this->isLanguageAccessibleForCurrentUser($table, $rec)) {
423 $permittedElements[] = $rec;
424 }
425 }
426 }
427 return $permittedElements;
428 }
429
430 /**
431 * Check current be users language access on given record.
432 *
433 * @param string $table Name of the table
434 * @param array $record Record row to be checked
435 * @return bool
436 */
437 protected function isLanguageAccessibleForCurrentUser($table, array $record) {
438 $languageUid = 0;
439 if (BackendUtility::isTableLocalizable($table)) {
440 $languageUid = $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
441 } else {
442 return TRUE;
443 }
444 return $GLOBALS['BE_USER']->checkLanguageAccess($languageUid);
445 }
446
447 /**
448 * Trivial check to see if the user already migrated his workspaces
449 * to the new style (either manually or with the migrator scripts)
450 *
451 * @return bool
452 */
453 static public function isOldStyleWorkspaceUsed() {
454 $oldStyleWorkspaceIsUsed = FALSE;
455 $cacheKey = 'workspace-oldstyleworkspace-notused';
456 $cacheResult = $GLOBALS['BE_USER']->getSessionData($cacheKey);
457 if (!$cacheResult) {
458 $where = 'adminusers != "" AND adminusers NOT LIKE "%be_users%" AND adminusers NOT LIKE "%be_groups%" AND deleted=0';
459 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'sys_workspace', $where);
460 $oldStyleWorkspaceIsUsed = $count > 0;
461 $GLOBALS['BE_USER']->setAndSaveSessionData($cacheKey, !$oldStyleWorkspaceIsUsed);
462 } else {
463 $oldStyleWorkspaceIsUsed = !$cacheResult;
464 }
465 return $oldStyleWorkspaceIsUsed;
466 }
467
468 /**
469 * Determine whether a specific page is new and not yet available in the LIVE workspace
470 *
471 * @param int $id Primary key of the page to check
472 * @param int $language Language for which to check the page
473 * @return bool
474 */
475 static public function isNewPage($id, $language = 0) {
476 $isNewPage = FALSE;
477 // If the language is not default, check state of overlay
478 if ($language > 0) {
479 $whereClause = 'pid = ' . (int)$id;
480 $whereClause .= ' AND ' . $GLOBALS['TCA']['pages_language_overlay']['ctrl']['languageField'] . ' = ' . (int)$language;
481 $whereClause .= ' AND t3ver_wsid = ' . (int)$GLOBALS['BE_USER']->workspace;
482 $whereClause .= BackendUtility::deleteClause('pages_language_overlay');
483 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('t3ver_state', 'pages_language_overlay', $whereClause);
484 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
485 $isNewPage = VersionState::cast($row['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER);
486 }
487 } else {
488 $rec = BackendUtility::getRecord('pages', $id, 't3ver_state');
489 if (is_array($rec)) {
490 $isNewPage = VersionState::cast($rec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER);
491 }
492 }
493 return $isNewPage;
494 }
495
496 /**
497 * Generates a view link for a page.
498 *
499 * @static
500 * @param string $table Table to be used
501 * @param int $uid Uid of the version(!) record
502 * @param array $liveRecord Optional live record data
503 * @param array $versionRecord Optional version record data
504 * @return string
505 */
506 static public function viewSingleRecord($table, $uid, array $liveRecord = NULL, array $versionRecord = NULL) {
507 $viewUrl = '';
508
509 if ($table == 'pages') {
510 $viewUrl = BackendUtility::viewOnClick(BackendUtility::getLiveVersionIdOfRecord('pages', $uid));
511 } elseif ($table === 'pages_language_overlay' || $table === 'tt_content') {
512 if ($liveRecord === NULL) {
513 $liveRecord = BackendUtility::getLiveVersionOfRecord($table, $uid);
514 }
515 if ($versionRecord === NULL) {
516 $versionRecord = BackendUtility::getRecord($table, $uid);
517 }
518 if (VersionState::cast($versionRecord['t3ver_state'])->equals(VersionState::MOVE_POINTER)) {
519 $movePlaceholder = BackendUtility::getMovePlaceholder($table, $liveRecord['uid'], 'pid');
520 }
521
522 $previewPageId = (empty($movePlaceholder['pid']) ? $liveRecord['pid'] : $movePlaceholder['pid']);
523 $additionalParameters = '&tx_workspaces_web_workspacesworkspaces[previewWS]=' . $versionRecord['t3ver_wsid'];
524
525 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
526 if ($versionRecord[$languageField] > 0) {
527 $additionalParameters .= '&L=' . $versionRecord[$languageField];
528 }
529
530 $viewUrl = BackendUtility::viewOnClick($previewPageId, '', '', '', '', $additionalParameters);
531 } else {
532 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['workspaces']['viewSingleRecord'])) {
533 $_params = array(
534 'table' => $table,
535 'uid' => $uid,
536 'record' => $liveRecord,
537 'liveRecord' => $liveRecord,
538 'versionRecord' => $versionRecord,
539 );
540 $_funcRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['workspaces']['viewSingleRecord'];
541 $null = NULL;
542 $viewUrl = GeneralUtility::callUserFunction($_funcRef, $_params, $null);
543 }
544 }
545
546 return $viewUrl;
547 }
548
549 /**
550 * Determine whether this page for the current
551 *
552 * @param int $pageUid
553 * @param int $workspaceUid
554 * @return bool
555 */
556 public function canCreatePreviewLink($pageUid, $workspaceUid) {
557 $result = TRUE;
558 if ($pageUid > 0 && $workspaceUid > 0) {
559 $pageRecord = BackendUtility::getRecord('pages', $pageUid);
560 BackendUtility::workspaceOL('pages', $pageRecord, $workspaceUid);
561 if (
562 !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['content_doktypes'], $pageRecord['doktype'])
563 || VersionState::cast($pageRecord['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
564 ) {
565 $result = FALSE;
566 }
567 } else {
568 $result = FALSE;
569 }
570 return $result;
571 }
572
573 /**
574 * Generates a workspace preview link.
575 *
576 * @param int $uid The ID of the record to be linked
577 * @return string the full domain including the protocol http:// or https://, but without the trailing '/'
578 */
579 public function generateWorkspacePreviewLink($uid) {
580 $previewObject = GeneralUtility::makeInstance(\TYPO3\CMS\Version\Hook\PreviewHook::class);
581 $timeToLiveHours = $previewObject->getPreviewLinkLifetime();
582 $previewKeyword = $previewObject->compilePreviewKeyword('', $GLOBALS['BE_USER']->user['uid'], $timeToLiveHours * 3600, $this->getCurrentWorkspace());
583 $linkParams = array(
584 'ADMCMD_prev' => $previewKeyword,
585 'id' => $uid
586 );
587 return BackendUtility::getViewDomain($uid) . '/index.php?' . GeneralUtility::implodeArrayForUrl('', $linkParams);
588 }
589
590 /**
591 * Generates a workspace splitted preview link.
592 *
593 * @param int $uid The ID of the record to be linked
594 * @param bool $addDomain Parameter to decide if domain should be added to the generated link, FALSE per default
595 * @return string the preview link without the trailing '/'
596 */
597 public function generateWorkspaceSplittedPreviewLink($uid, $addDomain = FALSE) {
598 // In case a $pageUid is submitted we need to make sure it points to a live-page
599 if ($uid > 0) {
600 $uid = $this->getLivePageUid($uid);
601 }
602 /** @var $uriBuilder \TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder */
603 $uriBuilder = $this->getObjectManager()->get('TYPO3\\CMS\\Extbase\\Mvc\\Web\\Routing\\UriBuilder');
604 // This seems to be very harsh to set this directly to "/typo3 but the viewOnClick also
605 // has /index.php as fixed value here and dealing with the backPath is very error-prone
606 // @todo make sure this would work in local extension installation too
607 $backPath = '/' . TYPO3_mainDir;
608 $redirect = $backPath . 'index.php?redirect_url=';
609 // @todo this should maybe be changed so that the extbase URI Builder can deal with module names directly
610 $originalM = GeneralUtility::_GET('M');
611 GeneralUtility::_GETset('web_WorkspacesWorkspaces', 'M');
612 $viewScript = $backPath . $uriBuilder->uriFor('index', array(), 'Preview', 'workspaces', 'web_workspacesworkspaces') . '&id=';
613 GeneralUtility::_GETset($originalM, 'M');
614 if ($addDomain === TRUE) {
615 return BackendUtility::getViewDomain($uid) . $redirect . urlencode($viewScript) . $uid;
616 } else {
617 return $viewScript;
618 }
619 }
620
621 /**
622 * Find the Live-Uid for a given page,
623 * the results are cached at run-time to avoid too many database-queries
624 *
625 * @throws \InvalidArgumentException
626 * @param int $uid
627 * @return int
628 */
629 public function getLivePageUid($uid) {
630 if (!isset($this->pageCache[$uid])) {
631 $pageRecord = BackendUtility::getRecord('pages', $uid);
632 if (is_array($pageRecord)) {
633 $this->pageCache[$uid] = $pageRecord['t3ver_oid'] ? $pageRecord['t3ver_oid'] : $uid;
634 } else {
635 throw new \InvalidArgumentException('uid is supposed to point to an existing page - given value was:' . $uid, 1290628113);
636 }
637 }
638 return $this->pageCache[$uid];
639 }
640
641 /**
642 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
643 */
644 protected function getObjectManager() {
645 return GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
646 }
647
648 }