[TASK] Remove unused ADMCMD_previewWS GET parameter
[Packages/TYPO3.CMS.git] / typo3 / sysext / workspaces / Classes / Hook / PreviewHook.php
1 <?php
2 namespace TYPO3\CMS\Workspaces\Hook;
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\FrontendBackendUserAuthentication;
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
20 use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
21 use TYPO3\CMS\Core\Type\Bitmask\Permission;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\MathUtility;
24
25 /**
26 * Hook for checking if the preview mode is activated
27 * preview mode = show a page of a workspace without having to log in
28 */
29 class PreviewHook implements \TYPO3\CMS\Core\SingletonInterface
30 {
31 /**
32 * the GET parameter to be used
33 *
34 * @var string
35 */
36 protected $previewKey = 'ADMCMD_prev';
37
38 /**
39 * instance of the \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController object
40 *
41 * @var \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
42 */
43 protected $tsfeObj;
44
45 /**
46 * preview configuration
47 *
48 * @var array
49 */
50 protected $previewConfiguration = false;
51
52 /**
53 * Defines whether to force read permissions on pages.
54 *
55 * @var bool
56 * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getPagePermsClause
57 */
58 protected $forceReadPermissions = false;
59
60 /**
61 * hook to check if the preview is activated
62 * right now, this hook is called at the end of "$TSFE->connectToDB"
63 *
64 * @param array $params (not needed right now)
65 * @param \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController $pObj
66 */
67 public function checkForPreview($params, &$pObj)
68 {
69 $this->tsfeObj = $pObj;
70 $this->previewConfiguration = $this->getPreviewConfiguration();
71 if (is_array($this->previewConfiguration)) {
72 // In case of a keyword-authenticated preview,
73 // re-initialize the TSFE object:
74 // because the GET variables are taken from the preview
75 // configuration
76 $this->tsfeObj = GeneralUtility::makeInstance(
77 \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::class,
78 null,
79 GeneralUtility::_GP('id'),
80 GeneralUtility::_GP('type'),
81 GeneralUtility::_GP('no_cache'),
82 GeneralUtility::_GP('cHash'),
83 null,
84 GeneralUtility::_GP('MP')
85 );
86 $GLOBALS['TSFE'] = $this->tsfeObj;
87 // Configuration after initialization of TSFE object.
88 // Basically this unsets the BE cookie if any and forces
89 // the BE user set according to the preview configuration.
90 // @previouslyknownas TSFE->ADMCMD_preview_postInit
91 // Clear cookies:
92 unset($_COOKIE['be_typo_user']);
93 }
94 }
95
96 /**
97 * hook after the regular BE user has been initialized
98 * if there is no BE user login, but a preview configuration
99 * the BE user of the preview configuration gets initialized
100 *
101 * @param array $params holding the BE_USER object
102 * @param \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController $pObj
103 */
104 public function initializePreviewUser(&$params, &$pObj)
105 {
106 // if there is a valid BE user, and the full workspace should be previewed, the workspacePreview option should be set
107 $workspaceUid = $this->previewConfiguration['fullWorkspace'];
108 $workspaceRecord = null;
109 if ((is_null($params['BE_USER']) || $params['BE_USER'] === false) && $this->previewConfiguration !== false && $this->previewConfiguration['BEUSER_uid'] > 0) {
110 // First initialize a temp user object and resolve usergroup information
111 /** @var FrontendBackendUserAuthentication $tempBackendUser */
112 $tempBackendUser = $this->createFrontendBackendUser();
113 $tempBackendUser->userTS_dontGetCached = 1;
114 $tempBackendUser->setBeUserByUid($this->previewConfiguration['BEUSER_uid']);
115 if ($tempBackendUser->user['uid']) {
116 $tempBackendUser->unpack_uc();
117 $tempBackendUser->setTemporaryWorkspace($workspaceUid);
118 $tempBackendUser->user['workspace_id'] = $workspaceUid;
119 $tempBackendUser->fetchGroupData();
120 // Handle degradation of admin users
121 if ($tempBackendUser->isAdmin()) {
122 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
123 ->getQueryBuilderForTable('sys_workspace');
124
125 $queryBuilder->getRestrictions()
126 ->removeAll()
127 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
128 ->add(GeneralUtility::makeInstance(RootLevelRestriction::class));
129
130 $workspaceRecord = $queryBuilder
131 ->select('uid', 'adminusers', 'reviewers', 'members', 'db_mountpoints')
132 ->from('sys_workspace')
133 ->where(
134 $queryBuilder->expr()->eq(
135 'uid',
136 $queryBuilder->createNamedParameter($workspaceUid, \PDO::PARAM_INT)
137 )
138 )
139 ->execute()
140 ->fetch();
141
142 // Either use configured workspace mount (of the workspace) or current page id
143 if (empty($tempBackendUser->groupData['webmounts'])) {
144 $tempBackendUser->groupData['webmounts'] = !empty($workspaceRecord['db_mountpoints']) ? $workspaceRecord['db_mountpoints'] : $pObj->id;
145 }
146 // Force add degraded admin user as member of this workspace
147 $workspaceRecord['members'] = 'be_users_' . $this->previewConfiguration['BEUSER_uid'];
148 // Force read permission for degraded admin user
149 $this->forceReadPermissions = true;
150 }
151 // Store only needed information in the real simulate backend
152 $BE_USER = $this->createFrontendBackendUser();
153 $BE_USER->userTS_dontGetCached = 1;
154 $BE_USER->user = $tempBackendUser->user;
155 $BE_USER->user['admin'] = 0;
156 $BE_USER->groupData['webmounts'] = $tempBackendUser->groupData['webmounts'];
157 $BE_USER->groupList = $tempBackendUser->groupList;
158 $BE_USER->userGroups = $tempBackendUser->userGroups;
159 $BE_USER->userGroupsUID = $tempBackendUser->userGroupsUID;
160 $pObj->beUserLogin = true;
161 } else {
162 $BE_USER = null;
163 $pObj->beUserLogin = false;
164 }
165 unset($tempBackendUser);
166 $params['BE_USER'] = $BE_USER;
167 }
168 if ($pObj->isBackendUserLoggedIn()
169 && is_object($params['BE_USER'])
170 && MathUtility::canBeInterpretedAsInteger($workspaceUid)
171 ) {
172 if ($workspaceUid == 0
173 || $workspaceUid >= -1
174 && $params['BE_USER']->checkWorkspace($workspaceRecord ?: $workspaceUid)
175 && $params['BE_USER']->isInWebMount($pObj->id)
176 ) {
177 // Check Access to workspace. Live (0) is OK to preview for all.
178 $pObj->workspacePreview = (int)$workspaceUid;
179 } else {
180 // No preview, will default to "Live" at the moment
181 $pObj->workspacePreview = -99;
182 }
183 }
184 }
185
186 /**
187 * Overrides the page permission clause in case an admin
188 * user has been degraded to a regular user without any user
189 * group assignments. This method is used as hook callback.
190 *
191 * @param array $parameters
192 * @return string
193 * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::getPagePermsClause
194 */
195 public function overridePagePermissionClause(array $parameters)
196 {
197 $clause = $parameters['currentClause'];
198 if ($parameters['perms'] & 1 && $this->forceReadPermissions) {
199 $clause = ' 1=1';
200 }
201 return $clause;
202 }
203
204 /**
205 * Overrides the row permission value in case an admin
206 * user has been degraded to a regular user without any user
207 * group assignments. This method is used as hook callback.
208 *
209 * @param array $parameters
210 * @return int
211 * @see \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::calcPerms
212 */
213 public function overridePermissionCalculation(array $parameters)
214 {
215 $permissions = $parameters['outputPermissions'];
216 if (!($permissions & Permission::PAGE_SHOW) && $this->forceReadPermissions) {
217 $permissions |= Permission::PAGE_SHOW;
218 }
219 return $permissions;
220 }
221
222 /**
223 * Looking for an ADMCMD_prev code, looks it up if found and returns configuration data.
224 * Background: From the backend a request to the frontend to show a page, possibly with
225 * workspace preview can be "recorded" and associated with a keyword.
226 * When the frontend is requested with this keyword the associated request parameters are
227 * restored from the database AND the backend user is loaded - only for that request.
228 * The main point is that a special URL valid for a limited time,
229 * eg. http://localhost/typo3site/index.php?ADMCMD_prev=035d9bf938bd23cb657735f68a8cedbf will
230 * open up for a preview that doesn't require login. Thus it's useful for sending in an email
231 * to someone without backend account.
232 * This can also be used to generate previews of hidden pages, start/endtimes, usergroups and
233 * those other settings from the Admin Panel - just not implemented yet.
234 *
235 * @throws \Exception
236 * @return array Preview configuration array from sys_preview record.
237 */
238 public function getPreviewConfiguration()
239 {
240 $inputCode = $this->getPreviewInputCode();
241 // If input code is available and shall not be ignored, look up the settings
242 if ($inputCode && $inputCode !== 'IGNORE') {
243 // "log out"
244 if ($inputCode === 'LOGOUT') {
245 setcookie($this->previewKey, '', 0, GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'));
246 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['workspacePreviewLogoutTemplate']) {
247 $templateFile = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['FE']['workspacePreviewLogoutTemplate'];
248 if (@is_file($templateFile)) {
249 $message = file_get_contents($templateFile);
250 } else {
251 $message = '<strong>ERROR!</strong><br>Template File "'
252 . $GLOBALS['TYPO3_CONF_VARS']['FE']['workspacePreviewLogoutTemplate']
253 . '" configured with $TYPO3_CONF_VARS["FE"]["workspacePreviewLogoutTemplate"] not found. Please contact webmaster about this problem.';
254 }
255 } else {
256 $message = 'You logged out from Workspace preview mode. Click this link to <a href="%1$s">go back to the website</a>';
257 }
258 $returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GET('returnUrl'));
259 die(sprintf($message, htmlspecialchars(preg_replace('/\\&?' . $this->previewKey . '=[[:alnum:]]+/', '', $returnUrl))));
260 }
261 // Look for keyword configuration record:
262 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
263 ->getQueryBuilderForTable('sys_preview');
264
265 $previewData = $queryBuilder
266 ->select('*')
267 ->from('sys_preview')
268 ->where(
269 $queryBuilder->expr()->eq(
270 'keyword',
271 $queryBuilder->createNamedParameter($inputCode, \PDO::PARAM_STR)
272 ),
273 $queryBuilder->expr()->gt(
274 'endtime',
275 $queryBuilder->createNamedParameter($GLOBALS['EXEC_TIME'], \PDO::PARAM_INT)
276 )
277 )
278 ->setMaxResults(1)
279 ->execute()
280 ->fetch();
281
282 // Get: Backend login status, Frontend login status
283 // - Make sure to remove fe/be cookies (temporarily);
284 // BE already done in ADMCMD_preview_postInit()
285 if (is_array($previewData)) {
286 if (empty(GeneralUtility::_POST())) {
287 // Unserialize configuration:
288 $previewConfig = unserialize($previewData['config']);
289 // For full workspace preview we only ADD a get variable
290 // to set the preview of the workspace - so all other Get
291 // vars are accepted. Hope this is not a security problem.
292 // Still posting is not allowed and even if a backend user
293 // get initialized it shouldn't lead to situations where
294 // users can use those credentials.
295 if ($previewConfig['fullWorkspace']) {
296 // If ADMCMD_prev is set the $inputCode value cannot come
297 // from a cookie and we set that cookie here. Next time it will
298 // be found from the cookie if ADMCMD_prev is not set again...
299 if (GeneralUtility::_GP($this->previewKey)) {
300 // Lifetime is 1 hour, does it matter much?
301 // Requires the user to click the link from their email again if it expires.
302 setcookie($this->previewKey, GeneralUtility::_GP($this->previewKey), 0, GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'), null, null, true);
303 }
304 return $previewConfig;
305 }
306 if (GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . 'index.php?' . $this->previewKey . '=' . $inputCode === GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
307 // Set GET variables
308 $GET_VARS = '';
309 parse_str($previewConfig['getVars'], $GET_VARS);
310 GeneralUtility::_GETset($GET_VARS);
311 // Return preview keyword configuration
312 return $previewConfig;
313 }
314 // This check is to prevent people from setting additional
315 // GET vars via realurl or other URL path based ways of passing parameters.
316 throw new \Exception(htmlspecialchars('Request URL did not match "'
317 . GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . 'index.php?' . $this->previewKey . '='
318 . $inputCode . '"', 1294585190));
319 }
320 throw new \Exception('POST requests are incompatible with keyword preview.', 1294585191);
321 }
322 throw new \Exception('ADMCMD command could not be executed! (No keyword configuration found)', 1294585192);
323 }
324 return false;
325 }
326
327 /**
328 * returns the input code value from the admin command variable
329 *
330 * @return string Input code
331 */
332 protected function getPreviewInputCode()
333 {
334 $inputCode = GeneralUtility::_GP($this->previewKey);
335 // If no inputcode and a cookie is set, load input code from cookie:
336 if (!$inputCode && $_COOKIE[$this->previewKey]) {
337 $inputCode = $_COOKIE[$this->previewKey];
338 }
339 return $inputCode;
340 }
341
342 /**
343 * Set preview keyword, eg:
344 * $previewUrl = GeneralUtility::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev='.$this->compilePreviewKeyword('id='.$pageId.'&L='.$language.'&ADMCMD_view=1&ADMCMD_editIcons=1&', $GLOBALS['BE_USER']->user['uid'], 120);
345 *
346 * @todo for sys_preview:
347 * - Add a comment which can be shown to previewer in frontend in some way (plus maybe ability to write back, take other action?)
348 * - Add possibility for the preview keyword to work in the backend as well: So it becomes a quick way to a certain action of sorts?
349 *
350 * @param string $getVarsStr Get variables to preview, eg. 'id=1150&L=0&ADMCMD_view=1&ADMCMD_editIcons=1'
351 * @param string $backendUserUid 32 byte MD5 hash keyword for the URL: "?ADMCMD_prev=[keyword]
352 * @param int $ttl Time-To-Live for keyword
353 * @param int|null $fullWorkspace Which workspace to preview. Workspace UID, -1 or >0. If set, the getVars is ignored in the frontend, so that string can be empty
354 * @return string Returns keyword to use in URL for ADMCMD_prev=
355 */
356 public function compilePreviewKeyword($getVarsStr, $backendUserUid, $ttl = 172800, $fullWorkspace = null)
357 {
358 $fieldData = [
359 'keyword' => md5(uniqid(microtime(), true)),
360 'tstamp' => $GLOBALS['EXEC_TIME'],
361 'endtime' => $GLOBALS['EXEC_TIME'] + $ttl,
362 'config' => serialize([
363 'fullWorkspace' => $fullWorkspace,
364 'getVars' => $getVarsStr,
365 'BEUSER_uid' => $backendUserUid
366 ])
367 ];
368 GeneralUtility::makeInstance(ConnectionPool::class)
369 ->getConnectionForTable('sys_preview')
370 ->insert(
371 'sys_preview',
372 $fieldData
373 );
374
375 return $fieldData['keyword'];
376 }
377
378 /**
379 * easy function to just return the number of hours
380 * a preview link is valid, based on the TSconfig value "options.workspaces.previewLinkTTLHours"
381 * by default, it's 48hs
382 *
383 * @return int The hours as a number
384 */
385 public function getPreviewLinkLifetime()
386 {
387 $ttlHours = (int)$GLOBALS['BE_USER']->getTSConfigVal('options.workspaces.previewLinkTTLHours');
388 return $ttlHours ? $ttlHours : 24 * 2;
389 }
390
391 /**
392 * @return FrontendBackendUserAuthentication
393 */
394 protected function createFrontendBackendUser()
395 {
396 return GeneralUtility::makeInstance(
397 FrontendBackendUserAuthentication::class
398 );
399 }
400 }