/** * @param ElasticSearchQueryResult $queryResultObject * @param NodeInterface $node * @param array|string $path * @return array */ public function render(ElasticSearchQueryResult $queryResultObject, NodeInterface $node, $path = NULL) { $hitArray = $queryResultObject->searchHitForNode($node); if (!empty($path)) { return \TYPO3\Flow\Utility\Arrays::getValueByPath($hitArray, $path); } return $hitArray; }
/** * Returns the form definitions for the step * * @param \TYPO3\Form\Core\Model\FormDefinition $formDefinition * @return void */ protected function buildForm(\TYPO3\Form\Core\Model\FormDefinition $formDefinition) { $page1 = $formDefinition->createPage('page1'); $page1->setRenderingOption('header', 'Select your Git Driver'); $driverSection = $page1->createElement('driverSection', 'TYPO3.Form:Section'); $gitDriver = $driverSection->createElement('gitDriver', 'TYPO3.Form:SingleSelectDropdown'); $gitDriver->setLabel('Git Driver'); $gitDriver->setProperty('options', array('GitHub' => 'Git Hub', 'GitLab' => 'Git Lab', 'BitBucket' => 'Bit Bucket')); $gitDriver->addValidator(new NotEmptyValidator()); $gitDriver->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.driver')); $formDefinition->setRenderingOption('skipStepNotice', 'If you skip this step make sure that you have configured your Git Repositories in Settings.yaml'); }
/** * @param string $packageKey * @param array $classNames * @return void */ public function findModelImplementations($packageKey, array &$classNames) { // TODO: OPTIMIZE and CLEANUP! $this->ignoredProperties = \TYPO3\Flow\Utility\Arrays::getValueByPath($this->settings, 'properties._exclude'); foreach ($this->getModelNames() as $entityClassName) { if (substr($entityClassName, 0, strlen($packageKey)) === str_replace('.', '\\', $packageKey)) { if (isset($classNames[$entityClassName])) { continue; } $classNames[$entityClassName] = $this->findModelProperties($entityClassName); } } }
/** * Returns the form definitions for the step * * @param \TYPO3\Form\Core\Model\FormDefinition $formDefinition * @return void */ protected function buildForm(\TYPO3\Form\Core\Model\FormDefinition $formDefinition) { $page1 = $formDefinition->createPage('page1'); $page1->setRenderingOption('header', 'Deployment Settings'); $deploymentSection = $page1->createElement('deploymentSection', 'TYPO3.Form:Section'); $user = $deploymentSection->createElement('defaultUser', 'TYPO3.Form:SingleLineText'); $user->setLabel('Deployment user. Default SSH user for deployment on target systems (optional, will be configurable per target system later on).'); $user->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.frontendSettings.defaultUser')); $path = $deploymentSection->createElement('defaultDeploymentPath', 'TYPO3.Form:SingleLineText'); $path->setLabel('Deployment Path. Default target path for deployments, e.g. "/var/www/{{project}}/{{suffix}}/htdocs/" (optional, will be configurable per target system later on ).'); $path->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.frontendSettings.defaultDeploymentPath')); $formDefinition->setRenderingOption('skipStepNotice', 'You can always configure your frontend settings later in Settings.yaml'); }
/** * Notify SSO servers about the logged out client * * All active authentication tokens of type SingleSignOnToken will be * used to get the registered global session id and send a request * to the session service on the SSO server. * * @return void */ public function logout() { $allConfiguration = $this->configurationManager->getConfiguration(\TYPO3\Flow\Configuration\ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow'); $tokens = $this->securityContext->getAuthenticationTokensOfType('Flowpack\\SingleSignOn\\Client\\Security\\SingleSignOnToken'); foreach ($tokens as $token) { $providerName = $token->getAuthenticationProviderName(); $serverIdentifier = \TYPO3\Flow\Utility\Arrays::getValueByPath($allConfiguration, 'security.authentication.providers.' . $providerName . '.providerOptions.server'); if ($serverIdentifier !== NULL) { $ssoClient = $this->ssoClientFactory->create(); $ssoServer = $this->ssoServerFactory->create($serverIdentifier); $ssoServer->destroySession($ssoClient, $token->getGlobalSessionId()); } } }
/** * @param array $module * @return mixed */ public function indexAction(array $module) { $moduleRequest = new ActionRequest($this->request); $moduleRequest->setArgumentNamespace('moduleArguments'); $moduleRequest->setControllerObjectName($module['controller']); $moduleRequest->setControllerActionName($module['action']); if (isset($module['format'])) { $moduleRequest->setFormat($module['format']); } if ($this->request->hasArgument($moduleRequest->getArgumentNamespace()) === true && is_array($this->request->getArgument($moduleRequest->getArgumentNamespace()))) { $moduleRequest->setArguments($this->request->getArgument($moduleRequest->getArgumentNamespace())); } foreach ($this->request->getPluginArguments() as $argumentNamespace => $argument) { $moduleRequest->setArgument('--' . $argumentNamespace, $argument); } $modules = explode('/', $module['module']); $moduleConfiguration = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $modules)); $moduleConfiguration['path'] = $module['module']; if (!$this->menuHelper->isModuleEnabled($moduleConfiguration['path'])) { throw new DisabledModuleException(sprintf('The module "%s" is disabled. You can enable it with the "enabled" flag in Settings.yaml.', $module['module']), 1437148922); } $moduleBreadcrumb = array(); $path = array(); foreach ($modules as $moduleIdentifier) { array_push($path, $moduleIdentifier); $config = Arrays::getValueByPath($this->settings['modules'], implode('.submodules.', $path)); $moduleBreadcrumb[implode('/', $path)] = $config; } $moduleRequest->setArgument('__moduleConfiguration', $moduleConfiguration); $moduleResponse = new Response($this->response); $this->dispatcher->dispatch($moduleRequest, $moduleResponse); if ($moduleResponse->hasHeader('Location')) { $this->redirectToUri($moduleResponse->getHeader('Location'), 0, $moduleResponse->getStatusCode()); } elseif ($moduleRequest->getFormat() !== 'html') { $mediaType = MediaTypes::getMediaTypeFromFilename('file.' . $moduleRequest->getFormat()); if ($mediaType !== 'application/octet-stream') { $this->controllerContext->getResponse()->setHeader('Content-Type', $mediaType); } return $moduleResponse->getContent(); } else { $user = $this->securityContext->getPartyByType('TYPO3\\Neos\\Domain\\Model\\User'); $sites = $this->menuHelper->buildSiteList($this->controllerContext); $this->view->assignMultiple(array('moduleClass' => implode('-', $modules), 'moduleContents' => $moduleResponse->getContent(), 'title' => $moduleRequest->hasArgument('title') ? $moduleRequest->getArgument('title') : $moduleConfiguration['label'], 'rootModule' => array_shift($modules), 'submodule' => array_shift($modules), 'moduleConfiguration' => $moduleConfiguration, 'moduleBreadcrumb' => $moduleBreadcrumb, 'user' => $user, 'modules' => $this->menuHelper->buildModuleList($this->controllerContext), 'sites' => $sites)); } }
/** * Create follow up issue to given issue * * @param array $issue */ public function createAction($issue) { $redmineClient = new Redmine\Client($this->settings['Redmine']['url'], $this->settings['Redmine']['apiKey']); $id = $issue['related_id']; unset($issue['related_id']); $params = $issue; // get additional issue data and assign to new issue $res = $redmineClient->api('issue')->show($id); $params['project_id'] = Arrays::getValueByPath($res, 'issue.project.id'); $params['category_id'] = Arrays::getValueByPath($res, 'issue.category.id'); $newIssue = $redmineClient->api('issue')->create($params); // create relation $relation['issue_to_id'] = $id; $relation['relation_type'] = self::RELATION_TYPE; $json = json_encode(array('relation' => $relation)); $redmineClient->post('/issues/' . (string) $newIssue->id . '/relations.json', $json); $this->view->assign('value', json_decode(json_encode((array) $newIssue), 1)); }
/** * Returns the form definitions for the step * * @param FormDefinition $formDefinition * @return void */ protected function buildForm(FormDefinition $formDefinition) { $page1 = $formDefinition->createPage('page1'); $page1->setRenderingOption('header', 'Configure database'); $introduction = $page1->createElement('introduction', 'TYPO3.Form:StaticText'); $introduction->setProperty('text', 'Please enter database details below:'); $connectionSection = $page1->createElement('connectionSection', 'TYPO3.Form:Section'); $connectionSection->setLabel('Connection'); $databaseDriver = $connectionSection->createElement('driver', 'TYPO3.Form:SingleSelectDropdown'); $databaseDriver->setLabel('DB Driver'); $databaseDriver->setProperty('options', $this->getAvailableDrivers()); $databaseDriver->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'TYPO3.Flow.persistence.backendOptions.driver')); $databaseDriver->addValidator(new NotEmptyValidator()); $databaseUser = $connectionSection->createElement('user', 'TYPO3.Form:SingleLineText'); $databaseUser->setLabel('DB Username'); $databaseUser->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'TYPO3.Flow.persistence.backendOptions.user')); $databaseUser->addValidator(new NotEmptyValidator()); $databasePassword = $connectionSection->createElement('password', 'TYPO3.Form:Password'); $databasePassword->setLabel('DB Password'); $databasePassword->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'TYPO3.Flow.persistence.backendOptions.password')); $databaseHost = $connectionSection->createElement('host', 'TYPO3.Form:SingleLineText'); $databaseHost->setLabel('DB Host'); $defaultHost = Arrays::getValueByPath($this->distributionSettings, 'TYPO3.Flow.persistence.backendOptions.host'); if ($defaultHost === NULL) { $defaultHost = '127.0.0.1'; } $databaseHost->setDefaultValue($defaultHost); $databaseHost->addValidator(new NotEmptyValidator()); $databaseSection = $page1->createElement('databaseSection', 'TYPO3.Form:Section'); $databaseSection->setLabel('Database'); $databaseName = $databaseSection->createElement('dbname', 'TYPO3.Setup:DatabaseSelector'); $databaseName->setLabel('DB Name'); $databaseName->setProperty('driverDropdownFieldId', $databaseDriver->getUniqueIdentifier()); $databaseName->setProperty('userFieldId', $databaseUser->getUniqueIdentifier()); $databaseName->setProperty('passwordFieldId', $databasePassword->getUniqueIdentifier()); $databaseName->setProperty('hostFieldId', $databaseHost->getUniqueIdentifier()); $databaseName->setDefaultValue(Arrays::getValueByPath($this->distributionSettings, 'TYPO3.Flow.persistence.backendOptions.dbname')); $databaseName->addValidator(new NotEmptyValidator()); }
/** * @param string $value */ protected function initializeValue($value) { $value = trim($value); $config = \HTMLPurifier_Config::createDefault(); $options = Arrays::getValueByPath($this->options, 'htmlPurifierOptions') ?: []; foreach ($options as $optionName => $optionValue) { $config->set($optionName, $optionValue); } $purifier = new \HTMLPurifier($config); $value = $purifier->purify($value); // Todo add options in data type settings $value = str_replace(['<ul>', '</ul>', '<ol>', '</ol>', ' '], [PHP_EOL . '<ul>' . PHP_EOL, PHP_EOL . '</ul>' . PHP_EOL, PHP_EOL . '<ol>' . PHP_EOL, PHP_EOL . '</ol>' . PHP_EOL, ' '], $value); // Normalize tag $options = Arrays::getValueByPath($this->options, 'preProcessing') ?: []; if (count($options)) { $value = preg_replace(array_keys($options), array_values($options), $value); } // Normalize line break $value = preg_replace('/(^[\\r\\n]*|[\\r\\n]+)[\\s\\t]*[\\r\\n]+/', '\\n', $value); // Process line per line $lines = preg_split("/\\r\\n|\\r|\\n/", $value); foreach ($lines as $key => $line) { $line = trim($line); $options = Arrays::getValueByPath($this->options, 'processingPerLine') ?: []; if (count($options)) { $lines[$key] = preg_replace(array_keys($options), array_values($options), $line); } } $value = implode(' ' . PHP_EOL, $lines); // Global post processing $options = Arrays::getValueByPath($this->options, 'postProcessing') ?: []; if (count($options)) { $value = preg_replace(array_keys($options), array_values($options), $value); } // Return everything on one line $value = str_replace(PHP_EOL, '', $value); // Remove duplicated space and trim $this->value = trim(preg_replace('/\\s+/u', ' ', $value)); }
/** * Shows the status of the current mapping... * * @param string $clientName The client name for the configuration. Defaults to the default client configured. * @return void */ public function showStatusCommand($clientName = null) { $entityMappingCollection = $this->entityMappingBuilder->buildMappingInformation(); $entityMappingCollection = $this->buildArrayFromMappingCollection($entityMappingCollection); $client = $this->clientFactory->create($clientName); $this->backendMappingBuilder->setClient($client); $backendMappingCollection = $this->backendMappingBuilder->buildMappingInformation(); $backendMappingCollection = $this->buildArrayFromMappingCollection($backendMappingCollection); $this->printLegend(); $this->outputFormatted('<b>Mapping status:</b>'); $this->outputFormatted('<b>---------------</b>'); $mergedMappingCollection = array_merge_recursive($entityMappingCollection, $backendMappingCollection); foreach ($mergedMappingCollection as $indexName => $typeSet) { $this->outputFormatted('index %s:', array($this->markupDiffValue(isset($entityMappingCollection[$indexName]) ? $indexName : null, isset($backendMappingCollection[$indexName]) ? $indexName : null))); foreach ($typeSet as $typeName => $mappingSet) { $propertiesSet = $mappingSet['properties']; $this->outputFormatted('type %s:', array($this->markupDiffValue(isset($entityMappingCollection[$indexName][$typeName]) ? $typeName : null, isset($backendMappingCollection[$indexName][$typeName]) ? $typeName : null)), 4); foreach ($propertiesSet as $propertyName => $properties) { $entityProperties = \TYPO3\Flow\Utility\Arrays::getValueByPath($entityMappingCollection, array($indexName, $typeName, 'properties', $propertyName)); $backendProperties = \TYPO3\Flow\Utility\Arrays::getValueByPath($backendMappingCollection, array($indexName, $typeName, 'properties', $propertyName)); $this->outputFormatted('property %s:', array($this->markupDiffValue($entityProperties ? $propertyName : null, $backendProperties ? $propertyName : null)), 8); foreach ($properties as $key => $value) { $keyMarkup = $this->markupDiffValue(isset($entityProperties[$key]) ? $key : null, isset($backendProperties[$key]) ? $key : null); $valueMarkup = $this->markupDiffValue(isset($entityProperties[$key]) ? $entityProperties[$key] : null, isset($backendProperties[$key]) ? $backendProperties[$key] : null); $this->outputFormatted("%s : %s", array($keyMarkup, $valueMarkup), 12); } } $this->outputLine(); } $this->outputLine(); } if (count($indicesWithoutTypeInformation = $this->backendMappingBuilder->getIndicesWithoutTypeInformation())) { $this->outputFormatted("[43mNotice:[0m The following indices are present in the backend's mapping but having no type configuration, can hence be regarded as garbage:"); foreach ($indicesWithoutTypeInformation as $indexName) { $this->outputFormatted('* %s', array($indexName), 4); } } }
/** * Sets labels for global NodeType elements like tabs and groups and the general label. * * @param string $nodeTypeLabelIdPrefix * @param array $configuration * @return void */ protected function setGlobalUiElementLabels($nodeTypeLabelIdPrefix, &$configuration) { if ($this->shouldFetchTranslation($configuration['ui'])) { $configuration['ui']['label'] = $this->getInspectorElementTranslationId($nodeTypeLabelIdPrefix, 'ui', 'label'); } $inspectorConfiguration = Arrays::getValueByPath($configuration, 'ui.inspector'); if (is_array($inspectorConfiguration)) { foreach ($inspectorConfiguration as $elementTypeName => $elementTypeItems) { foreach ($elementTypeItems as $elementName => $elementConfiguration) { if (!$this->shouldFetchTranslation($elementConfiguration)) { continue; } $translationLabelId = $this->getInspectorElementTranslationId($nodeTypeLabelIdPrefix, $elementTypeName, $elementName); $configuration['ui']['inspector'][$elementTypeName][$elementName]['label'] = $translationLabelId; } } } }
/** * @return array * @throws Exception */ protected function initializeConfiguration() { $configuration = Arrays::getValueByPath($this->settings, ['resources', $this->resource]); if (!is_array($configuration)) { throw new Exception(sprintf('Resource "%s" not configured', $this->resource), 1447947509); } return $configuration; }
/** * Generate a schema for the given configuration or YAML file. * * ./flow configuration:generateschema --type Settings --path TYPO3.Flow.persistence * * The schema will be output to standard output. * * @param string $type Configuration type to create a schema for * @param string $path path to the subconfiguration separated by "." like "TYPO3.Flow" * @param string $yaml YAML file to create a schema for * @return void */ public function generateSchemaCommand($type = null, $path = null, $yaml = null) { $data = null; if ($yaml !== null && is_file($yaml) && is_readable($yaml)) { $data = Yaml::parse($yaml); } elseif ($type !== null) { $data = $this->configurationManager->getConfiguration($type); if ($path !== null) { $data = Arrays::getValueByPath($data, $path); } } if (empty($data)) { $this->outputLine('Data was not found or is empty'); $this->quit(1); } $this->outputLine(Yaml::dump($this->schemaGenerator->generate($data), 99)); }
/** * FIXME: Not yet completely refactored to new proxy mechanism * * @param array $argumentConfigurations * @return string */ protected function buildMethodParametersCode(array $argumentConfigurations) { $preparedArguments = array(); foreach ($argumentConfigurations as $argument) { if ($argument === null) { $preparedArguments[] = 'NULL'; } else { $argumentValue = $argument->getValue(); switch ($argument->getType()) { case ConfigurationArgument::ARGUMENT_TYPES_OBJECT: if ($argumentValue instanceof Configuration) { $argumentValueObjectName = $argumentValue->getObjectName(); if ($this->objectConfigurations[$argumentValueObjectName]->getScope() === Configuration::SCOPE_PROTOTYPE) { $preparedArguments[] = 'new \\' . $argumentValueObjectName . '(' . $this->buildMethodParametersCode($argumentValue->getArguments(), $this->objectConfigurations) . ')'; } else { $preparedArguments[] = '\\TYPO3\\Flow\\Core\\Bootstrap::$staticObjectManager->get(\'' . $argumentValueObjectName . '\')'; } } else { if (strpos($argumentValue, '.') !== false) { $settingPath = explode('.', $argumentValue); $settings = Arrays::getValueByPath($this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS), array_shift($settingPath)); $argumentValue = Arrays::getValueByPath($settings, $settingPath); } $preparedArguments[] = '\\TYPO3\\Flow\\Core\\Bootstrap::$staticObjectManager->get(\'' . $argumentValue . '\')'; } break; case ConfigurationArgument::ARGUMENT_TYPES_STRAIGHTVALUE: $preparedArguments[] = var_export($argumentValue, true); break; case ConfigurationArgument::ARGUMENT_TYPES_SETTING: $preparedArguments[] = '\\TYPO3\\Flow\\Core\\Bootstrap::$staticObjectManager->getSettingsByPath(explode(\'.\', \'' . $argumentValue . '\'))'; break; } } } return implode(', ', $preparedArguments); }
/** * Renames the original repository to upstream * and adds the own fork as origin * * @param $collectionName * @throws \Exception */ protected function setupRemotes($collectionName) { $packageCollectionPath = Files::concatenatePaths(array(FLOW_PATH_PACKAGES, (string) Arrays::getValueByPath($this->gitHubSettings, sprintf('origin.repositories.%s.packageDirectory', $collectionName)))); $originRepositoryName = (string) Arrays::getValueByPath($this->gitHubSettings, sprintf('origin.repositories.%s.name', $collectionName)); $contributorRepositoryName = (string) Arrays::getValueByPath($this->gitHubSettings, sprintf('contributor.repositories.%s.name', $collectionName)); $sshUrl = $this->gitHubService->buildSSHUrlForRepository($contributorRepositoryName); $this->executeGitCommand('git remote rm origin', $packageCollectionPath, TRUE); $this->executeGitCommand('git remote add origin ' . $sshUrl, $packageCollectionPath); $this->executeGitCommand('git remote rm upstream', $packageCollectionPath, TRUE); $this->executeGitCommand(sprintf('git remote add upstream git://github.com/%s/%s.git', $this->gitHubSettings['origin']['organization'], $originRepositoryName), $packageCollectionPath); $this->executeGitCommand('git config --add remote.upstream.fetch \'+refs/pull/*/head:refs/remotes/upstream/pr/*\'', $packageCollectionPath); }
/** * @param \TYPO3\Form\Core\Model\Page $page * @return \TYPO3\Flow\Error\Result * @internal */ protected function mapAndValidatePage(\TYPO3\Form\Core\Model\Page $page) { $result = new \TYPO3\Flow\Error\Result(); $requestArguments = $this->request->getArguments(); $propertyPathsForWhichPropertyMappingShouldHappen = array(); $registerPropertyPaths = function ($propertyPath) use(&$propertyPathsForWhichPropertyMappingShouldHappen) { $propertyPathParts = explode('.', $propertyPath); $accumulatedPropertyPathParts = array(); foreach ($propertyPathParts as $propertyPathPart) { $accumulatedPropertyPathParts[] = $propertyPathPart; $temporaryPropertyPath = implode('.', $accumulatedPropertyPathParts); $propertyPathsForWhichPropertyMappingShouldHappen[$temporaryPropertyPath] = $temporaryPropertyPath; } }; foreach ($page->getElementsRecursively() as $element) { $value = \TYPO3\Flow\Utility\Arrays::getValueByPath($requestArguments, $element->getIdentifier()); $element->onSubmit($this, $value); $this->formState->setFormValue($element->getIdentifier(), $value); $registerPropertyPaths($element->getIdentifier()); } // The more parts the path has, the more early it is processed usort($propertyPathsForWhichPropertyMappingShouldHappen, function ($a, $b) { return substr_count($b, '.') - substr_count($a, '.'); }); $processingRules = $this->formDefinition->getProcessingRules(); foreach ($propertyPathsForWhichPropertyMappingShouldHappen as $propertyPath) { if (isset($processingRules[$propertyPath])) { $processingRule = $processingRules[$propertyPath]; $value = $this->formState->getFormValue($propertyPath); try { $value = $processingRule->process($value); } catch (\TYPO3\Flow\Property\Exception $exception) { throw new \TYPO3\Form\Exception\PropertyMappingException('Failed to process FormValue at "' . $propertyPath . '" from "' . gettype($value) . '" to "' . $processingRule->getDataType() . '"', 1355218921, $exception); } $result->forProperty($propertyPath)->merge($processingRule->getProcessingMessages()); $this->formState->setFormValue($propertyPath, $value); } } return $result; }
/** * Authenticate a username / password against the LDAP server * * @param string $username * @param string $password * @return array Search result from LDAP * @throws Exception */ public function authenticate($username, $password) { try { $this->ldapConnect(); $this->bindProvider->bind($username, $password); $entries = $this->getUserEntries($username); if (!empty($entries)) { $this->bindProvider->verifyCredentials($entries[0]['dn'], $password); // get all entries in the second run in the case of anonymous bind $anonymousBind = Arrays::getValueByPath($this->options, 'bind.anonymous'); if ($anonymousBind === true) { $entries = $this->getUserEntries($username); } else { $this->bindProvider->bind($username, $password); } } return $entries[0]; } catch (\Exception $exception) { throw new Exception('Error during LDAP server authentication: ' . $exception->getMessage(), 1323167213); } }
/** * @test */ public function getValueByPathReturnsNullIfThePathHasMoreSegmentsThanTheGivenArray() { $array = array('Foo' => array('Bar' => array('Baz' => 'the value'))); $this->assertNULL(\TYPO3\Flow\Utility\Arrays::getValueByPath($array, array('Foo', 'Bar', 'Baz', 'Bux'))); }
/** * @param string $propertyPath * @return mixed */ public function getFormValue($propertyPath) { return \TYPO3\Flow\Utility\Arrays::getValueByPath($this->formValues, $propertyPath); }
/** * @param array $additionalOptions * @return array * @throws InvalidConfigurationException */ protected function getOptionsMergedWithDefaults(array $additionalOptions = array()) { $defaultOptions = Arrays::getValueByPath($this->settings, 'image.defaultOptions'); if (!is_array($defaultOptions)) { $defaultOptions = array(); } if ($additionalOptions !== array()) { $defaultOptions = Arrays::arrayMergeRecursiveOverrule($defaultOptions, $additionalOptions); } $quality = isset($defaultOptions['quality']) ? (int) $defaultOptions['quality'] : 90; if ($quality < 0 || $quality > 100) { throw new InvalidConfigurationException(sprintf('Setting "TYPO3.Media.image.defaultOptions.quality" allow only value between 0 and 100, current value: %s', $quality), 1404982574); } $defaultOptions['jpeg_quality'] = $quality; // png_compression_level should be an integer between 0 and 9 and inverse to the quality level given. So quality 100 should result in compression 0. $defaultOptions['png_compression_level'] = 9 - ceil($quality * 9 / 100); return $defaultOptions; }
/** * @param string $path * @return mixed */ public function getValueByPath($path) { return Arrays::getValueByPath($this->options, $path); }
/** * Validate a single configuration type * * @param string $configurationType the configuration typr to validate * @param string $path configuration path to validate, or NULL. * @param array $loadedSchemaFiles will be filled with a list of loaded schema files * @return \TYPO3\Flow\Error\Result * @throws Exception\SchemaValidationException */ protected function validateSingleType($configurationType, $path, &$loadedSchemaFiles) { $availableConfigurationTypes = $this->configurationManager->getAvailableConfigurationTypes(); if (in_array($configurationType, $availableConfigurationTypes) === FALSE) { throw new Exception\SchemaValidationException('The configuration type "' . $configurationType . '" was not found. Only the following configuration types are supported: "' . implode('", "', $availableConfigurationTypes) . '"', 1364984886); } $configuration = $this->configurationManager->getConfiguration($configurationType); // find schema files for the given type and path $schemaFileInfos = array(); $activePackages = $this->packageManager->getActivePackages(); foreach ($activePackages as $package) { $packageKey = $package->getPackageKey(); $packageSchemaPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($package->getResourcesPath(), 'Private/Schema')); if (is_dir($packageSchemaPath)) { $packageSchemaFiles = \TYPO3\Flow\Utility\Files::readDirectoryRecursively($packageSchemaPath, '.schema.yaml'); foreach ($packageSchemaFiles as $schemaFile) { $schemaName = substr($schemaFile, strlen($packageSchemaPath) + 1, -strlen('.schema.yaml')); $schemaNameParts = explode('.', str_replace('/', '.', $schemaName), 2); $schemaType = $schemaNameParts[0]; $schemaPath = isset($schemaNameParts[1]) ? $schemaNameParts[1] : NULL; if ($schemaType === $configurationType && ($path === NULL || strpos($schemaPath, $path) === 0)) { $schemaFileInfos[] = array('file' => $schemaFile, 'name' => $schemaName, 'path' => $schemaPath, 'packageKey' => $packageKey); } } } } if (count($schemaFileInfos) === 0) { throw new Exception\SchemaValidationException('No schema files found for configuration type "' . $configurationType . '"' . ($path !== NULL ? ' and path "' . $path . '".' : '.'), 1364985056); } $result = new Result(); foreach ($schemaFileInfos as $schemaFileInfo) { $loadedSchemaFiles[] = $schemaFileInfo['file']; if ($schemaFileInfo['path'] !== NULL) { $data = \TYPO3\Flow\Utility\Arrays::getValueByPath($configuration, $schemaFileInfo['path']); } else { $data = $configuration; } if (empty($data)) { throw new Exception\SchemaValidationException('The schema file "' . $schemaFileInfo['file'] . '" is empty.', 1364985445); } else { $parsedSchema = \Symfony\Component\Yaml\Yaml::parse($schemaFileInfo['file']); $validationResultForSingleSchema = $this->schemaValidator->validate($data, $parsedSchema); if ($schemaFileInfo['path'] !== NULL) { $result->forProperty($schemaFileInfo['path'])->merge($validationResultForSingleSchema); } else { $result->merge($validationResultForSingleSchema); } } } return $result; }
/** * Gets a property setting by its path * * @param array|string $path * @return mixed */ public function getPropertyByPath($path) { return \TYPO3\Flow\Utility\Arrays::getValueByPath($this->properties, $path); }
/** * @param string $presetName * @param string $partName * @param string $dataProviderClassName * @param string $importerClassName * @param string $logPrefix * @param integer $offset * @param integer $batchSize * @return integer * @Flow\Internal */ public function executeBatchCommand($presetName, $partName, $dataProviderClassName, $importerClassName, $logPrefix, $offset = NULL, $batchSize = NULL) { try { $dataProviderOptions = Arrays::getValueByPath($this->settings, implode('.', ['presets', $presetName, $partName, 'dataProviderOptions'])); /** @var DataProvider $dataProvider */ $dataProvider = $dataProviderClassName::create(is_array($dataProviderOptions) ? $dataProviderOptions : [], $offset, $batchSize); $importerOptions = Arrays::getValueByPath($this->settings, ['presets', $presetName, $partName, 'importerOptions']); /** @var Importer $importer */ $importer = $this->objectManager->get($importerClassName, is_array($importerOptions) ? $importerOptions : []); $importer->setLogPrefix($logPrefix); $importer->import($dataProvider); $this->output($dataProvider->getCount()); } catch (\Exception $exception) { $this->logger->logException($exception); $this->quit(1); } }
/** * @return string */ public function editPreviewAction() { $this->response->setHeader('Content-Type', 'application/json'); $configuration = new PositionalArraySorter(Arrays::getValueByPath($this->settings, 'userInterface.editPreviewModes')); return json_encode($configuration->toArray()); }
/** * Validate a single configuration type * * @param string $configurationType the configuration typr to validate * @param string $path configuration path to validate, or NULL. * @param array $loadedSchemaFiles will be filled with a list of loaded schema files * @return \TYPO3\Flow\Error\Result * @throws Exception\SchemaValidationException */ protected function validateSingleType($configurationType, $path, &$loadedSchemaFiles) { $availableConfigurationTypes = $this->configurationManager->getAvailableConfigurationTypes(); if (in_array($configurationType, $availableConfigurationTypes) === false) { throw new Exception\SchemaValidationException('The configuration type "' . $configurationType . '" was not found. Only the following configuration types are supported: "' . implode('", "', $availableConfigurationTypes) . '"', 1364984886); } $configuration = $this->configurationManager->getConfiguration($configurationType); // find schema files for the given type and path $schemaFileInfos = []; $activePackages = $this->packageManager->getActivePackages(); foreach ($activePackages as $package) { $packageKey = $package->getPackageKey(); $packageSchemaPath = Files::concatenatePaths([$package->getResourcesPath(), 'Private/Schema']); if (is_dir($packageSchemaPath)) { foreach (Files::getRecursiveDirectoryGenerator($packageSchemaPath, '.schema.yaml') as $schemaFile) { $schemaName = substr($schemaFile, strlen($packageSchemaPath) + 1, -strlen('.schema.yaml')); $schemaNameParts = explode('.', str_replace('/', '.', $schemaName), 2); $schemaType = $schemaNameParts[0]; $schemaPath = isset($schemaNameParts[1]) ? $schemaNameParts[1] : null; if ($schemaType === $configurationType && ($path === null || strpos($schemaPath, $path) === 0)) { $schemaFileInfos[] = ['file' => $schemaFile, 'name' => $schemaName, 'path' => $schemaPath, 'packageKey' => $packageKey]; } } } } if (count($schemaFileInfos) === 0) { throw new Exception\SchemaValidationException('No schema files found for configuration type "' . $configurationType . '"' . ($path !== null ? ' and path "' . $path . '".' : '.'), 1364985056); } $result = new Result(); foreach ($schemaFileInfos as $schemaFileInfo) { $loadedSchemaFiles[] = $schemaFileInfo['file']; if ($schemaFileInfo['path'] !== null) { $data = Arrays::getValueByPath($configuration, $schemaFileInfo['path']); } else { $data = $configuration; } if (empty($data)) { $result->addNotice(new Notice('No configuration found, skipping schema "%s".', 1364985445, [substr($schemaFileInfo['file'], strlen(FLOW_PATH_ROOT))])); } else { $parsedSchema = Yaml::parse($schemaFileInfo['file']); $validationResultForSingleSchema = $this->schemaValidator->validate($data, $parsedSchema); if ($schemaFileInfo['path'] !== null) { $result->forProperty($schemaFileInfo['path'])->merge($validationResultForSingleSchema); } else { $result->merge($validationResultForSingleSchema); } } } return $result; }
/** * Transforms the convoluted _FILES superglobal into a manageable form. * * @param array $convolutedFiles The _FILES superglobal * @return array Untangled files */ protected function untangleFilesArray(array $convolutedFiles) { $untangledFiles = array(); $fieldPaths = array(); foreach ($convolutedFiles as $firstLevelFieldName => $fieldInformation) { if (!is_array($fieldInformation['error'])) { $fieldPaths[] = array($firstLevelFieldName); } else { $newFieldPaths = $this->calculateFieldPaths($fieldInformation['error'], $firstLevelFieldName); array_walk($newFieldPaths, function (&$value) { $value = explode('/', $value); }); $fieldPaths = array_merge($fieldPaths, $newFieldPaths); } } foreach ($fieldPaths as $fieldPath) { if (count($fieldPath) === 1) { $fileInformation = $convolutedFiles[$fieldPath[0]]; } else { $fileInformation = array(); foreach ($convolutedFiles[$fieldPath[0]] as $key => $subStructure) { $fileInformation[$key] = Arrays::getValueByPath($subStructure, array_slice($fieldPath, 1)); } } if (isset($fileInformation['error']) && $fileInformation['error'] !== \UPLOAD_ERR_NO_FILE) { $untangledFiles = Arrays::setValueByPath($untangledFiles, $fieldPath, $fileInformation); } } return $untangledFiles; }
/** * @return array|null */ protected function getSettings() { if ($this->client instanceof Client) { $settings = Arrays::getValueByPath($this->settings, 'indexes.' . $this->client->getBundle() . '.' . $this->settingsKey) ?: Arrays::getValueByPath($this->settings, 'indexes.default' . '.' . $this->settingsKey); } else { $settings = Arrays::getValueByPath($this->settings, 'indexes.default' . '.' . $this->settingsKey); } return $settings; }
/** * Invokes the Factory defined in the object configuration of the specified object in order * to build an instance. Arguments which were defined in the object configuration are * passed to the factory method. * * @param string $objectName Name of the object to build * @return object The built object */ protected function buildObjectByFactory($objectName) { $factory = $this->get($this->objects[$objectName]['f'][0]); $factoryMethodName = $this->objects[$objectName]['f'][1]; $factoryMethodArguments = array(); foreach ($this->objects[$objectName]['fa'] as $index => $argumentInformation) { switch ($argumentInformation['t']) { case ObjectConfigurationArgument::ARGUMENT_TYPES_SETTING: $settingPath = explode('.', $argumentInformation['v']); $factoryMethodArguments[$index] = \TYPO3\Flow\Utility\Arrays::getValueByPath($this->allSettings, $settingPath); break; case ObjectConfigurationArgument::ARGUMENT_TYPES_STRAIGHTVALUE: $factoryMethodArguments[$index] = $argumentInformation['v']; break; case ObjectConfigurationArgument::ARGUMENT_TYPES_OBJECT: $factoryMethodArguments[$index] = $this->get($argumentInformation['v']); break; } } if (count($factoryMethodArguments) === 0) { return $factory->{$factoryMethodName}(); } else { return call_user_func_array(array($factory, $factoryMethodName), $factoryMethodArguments); } }
/** * Loads special configuration defined in the specified packages and merges them with * those potentially existing in the global configuration folders. The result is stored * in the configuration manager's configuration registry and can be retrieved with the * getConfiguration() method. * * @param string $configurationType The kind of configuration to load - must be one of the CONFIGURATION_TYPE_* constants * @param array $packages An array of Package objects (indexed by package key) to consider * @throws Exception\InvalidConfigurationTypeException * @throws Exception\InvalidConfigurationException * @return void */ protected function loadConfiguration($configurationType, array $packages) { $this->cacheNeedsUpdate = true; $configurationProcessingType = $this->resolveConfigurationProcessingType($configurationType); $allowSplitSource = $this->isSplitSourceAllowedForConfigurationType($configurationType); switch ($configurationProcessingType) { case self::CONFIGURATION_PROCESSING_TYPE_SETTINGS: // Make sure that the Flow package is the first item of the packages array: if (isset($packages['TYPO3.Flow'])) { $flowPackage = $packages['TYPO3.Flow']; unset($packages['TYPO3.Flow']); $packages = array_merge(array('TYPO3.Flow' => $flowPackage), $packages); unset($flowPackage); } $settings = array(); /** @var $package PackageInterface */ foreach ($packages as $packageKey => $package) { if (Arrays::getValueByPath($settings, $packageKey) === null) { $settings = Arrays::setValueByPath($settings, $packageKey, array()); } $settings = Arrays::arrayMergeRecursiveOverrule($settings, $this->configurationSource->load($package->getConfigurationPath() . $configurationType, $allowSplitSource)); } $settings = Arrays::arrayMergeRecursiveOverrule($settings, $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $configurationType, $allowSplitSource)); foreach ($this->orderedListOfContextNames as $contextName) { /** @var $package PackageInterface */ foreach ($packages as $package) { $settings = Arrays::arrayMergeRecursiveOverrule($settings, $this->configurationSource->load($package->getConfigurationPath() . $contextName . '/' . $configurationType, $allowSplitSource)); } $settings = Arrays::arrayMergeRecursiveOverrule($settings, $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $contextName . '/' . $configurationType, $allowSplitSource)); } if ($this->configurations[$configurationType] !== array()) { $this->configurations[$configurationType] = Arrays::arrayMergeRecursiveOverrule($this->configurations[$configurationType], $settings); } else { $this->configurations[$configurationType] = $settings; } $this->configurations[$configurationType]['TYPO3']['Flow']['core']['context'] = (string) $this->context; break; case self::CONFIGURATION_PROCESSING_TYPE_OBJECTS: $this->configurations[$configurationType] = array(); /** @var $package PackageInterface */ foreach ($packages as $packageKey => $package) { $configuration = $this->configurationSource->load($package->getConfigurationPath() . $configurationType); $configuration = Arrays::arrayMergeRecursiveOverrule($configuration, $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $configurationType)); foreach ($this->orderedListOfContextNames as $contextName) { $configuration = Arrays::arrayMergeRecursiveOverrule($configuration, $this->configurationSource->load($package->getConfigurationPath() . $contextName . '/' . $configurationType)); $configuration = Arrays::arrayMergeRecursiveOverrule($configuration, $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $contextName . '/' . $configurationType)); } $this->configurations[$configurationType][$packageKey] = $configuration; } break; case self::CONFIGURATION_PROCESSING_TYPE_POLICY: if ($this->context->isTesting()) { $testingPolicyPathAndFilename = $this->environment->getPathToTemporaryDirectory() . 'Policy'; if ($this->configurationSource->has($testingPolicyPathAndFilename)) { $this->configurations[$configurationType] = $this->configurationSource->load($testingPolicyPathAndFilename); break; } } $this->configurations[$configurationType] = array(); /** @var $package PackageInterface */ foreach ($packages as $package) { $packagePolicyConfiguration = $this->configurationSource->load($package->getConfigurationPath() . $configurationType, $allowSplitSource); $this->validatePolicyConfiguration($packagePolicyConfiguration, $package); $this->configurations[$configurationType] = $this->mergePolicyConfiguration($this->configurations[$configurationType], $packagePolicyConfiguration); } $this->configurations[$configurationType] = $this->mergePolicyConfiguration($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $configurationType, $allowSplitSource)); foreach ($this->orderedListOfContextNames as $contextName) { /** @var $package PackageInterface */ foreach ($packages as $package) { $packagePolicyConfiguration = $this->configurationSource->load($package->getConfigurationPath() . $contextName . '/' . $configurationType, $allowSplitSource); $this->validatePolicyConfiguration($packagePolicyConfiguration, $package); $this->configurations[$configurationType] = $this->mergePolicyConfiguration($this->configurations[$configurationType], $packagePolicyConfiguration); } $this->configurations[$configurationType] = $this->mergePolicyConfiguration($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $contextName . '/' . $configurationType, $allowSplitSource)); } break; case self::CONFIGURATION_PROCESSING_TYPE_DEFAULT: $this->configurations[$configurationType] = array(); /** @var $package PackageInterface */ foreach ($packages as $package) { $this->configurations[$configurationType] = Arrays::arrayMergeRecursiveOverrule($this->configurations[$configurationType], $this->configurationSource->load($package->getConfigurationPath() . $configurationType, $allowSplitSource)); } $this->configurations[$configurationType] = Arrays::arrayMergeRecursiveOverrule($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $configurationType, $allowSplitSource)); foreach ($this->orderedListOfContextNames as $contextName) { /** @var $package PackageInterface */ foreach ($packages as $package) { $this->configurations[$configurationType] = Arrays::arrayMergeRecursiveOverrule($this->configurations[$configurationType], $this->configurationSource->load($package->getConfigurationPath() . $contextName . '/' . $configurationType, $allowSplitSource)); } $this->configurations[$configurationType] = Arrays::arrayMergeRecursiveOverrule($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $contextName . '/' . $configurationType, $allowSplitSource)); } break; case self::CONFIGURATION_PROCESSING_TYPE_ROUTES: // load main routes $this->configurations[$configurationType] = array(); foreach (array_reverse($this->orderedListOfContextNames) as $contextName) { $this->configurations[$configurationType] = array_merge($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $contextName . '/' . $configurationType)); } $this->configurations[$configurationType] = array_merge($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $configurationType)); // Merge routes with SubRoutes recursively $this->mergeRoutesWithSubRoutes($this->configurations[$configurationType]); break; case self::CONFIGURATION_PROCESSING_TYPE_APPEND: $this->configurations[$configurationType] = array(); /** @var $package PackageInterface */ foreach ($packages as $package) { $this->configurations[$configurationType] = array_merge($this->configurations[$configurationType], $this->configurationSource->load($package->getConfigurationPath() . $configurationType, $allowSplitSource)); } $this->configurations[$configurationType] = array_merge($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $configurationType, $allowSplitSource)); foreach ($this->orderedListOfContextNames as $contextName) { foreach ($packages as $package) { $this->configurations[$configurationType] = array_merge($this->configurations[$configurationType], $this->configurationSource->load($package->getConfigurationPath() . $contextName . '/' . $configurationType, $allowSplitSource)); } $this->configurations[$configurationType] = array_merge($this->configurations[$configurationType], $this->configurationSource->load(FLOW_PATH_CONFIGURATION . $contextName . '/' . $configurationType, $allowSplitSource)); } break; default: throw new Exception\InvalidConfigurationTypeException('Configuration type "' . $configurationType . '" cannot be loaded with loadConfiguration().', 1251450613); } $this->postProcessConfiguration($this->configurations[$configurationType]); }