/**
  * Executes this finisher
  * @see AbstractFinisher::execute()
  *
  * @return void
  * @throws \TYPO3\Flow\Mvc\Exception\StopActionException();
  */
 protected function executeInternal()
 {
     /** @var \TYPO3\Form\Core\Runtime\FormRuntime $formRuntime */
     $formRuntime = $this->finisherContext->getFormRuntime();
     $formValueArray = $formRuntime->getFormState()->getFormValues();
     /** @var \GIB\GradingTool\Domain\Model\Project $project */
     $project = $this->projectRepository->findByIdentifier($formRuntime->getRequest()->getParentRequest()->getArgument('project'));
     // store changes to project
     $project->setProjectData($formValueArray);
     $this->projectRepository->update($project);
     // add a flash message
     $message = new \TYPO3\Flow\Error\Message('The project data for "%s" was successfully edited.', \TYPO3\Flow\Error\Message::SEVERITY_OK, array($project->getProjectTitle()));
     $this->flashMessageContainer->addMessage($message);
     $this->persistenceManager->persistAll();
     // redirect to dashboard
     $formRuntime = $this->finisherContext->getFormRuntime();
     $request = $formRuntime->getRequest()->getMainRequest();
     $uriBuilder = new \TYPO3\Flow\Mvc\Routing\UriBuilder();
     $uriBuilder->setRequest($request);
     $uriBuilder->reset();
     $uri = $uriBuilder->uriFor('index', NULL, 'Admin');
     $response = $formRuntime->getResponse();
     $mainResponse = $response;
     while ($response = $response->getParentResponse()) {
         $mainResponse = $response;
     }
     $mainResponse->setStatus(303);
     $mainResponse->setHeader('Location', (string) $uri);
     throw new \TYPO3\Flow\Mvc\Exception\StopActionException();
 }
 /**
  * @param string $identifier
  */
 public function deleteById($identifier)
 {
     $object = $this->findById($identifier);
     // todo: check if we want to throw an exception here
     if ($object !== NULL) {
         $this->persistenceManager->remove($object);
         $this->persistenceManager->persistAll();
     }
 }
 /**
  * Fetches the identifier from the set content object. If that
  * is not using automatically introduced UUIDs by Flow it tries
  * to call persistAll() and fetch the identifier again. If it still
  * fails, an exception is thrown.
  *
  * @return void
  * @throws \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException
  */
 protected function initializeObject()
 {
     if ($this->contentObject !== null) {
         $this->targetType = get_class($this->contentObject);
         $this->targetId = $this->persistenceManager->getIdentifierByObject($this->contentObject);
         if ($this->targetId === null) {
             $this->persistenceManager->persistAll();
             $this->targetId = $this->persistenceManager->getIdentifierByObject($this->contentObject);
             if ($this->targetId === null) {
                 throw new \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException('You cannot add an object without an identifier to a ContentObjectProxy. Probably you didn\'t add a valid entity?', 1303859434);
             }
         }
     }
 }
