/** * Checks if the field value is not empty. * * @param AbstractField $field The field. */ protected function isValid($field) { $value = $field->getValue(); if ($value === null || $value === '' || is_array($value) && empty($value)) { $this->addError($this->translateErrorMessage('fields.validation.empty_value', Core::getExtensionKey()), 1431103424); } }
/** * Deletes a specific file from the processing folder. */ public function deleteFile() { $fileName = GeneralUtility::_GP('fileName'); $filePath = PATH_site . Core::getProcessedFolderPath() . $fileName; if (file_exists($filePath)) { unlink($filePath); } }
/** * Creates a backend user. * * See class documentation for more details. */ public function run() { $backendUserModelUid = $this->getProcessSettings('modelUid'); // Checking if something was given in "settings.modelUid". if (!MathUtility::canBeInterpretedAsInteger($backendUserModelUid)) { $this->addError('duplication_process.backend_user_creation.error.must_be_integer', 1432908303); return; } // Checking if the given backend user is valid. /** @var BackendUserRepository $backendUserRepository */ $backendUserRepository = $this->objectManager->get(BackendUserRepository::class); /** @var BackendUser $backendUser */ $backendUser = $backendUserRepository->findByUid($backendUserModelUid); if (!$backendUser) { $this->addError('duplication_process.backend_user_creation.error.wrong_uid', 1432908427, ['d' => $backendUserModelUid]); return; } // Creating a new instance of backend user, and copying the values from the model one. /** @var BackendUser $backendUserClone */ $backendUserClone = GeneralUtility::makeInstance(BackendUser::class); $backendUserClone->setPid($this->getDuplicatedPageUid()); $backendUserName = Core::getCleanedValueFromTCA('be_users', 'username', $backendUser->getUserName(), 0); $backendUserClone->setUserName($backendUserName); /** @var PersistenceManager $persistenceManager */ $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->add($backendUserClone); $persistenceManager->persistAll(); $this->addNotice('duplication_process.backend_user_creation.notice.success', 1432909010, ['s' => $backendUserClone->getUserName()]); // Managing base mount. $duplicatedPageUid = $this->getDuplicatedPageUid(); if ($duplicatedPageUid) { $this->fixDataBaseMountPointForBackendUser($backendUserClone, $this->getDuplicatedPageUid()); } // Managing file mount. $fileMountUid = $this->getProcessSettings('sysFileMountUid'); if ($fileMountUid) { /** @var FileMountRepository $fileMountRepository */ $fileMountRepository = $this->objectManager->get(FileMountRepository::class); /** @var FileMount $fileMount */ $fileMount = $fileMountRepository->findByUid($fileMountUid); if (!$fileMount) { $this->addWarning('duplication_process.backend_user_creation.warning.wrong_mount_point_uid', 1432909510, ['s' => $fileMountUid]); } else { $flag = $this->fixFileMountForBackendUser($backendUserClone, $fileMount); if ($flag) { $this->addNotice('duplication_process.backend_user_creation.notice.filemount_association_success', 1432909851, ['s' => $fileMount->getTitle()]); } } } // Checking if "settings.createdRecordName" can be used, use self::DEFAULT_CREATED_RECORD_NAME otherwise. $backendUserUid = $backendUserClone->getUid(); $createdRecordName = $this->getProcessSettings('createdRecordName'); $createdRecordName = !empty($createdRecordName) ? $createdRecordName : self::DEFAULT_CREATED_RECORD_NAME; $this->setDuplicationDataValue($createdRecordName, $backendUserUid); }
/** * Returns a select containing all the Backend users. * * @param array $options Current options of the field. * @return string The HTML code containing the <select> tag with filled options. */ public function getBackendUsersSelect($options) { $html = '<select name="' . $options['fieldName'] . '">'; $backendUserGroups = GeneralUtility::array_merge([0 => ['uid' => -1, 'title' => '']], Core::getDatabase()->exec_SELECTgetRows('uid, username', 'be_users', '1=1')); foreach ($backendUserGroups as $group) { $selected = $group['uid'] == $options['fieldValue'] ? ' selected="selected"' : ''; $uidLabel = $group['uid'] != -1 ? ' [' . $group['uid'] . ']' : ''; $html .= '<option value="' . $group['uid'] . '"' . $selected . '>' . $group['username'] . $uidLabel . '</option>'; } $html .= '</select>'; return $html; }
/** * Returns a cache instance. * * @param string $name Name of the cache. Must be one of the class' constants. * @return FrontendInterface */ public static function getCacheInstance($name) { if (!self::$cacheManager) { self::$cacheManager = Core::getObjectManager()->get(TYPO3CacheManager::class); } $cacheInstance = null; switch ($name) { case self::CACHE_MAIN: case self::CACHE_PROCESSED: $cacheInstance = self::$cacheManager->getCache($name); } return $cacheInstance; }
/** * Ajax implementation of the function "validateField". Will display the * result encoded in JSON. * * @param array $arguments Parameters. * @return string JSON encoded result. */ public function ajaxValidateField($arguments) { // @todo : Exception ? if (!isset($arguments['fieldName']) || !isset($arguments['value']) || !isset($arguments['pageUid'])) { return ''; } // @todo : check pageUid $field = Fields\Field::getField($arguments['fieldName'], $arguments['pageUid']); $field->setValue($arguments['value']); $validation = $this->validateField($field); $validationResult = Core::convertValidationResultToArray($validation['validationResult']); $validation['validationResult'] = $validationResult; return $validation; }
/** * Gets an ordered list of the backend layouts. * * @return array The backend layouts in an array. Empty array if none was found. */ public static function getBackendLayoutsList() { /** @var \TYPO3\CMS\Backend\View\BackendLayoutView $backendLayoutView */ $backendLayoutView = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\View\\BackendLayoutView'); $items = array(); $params = array('table' => 'pages', 'field' => 'backend_layout', 'row' => BackendUtility::getRecord('pages', 1, '*'), 'items' => &$items); $backendLayoutView->addBackendLayoutItems($params); $result = array(); foreach ($GLOBALS['TCA']['pages']['columns']['backend_layout']['config']['items'] as $item) { $result[$item[1]] = Core::translate($item[0]); } foreach ($params['items'] as $item) { $result[$item[1]] = $item[0]; } return $result; }
/** * Will set the page linked to the "Save" records (based on their attribute * "rootPageUid"). * * @param array|Save $records An array containing "Save" models, or a single "Save" model. * @return array|null Returns the array sent with modified "page" attribute, or null if the parameter was empty. */ public function attachPage($records) { if (!$records) { return null; } $objectManager = Core::getObjectManager(); /** @var PagesRepository $pagesRepository */ $pagesRepository = $objectManager->get(PagesRepository::class); if (is_array($records) || $records instanceof QueryResult) { /** @var Save[] $records */ foreach ($records as $key => $record) { $page = $pagesRepository->findByUidWithoutCondition($record->getRootPageUid()); $records[$key]->setPage($page[0]); } } elseif ($records instanceof Save) { /** @var Pages $page */ $page = $pagesRepository->findByUidWithoutCondition($records->getRootPageUid()); $records->setPage($page[0]); } return $records; }
/** * When a site is being saved, this function will save all the fields values * in the DataBase, for further usage. */ public function run() { $objectManager = Core::getObjectManager(); /** @var \Romm\SiteFactory\Domain\Repository\SaveRepository $saveRepository */ $saveRepository = $objectManager->get('Romm\\SiteFactory\\Domain\\Repository\\SaveRepository'); $saveObject = $saveRepository->findOneByRootPageUid($this->getDuplicatedPageUid()); $newObject = false; if (empty($saveObject)) { $newObject = true; /** @var \Romm\SiteFactory\Domain\Model\Save $saveObject */ $saveObject = GeneralUtility::makeInstance('Romm\\SiteFactory\\Domain\\Model\\Save'); $saveObject->setRootPageUid($this->getDuplicatedPageUid()); } $configuration = $this->getDuplicationData(); ArrayUtility::mergeRecursiveWithOverrule($configuration, array('fieldsValues' => $this->getFieldsValues())); $saveObject->setConfiguration(json_encode($configuration)); if ($newObject) { $saveRepository->add($saveObject); } else { $saveRepository->update($saveObject); } }
/** * @param string $siteTitle The name of the new site, will be used for both the file mount's name and the directory created in fileadmin. * @return null|int Returns null if the file mount could not be created, or the uid of the last inserted "sys_filemounts" record. */ private function manageSysFileMounts($siteTitle) { $pathFirstPart = $this->getProcessSettings('path') ? $this->getProcessSettings('path') : self::$defaultPath; $pathFirstPart = substr($pathFirstPart, -1, 1) == '/' ? $pathFirstPart : $pathFirstPart . '/'; $folderPath = $pathFirstPart . GeneralUtility::strtolower($siteTitle); $folderPath = Core::formatAccentsInString($folderPath); $folderPath = preg_replace('/\\s+/', ' ', $folderPath); $folderPath = preg_replace('/\\s/', '_', $folderPath); $folderPath = '/' . $folderPath . '/'; // @todo: manage warning when overriding a folder? GeneralUtility::mkdir_deep(PATH_site . 'fileadmin' . $folderPath); /** @var FileMount $fileMount */ $fileMount = GeneralUtility::makeInstance(FileMount::class); $fileMount->setPath($folderPath); $fileMount->setTitle($siteTitle); $fileMount->setIsAbsolutePath(true); // @todo: seems it must be on pid=0, check? $fileMount->setPid(0); /** @var PersistenceManager $persistenceManager */ $persistenceManager = $this->objectManager->get(PersistenceManager::class); $persistenceManager->add($fileMount); $persistenceManager->persistAll(); return $fileMount->getUid(); }
/** * @todo: rewrite function doc * @param string $cacheToken The token of the cache file to get the current state of the duplication. * @param string $index The index of the process which will be executed (e.g. "pagesDuplication" or "treeUidAssociation"). * @param bool $checkAjax If true, will call the function "checkAjaxCall" of the current process class. * @return array The result of the function, may contain these keys : * - "success": "False" if error(s) occurred, "true" otherwise. * - "result": The result of the execution function. Contains useful data for further duplication process steps. * - "errorMessage": If error(s) occurred, will contain an error message. If the current user is admin, it will get a detailed message. */ private function processDuplication($cacheToken, $index, $checkAjax = false) { // Getting configuration in cache file. $cache = CacheManager::getCacheInstance(CacheManager::CACHE_PROCESSED); $cacheData = $cache->get($cacheToken); $cacheData = json_decode($cacheData, true); /** @var Result $result */ $result = $this->objectManager->get(Result::class); try { if (isset($cacheData['duplicationData']['modelPageUid']) && MathUtility::canBeInterpretedAsInteger($cacheData['duplicationData']['modelPageUid']) && $cacheData['duplicationData']['modelPageUid'] > 0) { $duplicationConfiguration = AbstractDuplicationProcess::getCleanedDuplicationConfiguration($cacheData['duplicationData']['modelPageUid']); if (isset($duplicationConfiguration[$index])) { if (isset($duplicationConfiguration[$index]['class'])) { $class = $duplicationConfiguration[$index]['class']; $settings = array_key_exists('settings', $duplicationConfiguration[$index]) ? is_array($duplicationConfiguration[$index]['settings']) ? $duplicationConfiguration[$index]['settings'] : [] : []; // Calling the function of the current process step. /** @var AbstractDuplicationProcess $class */ $class = GeneralUtility::makeInstance($class, $cacheData['duplicationData'], $settings, $cacheData['fieldsValues']); if ($class instanceof AbstractDuplicationProcess) { // @todo : else // if (!$checkAjax || ($checkAjax && $class->checkAjaxCall())) { $class->run(); $fieldsValues = $class->getFieldsValues(); $result->merge($class->getResult()); // Saving modified data in cache. $configuration = ['duplicationData' => $class->getDuplicationData(), 'fieldsValues' => $fieldsValues]; $cache->set($cacheToken, json_encode($configuration)); // } } else { throw new \Exception('The class "' . $class . '" must extend "' . AbstractDuplicationProcess::class . '".', 1422887215); } } else { throw new \Exception('The class is not set for the duplication configuration named "' . $index . '".', 1422885526); } } else { throw new \Exception('Trying to get the duplication configuration named "' . $index . '" but it does not exist.', 1422885438); } } else { throw new \Exception('The duplication data must contain a valid index for "modelPageUid".', 1422885697); } } catch (\Exception $exception) { /** @var BackendUserAuthentication $backendUser */ $backendUser = $GLOBALS['BE_USER']; // Setting up error message. If the user is admin, it gets a detailed message. if ($backendUser->isAdmin()) { $errorMessage = Core::translate('duplication_process.process_error_detailed') . ' ' . $exception->getMessage(); } else { $errorMessage = Core::translate('duplication_process.process_error_single'); } $result->addError(new Error($errorMessage, 1431985617)); } return Core::convertValidationResultToArray($result); }
/** * Adds a message (error, warning or notice) to the process result. * * @param string $type The type of the message. Can only be one of the following: error, warning or notice. * @param string $message The message, can be a locallang reference. * @param int $code A unique code for this notice. * @param array $arguments Array of arguments to be replaced in the message. * @param string $title The title for the message. */ private function addMessage($type, $message, $code, array $arguments = array(), $title = '') { if (!in_array(strtolower($type), array('error', 'warning', 'notice'))) { return; } $function = 'add' . ucfirst($type); $type = 'TYPO3\\CMS\\Extbase\\Error\\' . ucfirst($type); $this->result->{$function}(new $type(Core::translate($message), $code, $arguments, $title)); }
/** * Checks if the field value matches a hexadecimal value. * * @param AbstractField $field The field. */ protected function isValid($field) { if (!preg_match('/^#[0123456789ABCDEF]{6}$/', strtoupper($field->getValue()))) { $this->addError($this->translateErrorMessage('fields.validation.wrong_hexadecimal_value', Core::getExtensionKey(), ['s' => $field->getValue()]), 1430127326); } }
/** * Will set the page linked to the "Save" records (based on their attribute * "rootPageUid"). * * @param array|Save $records An array containing "Save" models, or a single "Save" model. * @return array|null Returns the array sent with modified "page" attribute, or null if the parameter was empty. */ public function attachPage($records) { if (!$records) { return NULL; } $objectManager = Core::getObjectManager(); /** @var \Romm\SiteFactory\Domain\Repository\PagesRepository $pagesRepository */ $pagesRepository = $objectManager->get('Romm\\SiteFactory\\Domain\\Repository\\PagesRepository'); if (is_array($records) || $records instanceof QueryResult) { /** @var \Romm\SiteFactory\Domain\Model\Save[] $records */ foreach ($records as $key => $record) { $page = $pagesRepository->findByUidWithoutCondition($record->getRootPageUid()); $records[$key]->setPage($page[0]); } } elseif ($records instanceof Save) { /** @var \Romm\SiteFactory\Domain\Model\Pages $page */ $page = $pagesRepository->findByUidWithoutCondition($records->getRootPageUid()); $records->setPage($page[0]); } return $records; }
/** * Checks if the select field current value is in its available options. If * not, an error is thrown. * * @param \Romm\SiteFactory\Form\Fields\SelectField $field The select field. */ protected function isValid($field) { if (!array_key_exists($field->getValue(), $field->getOptions())) { $this->addError($this->translateErrorMessage('fields.validation.select.wrong_option_value', Core::getExtensionKey(), array('s' => $field->getValue())), 1430127401); } }
/** * Checks if the field value matches a domain name value. * * @param \Romm\SiteFactory\Form\Fields\AbstractField $field The field. */ protected function isValid($field) { if (filter_var($field->getValue(), FILTER_VALIDATE_INT) === FALSE) { $this->addError($this->translateErrorMessage('fields.validation.integer_value', Core::getExtensionKey()), 1431105694); } }
/** * Returns the sys_template record marked with "site_factory_template" for * the given page. * * @param int $pageUid The page uid. * @return array|false Array of result, false if no template was found. */ private static function getPageTemplate($pageUid) { /** @var ExtendedTemplateService $templateService */ $templateService = Core::getObjectManager()->get(ExtendedTemplateService::class); $template = $templateService->ext_getFirstTemplate($pageUid); return $template; }
/** * Checks if the field value matches a Facebook URL. * * @param AbstractField $field The field. */ protected function isValid($field) { if (!preg_match('/^$|^(https:\\/\\/)?(www.)?facebook.com\\/.+$/', $field->getValue())) { $this->addError($this->translateErrorMessage('fields.validation.facebook_url_value', Core::getExtensionKey()), 1431104928); } }
/** * This action is called when a form has been submitted to create a new * site. * * It will get all the information needed to duplicate the model site, and * further: management of uploaded files, constants management, etc. */ public function processCopyAction() { $cacheToken = $this->request->getArgument('duplicationToken'); $cache = CacheManager::getCacheInstance(CacheManager::CACHE_PROCESSED); $cacheData = $cache->get($cacheToken); // @todo: manage wrong token or wrong cacheData $cacheData = json_decode($cacheData, true); // Check if the process is a modification of an already duplicated site. $modifySite = null; if ($this->request->hasArgument('modifySite') && Core::checkUidIsSavedSite($this->request->getArgument('modifySite'))) { $modifySite = $this->request->getArgument('modifySite'); $cacheData['duplicationData']['modelPageUid'] = $cacheData['fieldsValues']['modelSite']; $cacheData['duplicationData']['modifySite'] = $modifySite; $cacheData['duplicationData']['duplicatedPageUid'] = $modifySite; /** @var Save $savedSite */ $savedSite = $this->saveRepository->findLastByRootPageUid($modifySite); $cacheData['savedSite'] = $savedSite->getConfiguration(); } else { $cacheData['duplicationData']['modelPageUid'] = $cacheData['fieldsValues']['modelSite']; $cacheData['duplicationData']['copyDestination'] = Core::getExtensionConfiguration('copyDestination'); } // Saving modified data in cache. $cache->set($cacheToken, json_encode($cacheData)); $this->view->assign('duplicationToken', $cacheToken); $siteModificationToken = $modifySite ? true : false; $duplicationConfiguration = AbstractDuplicationProcess::getCleanedDuplicationConfiguration($cacheData['duplicationData']['modelPageUid'], $siteModificationToken); $this->view->assign('duplicationConfiguration', $duplicationConfiguration); $this->view->assign('duplicationConfigurationJSON', addslashes(json_encode(array_keys($duplicationConfiguration)))); }
/** * Returns the sys_template record marked with "site_factory_template" for * the given page. * * @param int $pageUid The page uid. * @return array|false Array of result, false if no template was found. */ private static function getPageTemplate($pageUid) { /** @var \TYPO3\CMS\Core\TypoScript\ExtendedTemplateService $templateService */ $templateService = Core::getObjectManager()->get('TYPO3\\CMS\\Core\\TypoScript\\ExtendedTemplateService'); $template = $templateService->ext_getFirstTemplate($pageUid); return $template; }
/** * Is called before any action. */ public function initializeAction() { Core::loadJquery(); }
/** * Generates a TemplateService from a given page uid, by running through * the pages root line. * * @param int|null|bool $pageUid The uid of the page you want the TypoScript configuration from. If "null" is given, only the static configuration is returned. * @return TemplateService */ private static function generateConfiguration($pageUid = null) { if (!array_key_exists($pageUid, self::$pageConfiguration)) { $objectManager = Core::getObjectManager(); $rootLine = null; if ($pageUid && MathUtility::canBeInterpretedAsInteger($pageUid) && $pageUid > 0) { /** @var PageRepository $pageRepository */ $pageRepository = $objectManager->get(PageRepository::class); $rootLine = $pageRepository->getRootLine($pageUid); } /** @var ExtendedTemplateService $templateService */ $templateService = $objectManager->get(ExtendedTemplateService::class); $templateService->tt_track = 0; $templateService->init(); if ($rootLine !== null) { $templateService->runThroughTemplates($rootLine); } $templateService->generateConfig(); $templateService->generateConfig_constants(); self::$pageConfiguration[$pageUid] = $templateService; } return self::$pageConfiguration[$pageUid]; }
/** * Checks if the field value matches a domain name value. * * @param AbstractField $field The field. */ protected function isValid($field) { if (!preg_match('/^[a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,6}$/', $field->getValue())) { $this->addError($this->translateErrorMessage('fields.validation.domain_name_value', Core::getExtensionKey()), 1431104484); } }
/** * Sets the hint of the field. * * @param string $hint * @return $this */ public function setHint($hint) { $this->hint = Core::translate((string) $hint); return $this; }
/** * Returns the fields configuration of a given page. * * @param $pageUid int The id of the page you want the fields of. * @return array The fields configuration. */ private static function getFieldsConfiguration($pageUid) { if (!isset(self::$fieldsConfiguration[$pageUid])) { self::$fieldsConfiguration[$pageUid] = Core::sortArrayByPositionValue(TypoScriptUtility::getExtensionConfigurationFromPath('fields', $pageUid)); } return self::$fieldsConfiguration[$pageUid]; }
/** * Sets the placeholder of the field. * * @param string $placeholder * @return $this */ public function setPlaceholder($placeholder) { $this->placeholder = Core::translate((string) $placeholder); return $this; }