/**
  * Create a new user
  *
  * This command creates a new user which has access to the backend user interface.
  *
  * More specifically, this command will create a new user and a new account at the same time. The created account
  * is, by default, a Neos backend account using the the "Typo3BackendProvider" for authentication. The given username
  * will be used as an account identifier for that new account.
  *
  * If an authentication provider name is specified, the new account will be created for that provider instead.
  *
  * Roles for the new user can optionally be specified as a comma separated list. For all roles provided by
  * Neos, the role namespace "TYPO3.Neos:" can be omitted.
  *
  * @param string $username The username of the user to be created, used as an account identifier for the newly created account
  * @param string $password Password of the user to be created
  * @param string $firstName First name of the user to be created
  * @param string $lastName Last name of the user to be created
  * @param string $department department name of the user to be created
  * @param string $photo photo name of the user to be created
  * @param string $roles A comma separated list of roles to assign. Examples: "Editor, Acme.Foo:Reviewer"
  * @param string $authenticationProvider Name of the authentication provider to use for the new account. Example: "Typo3BackendProvider"
  * @return void
  */
 public function createPhluCommand($username, $password, $firstName, $lastName, $department, $photo, $roles = null, $authenticationProvider = null)
 {
     $user = $this->userService->getUser($username, $authenticationProvider);
     if ($user instanceof User) {
         $this->outputLine('The username "%s" is already in use', array($username));
         $this->quit(1);
     }
     try {
         if ($roles === null) {
             $user = $this->userService->createUserPhlu($username, $password, $firstName, $lastName, $department, $photo, null, $authenticationProvider);
         } else {
             $roleIdentifiers = Arrays::trimExplode(',', $roles);
             $user = $this->userService->createUserPhlu($username, $password, $firstName, $lastName, $department, $photo, $roleIdentifiers, $authenticationProvider);
         }
         $roleIdentifiers = array();
         foreach ($user->getAccounts() as $account) {
             /** @var Account $account */
             foreach ($account->getRoles() as $role) {
                 /** @var Role $role */
                 $roleIdentifiers[$role->getIdentifier()] = true;
             }
         }
         $roleIdentifiers = array_keys($roleIdentifiers);
         if (count($roleIdentifiers) === 0) {
             $this->outputLine('Created user "%s".', array($username));
             $this->outputLine('<b>Please note that this user currently does not have any roles assigned.</b>');
         } else {
             $this->outputLine('Created user "%s" and assigned the following role%s: %s.', array($username, count($roleIdentifiers) > 1 ? 's' : '', implode(', ', $roleIdentifiers)));
         }
     } catch (\Exception $exception) {
         $this->outputLine($exception->getMessage());
         $this->quit(1);
     }
 }
 /**
  * @return void
  */
 protected function initializeView(FluidView $fluidView)
 {
     $user = $this->getUserData($this['username']);
     $excludedProjects = Arrays::trimExplode(',', $this['excludedprojects']);
     $decodedProjects = $this->getProjectsData($user['id']);
     $projects = [];
     foreach ($decodedProjects['objects'] as $project) {
         if (!in_array($project['slug'], $excludedProjects)) {
             $projects[] = $project;
         }
     }
     $fluidView->assign('projects', $projects);
 }
 /**
  * Iterate through the segments of the current request path
  * find the corresponding module configuration and set controller & action
  * accordingly
  *
  * @param string $value
  * @return boolean|integer
  */
 protected function matchValue($value)
 {
     $format = pathinfo($value, PATHINFO_EXTENSION);
     if ($format !== '') {
         $value = substr($value, 0, strlen($value) - strlen($format) - 1);
     }
     $segments = Arrays::trimExplode('/', $value);
     $currentModuleBase = $this->settings['modules'];
     if ($segments === array() || !isset($currentModuleBase[$segments[0]])) {
         return self::MATCHRESULT_NOSUCHMODULE;
     }
     $modulePath = array();
     $level = 0;
     $moduleConfiguration = null;
     $moduleController = null;
     $moduleAction = 'index';
     foreach ($segments as $segment) {
         if (isset($currentModuleBase[$segment])) {
             $modulePath[] = $segment;
             $moduleConfiguration = $currentModuleBase[$segment];
             if (isset($moduleConfiguration['controller'])) {
                 $moduleController = $moduleConfiguration['controller'];
             } else {
                 $moduleController = null;
             }
             if (isset($moduleConfiguration['submodules'])) {
                 $currentModuleBase = $moduleConfiguration['submodules'];
             } else {
                 $currentModuleBase = array();
             }
         } else {
             if ($level === count($segments) - 1) {
                 $moduleMethods = array_change_key_case(array_flip(get_class_methods($moduleController)), CASE_LOWER);
                 if (array_key_exists($segment . 'action', $moduleMethods)) {
                     $moduleAction = $segment;
                     break;
                 }
             }
             return self::MATCHRESULT_NOSUCHMODULE;
         }
         $level++;
     }
     if ($moduleController === null) {
         return self::MATCHRESULT_NOCONTROLLER;
     }
     $this->value = array('module' => implode('/', $modulePath), 'controller' => $moduleController, 'action' => $moduleAction);
     if ($format !== '') {
         $this->value['format'] = $format;
     }
     return self::MATCHRESULT_FOUND;
 }
 /**
  * Convert (and optionally filter) code coverage data generated by functional tests,
  * such that file references inside point not to the code cache inside Data/Temporary/....,
  * but to the Classes/ directory of the packages.
  *
  * <b>Example Usage:</b>
  * phpunit -c Build/BuildEssentials/FunctionalTests.xml --coverage-php Build/Reports/RawFunctionalTestCoverageReport.php
  * ./flow codeCoverage:convert Build/Reports/RawFunctionalTestCoverageReport.php Build/Reports/FunctionalTestCoverageReport.php --packages 'Your.Packages,Separated.By.Comma'
  *
  * The "--packages" argument is optional; but using it results in a huge speed boost;
  * as only the classes from the specified packages are included in the coverage result.
  *
  * @param string $codeCoverageFile Path to the code coverage file generated with "--coverage-php" of phpunit.
  * @param string $outFile Path to the converted code coverage file
  * @param string $packages The comma-separated list of packages to filter for. These packages must be installed here.
  * @param string $context The Flow context which has been used during the functional test run. Only needs to be modified if tests are ran in a special context.
  */
 public function convertCommand($codeCoverageFile, $outFile, $packages = '*', $context = 'Testing')
 {
     // Load $packages which should be taken into account while conversion
     $packageKeys = $packages;
     if ($packageKeys === '*') {
         $packages = $this->packageManager->getActivePackages();
     } else {
         $packages = array();
         foreach (\TYPO3\Flow\Utility\Arrays::trimExplode(',', $packageKeys) as $packageKey) {
             $packages[] = $this->packageManager->getPackage($packageKey);
         }
     }
     // For all $packages which should be used, build up a "cache-file-name" -> "real-file-name" mapping.
     $reverseIndexOfCacheFileNamesToClassFiles = array();
     foreach ($packages as $package) {
         /* @var $package \TYPO3\Flow\Package\PackageInterface */
         foreach ($package->getClassFiles() as $className => $fileName) {
             $cacheFileName = str_replace('\\', '_', $className);
             $reverseIndexOfCacheFileNamesToClassFiles[$cacheFileName] = $package->getPackagePath() . $fileName;
         }
     }
     // Modify the coverage report
     /* @var $coverage \Php_CodeCoverage */
     $coverage = unserialize(file_get_contents($codeCoverageFile));
     $coverageData = $coverage->getData();
     $baseDirectoryLength = strlen(FLOW_PATH_ROOT . 'Data/Temporary/' . $context . '/Cache/Code/Flow_Object_Classes/');
     $adjustedCoverageData = array();
     foreach ($coverageData as $fullCacheFileName => $coverageDataForFile) {
         $shortCacheFileName = substr($fullCacheFileName, $baseDirectoryLength, -4);
         if (isset($reverseIndexOfCacheFileNamesToClassFiles[$shortCacheFileName])) {
             $classFileInPackage = $reverseIndexOfCacheFileNamesToClassFiles[$shortCacheFileName];
             $numberOfLinesOfFile = count(file($classFileInPackage));
             if (isset($adjustedCoverageData[$classFileInPackage])) {
                 throw new \Sandstorm\Fuzzer\Exception('Coverage data already found for class file "' . $classFileInPackage . '". This should never happen; so we do not override it. It is probably a bug in Fuzzer.', 1367238729);
             }
             $adjustedCoverageData[$classFileInPackage] = array();
             foreach ($coverageDataForFile as $lineNumber => $coveredBy) {
                 if ($lineNumber <= $numberOfLinesOfFile) {
                     $adjustedCoverageData[$classFileInPackage][$lineNumber] = $coveredBy;
                 }
             }
         }
     }
     // Save the new coverage report
     $adjustedCoverage = new PhpunitCodeCoverage();
     $adjustedCoverage->setData($adjustedCoverageData);
     $adjustedCoverage->setTests($coverage->getTests());
     file_put_contents($outFile, serialize($adjustedCoverage));
 }
 /**
  * @param mixed $includeFields
  */
 public function setIncludeFields($includeFields)
 {
     if (is_array($includeFields)) {
         $includeFields = join(',', $includeFields);
     }
     $this->includeFields = array();
     if (is_string($includeFields)) {
         foreach (Arrays::trimExplode(',', $includeFields) as $includeField) {
             if (!$includeField) {
                 continue;
             }
             $this->includeFields[$includeField] = $includeField;
         }
     }
 }
 /**
  * @param mixed $sparseFields
  */
 public function setSparseFields($sparseFields)
 {
     if (is_array($sparseFields)) {
         $sparseFields = join(',', $sparseFields);
     }
     $this->sparseFields = array();
     if (is_string($sparseFields)) {
         foreach (Arrays::trimExplode(',', $sparseFields) as $sparseField) {
             if (!$sparseField) {
                 continue;
             }
             $this->sparseFields[$sparseField] = $sparseField;
         }
     }
 }
