/**
  * @param Schema $schema
  * @return void
  */
 public function down(Schema $schema)
 {
     $this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP CONSTRAINT fk_30ab3a75b684c08");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event DROP CONSTRAINT typo3_neos_eventlog_domain_model_event_pkey");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD persistence_object_identifier VARCHAR(40) NULL");
     $result = $this->connection->executeQuery("SELECT installed_version FROM pg_available_extensions WHERE name = 'uuid-ossp'");
     if ($result->fetchColumn() !== null) {
         $this->addSql("UPDATE typo3_neos_eventlog_domain_model_event SET persistence_object_identifier = uuid_generate_v4()");
     } else {
         $result = $this->connection->executeQuery("SELECT uid FROM typo3_neos_eventlog_domain_model_event");
         while ($uid = $result->fetchColumn()) {
             $this->addSql("UPDATE typo3_neos_eventlog_domain_model_event SET persistence_object_identifier = '" . \Neos\Flow\Utility\Algorithms::generateUUID() . "' WHERE uid = " . $uid);
         }
     }
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER COLUMN persistence_object_identifier SET NOT NULL");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER uid DROP NOT NULL");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER parentevent TYPE VARCHAR(40) USING (parentevent::varchar)");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER parentevent DROP DEFAULT");
     $this->addSql("WITH p AS (SELECT DISTINCT uid, persistence_object_identifier FROM typo3_neos_eventlog_domain_model_event) UPDATE typo3_neos_eventlog_domain_model_event SET parentevent = p.persistence_object_identifier FROM p WHERE parentevent IS NOT NULL AND p.uid = parentevent::integer");
     $this->addSql("SELECT setval('typo3_neos_eventlog_domain_model_event_uid_seq', (SELECT MAX(uid) FROM typo3_neos_eventlog_domain_model_event)+1);");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ALTER uid SET DEFAULT nextval('typo3_neos_eventlog_domain_model_event_uid_seq')");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD PRIMARY KEY (persistence_object_identifier)");
     $this->addSql("ALTER TABLE typo3_neos_eventlog_domain_model_event ADD CONSTRAINT fk_30ab3a75b684c08 FOREIGN KEY (parentevent) REFERENCES typo3_neos_eventlog_domain_model_event (persistence_object_identifier) NOT DEFERRABLE INITIALLY IMMEDIATE");
 }
 /**
  * Redirects to the Neos backend on the given site, passing a one-time login token
  *
  * @param Site $site
  * @return void
  */
 public function switchSiteAction($site)
 {
     $token = Algorithms::generateRandomToken(32);
     $this->loginTokenCache->set($token, $this->currentSession->getId());
     $siteUri = $this->linkingService->createSiteUri($this->controllerContext, $site);
     $loginUri = $this->controllerContext->getUriBuilder()->reset()->uriFor('tokenLogin', ['token' => $token], 'Login', 'Neos.Neos');
     $this->redirectToUri($siteUri . $loginUri);
 }
 /**
  * Generates a new key & saves it encrypted with a hashing strategy
  *
  * @param string $name
  * @return string
  * @throws SecurityException
  */
 public function generateKey($name)
 {
     if (strlen($name) === 0) {
         throw new SecurityException('Required name argument was empty', 1334215474);
     }
     $password = UtilityAlgorithms::generateRandomString($this->passwordGenerationLength);
     $this->persistKey($name, $password);
     return $password;
 }
예제 #4
0
 /**
  * Generate a Token and assign it the given $identifier.
  *
  * A $presetName can be given to use a specific configuration preset. The given $meta data
  * will be stored with the Token and can be retrieved again when validation of the token
  * is done and was successful.
  *
  * @param string $identifier
  * @param string $presetName
  * @param array $meta
  * @return Token
  */
 public function generateToken($identifier, $presetName = 'default', array $meta = [])
 {
     $preset = $this->getPreset($presetName);
     $tokenHash = Algorithms::generateRandomToken($preset['tokenLength']);
     $this->tokenCache->set($tokenHash, ['identifier' => $identifier, 'presetName' => $presetName, 'meta' => $meta], [md5($identifier)], $preset['lifetime']);
     $expiryTime = new \DateTime(sprintf('now +%s seconds', $preset['lifetime']));
     $this->logger->log(sprintf('Token with hash %s generated for identifier %s (valid until %s) [%s]', $tokenHash, $identifier, $expiryTime->format('Y-m-d H:i:s'), $presetName), LOG_INFO);
     return new Token($tokenHash, $identifier, $preset, $meta);
 }
 /**
  * Generate UUIDs in PHP if the uuid-ossp extension is not installed.
  *
  * @param Schema $schema
  * @return void
  */
 public function preDown(Schema $schema)
 {
     $result = $this->connection->executeQuery("SELECT installed_version FROM pg_available_extensions WHERE name = 'uuid-ossp'");
     if ($result->fetchColumn() === null) {
         $this->connection->executeUpdate("ALTER TABLE typo3_typo3cr_domain_model_workspace ADD persistence_object_identifier VARCHAR(40)");
         $result = $this->connection->executeQuery('SELECT name FROM typo3_typo3cr_domain_model_workspace');
         foreach ($result->fetchAll() as $workspace) {
             $this->connection->update('typo3_typo3cr_domain_model_workspace', array('persistence_object_identifier' => \Neos\Flow\Utility\Algorithms::generateUUID()), array('name' => $workspace['name']));
         }
     }
 }
