2 /***************************************************************
5 * (c) 2010-2011 Workspaces Team (http://forge.typo3.org/projects/show/typo3v4-workspaces)
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
29 * @author Workspaces Team (http://forge.typo3.org/projects/show/typo3v4-workspaces)
33 class tx_Workspaces_Service_Workspaces
implements t3lib_Singleton
{
37 protected $pageCache = array();
39 const TABLE_WORKSPACE
= 'sys_workspace';
40 const SELECT_ALL_WORKSPACES
= -98;
41 const LIVE_WORKSPACE_ID
= 0;
44 * retrieves the available workspaces from the database and checks whether
45 * they're available to the current BE user
47 * @return array array of worspaces available to the current user
49 public function getAvailableWorkspaces() {
50 $availableWorkspaces = array();
52 // add default workspaces
53 if ($GLOBALS['BE_USER']->checkWorkspace(array('uid' => (string) self
::LIVE_WORKSPACE_ID
))) {
54 $availableWorkspaces[self
::LIVE_WORKSPACE_ID
] = self
::getWorkspaceTitle(self
::LIVE_WORKSPACE_ID
);
57 // add custom workspaces (selecting all, filtering by BE_USER check):
58 $customWorkspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid, title, adminusers, members', 'sys_workspace', 'pid = 0' . t3lib_BEfunc
::deleteClause('sys_workspace'), '', 'title');
59 if (count($customWorkspaces)) {
60 foreach ($customWorkspaces as $workspace) {
61 if ($GLOBALS['BE_USER']->checkWorkspace($workspace)) {
62 $availableWorkspaces[$workspace['uid']] = htmlspecialchars($workspace['title']);
67 return $availableWorkspaces;
71 * Gets the current workspace ID.
73 * @return integer The current workspace ID
75 public function getCurrentWorkspace() {
76 $workspaceId = $GLOBALS['BE_USER']->workspace
;
77 if ($GLOBALS['BE_USER']->isAdmin()) {
78 $activeId = $GLOBALS['BE_USER']->getSessionData('tx_workspace_activeWorkspace');
79 $workspaceId = $activeId !== NULL ?
$activeId : $workspaceId;
85 * Find the title for the requested workspace.
87 * @param integer $wsId
90 public static function getWorkspaceTitle($wsId) {
93 case self
::LIVE_WORKSPACE_ID
:
94 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:shortcut_onlineWS');
97 $labelField = $GLOBALS['TCA']['sys_workspace']['ctrl']['label'];
98 $wsRecord = t3lib_beFunc
::getRecord('sys_workspace', $wsId, 'uid,' . $labelField);
99 if (is_array($wsRecord)) {
100 $title = $wsRecord[$labelField];
104 if ($title === FALSE) {
105 throw new InvalidArgumentException('No such workspace defined');
113 * Building tcemain CMD-array for swapping all versions in a workspace.
115 * @param integer Real workspace ID, cannot be ONLINE (zero).
116 * @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.
117 * @param integer $pageId: ...
118 * @return array Command array for tcemain
120 public function getCmdArrayForPublishWS($wsid, $doSwap, $pageId = 0) {
122 $wsid = intval($wsid);
125 if ($wsid >= -1 && $wsid!==0) {
127 // Define stage to select:
130 $workspaceRec = t3lib_BEfunc
::getRecord('sys_workspace', $wsid);
131 if ($workspaceRec['publish_access'] & 1) {
132 $stage = Tx_Workspaces_Service_Stages
::STAGE_PUBLISH_ID
;
136 // Select all versions to swap:
137 $versions = $this->selectVersionsInWorkspace($wsid, 0, $stage, ($pageId ?
$pageId : -1), 0, 'tables_modify');
139 // Traverse the selection to build CMD array:
140 foreach ($versions as $table => $records) {
141 foreach ($records as $rec) {
142 // Build the cmd Array:
143 $cmd[$table][$rec['t3ver_oid']]['version'] = array('action' => 'swap', 'swapWith' => $rec['uid'], 'swapIntoWS' => $doSwap ?
1 : 0);
152 * Building tcemain CMD-array for releasing all versions in a workspace.
154 * @param integer Real workspace ID, cannot be ONLINE (zero).
155 * @param boolean Run Flush (TRUE) or ClearWSID (FALSE) command
156 * @param integer $pageId: ...
157 * @return array Command array for tcemain
159 public function getCmdArrayForFlushWS($wsid, $flush = TRUE, $pageId = 0) {
161 $wsid = intval($wsid);
164 if ($wsid >= -1 && $wsid!==0) {
165 // Define stage to select:
168 // Select all versions to swap:
169 $versions = $this->selectVersionsInWorkspace($wsid, 0, $stage, ($pageId ?
$pageId : -1), 0, 'tables_modify');
171 // Traverse the selection to build CMD array:
172 foreach ($versions as $table => $records) {
173 foreach ($records as $rec) {
174 // Build the cmd Array:
175 $cmd[$table][$rec['uid']]['version'] = array('action' => ($flush ?
'flush' : 'clearWSID'));
184 * Select all records from workspace pending for publishing
185 * Used from backend to display workspace overview
186 * User for auto-publishing for selecting versions for publication
188 * @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
189 * @param integer Lifecycle filter: 1 = select all drafts (never-published), 2 = select all published one or more times (archive/multiple), anything else selects all.
190 * @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"
191 * @param integer Page id: Live page for which to find versions in workspace!
192 * @param integer Recursion Level - select versions recursive - parameter is only relevant if $pageId != -1
193 * @param string How to collect records for "listing" or "modify" these tables. Support the permissions of each type of record (@see t3lib_userAuthGroup::check).
194 * @return array Array of all records uids etc. First key is table name, second key incremental integer. Records are associative arrays with uid, t3ver_oid and t3ver_swapmode fields. The pid of the online record is found as "livepid" the pid of the offline record is found in "wspid"
196 public function selectVersionsInWorkspace($wsid, $filter = 0, $stage = -99, $pageId = -1, $recursionLevel = 0, $selectionType = 'tables_select') {
198 $wsid = intval($wsid);
199 $filter = intval($filter);
202 // Contains either nothing or a list with live-uids
203 if ($pageId != -1 && $recursionLevel > 0) {
204 $pageList = $this->getTreeUids($pageId, $wsid, $recursionLevel);
205 } elseif ($pageId != -1) {
211 // Traversing all tables supporting versioning:
212 foreach ($GLOBALS['TCA'] as $table => $cfg) {
214 // we do not collect records from tables without permissions on them.
215 if (! $GLOBALS['BE_USER']->check($selectionType, $table)) {
219 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
221 $recs = $this->selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage);
222 if (intval($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) === 2) {
223 $moveRecs = $this->getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage);
224 $recs = array_merge($recs, $moveRecs);
226 $recs = $this->filterPermittedElements($recs, $table);
228 $output[$table] = $recs;
236 * Find all versionized elements except moved records.
238 * @param string $table
239 * @param string $pageList
240 * @param integer $filter
241 * @param integer $stage
244 protected function selectAllVersionsFromPages($table, $pageList, $wsid, $filter, $stage) {
246 $fields = 'A.uid, A.t3ver_oid,' . ($table==='pages' ?
' A.t3ver_swapmode,' : '') . 'B.pid AS wspid, B.pid AS livepid';
247 $from = $table . ' A,' . $table . ' B';
249 // Table A is the offline version and pid=-1 defines offline
250 $where = 'A.pid=-1 AND A.t3ver_state!=4';
252 $pidField = ($table==='pages' ?
'uid' : 'pid');
253 $pidConstraint = strstr($pageList, ',') ?
' IN (' . $pageList . ')' : '=' . $pageList;
254 $where .= ' AND B.' . $pidField . $pidConstraint;
258 * For "real" workspace numbers, select by that.
259 * If = -98, select all that are NOT online (zero).
260 * Anything else below -1 will not select on the wsid and therefore select all!
262 if ($wsid > self
::SELECT_ALL_WORKSPACES
) {
263 $where .= ' AND A.t3ver_wsid=' . $wsid;
264 } elseif ($wsid === self
::SELECT_ALL_WORKSPACES
) {
265 $where .= ' AND A.t3ver_wsid!=0';
270 * 1 = select all drafts (never-published),
271 * 2 = select all published one or more times (archive/multiple)
273 if ($filter===1 ||
$filter===2) {
274 $where .= ' AND A.t3ver_count ' . ($filter === 1 ?
'= 0' : '> 0');
278 $where .= ' AND A.t3ver_stage=' . intval($stage);
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 .= t3lib_BEfunc
::deleteClause($table, 'A');
286 $where .= t3lib_BEfunc
::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.
293 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'B.uid');
294 return is_array($res) ?
$res : array();
298 * Find all moved records at their new position.
300 * @param string $table
301 * @param string $pageList
302 * @param integer $wsid
305 protected function getMoveToPlaceHolderFromPages($table, $pageList, $wsid, $filter, $stage) {
309 * A - moveTo placeholder
311 * C - moveFrom placeholder
313 $fields = 'A.pid AS wspid, B.uid AS t3ver_oid, C.uid AS uid, B.pid AS livepid';
314 $from = $table . ' A, ' . $table . ' B,' . $table . ' C';
315 $where = 'A.t3ver_state=3 AND B.pid>0 AND B.t3ver_state=0 AND B.t3ver_wsid=0 AND C.pid=-1 AND C.t3ver_state=4';
317 if ($wsid > self
::SELECT_ALL_WORKSPACES
) {
318 $where .= ' AND A.t3ver_wsid=' . $wsid . ' AND C.t3ver_wsid=' . $wsid;
319 } elseif ($wsid === self
::SELECT_ALL_WORKSPACES
) {
320 $where .= ' AND A.t3ver_wsid!=0 AND C.t3ver_wsid!=0 ';
325 * 1 = select all drafts (never-published),
326 * 2 = select all published one or more times (archive/multiple)
328 if ($filter===1 ||
$filter===2) {
329 $where .= ' AND C.t3ver_count ' . ($filter === 1 ?
'= 0' : '> 0');
333 $where .= ' AND C.t3ver_stage=' . intval($stage);
337 $pidField = ($table==='pages' ?
'B.uid' : 'A.pid');
338 $pidConstraint = strstr($pageList, ',') ?
' IN (' . $pageList . ')' : '=' . $pageList;
339 $where .= ' AND ' . $pidField . $pidConstraint;
342 $where .= ' AND A.t3ver_move_id = B.uid AND B.uid = C.t3ver_oid';
343 $where .= t3lib_BEfunc
::deleteClause($table, 'A');
344 $where .= t3lib_BEfunc
::deleteClause($table, 'B');
345 $where .= t3lib_BEfunc
::deleteClause($table, 'C');
346 $res = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fields, $from, $where, '', 'A.uid');
348 return is_array($res) ?
$res : array();
353 * Find all page uids recursive starting from a specific page
355 * @param integer $pageId
356 * @param integer $wsid
357 * @param integer $recursionLevel
358 * @return string Comma sep. uid list
360 protected function getTreeUids($pageId, $wsid, $recursionLevel) {
362 * Reusing existing functionality with the drawback that
363 * mount points are not covered yet
365 $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
366 $searchObj = t3lib_div
::makeInstance('t3lib_fullsearch');
369 $pageList = $searchObj->getTreeList($pageId, $recursionLevel, 0, $perms_clause);
371 $mountPoints = $GLOBALS['BE_USER']->uc
['pageTree_temporaryMountPoint'];
372 if (!is_array($mountPoints) ||
empty($mountPoints)) {
373 $mountPoints = array_map('intval', $GLOBALS['BE_USER']->returnWebmounts());
374 $mountPoints = array_unique($mountPoints);
377 foreach($mountPoints as $mountPoint) {
378 $newList[] = $searchObj->getTreeList($mountPoint, $recursionLevel, 0, $perms_clause);
380 $pageList = implode(',', $newList);
384 if (intval($GLOBALS['TCA']['pages']['ctrl']['versioningWS']) === 2 && $pageList) {
385 // Remove the "subbranch" if a page was moved away
386 $movedAwayPages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
387 'uid, pid, t3ver_move_id',
389 't3ver_move_id IN (' . $pageList . ') AND t3ver_wsid=' . intval($wsid) . t3lib_BEfunc
::deleteClause('pages'),
395 $pageIds = t3lib_div
::intExplode(',', $pageList, TRUE);
397 // move all pages away
398 $newList = array_diff($pageIds, array_keys($movedAwayPages));
400 // keep current page in the list
401 $newList[] = $pageId;
402 // move back in if still connected to the "remaining" pages
405 foreach ($movedAwayPages as $uid => $rec) {
406 if (in_array($rec['pid'], $newList) && !in_array($uid, $newList)) {
412 $pageList = implode(',', $newList);
414 // In case moving pages is enabled we need to replace all move-to pointer with their origin
415 $pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
416 'uid, t3ver_move_id',
418 'uid IN (' . $pageList . ')' . t3lib_BEfunc
::deleteClause('pages'),
426 $pageIds = t3lib_div
::intExplode(',', $pageList, TRUE);
427 if (!in_array($pageId, $pageIds)) {
428 $pageIds[] = $pageId;
430 foreach ($pageIds as $pageId) {
431 if (intval($pages[$pageId]['t3ver_move_id']) > 0) {
432 $newList[] = intval($pages[$pageId]['t3ver_move_id']);
434 $newList[] = $pageId;
437 $pageList = implode(',', $newList);
443 * Remove all records which are not permitted for the user
446 * @param string $table
449 protected function filterPermittedElements($recs, $table) {
450 $checkField = ($table == 'pages') ?
'uid' : 'wspid';
451 $permittedElements = array();
452 if (is_array($recs)) {
453 foreach ($recs as $rec) {
454 $page = t3lib_beFunc
::getRecord('pages', $rec[$checkField], 'uid,pid,perms_userid,perms_user,perms_groupid,perms_group,perms_everybody');
455 if ($GLOBALS['BE_USER']->doesUserHaveAccess($page, 1)) {
456 $permittedElements[] = $rec;
460 return $permittedElements;
465 * Trivial check to see if the user already migrated his workspaces
466 * to the new style (either manually or with the migrator scripts)
470 public static function isOldStyleWorkspaceUsed() {
471 $oldStyleWorkspaceIsUsed = FALSE;
472 $cacheKey = 'workspace-oldstyleworkspace-notused';
473 $cacheResult = $GLOBALS['BE_USER']->getSessionData($cacheKey);
475 $where = 'adminusers != "" AND adminusers NOT LIKE "%be_users%" AND adminusers NOT LIKE "%be_groups%" AND deleted=0';
476 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'sys_workspace', $where);
477 $oldStyleWorkspaceIsUsed = $count > 0;
478 $GLOBALS['BE_USER']->setAndSaveSessionData($cacheKey, !$oldStyleWorkspaceIsUsed);
480 $oldStyleWorkspaceIsUsed = !$cacheResult;
482 return $oldStyleWorkspaceIsUsed;
486 * Determine whether a specific page is new and not yet available in the LIVE workspace
489 * @param $id Primary key of the page to check
490 * @param $language Language for which to check the page
493 public static function isNewPage($id, $language = 0) {
495 // If the language is not default, check state of overlay
497 $whereClause = 'pid = ' . $id;
498 $whereClause .= ' AND ' .$GLOBALS['TCA']['pages_language_overlay']['ctrl']['languageField'] . ' = ' . $language;
499 $whereClause .= ' AND t3ver_wsid = ' . $GLOBALS['BE_USER']->workspace
;
500 $whereClause .= t3lib_BEfunc
::deleteClause('pages_language_overlay');
501 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('t3ver_state', 'pages_language_overlay', $whereClause);
502 if (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
503 $isNewPage = (int) $row['t3ver_state'] === 1;
506 // Otherwise check state of page itself
508 $rec = t3lib_BEfunc
::getRecord('pages', $id, 't3ver_state');
509 if (is_array($rec)) {
510 $isNewPage = (int) $rec['t3ver_state'] === 1;
517 * Generates a view link for a page.
525 public static function viewSingleRecord($table, $uid, $record=NULL) {
527 if ($table == 'pages') {
528 $viewUrl = t3lib_BEfunc
::viewOnClick(t3lib_BEfunc
::getLiveVersionIdOfRecord('pages', $uid));
529 } elseif ($table == 'pages_language_overlay' ||
$table == 'tt_content') {
530 $elementRecord = is_array($record) ?
$record : t3lib_BEfunc
::getLiveVersionOfRecord($table, $uid);
531 $viewUrl = t3lib_BEfunc
::viewOnClick($elementRecord['pid']);
533 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['workspaces']['viewSingleRecord'])) {
534 $_params = array('table' => $table, 'uid' => $uid, 'record' => $record);
535 $_funcRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['workspaces']['viewSingleRecord'];
536 $viewUrl = t3lib_div
::callUserFunction($_funcRef, $_params, NULL);
543 * Determine whether this page for the current
546 * @param $workspaceUid
549 public function canCreatePreviewLink($pageUid, $workspaceUid) {
551 if ($pageUid > 0 && $workspaceUid > 0) {
552 $pageRecord = t3lib_BEfunc
::getRecord('pages', $pageUid);
553 t3lib_BEfunc
::workspaceOL('pages', $pageRecord, $workspaceUid);
554 if (!t3lib_div
::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['content_doktypes'], $pageRecord['doktype'])) {
564 * Generates a workspace preview link.
566 * @param integer $uid The ID of the record to be linked
567 * @return string the full domain including the protocol http:// or https://, but without the trailing '/'
569 public function generateWorkspacePreviewLink($uid) {
570 $previewObject = t3lib_div
::makeInstance('Tx_Version_Preview');
571 $timeToLiveHours = $previewObject->getPreviewLinkLifetime();
572 $previewKeyword = $previewObject->compilePreviewKeyword('', $GLOBALS['BE_USER']->user
['uid'], ($timeToLiveHours*3600), $this->getCurrentWorkspace());
575 'ADMCMD_prev' => $previewKeyword,
578 return t3lib_BEfunc
::getViewDomain($uid) . '/index.php?' . t3lib_div
::implodeArrayForUrl('', $linkParams);
582 * Generates a workspace splitted preview link.
584 * @param integer $uid The ID of the record to be linked
585 * @param boolean $addDomain Parameter to decide if domain should be added to the generated link, FALSE per default
586 * @return string the preview link without the trailing '/'
588 public function generateWorkspaceSplittedPreviewLink($uid, $addDomain = FALSE) {
589 // In case a $pageUid is submitted we need to make sure it points to a live-page
591 $uid = $this->getLivePageUid($uid);
594 $objectManager = t3lib_div
::makeInstance('Tx_Extbase_Object_ObjectManager');
595 /** @var $uriBuilder Tx_Extbase_MVC_Web_Routing_UriBuilder */
596 $uriBuilder = $objectManager->create('Tx_Extbase_MVC_Web_Routing_UriBuilder');
598 * This seems to be very harsh to set this directly to "/typo3 but the viewOnClick also
599 * has /index.php as fixed value here and dealing with the backPath is very error-prone
601 * @todo make sure this would work in local extension installation too
603 $backPath = '/' . TYPO3_mainDir
;
604 $redirect = $backPath . 'index.php?redirect_url=';
605 // @todo why do we need these additional params? the URIBuilder should add the controller, but he doesn't :(
606 $additionalParams = '&tx_workspaces_web_workspacesworkspaces%5Bcontroller%5D=Preview&M=web_WorkspacesWorkspaces&id=';
607 $viewScript = $backPath . $uriBuilder->setArguments(array('tx_workspaces_web_workspacesworkspaces' => array('previewWS' => $GLOBALS['BE_USER']->workspace
)))
608 ->uriFor('index', array(), 'Tx_Workspaces_Controller_PreviewController', 'workspaces', 'web_workspacesworkspaces') . $additionalParams;
610 if ($addDomain === TRUE) {
611 return t3lib_BEfunc
::getViewDomain($uid) . $redirect . urlencode($viewScript) . $uid;
618 * Find the Live-Uid for a given page,
619 * the results are cached at run-time to avoid too many database-queries
621 * @throws InvalidArgumentException
622 * @param integer $uid
625 public function getLivePageUid($uid) {
626 if (!isset($this->pageCache
[$uid])) {
627 $pageRecord = t3lib_beFunc
::getRecord('pages', $uid);
628 if (is_array($pageRecord)) {
629 $this->pageCache
[$uid] = ($pageRecord['t3ver_oid'] ?
$pageRecord['t3ver_oid'] : $uid);
631 throw new InvalidArgumentException('uid is supposed to point to an existing page - given value was:' . $uid, 1290628113);
635 return $this->pageCache
[$uid];
640 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE
]['XCLASS']['ext/workspaces/Classes/Service/Workspaces.php'])) {
641 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE
]['XCLASS']['ext/workspaces/Classes/Service/Workspaces.php']);