Example #7
0
 public function compileSchema()
 {
     $schema = (array) $this->configurationManager->getConfiguration('Expose', $this->className);
     SettingsValidator::validate($schema, $this->supportedClassSettings);
     if (isset($schema['properties'])) {
         foreach ($schema['properties'] as $propertyName => $propertySettings) {
             SettingsValidator::validate($propertySettings, $this->supportedPropertySettings);
         }
     }
     $arrayKeys = array('listProperties', 'searchProperties', 'filterProperties');
     foreach ($arrayKeys as $key) {
         if (isset($schema[$key]) && is_string($schema[$key])) {
             $schema[$key] = Arrays::trimExplode(',', $schema[$key]);
         }
     }
     return $schema;
 }
 /**
  * @param array $humanReadableContextProperties
  * @param boolean $addDimensionDefaults
  * @return \TYPO3\TYPO3CR\Domain\Service\Context
  */
 protected function getContextForProperties(array $humanReadableContextProperties, $addDimensionDefaults = FALSE)
 {
     /** @var \TYPO3\TYPO3CR\Domain\Service\ContextFactoryInterface $contextFactory */
     $contextFactory = $this->objectManager->get('TYPO3\\TYPO3CR\\Domain\\Service\\ContextFactoryInterface');
     $contextProperties = array();
     if (isset($humanReadableContextProperties['Locale'])) {
         $contextProperties['dimensions']['locales'] = array($humanReadableContextProperties['Locale'], 'mul_ZZ');
     }
     if (isset($humanReadableContextProperties['Locales'])) {
         $contextProperties['dimensions']['locales'] = Arrays::trimExplode(',', $humanReadableContextProperties['Locales']);
     }
     if (isset($humanReadableContextProperties['Workspace'])) {
         $contextProperties['workspaceName'] = $humanReadableContextProperties['Workspace'];
     }
     foreach ($humanReadableContextProperties as $propertyName => $propertyValue) {
         // Set flexible dimensions from features
         if (strpos($propertyName, 'Dimension: ') === 0) {
             $contextProperties['dimensions'][substr($propertyName, strlen('Dimension: '))] = Arrays::trimExplode(',', $propertyValue);
         }
         if (strpos($propertyName, 'Target dimension: ') === 0) {
             $contextProperties['targetDimensions'][substr($propertyName, strlen('Target dimension: '))] = $propertyValue;
         }
     }
     if ($addDimensionDefaults) {
         $contentDimensionRepository = $this->objectManager->get('TYPO3\\TYPO3CR\\Domain\\Repository\\ContentDimensionRepository');
         $availableDimensions = $contentDimensionRepository->findAll();
         foreach ($availableDimensions as $dimension) {
             if (isset($contextProperties['dimensions'][$dimension->getIdentifier()]) && !in_array($dimension->getDefault(), $contextProperties['dimensions'][$dimension->getIdentifier()])) {
                 $contextProperties['dimensions'][$dimension->getIdentifier()][] = $dimension->getDefault();
             }
         }
     }
     return $contextFactory->create($contextProperties);
 }
 /**
  * A method which runs the task implemented by the plugin for the given command
  *
  * @param string $controllerCommandName Name of the command in question, for example "repair"
  * @param ConsoleOutput $output An instance of ConsoleOutput which can be used for output or dialogues
  * @param NodeType $nodeType Only handle this node type (if specified)
  * @param string $workspaceName Only handle this workspace (if specified)
  * @param boolean $dryRun If TRUE, don't do any changes, just simulate what you would do
  * @param boolean $cleanup If FALSE, cleanup tasks are skipped
  * @param string $skip Skip the given check or checks (comma separated)
  * @param string $only Only execute the given check or checks (comma separated)
  * @return void
  */
 public function invokeSubCommand($controllerCommandName, ConsoleOutput $output, NodeType $nodeType = null, $workspaceName = 'live', $dryRun = false, $cleanup = true, $skip = null, $only = null)
 {
     $this->output = $output;
     $commandMethods = ['removeAbstractAndUndefinedNodes' => ['cleanup' => true], 'removeOrphanNodes' => ['cleanup' => true], 'removeDisallowedChildNodes' => ['cleanup' => true], 'removeUndefinedProperties' => ['cleanup' => true], 'removeBrokenEntityReferences' => ['cleanup' => true], 'removeNodesWithInvalidDimensions' => ['cleanup' => true], 'removeNodesWithInvalidWorkspace' => ['cleanup' => true], 'fixNodesWithInconsistentIdentifier' => ['cleanup' => false], 'createMissingChildNodes' => ['cleanup' => false], 'reorderChildNodes' => ['cleanup' => false], 'addMissingDefaultValues' => ['cleanup' => false], 'repairShadowNodes' => ['cleanup' => false]];
     $skipCommandNames = Arrays::trimExplode(',', $skip === null ? '' : $skip);
     $onlyCommandNames = Arrays::trimExplode(',', $only === null ? '' : $only);
     switch ($controllerCommandName) {
         case 'repair':
             foreach ($commandMethods as $commandMethodName => $commandMethodConfiguration) {
                 if (in_array($commandMethodName, $skipCommandNames)) {
                     continue;
                 }
                 if ($onlyCommandNames !== [] && !in_array($commandMethodName, $onlyCommandNames)) {
                     continue;
                 }
                 if (!$cleanup && $commandMethodConfiguration['cleanup']) {
                     continue;
                 }
                 $this->{$commandMethodName}($workspaceName, $dryRun, $nodeType);
             }
     }
 }
 /**
  *
  *
  * @param array $humanReadableContextProperties
  * @param boolean $addDimensionDefaults
  * @return \TYPO3\TYPO3CR\Domain\Service\Context
  * @throws Exception
  */
 protected function getContextForProperties(array $humanReadableContextProperties, $addDimensionDefaults = false)
 {
     if ($this->isolated === true) {
         $this->callStepInSubProcess(__METHOD__, sprintf(' %s %s %s %s', 'string', escapeshellarg($humanReadableContextProperties), 'integer', escapeshellarg($addDimensionDefaults)));
     } else {
         /** @var \TYPO3\TYPO3CR\Domain\Service\ContextFactoryInterface $contextFactory */
         $contextFactory = $this->getObjectManager()->get('TYPO3\\TYPO3CR\\Domain\\Service\\ContextFactoryInterface');
         $contextProperties = array();
         if (isset($humanReadableContextProperties['Language'])) {
             $contextProperties['dimensions']['language'] = array($humanReadableContextProperties['Language'], 'mul_ZZ');
         }
         if (isset($humanReadableContextProperties['Language'])) {
             $contextProperties['dimensions']['language'] = Arrays::trimExplode(',', $humanReadableContextProperties['Language']);
         }
         if (isset($humanReadableContextProperties['Workspace'])) {
             $contextProperties['workspaceName'] = $humanReadableContextProperties['Workspace'];
             $this->createWorkspaceIfNeeded($contextProperties['workspaceName']);
         } else {
             $this->createWorkspaceIfNeeded();
         }
         foreach ($humanReadableContextProperties as $propertyName => $propertyValue) {
             // Set flexible dimensions from features
             if (strpos($propertyName, 'Dimension: ') === 0) {
                 $contextProperties['dimensions'][substr($propertyName, strlen('Dimension: '))] = Arrays::trimExplode(',', $propertyValue);
             }
             if (strpos($propertyName, 'Target dimension: ') === 0) {
                 $contextProperties['targetDimensions'][substr($propertyName, strlen('Target dimension: '))] = $propertyValue;
             }
         }
         if ($addDimensionDefaults) {
             $contentDimensionRepository = $this->getObjectManager()->get('TYPO3\\TYPO3CR\\Domain\\Repository\\ContentDimensionRepository');
             $availableDimensions = $contentDimensionRepository->findAll();
             foreach ($availableDimensions as $dimension) {
                 if (isset($contextProperties['dimensions'][$dimension->getIdentifier()]) && !in_array($dimension->getDefault(), $contextProperties['dimensions'][$dimension->getIdentifier()])) {
                     $contextProperties['dimensions'][$dimension->getIdentifier()][] = $dimension->getDefault();
                 }
             }
         }
         return $contextFactory->create($contextProperties);
     }
 }
 /**
  * Shows a list of all defined privilege targets and the effective permissions
  *
  * @param string $privilegeType The privilege type ("entity", "method" or the FQN of a class implementing PrivilegeInterface)
  * @param string $roles A comma separated list of role identifiers. Shows policy for an unauthenticated user when left empty.
  */
 public function showEffectivePolicyCommand($privilegeType, $roles = '')
 {
     $systemRoleIdentifiers = array('TYPO3.Flow:Everybody', 'TYPO3.Flow:Anonymous', 'TYPO3.Flow:AuthenticatedUser');
     if (strpos($privilegeType, '\\') === false) {
         $privilegeType = sprintf('\\TYPO3\\Flow\\Security\\Authorization\\Privilege\\%s\\%sPrivilegeInterface', ucfirst($privilegeType), ucfirst($privilegeType));
     }
     if (!class_exists($privilegeType) && !interface_exists($privilegeType)) {
         $this->outputLine('The privilege type "%s" was not defined.', array($privilegeType));
         $this->quit(1);
     }
     if (!is_subclass_of($privilegeType, PrivilegeInterface::class)) {
         $this->outputLine('"%s" does not refer to a valid Privilege', array($privilegeType));
         $this->quit(1);
     }
     $requestedRoles = array();
     foreach (Arrays::trimExplode(',', $roles) as $roleIdentifier) {
         try {
             if (in_array($roleIdentifier, $systemRoleIdentifiers)) {
                 continue;
             }
             $currentRole = $this->policyService->getRole($roleIdentifier);
             $requestedRoles[$roleIdentifier] = $currentRole;
             foreach ($currentRole->getAllParentRoles() as $currentParentRole) {
                 if (!in_array($currentParentRole, $requestedRoles)) {
                     $requestedRoles[$currentParentRole->getIdentifier()] = $currentParentRole;
                 }
             }
         } catch (NoSuchRoleException $exception) {
             $this->outputLine('The role %s was not defined.', array($roleIdentifier));
             $this->quit(1);
         }
     }
     if (count($requestedRoles) > 0) {
         $requestedRoles['TYPO3.Flow:AuthenticatedUser'] = $this->policyService->getRole('TYPO3.Flow:AuthenticatedUser');
     } else {
         $requestedRoles['TYPO3.Flow:Anonymous'] = $this->policyService->getRole('TYPO3.Flow:Anonymous');
     }
     $requestedRoles['TYPO3.Flow:Everybody'] = $this->policyService->getRole('TYPO3.Flow:Everybody');
     $this->outputLine('Effective Permissions for the roles <b>%s</b> ', array(implode(', ', $requestedRoles)));
     $this->outputLine(str_repeat('-', $this->output->getMaximumLineLength()));
     $definedPrivileges = $this->policyService->getAllPrivilegesByType($privilegeType);
     $permissions = array();
     /** @var PrivilegeInterface $definedPrivilege */
     foreach ($definedPrivileges as $definedPrivilege) {
         $accessGrants = 0;
         $accessDenies = 0;
         $permission = 'ABSTAIN';
         /** @var Role $requestedRole */
         foreach ($requestedRoles as $requestedRole) {
             $privilegeType = $requestedRole->getPrivilegeForTarget($definedPrivilege->getPrivilegeTarget()->getIdentifier());
             if ($privilegeType === null) {
                 continue;
             }
             if ($privilegeType->isGranted()) {
                 $accessGrants++;
             } elseif ($privilegeType->isDenied()) {
                 $accessDenies++;
             }
         }
         if ($accessDenies > 0) {
             $permission = '<error>DENY</error>';
         }
         if ($accessGrants > 0 && $accessDenies === 0) {
             $permission = '<success>GRANT</success>';
         }
         $permissions[$definedPrivilege->getPrivilegeTarget()->getIdentifier()] = $permission;
     }
     ksort($permissions);
     foreach ($permissions as $privilegeTargetIdentifier => $permission) {
         $formattedPrivilegeTargetIdentifier = wordwrap($privilegeTargetIdentifier, $this->output->getMaximumLineLength() - 10, PHP_EOL . str_repeat(' ', 10), true);
         $this->outputLine('%-70s %s', array($formattedPrivilegeTargetIdentifier, $permission));
     }
 }