예제 #6
0
 /**
  * @inheritdoc
  */
 public function submit($payload, array $options = [])
 {
     $this->checkClientConnection();
     $messageId = Algorithms::generateUUID();
     $idStored = $this->client->hSet("queue:{$this->name}:ids", $messageId, json_encode($payload));
     if ($idStored === 0) {
         return null;
     }
     $this->client->lPush("queue:{$this->name}:messages", $messageId);
     return $messageId;
 }
예제 #7
0
 /**
  * @inheritdoc
  */
 public function submit($payload, array $options = [])
 {
     $messageId = Algorithms::generateUUID();
     $message = new Message($messageId, $payload);
     $commandArguments = [$this->name, base64_encode(serialize($message))];
     if ($this->async) {
         if (!method_exists(Scripts::class, 'executeCommandAsync')) {
             throw new \RuntimeException('The "async" flag is set, but the currently used Flow version doesn\'t support this (Flow 3.3+ is required)', 1469116604);
         }
         Scripts::executeCommandAsync('flowpack.jobqueue.common:job:execute', $this->flowSettings, $commandArguments);
     } else {
         Scripts::executeCommand('flowpack.jobqueue.common:job:execute', $this->flowSettings, true, $commandArguments);
     }
     return $messageId;
 }
예제 #8
0
 /**
  * Constructs this node data container
  *
  * Creating new nodes by instantiating NodeData is not part of the public API!
  * The content repository needs to properly integrate new nodes into the node
  * tree and therefore you must use createNode() or createNodeFromTemplate()
  * in a Node object which will internally create a NodeData object.
  *
  * @param string $path Absolute path of this node
  * @param Workspace $workspace The workspace this node will be contained in
  * @param string $identifier The node identifier (not the persistence object identifier!). Specifying this only makes sense while creating corresponding nodes
  * @param array $dimensions An array of dimension name to dimension values
  */
 public function __construct($path, Workspace $workspace, $identifier = null, array $dimensions = null)
 {
     parent::__construct();
     $this->creationDateTime = new \DateTime();
     $this->lastModificationDateTime = new \DateTime();
     $this->setPath($path, false);
     $this->workspace = $workspace;
     $this->identifier = $identifier === null ? Algorithms::generateUUID() : $identifier;
     $this->dimensions = new ArrayCollection();
     if ($dimensions !== null) {
         foreach ($dimensions as $dimensionName => $dimensionValues) {
             foreach ($dimensionValues as $dimensionValue) {
                 $this->dimensions->add(new NodeDimension($this, $dimensionName, $dimensionValue));
             }
         }
     }
     $this->buildDimensionValues();
 }
