9b0c50717d96e2076e9c7f3994bd9ba46d2013b0
[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 // Include root level page as there might be some records with where root level restriction is ignored (e.g. FAL records)
191 $pageList = '0,';
192 // Contains either nothing or a list with live-uids
193 if ($pageId != -1 && $recursionLevel > 0) {
194 $pageList .= $this->getTreeUids($pageId, $wsid, $recursionLevel);
195 } elseif ($pageId != -1) {
196 $pageList .= $pageId;
197 } else {
198 // check if person may only see a "virtual" page-root
199 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
200 $mountPoints = array_unique($mountPoints);
201 if (!in_array(0, $mountPoints)) {
202 $tempPageIds = array();
203 foreach ($mountPoints as $mountPoint) {
204 $tempPageIds[] = $this->getTreeUids($mountPoint, $wsid, $recursionLevel);
205 }
206 $pageList .= implode(',', $tempPageIds);
207 }
208 }
209 // Traversing all tables supporting versioning:
210 foreach ($GLOBALS['TCA'] as $table => $cfg) {
211 // we do not collect records from tables without permissions on them.
212 if (!$GLOBALS['BE_USER']->check($selectionType, $table)) {
213 continue;
214 }
215 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
216 $recs = $this->selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage, $language);
217 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] === 2) {
218 $moveRecs = $this->getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage);
219 $recs = array_merge($recs, $moveRecs);
220 }
221 $recs = $this->filterPermittedElements($recs, $table);
222 if (count($recs)) {
223 $output[$table] = $recs;
224 }
225 }
226 }
227 return $output;
228 }
229
230 /**
231 * Find all versionized elements except moved records.
232 *
233 * @param string $table
234 * @param string $pageList
235 * @param int $wsid
236 * @param int $filter
237 * @param int $stage
238 * @param int $language
239 * @return array
240 */
241 protected function selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage, $language = NULL) {
242 $isTableLocalizable = BackendUtility::isTableLocalizable($table);
243 $languageParentField = '';
244 // If table is not localizable, but localized reocrds shall
245 // be collected, an empty result array needs to be returned:
246 if ($isTableLocalizable === FALSE && $language > 0) {
247 return array();
248 } elseif ($isTableLocalizable) {
249 $languageParentField = 'A.' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . ', ';
250 }
251 $fields = 'A.uid, A.t3ver_oid, A.t3ver_stage, ' . $languageParentField . 'B.pid AS wspid, B.pid AS livepid';
252 if ($isTableLocalizable) {
253 $fields .= ', A.' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
254 }
255 $from = $table . ' A,' . $table . ' B';
256 // Table A is the offline version and pid=-1 defines offline
257 $where = 'A.pid=-1 AND A.t3ver_state!=' . new VersionState(VersionState::MOVE_POINTER);
258 if ($pageList) {
259 $pidField = $table === 'pages' ? 'uid' : 'pid';
260 $pidConstraint = strstr($pageList, ',') ? ' IN (' . $pageList . ')' : '=' . $pageList;
261 $where .= ' AND B.' . $pidField . $pidConstraint;
262 }
263 if ($isTableLocalizable && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($language)) {
264 $where .= ' AND A.' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '=' . $language;
265 }
266 // For "real" workspace numbers, select by that.
267 // If = -98, select all that are NOT online (zero).
268 // Anything else below -1 will not select on the wsid and therefore select all!
269 if ($wsid > self::SELECT_ALL_WORKSPACES) {
270 $where .= ' AND A.t3ver_wsid=' . $wsid;
271 } elseif ($wsid === self::SELECT_ALL_WORKSPACES) {
272 $where .= ' AND A.t3ver_wsid!=0';
273 }
274 // lifecycle filter:
275 // 1 = select all drafts (never-published),
276 // 2 = select all published one or more times (archive/multiple)
277 if ($filter === 1 || $filter === 2) {
278 $where .= ' AND A.t3ver_count ' . ($filter === 1 ? '= 0' : '> 0');
279 }
280 if ($stage != -99) {
281 $where .= ' AND A.t3ver_stage=' . (int)$stage;
282 }
283 // Table B (online) must have PID >= 0 to signify being online.
284 $where .= ' AND B.pid>=0';
285 // ... and finally the join between the two tables.
286 $where .= ' AND A.t3ver_oid=B.uid';
287 $where .= BackendUtility::deleteClause($table, 'A');
288 $where .= BackendUtility::deleteClause($table, 'B');
289 // Select all records from this table in the database from the workspace
290 // This joins the online version with the offline version as tables A and B
291 // Order by UID, mostly to have a sorting in the backend overview module which doesn't "jump around" when swapping.
292 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'B.uid');
293 return is_array($res) ? $res : array();
294 }
295
296 /**
297 * Find all moved records at their new position.
298 *
299 * @param string $table
300 * @param string $pageList
301 * @param int $wsid
302 * @param int $filter
303 * @param int $stage
304 * @return array
305 */
306 protected function getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage) {
307 // Aliases:
308 // A - moveTo placeholder
309 // B - online record
310 // C - moveFrom placeholder
311 $fields = 'A.pid AS wspid, B.uid AS t3ver_oid, C.uid AS uid, B.pid AS livepid';
312 $from = $table . ' A, ' . $table . ' B,' . $table . ' C';
313 $where = 'A.t3ver_state=' . new VersionState(VersionState::MOVE_PLACEHOLDER) . ' AND B.pid>0 AND B.t3ver_state='
314 . new VersionState(VersionState::DEFAULT_STATE) . ' AND B.t3ver_wsid=0 AND C.pid=-1 AND C.t3ver_state='
315 . new VersionState(VersionState::MOVE_POINTER);
316 if ($wsid > self::SELECT_ALL_WORKSPACES) {
317 $where .= ' AND A.t3ver_wsid=' . $wsid . ' AND C.t3ver_wsid=' . $wsid;
318 } elseif ($wsid === self::SELECT_ALL_WORKSPACES) {
319 $where .= ' AND A.t3ver_wsid!=0 AND C.t3ver_wsid!=0 ';
320 }
321 // lifecycle filter:
322 // 1 = select all drafts (never-published),
323 // 2 = select all published one or more times (archive/multiple)
324 if ($filter === 1 || $filter === 2) {
325 $where .= ' AND C.t3ver_count ' . ($filter === 1 ? '= 0' : '> 0');
326 }
327 if ($stage != -99) {
328 $where .= ' AND C.t3ver_stage=' . (int)$stage;
329 }
330 if ($pageList) {
331 $pidField = $table === 'pages' ? 'B.uid' : 'A.pid';
332 $pidConstraint = strstr($pageList, ',') ? ' IN (' . $pageList . ')' : '=' . $pageList;
333 $where .= ' AND ' . $pidField . $pidConstraint;
334 }
335 $where .= ' AND A.t3ver_move_id = B.uid AND B.uid = C.t3ver_oid';
336 $where .= BackendUtility::deleteClause($table, 'A');
337 $where .= BackendUtility::deleteClause($table, 'B');
338 $where .= BackendUtility::deleteClause($table, 'C');
339 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'A.uid');
340 return is_array($res) ? $res : array();
341 }
342
343 /**
344 * Find all page uids recursive starting from a specific page
345 *
346 * @param int $pageId
347 * @param int $wsid
348 * @param int $recursionLevel
349 * @return string Comma sep. uid list
350 */
351 protected function getTreeUids($pageId, $wsid, $recursionLevel) {
352 // Reusing existing functionality with the drawback that
353 // mount points are not covered yet
354 $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
355 /** @var $searchObj \TYPO3\CMS\Core\Database\QueryView */
356 $searchObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\QueryView::class);
357 if ($pageId > 0) {
358 $pageList = $searchObj->getTreeList($pageId, $recursionLevel, 0, $perms_clause);
359 } else {
360 $mountPoints = $GLOBALS['BE_USER']->uc['pageTree_temporaryMountPoint'];
361 if (!is_array($mountPoints) || empty($mountPoints)) {
362 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
363 $mountPoints = array_unique($mountPoints);
364 }
365 $newList = array();
366 foreach ($mountPoints as $mountPoint) {
367 $newList[] = $searchObj->getTreeList($mountPoint, $recursionLevel, 0, $perms_clause);
368 }
369 $pageList = implode(',', $newList);
370 }
371 unset($searchObj);
372 if ((int)$GLOBALS['TCA']['pages']['ctrl']['versioningWS'] === 2 && $pageList) {
373 // Remove the "subbranch" if a page was moved away
374 $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');
375 $pageIds = GeneralUtility::intExplode(',', $pageList, TRUE);
376 // move all pages away
377 $newList = array_diff($pageIds, array_keys($movedAwayPages));
378 // keep current page in the list
379 $newList[] = $pageId;
380 // move back in if still connected to the "remaining" pages
381 do {
382 $changed = FALSE;
383 foreach ($movedAwayPages as $uid => $rec) {
384 if (in_array($rec['pid'], $newList) && !in_array($uid, $newList)) {
385 $newList[] = $uid;
386 $changed = TRUE;
387 }
388 }
389 } while ($changed);
390 $pageList = implode(',', $newList);
391 // In case moving pages is enabled we need to replace all move-to pointer with their origin
392 $pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid, t3ver_move_id', 'pages', 'uid IN (' . $pageList . ')' . BackendUtility::deleteClause('pages'), '', 'uid', '', 'uid');
393 $newList = array();
394 $pageIds = GeneralUtility::intExplode(',', $pageList, TRUE);
395 if (!in_array($pageId, $pageIds)) {
396 $pageIds[] = $pageId;
397 }
398 foreach ($pageIds as $pageId) {
399 if ((int)$pages[$pageId]['t3ver_move_id'] > 0) {
400 $newList[] = (int)$pages[$pageId]['t3ver_move_id'];
401 } else {
402 $newList[] = $pageId;
403 }
404 }
405 $pageList = implode(',', $newList);
406 }
407 return $pageList;
408 }
409
410 /**
411 * Remove all records which are not permitted for the user
412 *
413 * @param array $recs
414 * @param string $table
415 * @return array
416 */
417 protected function filterPermittedElements($recs, $table) {
418 $permittedElements = array();
419 if (is_array($recs)) {
420 foreach ($recs as $rec) {
421 if ($this->isPageAccessibleForCurrentUser($table, $rec) && $this->isLanguageAccessibleForCurrentUser($table, $rec)) {
422 $permittedElements[] = $rec;
423 }
424 }
425 }
426 return $permittedElements;
427 }
428
429 /**
430 * Checking access to the page the record is on, respecting ignored root level restrictions
431 *
432 * @param string $table Name of the table
433 * @param array $record Record row to be checked
434 * @return bool
435 */
436 protected function isPageAccessibleForCurrentUser($table, array $record) {
437 $pageIdField = $table == 'pages' ? 'uid' : 'wspid';
438 $pageId = isset($record[$pageIdField]) ? (int)$record[$pageIdField] : NULL;
439 if ($pageId === NULL) {
440 return FALSE;
441 }
442 if ($pageId === 0 && BackendUtility::isRootLevelRestrictionIgnored($table)) {
443 return TRUE;
444 }
445 $page = BackendUtility::getRecord('pages', $pageId, 'uid,pid,perms_userid,perms_user,perms_groupid,perms_group,perms_everybody');
446
447 return $GLOBALS['BE_USER']->doesUserHaveAccess($page, 1);
448 }
449
450 /**
451 * Check current be users language access on given record.
452 *
453 * @param string $table Name of the table
454 * @param array $record Record row to be checked
455 * @return bool
456 */
457 protected function isLanguageAccessibleForCurrentUser($table, array $record) {
458 if (BackendUtility::isTableLocalizable($table)) {
459 $languageUid = $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
460 } else {
461 return TRUE;
462 }
463 return $GLOBALS['BE_USER']->checkLanguageAccess($languageUid);
464 }
465
466 /**
467 * Trivial check to see if the user already migrated his workspaces
468 * to the new style (either manually or with the migrator scripts)
469 *
470 * @return bool
471 */
472 static public function isOldStyleWorkspaceUsed() {
473 $oldStyleWorkspaceIsUsed = FALSE;
474 $cacheKey = 'workspace-oldstyleworkspace-notused';
475 $cacheResult = $GLOBALS['BE_USER']->getSessionData($cacheKey);
476 if (!$cacheResult) {
477 $where = 'adminusers != "" AND adminusers NOT LIKE "%be_users%" AND adminusers NOT LIKE "%be_groups%" AND deleted=0';
478 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'sys_workspace', $where);
479 $oldStyleWorkspaceIsUsed = $count > 0;
480 $GLOBALS['BE_USER']->setAndSaveSessionData($cacheKey, !$oldStyleWorkspaceIsUsed);
481 } else {
482 $oldStyleWorkspaceIsUsed = !$cacheResult;
483 }
484 return $oldStyleWorkspaceIsUsed;
485 }
486
487 /**
488 * Determine whether a specific page is new and not yet available in the LIVE workspace
489 *
490 * @param int $id Primary key of the page to check
491 * @param int $language Language for which to check the page
492 * @return bool
493 */
494 static public function isNewPage($id, $language = 0) {
495 $isNewPage = FALSE;
496 // If the language is not default, check state of overlay
497 if ($language > 0) {
498 $whereClause = 'pid = ' . (int)$id;
499 $whereClause .= ' AND ' . $GLOBALS['TCA']['pages_language_overlay']['ctrl']['languageField'] . ' = ' . (int)$language;
500 $whereClause .= ' AND t3ver_wsid = ' . (int)$GLOBALS['BE_USER']->workspace;
501 $whereClause .= BackendUtility::deleteClause('pages_language_overlay');
502 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('t3ver_state', 'pages_language_overlay', $whereClause);
503 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
504 $isNewPage = VersionState::cast($row['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER);
505 }
506 } else {
507 $rec = BackendUtility::getRecord('pages', $id, 't3ver_state');
508 if (is_array($rec)) {
509 $isNewPage = VersionState::cast($rec['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER);
510 }
511 }
512 return $isNewPage;
513 }
514
515 /**
516 * Generates a view link for a page.
517 *
518 * @static
519 * @param string $table Table to be used
520 * @param int $uid Uid of the version(!) record
521 * @param array $liveRecord Optional live record data
522 * @param array $versionRecord Optional version record data
523 * @return string
524 */
525 static public function viewSingleRecord($table, $uid, array $liveRecord = NULL, array $versionRecord = NULL) {
526 $viewUrl = '';
527
528 if ($table == 'pages') {
529 $viewUrl = BackendUtility::viewOnClick(BackendUtility::getLiveVersionIdOfRecord('pages', $uid));
530 } elseif ($table === 'pages_language_overlay' || $table === 'tt_content') {
531 if ($liveRecord === NULL) {
532 $liveRecord = BackendUtility::getLiveVersionOfRecord($table, $uid);
533 }
534 if ($versionRecord === NULL) {
535 $versionRecord = BackendUtility::getRecord($table, $uid);
536 }
537 if (VersionState::cast($versionRecord['t3ver_state'])->equals(VersionState::MOVE_POINTER)) {
538 $movePlaceholder = BackendUtility::getMovePlaceholder($table, $liveRecord['uid'], 'pid');
539 }
540
541 $previewPageId = (empty($movePlaceholder['pid']) ? $liveRecord['pid'] : $movePlaceholder['pid']);
542 $additionalParameters = '&tx_workspaces_web_workspacesworkspaces[previewWS]=' . $versionRecord['t3ver_wsid'];
543
544 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
545 if ($versionRecord[$languageField] > 0) {
546 $additionalParameters .= '&L=' . $versionRecord[$languageField];
547 }
548
549 $viewUrl = BackendUtility::viewOnClick($previewPageId, '', '', '', '', $additionalParameters);
550 } else {
551 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['workspaces']['viewSingleRecord'])) {
552 $_params = array(
553 'table' => $table,
554 'uid' => $uid,
555 'record' => $liveRecord,
556 'liveRecord' => $liveRecord,
557 'versionRecord' => $versionRecord,
558 );
559 $_funcRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['workspaces']['viewSingleRecord'];
560 $null = NULL;
561 $viewUrl = GeneralUtility::callUserFunction($_funcRef, $_params, $null);
562 }
563 }
564
565 return $viewUrl;
566 }
567
568 /**
569 * Determine whether this page for the current
570 *
571 * @param int $pageUid
572 * @param int $workspaceUid
573 * @return bool
574 */
575 public function canCreatePreviewLink($pageUid, $workspaceUid) {
576 $result = TRUE;
577 if ($pageUid > 0 && $workspaceUid > 0) {
578 $pageRecord = BackendUtility::getRecord('pages', $pageUid);
579 BackendUtility::workspaceOL('pages', $pageRecord, $workspaceUid);
580 if (
581 !GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['content_doktypes'], $pageRecord['doktype'])
582 || VersionState::cast($pageRecord['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
583 ) {
584 $result = FALSE;
585 }
586 } else {
587 $result = FALSE;
588 }
589 return $result;
590 }
591
592 /**
593 * Generates a workspace preview link.
594 *
595 * @param int $uid The ID of the record to be linked
596 * @return string the full domain including the protocol http:// or https://, but without the trailing '/'
597 */
598 public function generateWorkspacePreviewLink($uid) {
599 $previewObject = GeneralUtility::makeInstance(\TYPO3\CMS\Version\Hook\PreviewHook::class);
600 $timeToLiveHours = $previewObject->getPreviewLinkLifetime();
601 $previewKeyword = $previewObject->compilePreviewKeyword('', $GLOBALS['BE_USER']->user['uid'], $timeToLiveHours * 3600, $this->getCurrentWorkspace());
602 $linkParams = array(
603 'ADMCMD_prev' => $previewKeyword,
604 'id' => $uid
605 );
606 return BackendUtility::getViewDomain($uid) . '/index.php?' . GeneralUtility::implodeArrayForUrl('', $linkParams);
607 }
608
609 /**
610 * Generates a workspace splitted preview link.
611 *
612 * @param int $uid The ID of the record to be linked
613 * @param bool $addDomain Parameter to decide if domain should be added to the generated link, FALSE per default
614 * @return string the preview link without the trailing '/'
615 */
616 public function generateWorkspaceSplittedPreviewLink($uid, $addDomain = FALSE) {
617 // In case a $pageUid is submitted we need to make sure it points to a live-page
618 if ($uid > 0) {
619 $uid = $this->getLivePageUid($uid);
620 }
621 /** @var $uriBuilder \TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder */
622 $uriBuilder = $this->getObjectManager()->get('TYPO3\\CMS\\Extbase\\Mvc\\Web\\Routing\\UriBuilder');
623 // This seems to be very harsh to set this directly to "/typo3 but the viewOnClick also
624 // has /index.php as fixed value here and dealing with the backPath is very error-prone
625 // @todo make sure this would work in local extension installation too
626 $backPath = '/' . TYPO3_mainDir;
627 $redirect = $backPath . 'index.php?redirect_url=';
628 // @todo this should maybe be changed so that the extbase URI Builder can deal with module names directly
629 $originalM = GeneralUtility::_GET('M');
630 GeneralUtility::_GETset('web_WorkspacesWorkspaces', 'M');
631 $viewScript = $backPath . $uriBuilder->uriFor('index', array(), 'Preview', 'workspaces', 'web_workspacesworkspaces') . '&id=';
632 GeneralUtility::_GETset($originalM, 'M');
633 if ($addDomain === TRUE) {
634 return BackendUtility::getViewDomain($uid) . $redirect . urlencode($viewScript) . $uid;
635 } else {
636 return $viewScript;
637 }
638 }
639
640 /**
641 * Find the Live-Uid for a given page,
642 * the results are cached at run-time to avoid too many database-queries
643 *
644 * @throws \InvalidArgumentException
645 * @param int $uid
646 * @return int
647 */
648 public function getLivePageUid($uid) {
649 if (!isset($this->pageCache[$uid])) {
650 $pageRecord = BackendUtility::getRecord('pages', $uid);
651 if (is_array($pageRecord)) {
652 $this->pageCache[$uid] = $pageRecord['t3ver_oid'] ? $pageRecord['t3ver_oid'] : $uid;
653 } else {
654 throw new \InvalidArgumentException('uid is supposed to point to an existing page - given value was:' . $uid, 1290628113);
655 }
656 }
657 return $this->pageCache[$uid];
658 }
659
660 /**
661 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
662 */
663 protected function getObjectManager() {
664 return GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
665 }
666
667 }