Example #12
0
 /**
  *
  */
 public function initializeAction()
 {
     $this->relationshipIterator->setSupportedMediaTypes($this->supportedMediaTypes);
     if ($this->request->hasArgument('include')) {
         $include = Arrays::trimExplode(',', $this->request->getArgument('include'));
         $this->relationshipIterator->setInclude($include);
     }
     if ($this->request->hasArgument('fields')) {
         $fields = array();
         foreach ((array) $this->request->getArgument('fields') as $typeName => $fieldsList) {
             $fields[$typeName] = Arrays::trimExplode(',', $fieldsList);
         }
         $this->relationshipIterator->setFields($fields);
     }
 }
 /**
  * @Then /^I can (not )?call the method "([^"]*)" of class "([^"]*)"(?: with arguments "([^"]*)")?$/
  */
 public function iCanCallTheMethodOfClassWithArguments($not, $methodName, $className, $arguments = '')
 {
     if ($this->isolated === true) {
         $this->callStepInSubProcess(__METHOD__, sprintf(' %s %s %s %s %s %s %s %s', 'string', escapeshellarg(trim($not)), 'string', escapeshellarg($methodName), 'string', escapeshellarg($className), 'string', escapeshellarg($arguments)));
     } else {
         $this->setupSecurity();
         $instance = $this->objectManager->get($className);
         try {
             $result = call_user_func_array(array($instance, $methodName), Arrays::trimExplode(',', $arguments));
             if ($not === 'not') {
                 Assert::fail('Method should not be callable');
             }
             return $result;
         } catch (\TYPO3\Flow\Security\Exception\AccessDeniedException $exception) {
             if ($not !== 'not') {
                 throw $exception;
             }
         }
     }
 }
 /**
  * Updates the given news object
  *
  * @param \Lelesys\Plugin\News\Domain\Model\News $news The news to update
  * @param array $media  News media
  * @param array $file News file
  * @param array $tags News tags
  * @param array $relatedLink News related links
  * @return void
  */
 public function update(\Lelesys\Plugin\News\Domain\Model\News $news, $media, $file, $relatedLink, $tags)
 {
     if (!empty($tags['title'])) {
         $tagsArray = array_unique(\TYPO3\Flow\Utility\Arrays::trimExplode(',', strtolower($tags['title'])));
         foreach ($tagsArray as $tag) {
             $existTag = $this->tagService->findTagByName($tag);
             if (!empty($existTag)) {
                 $newsTags = $news->getTags()->toArray();
                 if (!in_array($existTag, $newsTags)) {
                     $news->addTags($existTag);
                 }
             } else {
                 $newTag = new \Lelesys\Plugin\News\Domain\Model\Tag();
                 $newTag->setTitle($tag);
                 $this->tagService->create($newTag);
                 $news->addTags($newTag);
             }
         }
     }
     $news->setUpdatedDate(new \DateTime());
     $mediaPath = $media;
     foreach ($mediaPath as $mediaSource) {
         if (!empty($mediaSource['uuid'])) {
             $updateAsset = $this->propertyMapper->convert($mediaSource['uuid']['__identity'], '\\TYPO3\\Media\\Domain\\Model\\Image');
             $updateAsset->setCaption($mediaSource['caption']);
             $this->imageRepository->update($updateAsset);
         } else {
             if (!empty($mediaSource['resource']['name'])) {
                 $resource = $this->propertyMapper->convert($mediaSource['resource'], 'TYPO3\\Flow\\Resource\\Resource');
                 $media = new \TYPO3\Media\Domain\Model\Image($resource);
                 $media->setCaption($mediaSource['caption']);
                 $this->imageRepository->add($media);
                 $news->addAssets($media);
             }
         }
     }
     $filePath = $file;
     foreach ($filePath as $fileSource) {
         if (isset($fileSource['uuid'])) {
             $updateFile = $this->propertyMapper->convert($fileSource['uuid']['__identity'], '\\TYPO3\\Media\\Domain\\Model\\Document');
             $updateFile->setTitle($fileSource['title']);
             $this->assetRepository->update($updateFile);
         } else {
             if (!empty($fileSource['resource']['name'])) {
                 $resource = $this->propertyMapper->convert($fileSource['resource'], 'TYPO3\\Flow\\Resource\\Resource');
                 $file = new \TYPO3\Media\Domain\Model\Document($resource);
                 $file->setTitle($fileSource['title']);
                 $this->assetRepository->add($file);
                 $news->addFiles($file);
             }
         }
     }
     $related = $relatedLink;
     foreach ($related as $link) {
         if (isset($link['uuid'])) {
             $updateLink = $this->linkService->findById($link['uuid']);
             $updateLink->setUri($link['relatedUri']);
             $updateLink->setTitle($link['relatedUriTitle']);
             $updateLink->setDescription($link['relatedUriDescription']);
             $updateLink->setHidden($link['hidden']);
             $this->linkService->update($updateLink);
         } else {
             if (!empty($link['relatedUri'])) {
                 $newLink = new \Lelesys\Plugin\News\Domain\Model\Link();
                 $newLink->setTitle($link['relatedUriTitle']);
                 $newLink->setUri($link['relatedUri']);
                 $newLink->setDescription($link['relatedUriDescription']);
                 $newLink->setHidden($link['hidden']);
                 $this->linkService->create($newLink);
                 $news->addRelatedLinks($newLink);
             }
         }
     }
     $this->newsRepository->update($news);
     $this->emitNewsUpdated($news);
 }
 /**
  * @Given /^the following users exist:$/
  */
 public function theFollowingUsersExist(TableNode $table)
 {
     $rows = $table->getHash();
     /** @var \TYPO3\Neos\Domain\Service\UserService $userService */
     $userService = $this->objectManager->get(\TYPO3\Neos\Domain\Service\UserService::class);
     /** @var \TYPO3\Party\Domain\Repository\PartyRepository $partyRepository */
     $partyRepository = $this->objectManager->get(\TYPO3\Party\Domain\Repository\PartyRepository::class);
     /** @var \TYPO3\Flow\Security\AccountRepository $accountRepository */
     $accountRepository = $this->objectManager->get(\TYPO3\Flow\Security\AccountRepository::class);
     foreach ($rows as $row) {
         $roleIdentifiers = array_map(function ($role) {
             return 'TYPO3.Neos:' . $role;
         }, Arrays::trimExplode(',', $row['roles']));
         $userService->createUser($row['username'], $row['password'], $row['firstname'], $row['lastname'], $roleIdentifiers);
     }
     $this->getSubcontext('flow')->persistAll();
 }
 /**
  * @param string $assertionStepsString
  */
 public function setAssertionStepsString($assertionStepsString)
 {
     $this->assertionSteps = \TYPO3\Flow\Utility\Arrays::trimExplode(',', $assertionStepsString, TRUE);
 }
 /**
  * Batch process of the given preset
  *
  * @param string $preset
  * @param string $parts
  */
 public function batchCommand($preset, $parts = NULL)
 {
     $this->startTime = microtime(TRUE);
     $parts = Arrays::trimExplode(',', $parts);
     $this->outputLine('Start import ...');
     $logPrefix = Algorithms::generateRandomString(12);
     $presetSettings = Arrays::getValueByPath($this->settings, array('presets', $preset));
     if (!is_array($presetSettings)) {
         $this->outputLine(sprintf('Preset "%s" not found ...', $preset));
         $this->quit(1);
     }
     array_walk($presetSettings, function ($partSetting, $partName) use($preset, $logPrefix, $parts) {
         $this->elapsedTime = 0;
         $this->batchCounter = 0;
         $this->outputLine();
         $this->outputFormatted(sprintf('<b>%s</b>', $partSetting['label']));
         $partSetting['__currentPresetName'] = $preset;
         $partSetting['__currentPartName'] = $partName;
         $partSetting = new PresetPartDefinition($partSetting, $logPrefix);
         if ($parts !== array() && !in_array($partName, $parts)) {
             $this->outputLine('Skipped');
             return;
         }
         if ($partSetting->getBatchSize()) {
             while (($count = $this->executeCommand($partSetting)) > 0) {
                 $partSetting->nextBatch();
             }
         } else {
             $this->executeCommand($partSetting);
         }
     });
     $this->outputLine();
     $this->outputLine('Import finished');
 }
 /**
  * @param string $serializedLocation
  * @return array
  */
 public function parseString($serializedLocation)
 {
     $location = Arrays::trimExplode(',', $serializedLocation);
     return ['latitude' => (double) $location[0], 'longitude' => (double) $location[1]];
 }
 /**
  * A method which runs the task implemented by the plugin for the given command
  *
  * @param string $controllerCommandName Name of the command in question, for example "repair"
  * @param ConsoleOutput $output An instance of ConsoleOutput which can be used for output or dialogues
  * @param NodeType $nodeType Only handle this node type (if specified)
  * @param string $workspaceName Only handle this workspace (if specified)
  * @param boolean $dryRun If TRUE, don't do any changes, just simulate what you would do
  * @param boolean $cleanup If FALSE, cleanup tasks are skipped
  * @param string $skip Skip the given check or checks (comma separated)
  * @param string $only Only execute the given check or checks (comma separated)
  * @return void
  */
 public function invokeSubCommand($controllerCommandName, ConsoleOutput $output, NodeType $nodeType = null, $workspaceName = 'live', $dryRun = false, $cleanup = true, $skip = null, $only = null)
 {
     $this->output = $output;
     $commandMethods = ['generateUriPathSegments' => ['cleanup' => false], 'removeContentDimensionsFromRootAndSitesNode' => ['cleanup' => true]];
     $skipCommandNames = Arrays::trimExplode(',', $skip === null ? '' : $skip);
     $onlyCommandNames = Arrays::trimExplode(',', $only === null ? '' : $only);
     switch ($controllerCommandName) {
         case 'repair':
             foreach ($commandMethods as $commandMethodName => $commandMethodConfiguration) {
                 if (in_array($commandMethodName, $skipCommandNames)) {
                     continue;
                 }
                 if ($onlyCommandNames !== [] && !in_array($commandMethodName, $onlyCommandNames)) {
                     continue;
                 }
                 if (!$cleanup && $commandMethodConfiguration['cleanup']) {
                     continue;
                 }
                 $this->{$commandMethodName}($workspaceName, $dryRun, $nodeType);
             }
     }
 }