Esempio n. 4
0
 /**
  * Appends the given message along with the additional information into the log.
  *
  * @param string $message The message to log
  * @param integer $severity One of the LOG_* constants
  * @param mixed $additionalData A variable containing more information about the event to be logged
  * @param string $packageKey Key of the package triggering the log (determined automatically if not specified)
  * @param string $className Name of the class triggering the log (determined automatically if not specified)
  * @param string $methodName Name of the method triggering the log (determined automatically if not specified)
  * @return void
  * @api
  */
 public function append($message, $severity = LOG_INFO, $additionalData = NULL, $packageKey = NULL, $className = NULL, $methodName = NULL)
 {
     if ($this->number < self::MAX_LOGS) {
         $log = new Log();
         $log->setDeployment($this->deployment)->setDate(new \DateTime())->setNumber(++$this->number)->setMessage($message)->setSeverity($severity);
         $this->logRepository->add($log);
         $this->persistenceManager->persistAll();
     } elseif ($this->number === self::MAX_LOGS) {
         $log = new Log();
         $log->setDeployment($this->deployment)->setDate(new \DateTime())->setNumber(++$this->number)->setMessage('logging killed with #logs > ' . self::MAX_LOGS)->setSeverity(LOG_EMERG);
         $this->logRepository->add($log);
         $this->persistenceManager->persistAll();
     }
 }
 /**
  * Remove given site all nodes for that site and all domains associated.
  *
  * @param Site $site
  * @return void
  */
 public function pruneSite(Site $site)
 {
     $siteNodePath = NodePaths::addNodePathSegment(static::SITES_ROOT_PATH, $site->getNodeName());
     $this->nodeDataRepository->removeAllInPath($siteNodePath);
     $siteNodes = $this->nodeDataRepository->findByPath($siteNodePath);
     foreach ($siteNodes as $siteNode) {
         $this->nodeDataRepository->remove($siteNode);
     }
     $domainsForSite = $this->domainRepository->findBySite($site);
     foreach ($domainsForSite as $domain) {
         $this->domainRepository->remove($domain);
     }
     $this->persistenceManager->persistAll();
     $this->siteRepository->remove($site);
     $this->emitSitePruned($site);
 }
 /**
  * Generate missing URI path segments
  *
  * This generates URI path segment properties for all document nodes which don't have
  * a path segment set yet.
  *
  * @param string $workspaceName
  * @param boolean $dryRun
  * @return void
  */
 public function generateUriPathSegments($workspaceName, $dryRun)
 {
     $baseContext = $this->createContext($workspaceName, []);
     $baseContextSitesNode = $baseContext->getNode(SiteService::SITES_ROOT_PATH);
     if (!$baseContextSitesNode) {
         $this->output->outputLine('<error>Could not find "' . SiteService::SITES_ROOT_PATH . '" root node</error>');
         return;
     }
     $baseContextSiteNodes = $baseContextSitesNode->getChildNodes();
     if ($baseContextSiteNodes === []) {
         $this->output->outputLine('<error>Could not find any site nodes in "' . SiteService::SITES_ROOT_PATH . '" root node</error>');
         return;
     }
     foreach ($this->dimensionCombinator->getAllAllowedCombinations() as $dimensionCombination) {
         $flowQuery = new FlowQuery($baseContextSiteNodes);
         $siteNodes = $flowQuery->context(['dimensions' => $dimensionCombination, 'targetDimensions' => []])->get();
         if (count($siteNodes) > 0) {
             $this->output->outputLine('Checking for nodes with missing URI path segment in dimension "%s"', array(trim(NodePaths::generateContextPath('', '', $dimensionCombination), '@;')));
             foreach ($siteNodes as $siteNode) {
                 $this->generateUriPathSegmentsForNode($siteNode, $dryRun);
             }
         }
     }
     $this->persistenceManager->persistAll();
 }
 /**
  * @param \TYPO3\Form\Core\Model\FinisherContext $finisherContext
  * @return void
  * @throws \TYPO3\Setup\Exception
  */
 public function importSite(\TYPO3\Form\Core\Model\FinisherContext $finisherContext)
 {
     $formValues = $finisherContext->getFormRuntime()->getFormState()->getFormValues();
     if (isset($formValues['prune']) && intval($formValues['prune']) === 1) {
         $this->nodeDataRepository->removeAll();
         $this->workspaceRepository->removeAll();
         $this->domainRepository->removeAll();
         $this->siteRepository->removeAll();
         $this->persistenceManager->persistAll();
     }
     if (!empty($formValues['packageKey'])) {
         if ($this->packageManager->isPackageAvailable($formValues['packageKey'])) {
             throw new \TYPO3\Setup\Exception(sprintf('The package key "%s" already exists.', $formValues['packageKey']), 1346759486);
         }
         $packageKey = $formValues['packageKey'];
         $siteName = $formValues['siteName'];
         $generatorService = $this->objectManager->get('TYPO3\\Neos\\Kickstarter\\Service\\GeneratorService');
         $generatorService->generateSitePackage($packageKey, $siteName);
     } elseif (!empty($formValues['site'])) {
         $packageKey = $formValues['site'];
     }
     $this->deactivateOtherSitePackages($packageKey);
     $this->packageManager->activatePackage($packageKey);
     if (!empty($packageKey)) {
         try {
             $contentContext = $this->contextFactory->create(array('workspaceName' => 'live'));
             $this->siteImportService->importFromPackage($packageKey, $contentContext);
         } catch (\Exception $exception) {
             $finisherContext->cancel();
             $this->systemLogger->logException($exception);
             throw new SetupException(sprintf('Error: During the import of the "Sites.xml" from the package "%s" an exception occurred: %s', $packageKey, $exception->getMessage()), 1351000864);
         }
     }
 }
