/** * Set defaults of auto configuration, mark installation as completed * * @return array<\TYPO3\CMS\Install\Status\StatusInterface> */ public function execute() { /** @var \TYPO3\CMS\Install\Configuration\FeatureManager $featureManager */ $featureManager = $this->objectManager->get('TYPO3\\CMS\\Install\\Configuration\\FeatureManager'); // Get best matching configuration presets $configurationValues = $featureManager->getBestMatchingConfigurationForAllFeatures(); // let the admin user redirect to the distributions page on first login if (isset($this->postValues['values']['loaddistributions'])) { // update the admin backend user to show the distribution management on login $adminUserFirstLogin = array('startModuleOnFirstLogin' => 'tools_ExtensionmanagerExtensionmanager->tx_extensionmanager_tools_extensionmanagerextensionmanager%5Baction%5D=distributions&tx_extensionmanager_tools_extensionmanagerextensionmanager%5Bcontroller%5D=List', 'ucSetByInstallTool' => '1'); $this->getDatabaseConnection()->exec_UPDATEquery('be_users', 'admin=1', array('uc' => serialize($adminUserFirstLogin))); } // Setting SYS/isInitialInstallationInProgress to FALSE marks this instance installation as complete $configurationValues['SYS/isInitialInstallationInProgress'] = FALSE; /** @var $configurationManager \TYPO3\CMS\Core\Configuration\ConfigurationManager */ $configurationManager = $this->objectManager->get('TYPO3\\CMS\\Core\\Configuration\\ConfigurationManager'); $configurationManager->setLocalConfigurationValuesByPathValuePairs($configurationValues); /** @var \TYPO3\CMS\Install\Service\SessionService $session */ $session = $this->objectManager->get('TYPO3\\CMS\\Install\\Service\\SessionService'); $session->destroySession(); /** @var $formProtection \TYPO3\CMS\Core\FormProtection\InstallToolFormProtection */ $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get('TYPO3\\CMS\\Core\\FormProtection\\InstallToolFormProtection'); $formProtection->clean(); if (!EnableFileService::isInstallToolEnableFilePermanent()) { EnableFileService::removeInstallToolEnableFile(); } \TYPO3\CMS\Core\Utility\HttpUtility::redirect('../../../index.php', \TYPO3\CMS\Core\Utility\HttpUtility::HTTP_STATUS_303); }
/** * @test */ public function logoffCleansFormProtection() { $formProtection = $this->getMock('TYPO3\\CMS\\Core\\FormProtection\\BackendFormProtection', array('clean')); $formProtection->expects($this->atLeastOnce())->method('clean'); \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::set('TYPO3\\CMS\\Core\\FormProtection\\BackendFormProtection', $formProtection); $this->fixture->logoff(); }
/** * Index action shows install tool / step installer or redirect to action to enable install tool * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function index(ServerRequestInterface $request, ResponseInterface $response) { /** @var EnableFileService $enableFileService */ $enableFileService = GeneralUtility::makeInstance(EnableFileService::class); /** @var AbstractFormProtection $formProtection */ $formProtection = FormProtectionFactory::get(); if ($enableFileService->checkInstallToolEnableFile()) { // Install tool is open and valid, redirect to it $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend'); } elseif ($request->getMethod() === 'POST' && $request->getParsedBody()['action'] === 'enableInstallTool') { // Request to open the install tool $installToolEnableToken = $request->getParsedBody()['installToolEnableToken']; if (!$formProtection->validateToken($installToolEnableToken, 'installTool')) { throw new \RuntimeException('Given form token was not valid', 1369161225); } $enableFileService->createInstallToolEnableFile(); // Install tool is open and valid, redirect to it $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend'); } else { // Show the "create enable install tool" button /** @var StandaloneView $view */ $view = GeneralUtility::makeInstance(StandaloneView::class); $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:install/Resources/Private/Templates/BackendModule/ShowEnableInstallToolButton.html')); $token = $formProtection->generateToken('installTool'); $view->assign('installToolEnableToken', $token); /** @var ModuleTemplate $moduleTemplate */ $moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class); $cssFile = 'EXT:install/Resources/Public/Css/BackendModule/ShowEnableInstallToolButton.css'; $cssFile = GeneralUtility::getFileAbsFileName($cssFile); $moduleTemplate->getPageRenderer()->addCssFile(PathUtility::getAbsoluteWebPath($cssFile)); $moduleTemplate->setContent($view->render()); $response->getBody()->write($moduleTemplate->renderContent()); } return $response; }
/** * Set defaults of auto configuration, mark installation as completed * * @return array<\TYPO3\CMS\Install\Status\StatusInterface> */ public function execute() { /** @var \TYPO3\CMS\Install\Configuration\FeatureManager $featureManager */ $featureManager = GeneralUtility::makeInstance(\TYPO3\CMS\Install\Configuration\FeatureManager::class); // Get best matching configuration presets $configurationValues = $featureManager->getBestMatchingConfigurationForAllFeatures(); // let the admin user redirect to the distributions page on first login switch ($this->postValues['values']['sitesetup']) { // Update the admin backend user to show the distribution management on login case 'loaddistribution': $adminUserFirstLogin = array('startModuleOnFirstLogin' => 'tools_ExtensionmanagerExtensionmanager->tx_extensionmanager_tools_extensionmanagerextensionmanager%5Baction%5D=distributions&tx_extensionmanager_tools_extensionmanagerextensionmanager%5Bcontroller%5D=List', 'ucSetByInstallTool' => '1'); $this->getDatabaseConnection()->exec_UPDATEquery('be_users', 'admin=1', array('uc' => serialize($adminUserFirstLogin))); break; // Create a page with UID 1 and PID1 and fluid_styled_content for page TS config, respect ownership // Create a page with UID 1 and PID1 and fluid_styled_content for page TS config, respect ownership case 'createsite': $this->getDatabaseConnection()->exec_INSERTquery('pages', array('pid' => 0, 'crdate' => time(), 'cruser_id' => 1, 'tstamp' => time(), 'title' => 'Home', 'doktype' => 1, 'is_siteroot' => 1, 'perms_userid' => 1, 'perms_groupid' => 1, 'perms_user' => 32, 'perms_group' => 32, 'perms_everybody' => 1)); $pageUid = $this->getDatabaseConnection()->sql_insert_id(); // add a root sys_template with fluid_styled_content and a default PAGE typoscript snippet $this->getDatabaseConnection()->exec_INSERTquery('sys_template', array('pid' => $pageUid, 'crdate' => time(), 'cruser_id' => 1, 'tstamp' => time(), 'title' => 'Main TypoScript Rendering', 'sitetitle' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'], 'root' => 1, 'clear' => 1, 'include_static_file' => 'EXT:fluid_styled_content/Configuration/TypoScript/Static/,EXT:fluid_styled_content/Configuration/TypoScript/Styling/', 'constants' => '', 'config' => 'page = PAGE page.10 = TEXT page.10.value ( <div style="width: 800px; margin: 15% auto;"> <div style="width: 300px;"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 42"><path d="M60.2 14.4v27h-3.8v-27h-6.7v-3.3h17.1v3.3h-6.6zm20.2 12.9v14h-3.9v-14l-7.7-16.2h4.1l5.7 12.2 5.7-12.2h3.9l-7.8 16.2zm19.5 2.6h-3.6v11.4h-3.8V11.1s3.7-.3 7.3-.3c6.6 0 8.5 4.1 8.5 9.4 0 6.5-2.3 9.7-8.4 9.7m.4-16c-2.4 0-4.1.3-4.1.3v12.6h4.1c2.4 0 4.1-1.6 4.1-6.3 0-4.4-1-6.6-4.1-6.6m21.5 27.7c-7.1 0-9-5.2-9-15.8 0-10.2 1.9-15.1 9-15.1s9 4.9 9 15.1c.1 10.6-1.8 15.8-9 15.8m0-27.7c-3.9 0-5.2 2.6-5.2 12.1 0 9.3 1.3 12.4 5.2 12.4 3.9 0 5.2-3.1 5.2-12.4 0-9.4-1.3-12.1-5.2-12.1m19.9 27.7c-2.1 0-5.3-.6-5.7-.7v-3.1c1 .2 3.7.7 5.6.7 2.2 0 3.6-1.9 3.6-5.2 0-3.9-.6-6-3.7-6H138V24h3.1c3.5 0 3.7-3.6 3.7-5.3 0-3.4-1.1-4.8-3.2-4.8-1.9 0-4.1.5-5.3.7v-3.2c.5-.1 3-.7 5.2-.7 4.4 0 7 1.9 7 8.3 0 2.9-1 5.5-3.3 6.3 2.6.2 3.8 3.1 3.8 7.3 0 6.6-2.5 9-7.3 9"/><path fill="#FF8700" d="M31.7 28.8c-.6.2-1.1.2-1.7.2-5.2 0-12.9-18.2-12.9-24.3 0-2.2.5-3 1.3-3.6C12 1.9 4.3 4.2 1.9 7.2 1.3 8 1 9.1 1 10.6c0 9.5 10.1 31 17.3 31 3.3 0 8.8-5.4 13.4-12.8M28.4.5c6.6 0 13.2 1.1 13.2 4.8 0 7.6-4.8 16.7-7.2 16.7-4.4 0-9.9-12.1-9.9-18.2C24.5 1 25.6.5 28.4.5"/></svg> </div> <h4 style="font-family: sans-serif;">Welcome to a default website made with <a href="https://typo3.org">TYPO3</a></h4> </div> ) page.100 < styles.content.get', 'description' => 'This is an Empty Site Package TypoScript template. For each website you need a TypoScript template on the main page of your website (on the top level). For better maintenance all TypoScript should be extracted into external files via <INCLUDE_TYPOSCRIPT: source="FILE:EXT:site_myproject/Configuration/TypoScript/setup.ts">.')); break; } // Setting SYS/isInitialInstallationInProgress to FALSE marks this instance installation as complete $configurationValues['SYS/isInitialInstallationInProgress'] = false; // Mark upgrade wizards as done $this->loadExtLocalconfDatabaseAndExtTables(); if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update'])) { $registry = GeneralUtility::makeInstance(Registry::class); foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/install']['update'] as $updateClassName) { $registry->set('installUpdate', $updateClassName, 1); } } /** @var $configurationManager \TYPO3\CMS\Core\Configuration\ConfigurationManager */ $configurationManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class); $configurationManager->setLocalConfigurationValuesByPathValuePairs($configurationValues); /** @var \TYPO3\CMS\Install\Service\SessionService $session */ $session = GeneralUtility::makeInstance(\TYPO3\CMS\Install\Service\SessionService::class); $session->destroySession(); /** @var $formProtection \TYPO3\CMS\Core\FormProtection\InstallToolFormProtection */ $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(\TYPO3\CMS\Core\FormProtection\InstallToolFormProtection::class); $formProtection->clean(); if (!EnableFileService::isInstallToolEnableFilePermanent()) { EnableFileService::removeInstallToolEnableFile(); } \TYPO3\CMS\Core\Utility\HttpUtility::redirect('../../../index.php', \TYPO3\CMS\Core\Utility\HttpUtility::HTTP_STATUS_303); }
/** * Performs the logout processing * * @return void */ public function logout() { // Logout written to log $GLOBALS['BE_USER']->writelog(255, 2, 0, 1, 'User %s logged out from TYPO3 Backend', array($GLOBALS['BE_USER']->user['username'])); \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->removeSessionTokenFromRegistry(); $GLOBALS['BE_USER']->logoff(); $redirect = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect')); $redirectUrl = $redirect ? $redirect : 'index.php'; \TYPO3\CMS\Core\Utility\HttpUtility::redirect($redirectUrl); }
/** * Crafts a link to edit a database record or create a new one * * @param string $table * @param integer $uid * @param string $returnUrl URL to return to * @return string The <a> tag * @see \TYPO3\CMS\Backend\Utility::editOnClick() */ public function render($table, $uid, $returnUrl = '') { if ($returnUrl == '') { $returnUrl = 'index.php?M=web_CadabraProductadministration&id=' . (int) \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('id') . '&moduleToken=' . \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->generateToken('moduleCall', 'web_CadabraProductadministration'); } $uri = \TYPO3\CMS\Backend\Utility\BackendUtility::getModuleUrl('record_edit', ['edit[' . $table . '][' . $uid . ']' => 'edit', 'returnUrl' => $returnUrl]); $this->tag->addAttribute('href', $uri); $this->tag->setContent($this->renderChildren()); $this->tag->forceClosingTag(true); return $this->tag->render(); }
/** * Initializes the controller before invoking an action method. * * @return void */ protected function initializeAction() { $this->pageRenderer->addCssFile(t3lib_extMgm::extRelPath('smoothmigration') . 'Resources/Public/StyleSheet/module.css'); $this->pageRenderer->addInlineLanguageLabelFile('EXT:smoothmigration/Resources/Private/Language/locallang.xml'); $this->pageRenderer->addJsLibrary('jquery', t3lib_extMgm::extRelPath('smoothmigration') . 'Resources/Public/JavaScript/jquery-1.10.1.min.js'); $this->pageRenderer->addJsLibrary('sprintf', t3lib_extMgm::extRelPath('smoothmigration') . 'Resources/Public/JavaScript/sprintf.min.js'); $this->pageRenderer->addJsFile(t3lib_extMgm::extRelPath('smoothmigration') . 'Resources/Public/JavaScript/General.js'); if (t3lib_div::int_from_ver(TYPO3_version) > 6001000) { $this->moduleToken = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->generateToken('moduleCall', 'tools_SmoothmigrationSmoothmigration'); } }
/** * Performs the logout processing * * @return void */ public function logout() { if (empty($this->getBackendUser()->user['username'])) { return; } // Logout written to log $this->getBackendUser()->writelog(255, 2, 0, 1, 'User %s logged out from TYPO3 Backend', array($this->getBackendUser()->user['username'])); /** @var \TYPO3\CMS\Core\FormProtection\BackendFormProtection $backendFormProtection */ $backendFormProtection = FormProtectionFactory::get(); $backendFormProtection->removeSessionTokenFromRegistry(); $this->getBackendUser()->logoff(); }
/** * Performs the logout processing * * @return void */ public function logout() { // Logout written to log $this->getBackendUser()->writelog(255, 2, 0, 1, 'User %s logged out from TYPO3 Backend', array($this->getBackendUser()->user['username'])); /** @var \TYPO3\CMS\Core\FormProtection\BackendFormProtection $backendFormProtection */ $backendFormProtection = FormProtectionFactory::get(); $backendFormProtection->removeSessionTokenFromRegistry(); $this->getBackendUser()->logoff(); $redirect = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect')); $redirectUrl = $redirect ? $redirect : 'index.php'; HttpUtility::redirect($redirectUrl); }
/** * @test */ public function logoffCleansFormProtectionIfBackendUserIsLoggedIn() { $formProtection = $this->getMock('TYPO3\\CMS\\Core\\FormProtection\\BackendFormProtection', array('clean'), array(), '', FALSE); $formProtection->expects($this->once())->method('clean'); \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::set('TYPO3\\CMS\\Core\\FormProtection\\BackendFormProtection', $formProtection); // logoff() call the static factory that has a dependency to a valid BE_USER object. Mock this away $GLOBALS['BE_USER'] = $this->getMock('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication', array(), array(), '', FALSE); $GLOBALS['BE_USER']->user = array('uid' => uniqid()); $GLOBALS['TYPO3_DB'] = $this->getMock('TYPO3\\CMS\\Core\\Database\\DatabaseConnection', array(), array(), '', FALSE); $subject = $this->getAccessibleMock('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication', array('dummy'), array(), '', FALSE); $subject->_set('db', $GLOBALS['TYPO3_DB']); $subject->logoff(); }
/** * Logout user if requested * * @return void */ protected function logoutIfRequested() { $action = $this->getAction(); if ($action === 'logout') { if (!EnableFileService::isInstallToolEnableFilePermanent()) { EnableFileService::removeInstallToolEnableFile(); } /** @var $formProtection \TYPO3\CMS\Core\FormProtection\InstallToolFormProtection */ $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get('TYPO3\\CMS\\Core\\FormProtection\\InstallToolFormProtection'); $formProtection->clean(); $this->session->destroySession(); $this->redirect(); } }
/** * Get base url of the report (use to generate links) * * @return string url */ public static function getBaseUrl() { // since 6.0> extbase is using by reports module $baseUrl = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . 'mod.php?'; $parameters = array(); $vars = \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('tx_reports_system_reportstxreportsm1'); $parameters[] = 'M=system_ReportsTxreportsm1'; $parameters[] = 'tx_reports_system_reportstxreportsm1%5Bextension%5D=additional_reports'; $parameters[] = 'tx_reports_system_reportstxreportsm1%5Breport%5D=' . $vars['report']; $parameters[] = 'tx_reports_system_reportstxreportsm1%5Baction%5D=detail'; $parameters[] = 'tx_reports_system_reportstxreportsm1%5Bcontroller%5D=Report'; $parameters[] = 'moduleToken=' . \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->generateToken('moduleCall', 'system_ReportsTxreportsm1'); return $baseUrl . implode('&', $parameters); }
/** * Handles the actual login process, more specifically it defines the response. * The login details were sent in as part of the ajax request and automatically logged in * the user inside the TYPO3 CMS bootstrap part of the ajax call. If that was successful, we have * a BE user and reset the timer and hide the login window. * If it was unsuccessful, we display that and show the login box again. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function loginAction(ServerRequestInterface $request, ResponseInterface $response) { if ($this->isAuthorizedBackendSession()) { $result = ['success' => true]; if ($this->hasLoginBeenProcessed()) { $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); $formProtection->setSessionTokenFromRegistry(); $formProtection->persistSessionToken(); } } else { $result = ['success' => false]; } $response->getBody()->write(json_encode(['login' => $result])); return $response; }
/** * Handles the actual login process, more specifically it defines the response. * The login details were sent in as part of the ajax request and automatically logged in * the user inside the init.php part of the ajax call. If that was successful, we have * a BE user and reset the timer and hide the login window. * If it was unsuccessful, we display that and show the login box again. * * @param array $parameters Parameters (not used) * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The calling parent AJAX object * @return void */ public function login(array $parameters, \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj) { if ($this->isAuthorizedBackendSession()) { $json = array('success' => TRUE); if ($this->hasLoginBeenProcessed()) { $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); $formProtection->setSessionTokenFromRegistry(); $formProtection->persistSessionToken(); } } else { $json = array('success' => FALSE); } $ajaxObj->addContent('login', $json); $ajaxObj->setContentFormat('json'); }
/** * Handles any AJAX request in the TYPO3 Backend * * @param ServerRequestInterface $request * @return NULL|\Psr\Http\Message\ResponseInterface */ public function handleRequest(ServerRequestInterface $request) { // First get the ajaxID $ajaxID = isset($request->getParsedBody()['ajaxID']) ? $request->getParsedBody()['ajaxID'] : $request->getQueryParams()['ajaxID']; // used for backwards-compatibility $GLOBALS['ajaxID'] = $ajaxID; $this->boot($ajaxID); // Finding the script path from the registry $ajaxRegistryEntry = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'][$ajaxID]) ? $GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'][$ajaxID] : NULL; $ajaxScript = NULL; $csrfTokenCheck = FALSE; if ($ajaxRegistryEntry !== NULL && is_array($ajaxRegistryEntry) && isset($ajaxRegistryEntry['callbackMethod'])) { $ajaxScript = $ajaxRegistryEntry['callbackMethod']; $csrfTokenCheck = $ajaxRegistryEntry['csrfTokenCheck']; } // Instantiating the AJAX object $ajaxObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Http\AjaxRequestHandler::class, $ajaxID); $ajaxParams = array(); // Evaluating the arguments and calling the AJAX method/function if (empty($ajaxID)) { $ajaxObj->setError('No valid ajaxID parameter given.'); } elseif (empty($ajaxScript)) { $ajaxObj->setError('No backend function registered for ajaxID "' . $ajaxID . '".'); } else { $success = TRUE; $tokenIsValid = TRUE; if ($csrfTokenCheck) { $ajaxToken = $request->getParsedBody()['ajaxToken'] ?: $request->getQueryParams()['ajaxToken']; $tokenIsValid = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->validateToken($ajaxToken, 'ajaxCall', $ajaxID); } if ($tokenIsValid) { // Cleanup global variable space unset($csrfTokenCheck, $ajaxRegistryEntry, $tokenIsValid, $success); $success = GeneralUtility::callUserFunction($ajaxScript, $ajaxParams, $ajaxObj, FALSE, TRUE); } else { $ajaxObj->setError('Invalid CSRF token detected for ajaxID "' . $ajaxID . '"!'); } if ($success === FALSE) { $ajaxObj->setError('Registered backend function for ajaxID "' . $ajaxID . '" was not found.'); } } // Outputting the content (and setting the X-JSON-Header) $ajaxObj->render(); return NULL; }
/** * Crafts a link to edit a database record or create a new one * * @param integer $pageId * @param string $returnUrl URL to return to * @param string $action * @param string $controller * @return string The <a> tag * @see \TYPO3\CMS\Backend\Utility::editOnClick() */ public function render($pageId, $returnUrl = '', $action = null, $controller = null) { if ($returnUrl == '') { $returnUrl = 'index.php?M=web_CadabraProductadministration&id=' . (int) \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('id') . '&moduleToken=' . \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->generateToken('moduleCall', 'web_CadabraProductadministration'); } $params = array('id' => $pageId, 'returnUrl' => $returnUrl); if ($action) { $params['tx_cadabra_web_cadabraproductadministration[action]'] = $action; } if ($controller) { $params['tx_cadabra_web_cadabraproductadministration[controller]'] = $controller; } \TYPO3\CMS\Backend\Utility\BackendUtility::openPageTree((int) $pageId, false); \TYPO3\CMS\Backend\Utility\BackendUtility::setUpdateSignal('updatePageTree'); $uri = \TYPO3\CMS\Backend\Utility\BackendUtility::getModuleUrl('web_CadabraProductadministration', $params); $this->tag->addAttribute('href', $uri); $this->tag->setContent($this->renderChildren()); $this->tag->forceClosingTag(true); return $this->tag->render(); }
/** * @test */ public function logoffCleansFormProtectionIfBackendUserIsLoggedIn() { /** @var ObjectProphecy|Connection $connection */ $connection = $this->prophesize(Connection::class); $connection->delete('be_sessions', Argument::cetera())->willReturn(1); /** @var ObjectProphecy|ConnectionPool $connectionPool */ $connectionPool = $this->prophesize(ConnectionPool::class); $connectionPool->getConnectionForTable(Argument::cetera())->willReturn($connection->reveal()); GeneralUtility::addInstance(ConnectionPool::class, $connectionPool->reveal()); /** @var ObjectProphecy|\TYPO3\CMS\Core\FormProtection\AbstractFormProtection $formProtection */ $formProtection = $this->prophesize(\TYPO3\CMS\Core\FormProtection\BackendFormProtection::class); $formProtection->clean()->shouldBeCalled(); \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::set('default', $formProtection->reveal()); // logoff() call the static factory that has a dependency to a valid BE_USER object. Mock this away $GLOBALS['BE_USER'] = $this->getMock(BackendUserAuthentication::class, array(), array(), '', false); $GLOBALS['BE_USER']->user = array('uid' => $this->getUniqueId()); $GLOBALS['TYPO3_DB'] = $this->getMock(\TYPO3\CMS\Core\Database\DatabaseConnection::class, array(), array(), '', false); $subject = $this->getAccessibleMock(BackendUserAuthentication::class, array('dummy'), array(), '', false); $subject->_set('db', $GLOBALS['TYPO3_DB']); $subject->logoff(); }
/** * Generates a token and returns a parameter for the URL * * @param string $formName Context of the token * @param string $tokenName The name of the token GET variable * @throws \InvalidArgumentException * @return string A URL GET variable including ampersand * @deprecated since TYPO3 7, will be removed in TYPO3 8. All backend modules and routes are secured by default now. If you need a url parameter with a token, use the form protection directly. */ public static function getUrlToken($formName = 'securityToken', $tokenName = 'formToken') { GeneralUtility::logDeprecatedFunction(); $formProtection = FormProtectionFactory::get(); return '&' . $tokenName . '=' . $formProtection->generateToken($formName); }
/** * @test */ public function setNotSetsInstanceForOtherType() { $instance = new \TYPO3\CMS\Core\Tests\Unit\FormProtection\Fixtures\FormProtectionTesting(); \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::set('TYPO3\\CMS\\Core\\FormProtection\\BackendFormProtection', $instance); $this->assertNotSame($instance, \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get('TYPO3\\CMS\\Core\\FormProtection\\InstallToolFormProtection')); }
* * The TYPO3 project - inspiring people to share! */ /** * Main form rendering script * By sending certain parameters to this script you can bring up a form * which allows the user to edit the content of one or more database records. * * @author Kasper Skårhøj <*****@*****.**> */ call_user_func(function () { $classLoader = (require __DIR__ . '/contrib/vendor/autoload.php'); (new \TYPO3\CMS\Backend\Http\Application($classLoader))->run(function () { \TYPO3\CMS\Backend\Utility\BackendUtility::lockRecords(); \TYPO3\CMS\Core\Utility\GeneralUtility::deprecationLog('The entry point to FormEngine was moved to an own module. Please use BackendUtility::getModuleUrl(\'record_edit\') to link to alt_doc.php. This script will be removed in TYPO3 CMS 8.'); /* @var $editDocumentController \TYPO3\CMS\Backend\Controller\EditDocumentController */ $editDocumentController = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Controller\EditDocumentController::class); // Preprocessing, storing data if submitted to $editDocumentController->preInit(); // Checks, if a save button has been clicked (or the doSave variable is sent) if ($editDocumentController->doProcessData()) { $formprotection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); if ($formprotection->validateToken(\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('formToken'), 'editRecord')) { $editDocumentController->processData(); } } $editDocumentController->init(); $editDocumentController->main(); $editDocumentController->printContent(); }); });
/** * Adds the ExtDirect code * * @param array $filterNamespaces Limit the output to defined namespaces. If empty, all namespaces are generated * @return void */ public function addExtDirectCode(array $filterNamespaces = array()) { if ($this->extDirectCodeAdded) { return; } $this->extDirectCodeAdded = TRUE; if (count($filterNamespaces) === 0) { $filterNamespaces = array('TYPO3'); } // For ExtDirect we need flash message support $this->addJsFile(GeneralUtility::resolveBackPath($this->backPath . 'sysext/backend/Resources/Public/JavaScript/flashmessages.js')); // Add language labels for ExtDirect if (TYPO3_MODE === 'FE') { $this->addInlineLanguageLabelArray(array('extDirect_timeoutHeader' => $GLOBALS['TSFE']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutHeader'), 'extDirect_timeoutMessage' => $GLOBALS['TSFE']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutMessage'))); } else { $this->addInlineLanguageLabelArray(array('extDirect_timeoutHeader' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutHeader'), 'extDirect_timeoutMessage' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutMessage'))); } $token = $api = ''; if (TYPO3_MODE === 'BE') { $formprotection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); $token = $formprotection->generateToken('extDirect'); } /** @var $extDirect \TYPO3\CMS\Core\ExtDirect\ExtDirectApi */ $extDirect = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\ExtDirect\\ExtDirectApi'); $api = $extDirect->getApiPhp($filterNamespaces); if ($api) { $this->addJsInlineCode('TYPO3ExtDirectAPI', $api, FALSE); } // Note: we need to iterate thru the object, because the addProvider method // does this only with multiple arguments $this->addExtOnReadyCode(' (function() { TYPO3.ExtDirectToken = "' . $token . '"; for (var api in Ext.app.ExtDirectAPI) { var provider = Ext.Direct.addProvider(Ext.app.ExtDirectAPI[api]); provider.on("beforecall", function(provider, transaction, meta) { if (transaction.data) { transaction.data[transaction.data.length] = TYPO3.ExtDirectToken; } else { transaction.data = [TYPO3.ExtDirectToken]; } }); provider.on("call", function(provider, transaction, meta) { if (transaction.isForm) { transaction.params.securityToken = TYPO3.ExtDirectToken; } }); } })(); var extDirectDebug = function(message, header, group) { var TYPO3ViewportInstance = null; if (top && top.TYPO3 && typeof top.TYPO3.Backend === "object") { TYPO3ViewportInstance = top.TYPO3.Backend; } else if (typeof TYPO3 === "object" && typeof TYPO3.Backend === "object") { TYPO3ViewportInstance = TYPO3.Backend; } if (TYPO3ViewportInstance !== null) { TYPO3ViewportInstance.DebugConsole.addTab(message, header, group); } else if (typeof console === "object") { console.log(message); } else { document.write(message); } }; Ext.Direct.on("exception", function(event) { if (event.code === Ext.Direct.exceptions.TRANSPORT && !event.where) { TYPO3.Flashmessage.display( TYPO3.Severity.error, TYPO3.l10n.localize("extDirect_timeoutHeader"), TYPO3.l10n.localize("extDirect_timeoutMessage"), 30 ); } else { var backtrace = ""; if (event.code === "parse") { extDirectDebug( "<p>" + event.xhr.responseText + "<\\/p>", event.type, "ExtDirect - Exception" ); } else if (event.code === "router") { TYPO3.Flashmessage.display( TYPO3.Severity.error, event.code, event.message, 30 ); } else if (event.where) { backtrace = "<p style=\\"margin-top: 20px;\\">" + "<strong>Backtrace:<\\/strong><br \\/>" + event.where.replace(/#/g, "<br \\/>#") + "<\\/p>"; extDirectDebug( "<p>" + event.message + "<\\/p>" + backtrace, event.method, "ExtDirect - Exception" ); } } }); Ext.Direct.on("event", function(event, provider) { if (typeof event.debug !== "undefined" && event.debug !== "") { extDirectDebug(event.debug, event.method, "ExtDirect - Debug"); } }); ', TRUE); }
/** * Set new encryption key * * @return void */ protected function setNewEncryptionKeyAndLogOut() { $newKey = \TYPO3\CMS\Core\Utility\GeneralUtility::getRandomHexString(96); /** @var \TYPO3\CMS\Core\Configuration\ConfigurationManager $configurationManager */ $configurationManager = $this->objectManager->get(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class); $configurationManager->setLocalConfigurationValueByPath('SYS/encryptionKey', $newKey); /** @var $formProtection \TYPO3\CMS\Core\FormProtection\InstallToolFormProtection */ $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(\TYPO3\CMS\Core\FormProtection\InstallToolFormProtection::class); $formProtection->clean(); /** @var \TYPO3\CMS\Install\Service\SessionService $session */ $session = $this->objectManager->get(\TYPO3\CMS\Install\Service\SessionService::class); $session->destroySession(); \TYPO3\CMS\Core\Utility\HttpUtility::redirect('Install.php?install[context]=' . $this->getContext()); }
/** * method that adds JS files within the page renderer * * @param array $parameters : An array of available parameters while adding JS to the page renderer * @param \TYPO3\CMS\Core\Page\PageRenderer $pageRenderer : The parent object that triggered this hook * * @return void */ protected function addJS($parameters, &$pageRenderer) { $formprotection = FormProtectionFactory::get(); if (count($parameters['jsFiles'])) { if (method_exists($GLOBALS['SOBE']->doc, 'issueCommand')) { /** @var \TYPO3\CMS\Backend\Clipboard\Clipboard $clipObj */ $clipObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Clipboard\\Clipboard'); // Start clipboard $clipObj->initializeClipboard(); $clipBoardHasContent = FALSE; if (isset($clipObj->clipData['normal']['el']) && strpos(key($clipObj->clipData['normal']['el']), 'tt_content') !== FALSE) { $pasteURL = str_replace('&', '&', $clipObj->pasteUrl('tt_content', 'DD_PASTE_UID', 0)); if (isset($clipObj->clipData['normal']['mode'])) { $clipBoardHasContent = 'copy'; } else { $clipBoardHasContent = 'move'; } } $moveParams = '&cmd[tt_content][DD_DRAG_UID][move]=DD_DROP_UID'; $moveURL = str_replace('&', '&', htmlspecialchars($GLOBALS['SOBE']->doc->issueCommand($moveParams, 1))); $copyParams = '&cmd[tt_content][DD_DRAG_UID][copy]=DD_DROP_UID&DDcopy=1'; $copyURL = str_replace('&', '&', htmlspecialchars($GLOBALS['SOBE']->doc->issueCommand($copyParams, 1))); // add JavaScript library $pageRenderer->addJsFile($GLOBALS['BACK_PATH'] . ExtensionManagementUtility::extRelPath('gridelements') . 'Resources/Public/Backend/JavaScript/dbNewContentElWizardFixDTM.js', $type = 'text/javascript', $compress = TRUE, $forceOnTop = FALSE, $allWrap = ''); // add JavaScript library $pageRenderer->addJsFile($GLOBALS['BACK_PATH'] . ExtensionManagementUtility::extRelPath('gridelements') . 'Resources/Public/Backend/JavaScript/GridElementsDD.js', $type = 'text/javascript', $compress = TRUE, $forceOnTop = FALSE, $allWrap = ''); // add JavaScript library $pageRenderer->addJsFile($GLOBALS['BACK_PATH'] . ExtensionManagementUtility::extRelPath('gridelements') . 'Resources/Public/Backend/JavaScript/GridElementsListView.js', $type = 'text/javascript', $compress = TRUE, $forceOnTop = FALSE, $allWrap = ''); if (!$pageRenderer->getCharSet()) { $pageRenderer->setCharSet($GLOBALS['LANG']->charSet ? $GLOBALS['LANG']->charSet : 'utf-8'); } if (is_array($clipObj->clipData['normal']['el'])) { $arrCBKeys = array_keys($clipObj->clipData['normal']['el']); $intFirstCBEl = str_replace('tt_content|', '', $arrCBKeys[0]); } // pull locallang_db.xml to JS side - only the tx_gridelements_js-prefixed keys $pageRenderer->addInlineLanguageLabelFile('EXT:gridelements/Resources/Private/Language/locallang_db.xml', 'tx_gridelements_js'); $pRaddExtOnReadyCode = ' TYPO3.l10n = { localize: function(langKey){ return TYPO3.lang[langKey]; } } '; $allowedCTypesAndGridTypesClassesByColPos = array(); $layoutSetup = GeneralUtility::callUserFunction('TYPO3\\CMS\\Backend\\View\\BackendLayoutView->getSelectedBackendLayout', intval(GeneralUtility::_GP('id')), $this); if (is_array($layoutSetup) && !empty($layoutSetup['__config']['backend_layout.']['rows.'])) { foreach ($layoutSetup['__config']['backend_layout.']['rows.'] as $rows) { foreach ($rows as $row) { if (!empty($layoutSetup['__config']['backend_layout.']['rows.'])) { foreach ($row as $col) { $classes = ''; if ($col['allowed']) { $allowed = explode(',', $col['allowed']); foreach ($allowed as $ctypes) { $ctypes = trim($ctypes); if ($ctypes === '*') { $classes = 't3-allow-all'; break; } else { $ctypes = explode(',', $ctypes); foreach ($ctypes as $ctype) { $classes .= 't3-allow-' . $ctype . ' '; } } } } else { $classes = 't3-allow-all'; } if ($col['allowedGridTypes']) { $allowedGridTypes = explode(',', $col['allowedGridTypes']); $classes .= 't3-allow-gridelements_pi1 '; foreach ($allowedGridTypes as $gridTypes) { $gridTypes = trim($gridTypes); if ($gridTypes !== '*') { $gridTypes = explode(',', $gridTypes); foreach ($gridTypes as $gridType) { $classes .= 't3-allow-gridtype-' . $gridType . ' '; } } } } else { if ($classes !== 't3-allow-all') { $classes .= 't3-allow-gridelements_pi1 '; } } $allowedCTypesAndGridTypesClassesByColPos[] = $col['colPos'] . ':' . trim($classes); } } } } } // add Ext.onReady() code from file $modTSconfig = BackendUtility::getModTSconfig((int) GeneralUtility::_GP('id'), 'mod.web_layout'); $pageRenderer->addExtOnReadyCode($pRaddExtOnReadyCode . "\n\t\t\t\t\t\ttop.pageColumnsAllowedCTypes = '" . join('|', $allowedCTypesAndGridTypesClassesByColPos) . "';\n\t\t\t\t\t\ttop.pasteURL = '" . $pasteURL . "';\n\t\t\t\t\t\ttop.moveURL = '" . $moveURL . "';\n\t\t\t\t\t\ttop.copyURL = '" . $copyURL . "';\n\t\t\t\t\t\ttop.pasteTpl = '" . str_replace('&redirect=1', '', str_replace('DDcopy=1', 'DDcopy=1&reference=DD_REFYN', $copyURL)) . "';\n\t\t\t\t\t\ttop.DDtceActionToken = '" . $formprotection->generateToken('tceAction') . "';\n\t\t\t\t\t\ttop.DDtoken = '" . $formprotection->generateToken('editRecord') . "';\n\t\t\t\t\t\ttop.DDpid = '" . (int) GeneralUtility::_GP('id') . "';\n\t\t\t\t\t\ttop.DDclipboardfilled = '" . ($clipBoardHasContent ? $clipBoardHasContent : 'false') . "';\n\t\t\t\t\t\ttop.pasteReferenceAllowed = '" . ($GLOBALS['BE_USER']->checkAuthMode('tt_content', 'CType', 11, 'explicitAllow') ? 'true' : 'false') . "';\n\t\t\t\t\t\ttop.newElementWizard = '" . ($modTSconfig['properties']['disableNewContentElementWizard'] ? 'false' : 'true') . "';\n\t\t\t\t\t\ttop.DDclipboardElId = '" . $intFirstCBEl . "';\n\t\t\t\t\t" . str_replace(array('top.skipDraggableDetails = 0;', 'insert_ext_baseurl_here', 'insert_server_time_here', 'top.geSprites = {};', "top.backPath = '';"), array($GLOBALS['BE_USER']->uc['dragAndDropHideNewElementWizardInfoOverlay'] ? 'top.skipDraggableDetails = true;' : 'top.skipDraggableDetails = false;', GeneralUtility::locationHeaderUrl('/' . ExtensionManagementUtility::siteRelPath('gridelements')), time() . '000', "top.geSprites = {\n\t\t\t\t\t\t\tcopyfrompage: '" . IconUtility::getSpriteIconClasses('extensions-gridelements-copyfrompage') . "',\n\t\t\t\t\t\t\t\tpastecopy: '" . IconUtility::getSpriteIconClasses('extensions-gridelements-pastecopy') . "',\n\t\t\t\t\t\t\t\tpasteref: '" . IconUtility::getSpriteIconClasses('extensions-gridelements-pasteref') . "'\n\t\t\t\t\t\t\t};", "top.backPath = '" . $GLOBALS['BACK_PATH'] . "';"), file_get_contents(ExtensionManagementUtility::extPath('gridelements') . 'Resources/Public/Backend/JavaScript/GridElementsDD_onReady.js')), TRUE); } } }
/** * Get a CSRF token * * @param bool $tokenOnly Set it to TRUE to get only the token, otherwise including the &moduleToken= as prefix * @return string */ protected function getToken($tokenOnly = false) { $token = FormProtectionFactory::get()->generateToken('moduleCall', 'web_NewsTxNewsM2'); if ($tokenOnly) { return $token; } else { return '&moduleToken=' . $token; } }
/** * Adds the ExtDirect code * * @param array $filterNamespaces Limit the output to defined namespaces. If empty, all namespaces are generated * @return void */ public function addExtDirectCode(array $filterNamespaces = []) { if ($this->extDirectCodeAdded) { return; } $this->extDirectCodeAdded = true; if (empty($filterNamespaces)) { $filterNamespaces = ['TYPO3']; } // Add language labels for ExtDirect $this->addInlineLanguageLabelArray(['extDirect_timeoutHeader' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:extDirect_timeoutHeader', 'extDirect_timeoutMessage' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:extDirect_timeoutMessage'], true); $token = $api = ''; if (TYPO3_MODE === 'BE') { $formprotection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); $token = $formprotection->generateToken('extDirect'); // Debugger Console strings $this->addInlineLanguageLabelFile('EXT:core/Resources/Private/Language/debugger.xlf'); $this->addInlineLanguageLabelFile('EXT:core/Resources/Private/Language/wizard.xlf'); } /** @var $extDirect \TYPO3\CMS\Core\ExtDirect\ExtDirectApi */ $extDirect = GeneralUtility::makeInstance(\TYPO3\CMS\Core\ExtDirect\ExtDirectApi::class); $api = $extDirect->getApiPhp($filterNamespaces); if ($api) { $this->addJsInlineCode('TYPO3ExtDirectAPI', $api, false); } // Note: we need to iterate thru the object, because the addProvider method // does this only with multiple arguments $this->addExtOnReadyCode(' (function() { TYPO3.ExtDirectToken = "' . $token . '"; for (var api in Ext.app.ExtDirectAPI) { var provider = Ext.Direct.addProvider(Ext.app.ExtDirectAPI[api]); provider.on("beforecall", function(provider, transaction, meta) { if (transaction.data) { transaction.data[transaction.data.length] = TYPO3.ExtDirectToken; } else { transaction.data = [TYPO3.ExtDirectToken]; } }); provider.on("call", function(provider, transaction, meta) { if (transaction.isForm) { transaction.params.securityToken = TYPO3.ExtDirectToken; } }); } })(); var extDirectDebug = function(message, header, group) { var DebugConsole = null; if (top && top.TYPO3 && typeof top.TYPO3.DebugConsole === "object") { DebugConsole = top.TYPO3.DebugConsole; } else if (typeof TYPO3 === "object" && typeof TYPO3.DebugConsole === "object") { DebugConsole = TYPO3.DebugConsole; } if (DebugConsole !== null) { DebugConsole.add(message, header, group); } else if (typeof console === "object") { console.log(message); } else { document.write(message); } }; Ext.Direct.on("exception", function(event) { if (event.code === Ext.Direct.exceptions.TRANSPORT && !event.where) { top.TYPO3.Notification.error( TYPO3.l10n.localize("extDirect_timeoutHeader"), TYPO3.l10n.localize("extDirect_timeoutMessage") ); } else { var backtrace = ""; if (event.code === "parse") { extDirectDebug( "<p>" + event.xhr.responseText + "<\\/p>", event.type, "ExtDirect - Exception" ); } else if (event.code === "router") { top.TYPO3.Notification.error( event.code, event.message ); } else if (event.where) { backtrace = "<p style=\\"margin-top: 20px;\\">" + "<strong>Backtrace:<\\/strong><br \\/>" + event.where.replace(/#/g, "<br \\/>#") + "<\\/p>"; extDirectDebug( "<p>" + event.message + "<\\/p>" + backtrace, event.method, "ExtDirect - Exception" ); } } }); Ext.Direct.on("event", function(event, provider) { if (typeof event.debug !== "undefined" && event.debug !== "") { extDirectDebug(event.debug, event.method, "ExtDirect - Debug"); } }); ', true); }
/** * Generates a token and returns a parameter for the URL * * @param string $formName Context of the token * @param string $tokenName The name of the token GET variable * @return string A URL GET variable including ampersand */ public static function getUrlToken($formName = 'securityToken', $tokenName = 'formToken') { $formprotection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); return '&' . $tokenName . '=' . $formprotection->generateToken($formName); }
/** * Checks if enabling install tool is requested and form token is correct * * @return bool */ protected function isValidEnableRequest() { return \TYPO3\CMS\Core\Utility\GeneralUtility::_POST('enableInstallTool') && \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->validateToken(\TYPO3\CMS\Core\Utility\GeneralUtility::_POST('formToken'), 'installToolEnableToken'); }
/** * Set formprotection property */ public function initializeAction() { $this->formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(); }
/** * Generate token for specific action * * @param string $action Action name * @return string Form protection token * @throws Exception */ protected function generateTokenForAction($action = NULL) { if (!$action) { $action = $this->getAction(); } if ($action === '') { throw new Exception('Token must have a valid action name', 1369326592); } /** @var $formProtection \TYPO3\CMS\Core\FormProtection\InstallToolFormProtection */ $formProtection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get(\TYPO3\CMS\Core\FormProtection\InstallToolFormProtection::class); return $formProtection->generateToken('installTool', $action); }
/** * Instantiate the form protection before a simulated user is initialized. */ public function __construct() { parent::__construct(); $this->formProtection = FormProtectionFactory::get(); }