Example #20
0
 /**
  * Outputs a table for given search result
  *
  * @param resource $connection
  * @param resource $searchResult
  * @param $displayColumns
  * @return void
  */
 protected function outputLdapSearchResultTable($connection, $searchResult, $displayColumns)
 {
     $headers = [];
     $rows = [];
     $displayColumns = Arrays::trimExplode(',', $displayColumns);
     $entries = ldap_get_entries($connection, $searchResult);
     $this->outputLine('%s results found', [$entries['count']]);
     foreach ($entries as $index => $ldapSearchResult) {
         if ($index === 'count') {
             continue;
         }
         if ($headers === []) {
             foreach ($ldapSearchResult as $propertyName => $propertyValue) {
                 if (is_integer($propertyName)) {
                     continue;
                 }
                 if ($displayColumns === null || in_array($propertyName, $displayColumns)) {
                     $headers[] = $propertyName;
                 }
             }
         }
         $row = [];
         foreach ($ldapSearchResult as $propertyName => $propertyValue) {
             if (is_integer($propertyName)) {
                 continue;
             }
             if ($displayColumns !== null && !in_array($propertyName, $displayColumns)) {
                 continue;
             }
             if (isset($propertyValue['count'])) {
                 unset($propertyValue['count']);
             }
             if (is_array($propertyValue)) {
                 $row[$propertyName] = implode(", ", $propertyValue);
             } else {
                 $row[$propertyName] = $propertyValue;
             }
         }
         $rows[] = $row;
     }
     $this->output->outputTable($rows, $headers);
 }