Esempio n. 8
0
 /**
  * Creates a user based on the given information
  *
  * The created user and account are automatically added to their respective repositories and thus be persisted.
  *
  * @param string $username The username of the user to be created.
  * @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 of the user to be created
  * @param string $photo photo of the user to be created
  * @param array $roleIdentifiers A list of role identifiers to assign
  * @param string $authenticationProviderName Name of the authentication provider to use. Example: "Typo3BackendProvider"
  * @return User The created user instance
  * @api
  */
 public function createUserPhlu($username, $password, $firstName, $lastName, $department, $photo, array $roleIdentifiers = null, $authenticationProviderName = null)
 {
     $collection = $this->assetCollectionRepository->findByCollectionName('phluCollection2')->getFirst();
     if (!$collection) {
         $collection = new \TYPO3\Media\Domain\Model\AssetCollection('phluCollection2');
         $this->assetCollectionRepository->add($collection);
         $this->persistenceManager->persistAll();
     }
     $user = new User();
     $user->setDepartment($department);
     $name = new PersonName('', $firstName, '', $lastName, '', $username);
     $user->setName($name);
     $resource = $this->resourceManager->importResource($photo);
     $image = new Image($resource);
     $image->setTitle($name->getFullName());
     $tag = $this->tagRepository->findBySearchTerm('Hauswart')->getFirst();
     if (!$tag) {
         $tag = new Tag();
         $tag->setLabel('Hauswart');
         $this->tagRepository->add($tag);
         $collection->addTag($tag);
     }
     $image->addTag($tag);
     $user->setPhoto($image);
     $this->assetRepository->add($image);
     $collection->addAsset($image);
     $this->assetCollectionRepository->update($collection);
     return $this->addUserPhlu($username, $password, $user, $roleIdentifiers, $authenticationProviderName);
 }
 /**
  * Executes this finisher
  * @see AbstractFinisher::execute()
  *
  * @return void
  * @throws \TYPO3\Flow\Mvc\Exception\StopActionException();
  */
 protected function executeInternal()
 {
     /** @var \TYPO3\Form\Core\Runtime\FormRuntime $formRuntime */
     $formRuntime = $this->finisherContext->getFormRuntime();
     $formValueArray = $formRuntime->getFormState()->getFormValues();
     if ($formRuntime->getRequest()->getParentRequest()->getControllerActionName() == 'edit') {
         // we need to update the template
         /** @var \GIB\GradingTool\Domain\Model\Template $template */
         $template = $this->templateRepository->findByIdentifier($formRuntime->getRequest()->getParentRequest()->getArgument('template')['__identity']);
         $template->setTemplateIdentifier($formValueArray['templateIdentifier']);
         $template->setContent(serialize($formValueArray));
         //$project->setLastUpdated(new \TYPO3\Flow\Utility\Now);
         $this->templateRepository->update($template);
         // add a flash message
         $message = new \TYPO3\Flow\Error\Message('The template "%s" was successfully edited.', \TYPO3\Flow\Error\Message::SEVERITY_OK, array($template->getTemplateIdentifier()));
         $this->flashMessageContainer->addMessage($message);
     } else {
         // we need to add a new template
         /** @var \GIB\GradingTool\Domain\Model\Template $template */
         $template = new \GIB\GradingTool\Domain\Model\Template();
         $template->setTemplateIdentifier($formValueArray['templateIdentifier']);
         // serialize all form content and store it
         $template->setContent(serialize($formValueArray));
         //$project->setCreated(new \TYPO3\Flow\Utility\Now);
         $this->templateRepository->add($template);
         // add a flash message
         $message = new \TYPO3\Flow\Error\Message('The template "%s" was successfully created.', \TYPO3\Flow\Error\Message::SEVERITY_OK, array($formValueArray['templateIdentifier']));
         $this->flashMessageContainer->addMessage($message);
     }
     $this->persistenceManager->persistAll();
     // redirect to dashboard
     $formRuntime = $this->finisherContext->getFormRuntime();
     $request = $formRuntime->getRequest()->getMainRequest();
     $uriBuilder = new \TYPO3\Flow\Mvc\Routing\UriBuilder();
     $uriBuilder->setRequest($request);
     $uriBuilder->reset();
     $uri = $uriBuilder->uriFor('list', NULL, 'Template');
     $response = $formRuntime->getResponse();
     $mainResponse = $response;
     while ($response = $response->getParentResponse()) {
         $mainResponse = $response;
     }
     $mainResponse->setStatus(303);
     $mainResponse->setHeader('Location', (string) $uri);
     throw new \TYPO3\Flow\Mvc\Exception\StopActionException();
 }
Esempio n. 10
0
 /**
  * @return \TYPO3\Flow\Security\Account
  * @throws Exception
  * @throws \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException
  */
 protected function generateTokenAccount()
 {
     $account = $this->securityContext->getAccount();
     $tokenAccount = $this->accountFactory->createAccountWithPassword($account->getAccountIdentifier(), Algorithms::generateRandomString(25), array_keys($account->getRoles()), $this->apiToken->getAuthenticationProviderName());
     $this->accountRepository->add($tokenAccount);
     $this->persistenceManager->persistAll();
     return $tokenAccount;
 }
Esempio n. 11
0
 /**
  * @param string $email
  * @param \Ag\Login\Domain\Model\Role $role
  * @return \Ag\Login\Domain\Model\AccountDescriptor
  */
 public function removeRoleByEmail($email, $role)
 {
     $account = $this->getAccountByEmailThrowExceptionIfNotExistsing($email);
     $account->removeRole($role);
     $this->accountRepository->update($account);
     $this->persistenceManager->persistAll();
     return $account->getDescriptor();
 }