예제 #9
0
 /**
  * Generates and propagates a new session ID and transfers all existing data
  * to the new session.
  *
  * @return string The new session ID
  * @throws Exception\SessionNotStartedException
  * @throws Exception\OperationNotSupportedException
  * @api
  */
 public function renewId()
 {
     if ($this->started !== true) {
         throw new Exception\SessionNotStartedException('Tried to renew the session identifier, but the session has not been started yet.', 1351182429);
     }
     if ($this->remote === true) {
         throw new Exception\OperationNotSupportedException(sprintf('Tried to renew the session identifier on a remote session (%s).', $this->sessionIdentifier), 1354034230);
     }
     $this->removeSessionMetaDataCacheEntry($this->sessionIdentifier);
     $this->sessionIdentifier = Algorithms::generateRandomString(32);
     $this->writeSessionMetaDataCacheEntry();
     $this->sessionCookie->setValue($this->sessionIdentifier);
     return $this->sessionIdentifier;
 }
 /**
  * After returning advice, making sure we have an UUID for each and every entity.
  *
  * @param JoinPointInterface $joinPoint The current join point
  * @return void
  * @Flow\Before("Neos\Flow\Persistence\Aspect\PersistenceMagicAspect->isEntity && method(.*->(__construct|__clone)()) && filter(Neos\Flow\Persistence\Doctrine\Mapping\Driver\FlowAnnotationDriver)")
  */
 public function generateUuid(JoinPointInterface $joinPoint)
 {
     /** @var $proxy PersistenceMagicInterface */
     $proxy = $joinPoint->getProxy();
     ObjectAccess::setProperty($proxy, 'Persistence_Object_Identifier', Algorithms::generateUUID(), true);
     $this->persistenceManager->registerNewObject($proxy);
 }
 /**
  * Saves the given array as a node data entity without using the ORM.
  *
  * If the node data already exists (same dimensions, same identifier, same workspace)
  * it is replaced.
  *
  * @param array $nodeData node data to save as an associative array ( $column_name => $value )
  * @throws ImportException
  * @return void
  */
 protected function persistNodeData($nodeData)
 {
     if ($nodeData['workspace'] !== 'live') {
         throw new ImportException('Saving NodeData with workspace != "live" using direct SQL not supported yet. Workspace is "' . $nodeData['workspace'] . '".');
     }
     if ($nodeData['path'] === '/') {
         return;
     }
     // cleanup old data
     /** @var Connection $connection */
     $connection = $this->entityManager->getConnection();
     // prepare node dimensions
     $dimensionValues = $nodeData['dimensionValues'];
     $dimensionsHash = Utility::sortDimensionValueArrayAndReturnDimensionsHash($dimensionValues);
     $jsonPropertiesDataTypeHandler = JsonArrayType::getType(JsonArrayType::FLOW_JSON_ARRAY);
     // post-process node data
     $nodeData['dimensionsHash'] = $dimensionsHash;
     $nodeData['dimensionValues'] = $jsonPropertiesDataTypeHandler->convertToDatabaseValue($dimensionValues, $connection->getDatabasePlatform());
     $nodeData['properties'] = $jsonPropertiesDataTypeHandler->convertToDatabaseValue($nodeData['properties'], $connection->getDatabasePlatform());
     $nodeData['accessRoles'] = $jsonPropertiesDataTypeHandler->convertToDatabaseValue($nodeData['accessRoles'], $connection->getDatabasePlatform());
     $connection->executeQuery('DELETE FROM neos_contentrepository_domain_model_nodedimension' . ' WHERE nodedata IN (' . '   SELECT persistence_object_identifier FROM neos_contentrepository_domain_model_nodedata' . '   WHERE identifier = :identifier' . '   AND workspace = :workspace' . '   AND dimensionshash = :dimensionsHash' . ' )', array('identifier' => $nodeData['identifier'], 'workspace' => $nodeData['workspace'], 'dimensionsHash' => $nodeData['dimensionsHash']));
     /** @var \Doctrine\ORM\QueryBuilder $queryBuilder */
     $queryBuilder = $this->entityManager->createQueryBuilder();
     $queryBuilder->delete()->from(NodeData::class, 'n')->where('n.identifier = :identifier')->andWhere('n.dimensionsHash = :dimensionsHash')->andWhere('n.workspace = :workspace')->setParameter('identifier', $nodeData['identifier'])->setParameter('workspace', $nodeData['workspace'])->setParameter('dimensionsHash', $nodeData['dimensionsHash']);
     $queryBuilder->getQuery()->execute();
     // insert new data
     // we need to use executeUpdate to execute the INSERT -- else the data types are not taken into account.
     // That's why we build a DQL INSERT statement which is then executed.
     $queryParts = array();
     $queryArguments = array();
     $queryTypes = array();
     foreach ($this->nodeDataPropertyNames as $propertyName => $propertyConfig) {
         if (isset($nodeData[$propertyName])) {
             $queryParts[$propertyName] = ':' . $propertyName;
             $queryArguments[$propertyName] = $nodeData[$propertyName];
             if (isset($propertyConfig['columnType'])) {
                 $queryTypes[$propertyName] = $propertyConfig['columnType'];
             }
         }
     }
     $connection->executeUpdate('INSERT INTO neos_contentrepository_domain_model_nodedata (' . implode(', ', array_keys($queryParts)) . ') VALUES (' . implode(', ', $queryParts) . ')', $queryArguments, $queryTypes);
     foreach ($dimensionValues as $dimension => $values) {
         foreach ($values as $value) {
             $nodeDimension = array('persistence_object_identifier' => Algorithms::generateUUID(), 'nodedata' => $nodeData['Persistence_Object_Identifier'], 'name' => $dimension, 'value' => $value);
             $connection->insert('neos_contentrepository_domain_model_nodedimension', $nodeDimension);
         }
     }
 }
 /**
  * @test
  */
 public function nodeWithRelatedEntitiesWillTakeCareOfAddingToPersistence()
 {
     $identifier = Algorithms::generateUUID();
     $template = new NodeTemplate();
     $template->setName('new-node');
     $template->setIdentifier($identifier);
     $newEntity = new Fixtures\RelatedEntity();
     $newEntity->setFavoritePlace('Reykjavik');
     $anotherNewEntity = new Fixtures\RelatedEntity();
     $anotherNewEntity->setFavoritePlace('Japan');
     $template->setProperty('entity', array($newEntity, $anotherNewEntity));
     $rootNode = $this->context->getRootNode();
     $newNode = $rootNode->createNodeFromTemplate($template);
     $this->persistenceManager->persistAll();
     $this->persistenceManager->clearState();
     $this->inject($this->contextFactory, 'contextInstances', array());
     $newLiveContext = $this->contextFactory->create(array('workspaceName' => 'live'));
     $newNodeAgain = $newLiveContext->getNode('/new-node');
     $entityArray = $newNodeAgain->getProperty('entity');
     $this->assertCount(2, $entityArray);
     $this->assertEquals('Japan', $entityArray[1]->getFavoritePlace());
 }
 /**
  * Creates a BCrypt hash
  *
  * @param string $password   The plaintext password to hash
  * @param string $staticSalt Optional static salt that will not be stored in the hashed password
  * @return string the result of the crypt() call
  */
 public function hashPassword($password, $staticSalt = null)
 {
     $dynamicSalt = UtilityAlgorithms::generateRandomString(22, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./');
     return crypt($password, '$2a$' . $this->cost . '$' . $dynamicSalt);
 }
예제 #14
0
 /**
  * Returns the current CSRF protection token. A new one is created when needed, depending on the  configured CSRF
  * protection strategy.
  *
  * @return string
  * @Flow\Session(autoStart=true)
  */
 public function getCsrfProtectionToken()
 {
     if ($this->initialized === false) {
         $this->initialize();
     }
     if (count($this->csrfProtectionTokens) === 1 && $this->csrfProtectionStrategy !== self::CSRF_ONE_PER_URI) {
         reset($this->csrfProtectionTokens);
         return key($this->csrfProtectionTokens);
     }
     $newToken = Algorithms::generateRandomToken(16);
     $this->csrfProtectionTokens[$newToken] = true;
     return $newToken;
 }
예제 #15
0
 /**
  * @inheritdoc
  */
 public function submit($payload, array $options = [])
 {
     $this->lastSubmitOptions = $options;
     $messageId = Algorithms::generateUUID();
     $this->readyMessages[$messageId] = $payload;
     return $messageId;
 }
 /**
  * Returns the encryption key from the persistent cache or Data/Persistent directory. If none exists, a new
  * encryption key will be generated and stored in the cache.
  *
  * @return string The configured encryption key stored in Data/Persistent/EncryptionKey
  */
 protected function getEncryptionKey()
 {
     if ($this->encryptionKey === null) {
         $this->encryptionKey = $this->cache->get('encryptionKey');
     }
     if ($this->encryptionKey === false && file_exists(FLOW_PATH_DATA . 'Persistent/EncryptionKey')) {
         $this->encryptionKey = file_get_contents(FLOW_PATH_DATA . 'Persistent/EncryptionKey');
     }
     if ($this->encryptionKey === false) {
         $this->encryptionKey = bin2hex(Utility\Algorithms::generateRandomBytes(48));
         $this->cache->set('encryptionKey', $this->encryptionKey);
     }
     return $this->encryptionKey;
 }
 /**
  * @test
  * @dataProvider randomStringCharactersDataProvider
  */
 public function generateRandomStringGeneratesOnlyDefinedCharactersRange($regularExpression, $charactersClass)
 {
     $this->assertRegExp($regularExpression, Algorithms::generateRandomString(64, $charactersClass));
 }
 /**
  * Hash a password for storage using PBKDF2 and the configured parameters.
  * Will use a combination of a random dynamic salt and the given static salt.
  *
  * @param string $password Cleartext password that should be hashed
  * @param string $staticSalt Static salt that will be appended to the random dynamic salt
  * @return string A Base64 encoded string with the derived key (hashed password) and dynamic salt
  */
 public function hashPassword($password, $staticSalt = null)
 {
     $dynamicSalt = UtilityAlgorithms::generateRandomBytes($this->dynamicSaltLength);
     $result = CryptographyAlgorithms::pbkdf2($password, $dynamicSalt . $staticSalt, $this->iterationCount, $this->derivedKeyLength, $this->algorithm);
     return base64_encode($dynamicSalt) . ',' . base64_encode($result);
 }