Example #21
0
 /**
  * This method is called when the form of this step has been submitted
  *
  * @param array $formValues
  * @return void
  */
 public function postProcessFormValues(array $formValues)
 {
     $settings = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Lightwerk.SurfCaptain');
     $driver = $settings['sources']['default']['driver'];
     $repositories = Arrays::trimExplode(',', $formValues['repositories']);
     // reset
     $this->distributionSettings['Lightwerk']['SurfCaptain']['sources']['default']['repositories'] = array();
     for ($i = 0; $i < count($repositories); $i++) {
         $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.repositories.' . $i, $repositories[$i]);
     }
     $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.privateToken', $formValues['privateToken']);
     switch ($driver) {
         case 'GitHub':
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.accountName', '*****@*****.**');
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.apiUrl', 'https://api.github.com/');
             break;
         case 'GitLab':
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.accountName', $formValues['accountName']);
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.apiUrl', $formValues['apiUrl']);
             break;
         case 'BitBucket':
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.accountName', $formValues['accountName']);
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.apiUrl', 'https://api.bitbucket.org/2.0/');
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.fallbackApiUrl', 'https://api.bitbucket.org/1.0/');
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.privateSecret', $formValues['privateSecret']);
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.accessToken', $formValues['accessToken']);
             $this->distributionSettings = Arrays::setValueByPath($this->distributionSettings, 'Lightwerk.SurfCaptain.sources.default.accessSecret', $formValues['accessSecret']);
             break;
         default:
             throw new SetupException('Unknown driver ' . $driver, 1427623122);
     }
     $this->configurationSource->save(FLOW_PATH_CONFIGURATION . ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, $this->distributionSettings);
 }
 /**
  * Kickstart a new command controller
  *
  * Creates a new command controller with the given name in the specified
  * package. The generated controller class already contains an example command.
  *
  * @param string $packageKey The package key of the package for the new controller
  * @param string $controllerName The name for the new controller. This may also be a comma separated list of controller names.
  * @param boolean $force Overwrite any existing controller.
  * @return string
  * @see typo3.kickstart:kickstart:actioncontroller
  */
 public function commandControllerCommand($packageKey, $controllerName, $force = FALSE)
 {
     $this->validatePackageKey($packageKey);
     if (!$this->packageManager->isPackageAvailable($packageKey)) {
         $this->outputLine('Package "%s" is not available.', array($packageKey));
         exit(2);
     }
     $generatedFiles = array();
     $controllerNames = \TYPO3\Flow\Utility\Arrays::trimExplode(',', $controllerName);
     foreach ($controllerNames as $currentControllerName) {
         $generatedFiles += $this->generatorService->generateCommandController($packageKey, $currentControllerName, $force);
     }
     $this->outputLine(implode(PHP_EOL, $generatedFiles));
 }
 /**
  * Returns an array of packages that are available for translation.
  *
  * The list includes basically every active package
  * - minus the ones that are excluded in the configuration
  * - minus the ones that don't have the needed translation files
  *
  * @return array all the available packages
  */
 protected function getAvailablePackages()
 {
     $allPackages = $this->packageManager->getActivePackages();
     // make sure the packages of the framework are excluded depending on our settings
     $packages = array();
     $packagesToExclude = \TYPO3\Flow\Utility\Arrays::trimExplode(',', $this->settings['packagesToExclude']);
     foreach ($allPackages as $package) {
         if (!in_array($package->getPackageKey(), $packagesToExclude) && $this->hasXliffFilesInDefaultDirectories($package)) {
             $packages[] = $package;
         }
     }
     return $packages;
 }
 /**
  * @param QueryInterface $query
  * @param $nodeTypeFilter
  * @return array
  */
 protected function getNodeTypeFilterConstraints(QueryInterface $query, $nodeTypeFilter)
 {
     $includeNodeTypeConstraints = array();
     $excludeNodeTypeConstraints = array();
     $nodeTypeFilterParts = Arrays::trimExplode(',', $nodeTypeFilter);
     foreach ($nodeTypeFilterParts as $nodeTypeFilterPart) {
         $nodeTypeFilterPart = trim($nodeTypeFilterPart);
         if (strpos($nodeTypeFilterPart, '!') === 0) {
             $negate = true;
             $nodeTypeFilterPart = substr($nodeTypeFilterPart, 1);
         } else {
             $negate = false;
         }
         $nodeTypeFilterPartSubTypes = array_merge(array($nodeTypeFilterPart), $this->nodeTypeManager->getSubNodeTypes($nodeTypeFilterPart, false));
         foreach ($nodeTypeFilterPartSubTypes as $nodeTypeFilterPartSubType) {
             if ($negate === true) {
                 $excludeNodeTypeConstraints[] = $query->logicalNot($query->equals('nodeType', $nodeTypeFilterPartSubType));
             } else {
                 $includeNodeTypeConstraints[] = $query->equals('nodeType', $nodeTypeFilterPartSubType);
             }
         }
     }
     $constraints = $excludeNodeTypeConstraints;
     if (count($includeNodeTypeConstraints) > 0) {
         $constraints[] = $query->logicalOr($includeNodeTypeConstraints);
     }
     return $constraints;
 }