Esempio n. 12
0
 /**
  * Persists new Account.
  *
  * @param Account $account
  *
  * @return void
  */
 public function finalizePersistingNewUser(Account $account)
 {
     $party = $account->getParty();
     if ($party instanceof AbstractParty) {
         $this->partyRepository->add($party);
     }
     $this->accountRepository->add($account);
     $this->persistenceManager->persistAll();
 }
 /**
  * Adds a redirect to the repository and updates related redirects accordingly.
  *
  * @param string $sourceUriPath the relative URI path that should trigger a redirect
  * @param string $targetUriPath the relative URI path the redirect should point to
  * @param int $statusCode the status code of the redirect header
  * @param string $host the host for the current redirect
  * @return Redirect the freshly generated redirect DTO instance
  * @api
  */
 protected function addRedirectByHost($sourceUriPath, $targetUriPath, $statusCode, $host = null)
 {
     $redirect = new Redirect($sourceUriPath, $targetUriPath, $statusCode, $host);
     $this->updateDependingRedirects($redirect);
     $this->persistenceManager->persistAll();
     $this->redirectRepository->add($redirect);
     $this->routerCachingService->flushCachesForUriPath($sourceUriPath);
     return RedirectDto::create($redirect);
 }
 /**
  * Executes this finisher
  * @see AbstractFinisher::execute()
  *
  * @return void
  * @throws \TYPO3\Flow\Mvc\Exception\StopActionException();
  */
 protected function executeInternal()
 {
     /** @var \TYPO3\Form\Core\Runtime\FormRuntime $formRuntime */
     $formRuntime = $this->finisherContext->getFormRuntime();
     // The corresponding project
     $projectIdentifier = $formRuntime->getRequest()->getParentRequest()->getArgument('project');
     /** @var \GIB\GradingTool\Domain\Model\Project $project */
     $project = $this->projectRepository->findByIdentifier($projectIdentifier);
     $sendGradingToProjectManager = FALSE;
     if (is_null($project->getSubmissionLastUpdated())) {
         $sendGradingToProjectManager = TRUE;
     }
     // update the project with the data from the form
     $formValueArray = $formRuntime->getFormState()->getFormValues();
     $project->setSubmissionContent(serialize($formValueArray));
     $project->setSubmissionLastUpdated(new \TYPO3\Flow\Utility\Now());
     $this->projectRepository->update($project);
     $this->persistenceManager->persistAll();
     // add a flash message
     $message = new \TYPO3\Flow\Error\Message('Thank you for submitting the data for your project "%s".', \TYPO3\Flow\Error\Message::SEVERITY_OK, array($project->getProjectTitle()));
     $this->flashMessageContainer->addMessage($message);
     // send notification mail
     $templateIdentifierOverlay = $this->templateService->getTemplateIdentifierOverlay('newSubmissionNotification', $project);
     $this->notificationMailService->sendNotificationMail($templateIdentifierOverlay, $project, $project->getProjectManager());
     if ($sendGradingToProjectManager) {
         // The grading was completed for the first time, so we send the grading to the project manager
         $this->submissionService->sendGradingToProjectManager($project);
     }
     // redirect to dashboard
     $formRuntime = $this->finisherContext->getFormRuntime();
     $request = $formRuntime->getRequest()->getMainRequest();
     $uriBuilder = new \TYPO3\Flow\Mvc\Routing\UriBuilder();
     $uriBuilder->setRequest($request);
     $uriBuilder->reset();
     $uri = $uriBuilder->uriFor('index', NULL, 'Standard');
     $response = $formRuntime->getResponse();
     $mainResponse = $response;
     while ($response = $response->getParentResponse()) {
         $mainResponse = $response;
     }
     $mainResponse->setStatus(303);
     $mainResponse->setHeader('Location', (string) $uri);
     throw new \TYPO3\Flow\Mvc\Exception\StopActionException();
 }
 /**
  * @param Context $context
  * @return NodeInterface
  * @throws NodeTypeNotFoundException
  * @throws NodeConfigurationException
  */
 public function findOrCreateMetaDataRootNode(Context $context)
 {
     if ($this->metaDataRootNode instanceof NodeInterface) {
         return $this->metaDataRootNode;
     }
     $metaDataRootNodeData = $this->metaDataRepository->findOneByPath('/' . MetaDataRepository::METADATA_ROOT_NODE_NAME, $context->getWorkspace());
     if ($metaDataRootNodeData !== null) {
         $metaDataRootNode = $this->nodeFactory->createFromNodeData($metaDataRootNodeData, $context);
         return $metaDataRootNode;
     }
     $nodeTemplate = new NodeTemplate();
     $nodeTemplate->setNodeType($this->nodeTypeManager->getNodeType('unstructured'));
     $nodeTemplate->setName(MetaDataRepository::METADATA_ROOT_NODE_NAME);
     $context = $this->contextFactory->create(['workspaceName' => 'live']);
     $rootNode = $context->getRootNode();
     $this->metaDataRootNode = $rootNode->createNodeFromTemplate($nodeTemplate);
     $this->persistenceManager->persistAll();
     return $this->metaDataRootNode;
 }
 /**
  * Migrate Primary Sector
  *
  * Migrates the dataSheet field "singleselectdropdown1" in the serialized dataSheetContent field of a project.
  * Changes field name to "primarySector" and field values to speaking values.
  *
  * @param boolean $simulate If set, this command will only tell what it would do instead of doing it right away
  * @return void
  */
 public function migratePrimarySectorCommand($simulate = FALSE)
 {
     $affectedProjects = $this->projectRepository->findByDataSheetFormIdentifier('dataSheetFormV2');
     foreach ($affectedProjects as $project) {
         /** @var $project \GIB\GradingTool\Domain\Model\Project */
         $dataSheetContentArray = $project->getDataSheetContentArray();
         if (array_key_exists('singleselectdropdown1', $dataSheetContentArray)) {
             $value = $dataSheetContentArray['singleselectdropdown1'];
             $newValue = '';
             switch ($value) {
                 case 'transport':
                     $newValue = 'Transportation (Railway, Road, BRT, etc.)';
                     break;
                 case 'energy':
                     $newValue = 'Energy generation and distribution';
                     break;
                 case 'water':
                     $newValue = 'Water and waste processing';
                     break;
                 case 'social':
                     $newValue = 'Social Infrastructure (schools, hospitals, state housing)';
                     break;
                 case 'telecom':
                     $newValue = 'ICT';
                     break;
                 default:
                     break;
             }
             unset($dataSheetContentArray['singleselectdropdown1']);
             $dataSheetContentArray['primarySector'] = $newValue;
             $project->setDataSheetContent($dataSheetContentArray);
             $status = '[SIMULATE] ';
             if (!$simulate) {
                 $this->projectRepository->update($project);
                 $this->persistenceManager->persistAll();
                 $status = '';
             }
             $message = $status . 'Project "' . $project->getProjectTitle() . '": Changed singleselectdropdown "' . $value . '" to primarySector "' . $newValue . '".';
             $this->outputLine($message);
         }
     }
     $this->quit();
 }
 /**
  * Imports one or multiple sites from the XML file at $pathAndFilename
  *
  * @param string $pathAndFilename
  * @return Site The imported site
  * @throws UnknownPackageException|InvalidPackageStateException|NeosException
  */
 public function importFromFile($pathAndFilename)
 {
     /** @var Site $importedSite */
     $site = NULL;
     $this->eventEmittingService->withoutEventLog(function () use($pathAndFilename, &$site) {
         $xmlReader = new \XMLReader();
         $xmlReader->open($pathAndFilename, NULL, LIBXML_PARSEHUGE);
         if ($this->workspaceRepository->findOneByName('live') === NULL) {
             $this->workspaceRepository->add(new Workspace('live'));
         }
         $rootNode = $this->contextFactory->create()->getRootNode();
         $this->persistenceManager->persistAll();
         $sitesNode = $rootNode->getNode('/sites');
         if ($sitesNode === NULL) {
             $sitesNode = $rootNode->createSingleNode('sites');
         }
         while ($xmlReader->read()) {
             if ($xmlReader->nodeType != \XMLReader::ELEMENT || $xmlReader->name !== 'site') {
                 continue;
             }
             $isLegacyFormat = $xmlReader->getAttribute('nodeName') !== NULL && $xmlReader->getAttribute('state') === NULL && $xmlReader->getAttribute('siteResourcesPackageKey') === NULL;
             if ($isLegacyFormat) {
                 $site = $this->legacySiteImportService->importSitesFromFile($pathAndFilename);
                 return;
             }
             $site = $this->getSiteByNodeName($xmlReader->getAttribute('siteNodeName'));
             $site->setName($xmlReader->getAttribute('name'));
             $site->setState((int) $xmlReader->getAttribute('state'));
             $siteResourcesPackageKey = $xmlReader->getAttribute('siteResourcesPackageKey');
             if (!$this->packageManager->isPackageAvailable($siteResourcesPackageKey)) {
                 throw new UnknownPackageException(sprintf('Package "%s" specified in the XML as site resources package does not exist.', $siteResourcesPackageKey), 1303891443);
             }
             if (!$this->packageManager->isPackageActive($siteResourcesPackageKey)) {
                 throw new InvalidPackageStateException(sprintf('Package "%s" specified in the XML as site resources package is not active.', $siteResourcesPackageKey), 1303898135);
             }
             $site->setSiteResourcesPackageKey($siteResourcesPackageKey);
             $rootNode = $this->contextFactory->create()->getRootNode();
             // We fetch the workspace to be sure it's known to the persistence manager and persist all
             // so the workspace and site node are persisted before we import any nodes to it.
             $rootNode->getContext()->getWorkspace();
             $this->persistenceManager->persistAll();
             $sitesNode = $rootNode->getNode('/sites');
             if ($sitesNode === NULL) {
                 $sitesNode = $rootNode->createNode('sites');
             }
             $this->nodeImportService->import($xmlReader, $sitesNode->getPath(), dirname($pathAndFilename) . '/Resources');
         }
     });
     if ($site === NULL) {
         throw new NeosException(sprintf('The XML file did not contain a valid site node.'), 1418999522);
     }
     $this->emitSiteImported($site);
     return $site;
 }
