1fbd546a3660ecebc3b32b2e986a5014a739c1d1
[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 integer 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 integer $wsId
88 * @return string
89 */
90 static public function getWorkspaceTitle($wsId) {
91 $title = FALSE;
92 switch ($wsId) {
93 case self::LIVE_WORKSPACE_ID:
94 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:shortcut_onlineWS');
95 break;
96 default:
97 $labelField = $GLOBALS['TCA']['sys_workspace']['ctrl']['label'];
98 $wsRecord = BackendUtility::getRecord('sys_workspace', $wsId, 'uid,' . $labelField);
99 if (is_array($wsRecord)) {
100 $title = $wsRecord[$labelField];
101 }
102 }
103 if ($title === FALSE) {
104 throw new \InvalidArgumentException('No such workspace defined');
105 }
106 return $title;
107 }
108
109 /**
110 * Building tcemain CMD-array for swapping all versions in a workspace.
111 *
112 * @param integer Real workspace ID, cannot be ONLINE (zero).
113 * @param boolean If set, then the currently online versions are swapped into the workspace in exchange for the offline versions. Otherwise the workspace is emptied.
114 * @param integer $pageId: ...
115 * @param integer $language Select specific language only
116 * @return array Command array for tcemain
117 */
118 public function getCmdArrayForPublishWS($wsid, $doSwap, $pageId = 0, $language = NULL) {
119 $wsid = (int)$wsid;
120 $cmd = array();
121 if ($wsid >= -1 && $wsid !== 0) {
122 // Define stage to select:
123 $stage = -99;
124 if ($wsid > 0) {
125 $workspaceRec = BackendUtility::getRecord('sys_workspace', $wsid);
126 if ($workspaceRec['publish_access'] & 1) {
127 $stage = \TYPO3\CMS\Workspaces\Service\StagesService::STAGE_PUBLISH_ID;
128 }
129 }
130 // Select all versions to swap:
131 $versions = $this->selectVersionsInWorkspace($wsid, 0, $stage, $pageId ?: -1, 0, 'tables_modify', $language);
132 // Traverse the selection to build CMD array:
133 foreach ($versions as $table => $records) {
134 foreach ($records as $rec) {
135 // Build the cmd Array:
136 $cmd[$table][$rec['t3ver_oid']]['version'] = array('action' => 'swap', 'swapWith' => $rec['uid'], 'swapIntoWS' => $doSwap ? 1 : 0);
137 }
138 }
139 }
140 return $cmd;
141 }
142
143 /**
144 * Building tcemain CMD-array for releasing all versions in a workspace.
145 *
146 * @param integer Real workspace ID, cannot be ONLINE (zero).
147 * @param boolean Run Flush (TRUE) or ClearWSID (FALSE) command
148 * @param integer $pageId: ...
149 * @param integer $language Select specific language only
150 * @return array Command array for tcemain
151 */
152 public function getCmdArrayForFlushWS($wsid, $flush = TRUE, $pageId = 0, $language = NULL) {
153 $wsid = (int)$wsid;
154 $cmd = array();
155 if ($wsid >= -1 && $wsid !== 0) {
156 // Define stage to select:
157 $stage = -99;
158 // Select all versions to swap:
159 $versions = $this->selectVersionsInWorkspace($wsid, 0, $stage, $pageId ?: -1, 0, 'tables_modify', $language);
160 // Traverse the selection to build CMD array:
161 foreach ($versions as $table => $records) {
162 foreach ($records as $rec) {
163 // Build the cmd Array:
164 $cmd[$table][$rec['uid']]['version'] = array('action' => $flush ? 'flush' : 'clearWSID');
165 }
166 }
167 }
168 return $cmd;
169 }
170
171 /**
172 * Select all records from workspace pending for publishing
173 * Used from backend to display workspace overview
174 * User for auto-publishing for selecting versions for publication
175 *
176 * @param integer 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
177 * @param integer Lifecycle filter: 1 = select all drafts (never-published), 2 = select all published one or more times (archive/multiple), anything else selects all.
178 * @param integer Stage filter: -99 means no filtering, otherwise it will be used to select only elements with that stage. For publishing, that would be "10
179 * @param integer Page id: Live page for which to find versions in workspace!
180 * @param integer Recursion Level - select versions recursive - parameter is only relevant if $pageId != -1
181 * @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.
182 * @param integer $language Select specific language only
183 * @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
184 */
185 public function selectVersionsInWorkspace($wsid, $filter = 0, $stage = -99, $pageId = -1, $recursionLevel = 0, $selectionType = 'tables_select', $language = NULL) {
186 $wsid = (int)$wsid;
187 $filter = (int)$filter;
188 $output = array();
189 // Include root level page as there might be some records with where root level restriction is ignored (e.g. FAL records)
190 $pageList = '0,';
191 // Contains either nothing or a list with live-uids
192 if ($pageId != -1 && $recursionLevel > 0) {
193 $pageList .= $this->getTreeUids($pageId, $wsid, $recursionLevel);
194 } elseif ($pageId != -1) {
195 $pageList .= $pageId;
196 } else {
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 integer $wsid
235 * @param integer $filter
236 * @param integer $stage
237 * @param integer $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 integer $wsid
301 * @param integer $filter
302 * @param integer $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 integer $pageId
346 * @param integer $wsid
347 * @param integer $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 = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\QueryView');
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 = \TYPO3\CMS\Core\Utility\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 = \TYPO3\CMS\Core\Utility\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 $permittedElements = array();
418 if (is_array($recs)) {
419 foreach ($recs as $rec) {
420 if ($this->isPageAccessibleForCurrentUser($table, $rec) && $this->isLanguageAccessibleForCurrentUser($table, $rec)) {
421 $permittedElements[] = $rec;
422 }
423 }
424 }
425 return $permittedElements;
426 }
427
428 /**
429 * Checking access to the page the record is on, respecting ignored root level restrictions
430 *
431 * @param string $table Name of the table
432 * @param array $record Record row to be checked
433 * @return bool
434 */
435 protected function isPageAccessibleForCurrentUser($table, array $record) {
436 $pageIdField = $table === 'pages' ? 'uid' : 'wspid';
437 $pageId = isset($record[$pageIdField]) ? (int)$record[$pageIdField] : NULL;
438 if ($pageId === NULL) {
439 return FALSE;
440 }
441 if ($pageId === 0 && BackendUtility::isRootLevelRestrictionIgnored($table)) {
442 return TRUE;
443 }
444 $page = BackendUtility::getRecord('pages', $pageId, 'uid,pid,perms_userid,perms_user,perms_groupid,perms_group,perms_everybody');
445
446 return $GLOBALS['BE_USER']->doesUserHaveAccess($page, 1);
447 }
448
449 /**
450 * Check current be users language access on given record.
451 *
452 * @param string $table Name of the table
453 * @param array $record Record row to be checked
454 * @return boolean
455 */
456 protected function isLanguageAccessibleForCurrentUser($table, array $record) {
457 if (BackendUtility::isTableLocalizable($table)) {
458 $languageUid = $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
459 } else {
460 return TRUE;
461 }
462 return $GLOBALS['BE_USER']->checkLanguageAccess($languageUid);
463 }
464
465 /**
466 * Trivial check to see if the user already migrated his workspaces
467 * to the new style (either manually or with the migrator scripts)
468 *
469 * @return boolean
470 */
471 static public function isOldStyleWorkspaceUsed() {
472 $oldStyleWorkspaceIsUsed = FALSE;
473 $cacheKey = 'workspace-oldstyleworkspace-notused';
474 $cacheResult = $GLOBALS['BE_USER']->getSessionData($cacheKey);
475 if (!$cacheResult) {
476 $where = 'adminusers != "" AND adminusers NOT LIKE "%be_users%" AND adminusers NOT LIKE "%be_groups%" AND deleted=0';
477 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'sys_workspace', $where);
478 $oldStyleWorkspaceIsUsed = $count > 0;
479 $GLOBALS['BE_USER']->setAndSaveSessionData($cacheKey, !$oldStyleWorkspaceIsUsed);
480 } else {
481 $oldStyleWorkspaceIsUsed = !$cacheResult;
482 }
483 return $oldStyleWorkspaceIsUsed;
484 }
485
486 /**
487 * Determine whether a specific page is new and not yet available in the LIVE workspace
488 *
489 * @static
490 * @param integer $id Primary key of the page to check
491 * @param integer $language Language for which to check the page
492 * @return boolean
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 integer $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 = \TYPO3\CMS\Core\Utility\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 integer $pageUid
572 * @param integer $workspaceUid
573 * @return boolean
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 integer $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 = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Version\\Hook\\PreviewHook');
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?' . \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl('', $linkParams);
607 }
608
609 /**
610 * Generates a workspace splitted preview link.
611 *
612 * @param integer $uid The ID of the record to be linked
613 * @param boolean $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 integer $uid
646 * @return integer
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 \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
665 }
666
667 }