Example #25
0
 /**
  * Updates the profile given in $profileFilename with the tags given in
  * $tagList (comma-separated tags) and return the tags rendered as HTML.
  *
  * @param string $profileFilename
  * @param string $tagList
  * @return string
  */
 public function updateTagsAction($profileFilename, $tagList)
 {
     $profile = $this->getProfile($profileFilename);
     $tags = \TYPO3\Flow\Utility\Arrays::trimExplode(',', $tagList);
     $profile->setTags($tags);
     $profile->save();
     return $this->renderTagsService->render($tags);
 }
 /**
  * @param string $message
  * @throws \Exception
  * @return array
  */
 protected function extractReleases($message)
 {
     $pattern = '/Releases:\\s*(.*)/';
     preg_match($pattern, $message, $matches);
     if (!isset($matches[1])) {
         return ['omitted'];
     }
     /**
      * fix Stuff
      */
     if (strstr($matches[1], 'master.')) {
         $matches[1] = str_replace('master.', 'master,', $matches[1]);
     }
     if (strstr($matches[1], '4.7.')) {
         $matches[1] = str_replace('4.7.', '4.7,', $matches[1]);
     }
     if (strstr($matches[1], '4.5 LTS')) {
         $matches[1] = str_replace('4.5 LTS', '4.5', $matches[1]);
     }
     $releaseArray = Utility\Arrays::trimExplode(',', $matches[1]);
     foreach ($releaseArray as $key => $release) {
         if (strstr($release, ' ')) {
             \TYPO3\Flow\var_dump($releaseArray);
             throw new \Exception('Release contains space?');
         }
         $releaseArray[$key] = $release;
     }
     return $releaseArray;
 }
 /**
  *
  *
  * @param array $humanReadableContextProperties
  * @param boolean $addDimensionDefaults
  * @return \TYPO3\TYPO3CR\Domain\Service\Context
  * @throws Exception
  */
 protected function getContextForProperties(array $humanReadableContextProperties, $addDimensionDefaults = false)
 {
     if ($this->isolated === true) {
         $this->callStepInSubProcess(__METHOD__, sprintf(' %s %s %s %s', 'string', escapeshellarg($humanReadableContextProperties), 'integer', escapeshellarg($addDimensionDefaults)));
     } else {
         /** @var \TYPO3\TYPO3CR\Domain\Service\ContextFactoryInterface $contextFactory */
         $contextFactory = $this->getObjectManager()->get(\TYPO3\TYPO3CR\Domain\Service\ContextFactoryInterface::class);
         $contextProperties = array();
         if (isset($humanReadableContextProperties['Language'])) {
             $contextProperties['dimensions']['language'] = Arrays::trimExplode(',', $humanReadableContextProperties['Language']);
         }
         if (isset($humanReadableContextProperties['Workspace'])) {
             $contextProperties['workspaceName'] = $humanReadableContextProperties['Workspace'];
             $this->createWorkspaceIfNeeded($contextProperties['workspaceName']);
         } else {
             $this->createWorkspaceIfNeeded();
         }
         if (isset($humanReadableContextProperties['Hidden'])) {
             $contextProperties['hidden'] = $humanReadableContextProperties['Hidden'];
         }
         foreach ($humanReadableContextProperties as $propertyName => $propertyValue) {
             // Set flexible dimensions from features
             if (strpos($propertyName, 'Dimension: ') === 0) {
                 $contextProperties['dimensions'][substr($propertyName, strlen('Dimension: '))] = Arrays::trimExplode(',', $propertyValue);
             }
             // FIXME We lack a good API to manipulate dimension values explicitly or assign multiple values, so we are doing this via target dimension values
             if (strpos($propertyName, 'Target dimension: ') === 0) {
                 if ($propertyValue === '') {
                     $propertyValue = null;
                 }
                 $contextProperties['targetDimensions'][substr($propertyName, strlen('Target dimension: '))] = $propertyValue;
             }
         }
         if ($addDimensionDefaults) {
             $contentDimensionRepository = $this->getObjectManager()->get(\TYPO3\TYPO3CR\Domain\Repository\ContentDimensionRepository::class);
             $availableDimensions = $contentDimensionRepository->findAll();
             foreach ($availableDimensions as $dimension) {
                 if (isset($contextProperties['dimensions'][$dimension->getIdentifier()]) && !in_array($dimension->getDefault(), $contextProperties['dimensions'][$dimension->getIdentifier()])) {
                     $contextProperties['dimensions'][$dimension->getIdentifier()][] = $dimension->getDefault();
                 }
             }
         }
         $contextProperties['invisibleContentShown'] = true;
         return $contextFactory->create($contextProperties);
     }
 }
 /**
  * @When /^I create the following accounts:$/
  */
 public function iCreateTheFollowingAccounts(TableNode $table)
 {
     foreach ($table->getHash() as $row) {
         $user = $this->getObjectManager()->get(UserService::class)->createUser($row['User'], $row['Password'], $row['First Name'], $row['Last Name'], Arrays::trimExplode(',', $row['Roles']));
     }
     $this->getSubcontext('flow')->persistAll();
 }
 /**
  * Call an arbitrary method and return the result - or "EXCEPTION: <exception-code>" if an exception occurred
  *
  * @Flow\Internal
  * @param string $className The fully qualified class name
  * @param string $methodName The method to call
  * @param string $parameters Comma-separated list of method arguments
  */
 public function callMethodCommand($className, $methodName, $parameters = '')
 {
     $instance = $this->objectManager->get($className);
     try {
         $result = call_user_func_array(array($instance, $methodName), Arrays::trimExplode(',', $parameters));
     } catch (\Exception $exception) {
         $this->outputLine('EXCEPTION: %s', array($exception->getCode()));
         return;
     }
     $this->output('SUCCESS: %s', array($result));
 }