Esempio n. 18
0
 /**
  * @param string $authentication
  * @param string $quizIdentifier
  */
 public function quizDeleteAction($authentication, $quizIdentifier)
 {
     if (!$this->verifyAuthentication($authentication, (string) $quizIdentifier)) {
         throw new AccessDeniedException('Access denied');
     }
     $quiz = $this->quizRepository->findByIdentifier($quizIdentifier);
     if ($quiz) {
         $this->quizRepository->remove($quiz);
         $this->persistenceManager->persistAll();
     }
     $this->view->assign('value', array('ok'));
 }
 /**
  * Get data
  *
  * @param NodeInterface $node The node that is currently edited (optional)
  * @param array $arguments Additional arguments (key / value)
  * @return array JSON serializable data
  */
 public function getData(NodeInterface $node = NULL, array $arguments)
 {
     if ($this->newsCategoryRepository->countAll() === 0) {
         $category = new NewsCategory();
         $category->setName('test');
         $this->newsCategoryRepository->add($category);
         $this->persistenceManager->persistAll();
     }
     $categories = array();
     foreach ($this->newsCategoryRepository->findAll() as $category) {
         $categories[$category->getId()] = array('label' => $category->getName(), 'group' => substr($category->getName(), 0, 1), 'icon' => 'icon-key');
     }
     return $categories;
     //        return (array(
     //            'key' => array('label' => 'Foo', 'group' => 'A', 'icon' => 'icon-key'),
     //            'key2' => array('label' => 'Foo2', 'group' => 'A', 'icon' => 'icon-key'),
     //            'legal' => array('label' => 'Legal', 'group' => 'B', 'icon' => 'icon-legal'),
     //            'legal2' => array('label' => 'Legal2', 'group' => 'B', 'icon' => 'icon-legal'),
     //            'legal3' => array('label' => 'Legal3', 'group' => 'B', 'icon' => 'icon-legal'),
     //            'legal4' => array('label' => 'Legal4', 'group' => 'C', 'icon' => 'icon-legal')
     //        ));
 }
 /**
  * Send a mail to the project manager with the spider graph as attachement
  *
  * @param Project $project
  */
 public function sendGradingToProjectManager($project)
 {
     // send mail to project manager
     $radarChartImagePathAndFilename = $this->getRadarImage($project);
     $radarChartImageResource = $this->resourceManager->importResource($radarChartImagePathAndFilename);
     $radarChartUri = $this->resourcePublisher->getPersistentResourceWebUri($radarChartImageResource);
     // this is necessary because we're in a safe request, but generate a resource
     $this->persistenceManager->persistAll();
     $attachements = array(array('source' => $radarChartUri, 'fileName' => 'gib-grading.png'));
     $templateIdentifierOverlay = $this->templateService->getTemplateIdentifierOverlay('newSubmissionProjectManagerNotification', $project);
     $this->notificationMailService->sendNotificationMail($templateIdentifierOverlay, $project, $project->getProjectManager(), $project->getProjectManager()->getName()->getFirstName() . ' ' . $project->getProjectManager()->getName()->getLastName(), $project->getProjectManager()->getPrimaryElectronicAddress()->getIdentifier(), '', $attachements);
     // CC to GIB
     $this->notificationMailService->sendNotificationMail($templateIdentifierOverlay, $project, $project->getProjectManager(), $project->getProjectManager()->getName()->getFirstName() . ' ' . $project->getProjectManager()->getName()->getLastName(), '*****@*****.**', '', $attachements);
 }
 /**
  * Move tickets and rooms from the waiting list
  * to pending if there are free quota
  */
 public function updateWaitingListCommand()
 {
     $registrationsToNotify = [];
     $numberOfTickets = $this->bookableService->getTicketsStatus();
     if ($numberOfTickets > 0) {
         $waitingTickets = $this->ticketRepository->findWaitingByCount($numberOfTickets);
         /** @var Ticket $ticket */
         foreach ($waitingTickets as $ticket) {
             $priorBookingState = $ticket->getBookingState();
             $ticket->setBookingState(AbstractBookable::BOOKING_STATE_PENDING);
             $this->ticketRepository->update($ticket);
             /** @var Participant $participant */
             $participant = $this->registrationParticipantRepository->findOneByTicket($ticket);
             /** @var Registration $notification */
             $notification = $participant->getRegistration();
             $registrationIdentifier = $this->persistenceManager->getIdentifierByObject($notification);
             if (!array_key_exists($registrationIdentifier, $registrationsToNotify)) {
                 $registrationsToNotify[$registrationIdentifier] = ['registration' => $notification, 'ticketBookingStateChanged' => [], 'roomBookingStateChanged' => []];
             }
             $participantIdentifier = $this->persistenceManager->getIdentifierByObject($participant);
             $registrationsToNotify[$registrationIdentifier]['ticketBookingStateChanged'][$participantIdentifier] = ['participant' => $participant, 'priorBookingState' => $priorBookingState, 'newBookingState' => $ticket->getBookingState()];
         }
     }
     $numberOfRooms = $this->bookableService->getTicketsStatus();
     if ($numberOfRooms > 0) {
         $waitingRooms = $this->roomRepository->findWaitingByCount($numberOfRooms);
         /** @var Room $room */
         foreach ($waitingRooms as $room) {
             $priorBookingState = $room->getBookingState();
             $room->setBookingState(AbstractBookable::BOOKING_STATE_PENDING);
             $this->roomRepository->update($room);
             /** @var Participant $participant */
             $participant = $this->registrationParticipantRepository->findOneByRoom($room);
             /** @var Registration $registration */
             $notification = $participant->getRegistration();
             $registrationIdentifier = $this->persistenceManager->getIdentifierByObject($notification);
             if (!array_key_exists($registrationIdentifier, $registrationsToNotify)) {
                 $registrationsToNotify[$registrationIdentifier] = ['registration' => $notification, 'ticketBookingStateChanged' => [], 'roomBookingStateChanged' => []];
             }
             $participantIdentifier = $this->persistenceManager->getIdentifierByObject($participant);
             $registrationsToNotify[$registrationIdentifier]['roomBookingStateChanged'][$participantIdentifier] = ['participant' => $participant, 'priorBookingState' => $priorBookingState, 'newBookingState' => $room->getBookingState()];
         }
     }
     $this->persistenceManager->persistAll();
     /** @var array $notification */
     foreach ($registrationsToNotify as $notification) {
         $this->mailService->sendMoveToWaitingListMail($notification);
     }
 }
 /**
  * If the specified workspace or its root node does not exist yet, the workspace and root node will be created.
  *
  * This method is basically a safeguard for legacy and potentially broken websites where users might not have
  * their own workspace yet. In a normal setup, the Domain User Service is responsible for creating and deleting
  * user workspaces.
  *
  * @param string $workspaceName Name of the workspace
  * @return void
  */
 protected function createWorkspaceAndRootNodeIfNecessary($workspaceName)
 {
     $workspace = $this->workspaceRepository->findOneByName($workspaceName);
     if ($workspace === NULL) {
         $liveWorkspace = $this->workspaceRepository->findOneByName('live');
         $workspace = new Workspace($workspaceName, $liveWorkspace);
         $this->workspaceRepository->add($workspace);
         $this->persistenceManager->whitelistObject($workspace);
     }
     $contentContext = $this->createContext($workspaceName);
     $rootNode = $contentContext->getRootNode();
     $this->persistenceManager->whitelistObject($rootNode);
     $this->persistenceManager->whitelistObject($rootNode->getNodeData());
     $this->persistenceManager->persistAll(TRUE);
 }
 /**
  * @param Account $account
  * @param array $userdata
  * @return \TYPO3\Flow\Security\Account
  */
 protected function updateAccount(Account $account, array $userdata)
 {
     $person = $this->partyService->getAssignedPartyOfAccount($account);
     if ($person === null) {
         $person = new Person();
         $this->partyRepository->add($person);
         $this->partyService->assignAccountToParty($account, $person);
     }
     if (!$account->getRoles()) {
         $account->setRoles(array($this->policyService->getRole('T3DD.Backend:Authenticated')));
     }
     $this->updatePerson($person, $userdata);
     $this->accountRepository->update($account);
     $this->persistenceManager->persistAll();
     return $account;
 }
 /**
  * If the specified workspace or its root node does not exist yet, the workspace and root node will be created.
  *
  * This method is basically a safeguard for legacy and potentially broken websites where users might not have
  * their own workspace yet. In a normal setup, the Domain User Service is responsible for creating and deleting
  * user workspaces.
  *
  * @param string $workspaceName Name of the workspace
  * @return void
  */
 protected function createWorkspaceAndRootNodeIfNecessary($workspaceName)
 {
     $workspace = $this->workspaceRepository->findOneByName($workspaceName);
     if ($workspace === null) {
         $liveWorkspace = $this->workspaceRepository->findOneByName('live');
         $owner = $this->userService->getBackendUser();
         $workspace = new Workspace($workspaceName, $liveWorkspace, $owner);
         $this->workspaceRepository->add($workspace);
         $this->persistenceManager->whitelistObject($workspace);
     }
     $contentContext = $this->createContext($workspaceName);
     $rootNode = $contentContext->getRootNode();
     $this->persistenceManager->whitelistObject($rootNode);
     $this->persistenceManager->whitelistObject($rootNode->getNodeData());
     $this->persistenceManager->persistAll(true);
 }
 /**
  * Wait for a message in the queue and save the message to a safety queue
  *
  * TODO: Idea for implementing a TTR (time to run) with monitoring of safety queue. E.g.
  * use different queue names with encoded times? With brpoplpush we cannot modify the
  * queued item on transfer to the safety queue and we cannot update a timestamp to mark
  * the run start time in the message, so separate keys should be used for this.
  *
  * @param integer $timeout in seconds
  * @return Message
  */
 public function waitAndReserve($timeout = NULL)
 {
     if ($timeout === NULL) {
         sleep($timeout);
     }
     $doctrineMessage = $this->messageRepository->findOneInQueue($this->name);
     if (!$doctrineMessage instanceof DoctrineMessage) {
         return NULL;
     }
     $doctrineMessage->setState(Message::STATE_RESERVED);
     $this->messageRepository->update($doctrineMessage);
     $this->persistenceManager->persistAll();
     $message = new Message();
     $message->setIdentifier($doctrineMessage->getIdentifier());
     $message->setState($doctrineMessage->getState());
     $message->setPayload($doctrineMessage->getPayload());
     return $message;
 }
 /**
  * Update progression on playback, updated by trackerId.
  *
  */
 public function updateTrackerAction()
 {
     $trackerId = $this->request->getArgument('trackerId');
     $tracker = $this->persistenceManager->getObjectByIdentifier($trackerId, '\\_OurBrand_\\Quiz\\Domain\\Model\\TrackStudentAudioPlayback');
     if (is_a($tracker, '\\_OurBrand_\\Quiz\\Domain\\Model\\TrackStudentAudioPlayback')) {
         $elapsedTime = $this->request->getArgument('elapsedTime');
         $status = $this->request->getArgument('status');
         $tmpTime = $tracker->getTimeElapsed();
         // only update if new time is larger then the old one...
         if (intval($elapsedTime) > $tmpTime) {
             $tracker->setTimeElapsed($elapsedTime);
         }
         $tracker->setStatus($status);
         $this->trackStudentAudioPlaybackRepository->update($tracker);
         $this->persistenceManager->persistAll();
         return json_encode(array('elapsedTime' => $tracker->getTimeElapsed(), 'status' => $tracker->getStatus(), 'trackerId' => $this->persistenceManager->getIdentifierByObject($tracker)));
     }
 }
 /**
  * Render ungenerated thumbnails
  *
  * Loops over ungenerated thumbnails and renders them. Optional ``limit`` parameter to limit the amount of
  * thumbnails to be rendered to avoid memory exhaustion.
  *
  * @param integer $limit Limit the amount of thumbnails to be rendered to avoid memory exhaustion
  * @return void
  */
 public function renderThumbnailsCommand($limit = null)
 {
     $thumbnailCount = $this->thumbnailRepository->countUngenerated();
     $iterator = $this->thumbnailRepository->findUngeneratedIterator();
     $this->output->progressStart($limit !== null && $thumbnailCount > $limit ? $limit : $thumbnailCount);
     $iteration = 0;
     foreach ($this->thumbnailRepository->iterate($iterator) as $thumbnail) {
         if ($thumbnail->getResource() === null) {
             $this->thumbnailService->refreshThumbnail($thumbnail);
             $this->persistenceManager->persistAll();
         }
         $this->output->progressAdvance(1);
         $iteration++;
         if ($iteration === $limit) {
             break;
         }
     }
 }
 /**
  * @param string $username Crowd Username
  * @param string $providerName Name of the authentication provider, this account should be used with
  * @return Account
  */
 public function getLocalAccountForCrowdUser($username, $providerName)
 {
     $accountRepository = $this->accountRepository;
     $this->securityContext->withoutAuthorizationChecks(function () use($username, $providerName, $accountRepository, &$account) {
         $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($username, $providerName);
     });
     if ($account === NULL) {
         if ($this->getUser($username) === NULL) {
             return NULL;
         }
         $account = new Account();
         $account->setAuthenticationProviderName($providerName);
         $account->setAccountIdentifier($username);
         $roleIdentifier = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow.security.authentication.providers.' . $providerName . '.providerOptions.authenticateRole');
         $account->addRole($this->policyService->getRole($roleIdentifier));
         $this->accountRepository->add($account);
         $this->persistenceManager->persistAll();
     }
     return $account;
 }
 /**
  *
  *
  * @return void
  */
 public function updateEventsAfterPublish()
 {
     if (!$this->eventEmittingService->isEnabled()) {
         return;
     }
     /** @var $entityManager EntityManager */
     $entityManager = $this->entityManager;
     foreach ($this->scheduledNodeEventUpdates as $documentPublish) {
         /* @var $nodeEvent NodeEvent */
         $nodeEvent = $this->eventEmittingService->emit(self::DOCUMENT_PUBLISHED, array(), 'TYPO3\\Neos\\EventLog\\Domain\\Model\\NodeEvent');
         $nodeEvent->setNode($documentPublish['documentNode']);
         $nodeEvent->setWorkspaceName($documentPublish['targetWorkspace']);
         $this->persistenceManager->whitelistObject($nodeEvent);
         $this->persistenceManager->persistAll(true);
         $parentEventIdentifier = $this->persistenceManager->getIdentifierByObject($nodeEvent);
         $qb = $entityManager->createQueryBuilder();
         $qb->update('TYPO3\\Neos\\EventLog\\Domain\\Model\\NodeEvent', 'e')->set('e.parentEvent', $qb->expr()->literal($parentEventIdentifier))->where('e.parentEvent IS NULL')->andWhere('e.workspaceName = :workspaceName')->setParameter('workspaceName', $documentPublish['workspaceName'])->andWhere('e.documentNodeIdentifier = :documentNodeIdentifier')->setParameter('documentNodeIdentifier', $documentPublish['documentNode']->getIdentifier())->andWhere('e.eventType != :publishedEventType')->setParameter('publishedEventType', self::DOCUMENT_PUBLISHED)->getQuery()->execute();
     }
     $this->scheduledNodeEventUpdates = array();
 }
Esempio n. 30
0
 /**
  * @param \_OurBrand_\Quiz\Domain\Model\Exercise $exercise
  * @return void
  */
 public function deleteAction($exercise)
 {
     if (!$this->accessHelper->canUserEditQuiz($this->currentUser, $exercise->getQuiz())) {
         $this->throwStatus(403);
     }
     $number = $exercise->getNumber();
     $quiz = $exercise->getQuiz();
     $prevExercise = null;
     $quiz->removeExercise($exercise);
     $quiz->touch();
     if ($quiz->getExercises()->count() > 0) {
         $prevExercise = $quiz->getExerciseByNumber($number > 0 ? $number - 1 : 0);
     }
     $this->quizRepository->update($quiz);
     $this->persistenceManager->persistAll();
     if ($prevExercise) {
         $this->redirect('edit', 'exercise', null, array('exercise' => $prevExercise));
     } else {
         $this->redirect('edit', 'quiz', null, array('quiz' => $quiz));
     }
 }