[TASK] Re-work/simplify copyright header in PHP files - Part 9
[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 // Contains either nothing or a list with live-uids
190 if ($pageId != -1 && $recursionLevel > 0) {
191 $pageList = $this->getTreeUids($pageId, $wsid, $recursionLevel);
192 } elseif ($pageId != -1) {
193 $pageList = $pageId;
194 } else {
195 $pageList = '';
196 // check if person may only see a "virtual" page-root
197 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
198 $mountPoints = array_unique($mountPoints);
199 if (!in_array(0, $mountPoints)) {
200 $tempPageIds = array();
201 foreach ($mountPoints as $mountPoint) {
202 $tempPageIds[] = $this->getTreeUids($mountPoint, $wsid, $recursionLevel);
203 }
204 $pageList = implode(',', $tempPageIds);
205 }
206 }
207 // Traversing all tables supporting versioning:
208 foreach ($GLOBALS['TCA'] as $table => $cfg) {
209 // we do not collect records from tables without permissions on them.
210 if (!$GLOBALS['BE_USER']->check($selectionType, $table)) {
211 continue;
212 }
213 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
214 $recs = $this->selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage, $language);
215 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] === 2) {
216 $moveRecs = $this->getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage);
217 $recs = array_merge($recs, $moveRecs);
218 }
219 $recs = $this->filterPermittedElements($recs, $table);
220 if (count($recs)) {
221 $output[$table] = $recs;
222 }
223 }
224 }
225 return $output;
226 }
227
228 /**
229 * Find all versionized elements except moved records.
230 *
231 * @param string $table
232 * @param string $pageList
233 * @param integer $wsid
234 * @param integer $filter
235 * @param integer $stage
236 * @param integer $language
237 * @return array
238 */
239 protected function selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage, $language = NULL) {
240 $isTableLocalizable = BackendUtility::isTableLocalizable($table);
241 $languageParentField = '';
242 // If table is not localizable, but localized reocrds shall
243 // be collected, an empty result array needs to be returned:
244 if ($isTableLocalizable === FALSE && $language > 0) {
245 return array();
246 } elseif ($isTableLocalizable) {
247 $languageParentField = 'A.' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . ', ';
248 }
249 $fields = 'A.uid, A.t3ver_oid, A.t3ver_stage, ' . $languageParentField . 'B.pid AS wspid, B.pid AS livepid';
250 if ($isTableLocalizable) {
251 $fields .= ', A.' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
252 }
253 $from = $table . ' A,' . $table . ' B';
254 // Table A is the offline version and pid=-1 defines offline
255 $where = 'A.pid=-1 AND A.t3ver_state!=' . new VersionState(VersionState::MOVE_POINTER);
256 if ($pageList) {
257 $pidField = $table === 'pages' ? 'uid' : 'pid';
258 $pidConstraint = strstr($pageList, ',') ? ' IN (' . $pageList . ')' : '=' . $pageList;
259 $where .= ' AND B.' . $pidField . $pidConstraint;
260 }
261 if ($isTableLocalizable && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($language)) {
262 $where .= ' AND A.' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '=' . $language;
263 }
264 // For "real" workspace numbers, select by that.
265 // If = -98, select all that are NOT online (zero).
266 // Anything else below -1 will not select on the wsid and therefore select all!
267 if ($wsid > self::SELECT_ALL_WORKSPACES) {
268 $where .= ' AND A.t3ver_wsid=' . $wsid;
269 } elseif ($wsid === self::SELECT_ALL_WORKSPACES) {
270 $where .= ' AND A.t3ver_wsid!=0';
271 }
272 // lifecycle filter:
273 // 1 = select all drafts (never-published),
274 // 2 = select all published one or more times (archive/multiple)
275 if ($filter === 1 || $filter === 2) {
276 $where .= ' AND A.t3ver_count ' . ($filter === 1 ? '= 0' : '> 0');
277 }
278 if ($stage != -99) {
279 $where .= ' AND A.t3ver_stage=' . (int)$stage;
280 }
281 // Table B (online) must have PID >= 0 to signify being online.
282 $where .= ' AND B.pid>=0';
283 // ... and finally the join between the two tables.
284 $where .= ' AND A.t3ver_oid=B.uid';
285 $where .= BackendUtility::deleteClause($table, 'A');
286 $where .= BackendUtility::deleteClause($table, 'B');
287 // Select all records from this table in the database from the workspace
288 // This joins the online version with the offline version as tables A and B
289 // Order by UID, mostly to have a sorting in the backend overview module which doesn't "jump around" when swapping.
290 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'B.uid');
291 return is_array($res) ? $res : array();
292 }
293
294 /**
295 * Find all moved records at their new position.
296 *
297 * @param string $table
298 * @param string $pageList
299 * @param integer $wsid
300 * @param integer $filter
301 * @param integer $stage
302 * @return array
303 */
304 protected function getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage) {
305 // Aliases:
306 // A - moveTo placeholder
307 // B - online record
308 // C - moveFrom placeholder
309 $fields = 'A.pid AS wspid, B.uid AS t3ver_oid, C.uid AS uid, B.pid AS livepid';
310 $from = $table . ' A, ' . $table . ' B,' . $table . ' C';
311 $where = 'A.t3ver_state=' . new VersionState(VersionState::MOVE_PLACEHOLDER) . ' AND B.pid>0 AND B.t3ver_state='
312 . new VersionState(VersionState::DEFAULT_STATE) . ' AND B.t3ver_wsid=0 AND C.pid=-1 AND C.t3ver_state='
313 . new VersionState(VersionState::MOVE_POINTER);
314 if ($wsid > self::SELECT_ALL_WORKSPACES) {
315 $where .= ' AND A.t3ver_wsid=' . $wsid . ' AND C.t3ver_wsid=' . $wsid;
316 } elseif ($wsid === self::SELECT_ALL_WORKSPACES) {
317 $where .= ' AND A.t3ver_wsid!=0 AND C.t3ver_wsid!=0 ';
318 }
319 // lifecycle filter:
320 // 1 = select all drafts (never-published),
321 // 2 = select all published one or more times (archive/multiple)
322 if ($filter === 1 || $filter === 2) {
323 $where .= ' AND C.t3ver_count ' . ($filter === 1 ? '= 0' : '> 0');
324 }
325 if ($stage != -99) {
326 $where .= ' AND C.t3ver_stage=' . (int)$stage;
327 }
328 if ($pageList) {
329 $pidField = $table === 'pages' ? 'B.uid' : 'A.pid';
330 $pidConstraint = strstr($pageList, ',') ? ' IN (' . $pageList . ')' : '=' . $pageList;
331 $where .= ' AND ' . $pidField . $pidConstraint;
332 }
333 $where .= ' AND A.t3ver_move_id = B.uid AND B.uid = C.t3ver_oid';
334 $where .= BackendUtility::deleteClause($table, 'A');
335 $where .= BackendUtility::deleteClause($table, 'B');
336 $where .= BackendUtility::deleteClause($table, 'C');
337 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'A.uid');
338 return is_array($res) ? $res : array();
339 }
340
341 /**
342 * Find all page uids recursive starting from a specific page
343 *
344 * @param integer $pageId
345 * @param integer $wsid
346 * @param integer $recursionLevel
347 * @return string Comma sep. uid list
348 */
349 protected function getTreeUids($pageId, $wsid, $recursionLevel) {
350 // Reusing existing functionality with the drawback that
351 // mount points are not covered yet
352 $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
353 /** @var $searchObj \TYPO3\CMS\Core\Database\QueryView */
354 $searchObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\QueryView');
355 if ($pageId > 0) {
356 $pageList = $searchObj->getTreeList($pageId, $recursionLevel, 0, $perms_clause);
357 } else {
358 $mountPoints = $GLOBALS['BE_USER']->uc['pageTree_temporaryMountPoint'];
359 if (!is_array($mountPoints) || empty($mountPoints)) {
360 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
361 $mountPoints = array_unique($mountPoints);
362 }
363 $newList = array();
364 foreach ($mountPoints as $mountPoint) {
365 $newList[] = $searchObj->getTreeList($mountPoint, $recursionLevel, 0, $perms_clause);
366 }
367 $pageList = implode(',', $newList);
368 }
369 unset($searchObj);
370 if ((int)$GLOBALS['TCA']['pages']['ctrl']['versioningWS'] === 2 && $pageList) {
371 // Remove the "subbranch" if a page was moved away
372 $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');
373 $pageIds = \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $pageList, TRUE);
374 // move all pages away
375 $newList = array_diff($pageIds, array_keys($movedAwayPages));
376 // keep current page in the list
377 $newList[] = $pageId;
378 // move back in if still connected to the "remaining" pages
379 do {
380 $changed = FALSE;
381 foreach ($movedAwayPages as $uid => $rec) {
382 if (in_array($rec['pid'], $newList) && !in_array($uid, $newList)) {
383 $newList[] = $uid;
384 $changed = TRUE;
385 }
386 }
387 } while ($changed);
388 $pageList = implode(',', $newList);
389 // In case moving pages is enabled we need to replace all move-to pointer with their origin
390 $pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid, t3ver_move_id', 'pages', 'uid IN (' . $pageList . ')' . BackendUtility::deleteClause('pages'), '', 'uid', '', 'uid');
391 $newList = array();
392 $pageIds = \TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $pageList, TRUE);
393 if (!in_array($pageId, $pageIds)) {
394 $pageIds[] = $pageId;
395 }
396 foreach ($pageIds as $pageId) {
397 if ((int)$pages[$pageId]['t3ver_move_id'] > 0) {
398 $newList[] = (int)$pages[$pageId]['t3ver_move_id'];
399 } else {
400 $newList[] = $pageId;
401 }
402 }
403 $pageList = implode(',', $newList);
404 }
405 return $pageList;
406 }
407
408 /**
409 * Remove all records which are not permitted for the user
410 *
411 * @param array $recs
412 * @param string $table
413 * @return array
414 */
415 protected function filterPermittedElements($recs, $table) {
416 $checkField = $table == 'pages' ? 'uid' : 'wspid';
417 $permittedElements = array();
418 if (is_array($recs)) {
419 foreach ($recs as $rec) {
420 $page = BackendUtility::getRecord('pages', $rec[$checkField], 'uid,pid,perms_userid,perms_user,perms_groupid,perms_group,perms_everybody');
421 if ($GLOBALS['BE_USER']->doesUserHaveAccess($page, 1) && $this->isLanguageAccessibleForCurrentUser($table, $rec)) {
422 $permittedElements[] = $rec;
423 }
424 }
425 }
426 return $permittedElements;
427 }
428
429 /**
430 * Check current be users language access on given record.
431 *
432 * @param string $table Name of the table
433 * @param array $record Record row to be checked
434 * @return boolean
435 */
436 protected function isLanguageAccessibleForCurrentUser($table, array $record) {
437 $languageUid = 0;
438 if (BackendUtility::isTableLocalizable($table)) {
439 $languageUid = $record[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
440 } else {
441 return TRUE;
442 }
443 return $GLOBALS['BE_USER']->checkLanguageAccess($languageUid);
444 }
445
446 /**
447 * Trivial check to see if the user already migrated his workspaces
448 * to the new style (either manually or with the migrator scripts)
449 *
450 * @return boolean
451 */
452 static public function isOldStyleWorkspaceUsed() {
453 $oldStyleWorkspaceIsUsed = FALSE;
454 $cacheKey = 'workspace-oldstyleworkspace-notused';
455 $cacheResult = $GLOBALS['BE_USER']->getSessionData($cacheKey);
456 if (!$cacheResult) {
457 $where = 'adminusers != "" AND adminusers NOT LIKE "%be_users%" AND adminusers NOT LIKE "%be_groups%" AND deleted=0';
458 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'sys_workspace', $where);
459 $oldStyleWorkspaceIsUsed = $count > 0;
460 $GLOBALS['BE_USER']->setAndSaveSessionData($cacheKey, !$oldStyleWorkspaceIsUsed);
461 } else {
462 $oldStyleWorkspaceIsUsed = !$cacheResult;
463 }
464 return $oldStyleWorkspaceIsUsed;
465 }
466
467 /**
468 * Determine whether a specific page is new and not yet available in the LIVE workspace
469 *
470 * @static
471 * @param integer $id Primary key of the page to check
472 * @param integer $language Language for which to check the page
473 * @return boolean
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 integer $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 = \TYPO3\CMS\Core\Utility\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 integer $pageUid
553 * @param integer $workspaceUid
554 * @return boolean
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 integer $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 = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Version\\Hook\\PreviewHook');
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?' . \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl('', $linkParams);
588 }
589
590 /**
591 * Generates a workspace splitted preview link.
592 *
593 * @param integer $uid The ID of the record to be linked
594 * @param boolean $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 integer $uid
627 * @return integer
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 \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
646 }
647
648 }