/**
  * @param Message     $message
  * @param BackendUser $user
  *
  * @return mixed|void
  */
 protected function execute(Message $message, \BackendUser $user)
 {
     global $container;
     $general = new \ContaoCommunityAlliance\DcGeneral\DC_General('orm_avisota_message');
     $environment = $general->getEnvironment();
     $translator = $environment->getTranslator();
     $GLOBALS['TL_LANGUAGE'] = $message->getLanguage();
     /** @var \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher */
     $eventDispatcher = $GLOBALS['container']['event-dispatcher'];
     $user = \Input::get('recipient_user');
     /** @var \Doctrine\DBAL\Connection $connection */
     $connection = $container['doctrine.connection.default'];
     $queryBuilder = $connection->createQueryBuilder();
     /** @var \Doctrine\DBAL\Statement $statement */
     $statement = $queryBuilder->select('u.*')->from('tl_user', 'u')->where('id=:id')->setParameter(':id', $user)->execute();
     $userData = $statement->fetch();
     if (!$userData) {
         $_SESSION['AVISOTA_SEND_PREVIEW_TO_USER_EMPTY'] = true;
         header('Location: ' . $url);
         exit;
     }
     $idSerializer = new ModelId('orm_avisota_message', $message->getId());
     $pidSerializer = new ModelId('orm_avisota_message_category', $message->getCategory()->getId());
     $url = sprintf('%scontao/main.php?do=avisota_newsletter&table=orm_avisota_message&act=preview&id=%s&pid=%s', \Environment::get('base'), $idSerializer->getSerialized(), $pidSerializer->getSerialized());
     if ($message->getCategory()->getViewOnlinePage()) {
         $event = new LoadLanguageFileEvent('avisota_message');
         $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
         $viewOnlineLink = sprintf($translator->translate('viewOnline', 'avisota_message'), $url);
     } else {
         $viewOnlineLink = false;
     }
     $event = new \Avisota\Contao\Core\Event\CreateFakeRecipientEvent($message);
     $eventDispatcher->dispatch(\Avisota\Contao\Core\CoreEvents::CREATE_FAKE_RECIPIENT, $event);
     $recipient = $event->getRecipient();
     $recipient->setEmail($userData['email']);
     $additionalData = array('view_online_link' => $viewOnlineLink);
     /** @var \Avisota\Contao\Message\Core\Renderer\MessageRendererInterface $renderer */
     $renderer = $container['avisota.message.renderer'];
     $messageTemplate = $renderer->renderMessage($message);
     $messageMail = $messageTemplate->render($recipient, $additionalData);
     /** @var \Avisota\Transport\TransportInterface $transport */
     $transport = $GLOBALS['container']['avisota.transport.' . $message->getQueue()->getTransport()->getId()];
     $transport->send($messageMail);
     $event = new \ContaoCommunityAlliance\Contao\Bindings\Events\System\LoadLanguageFileEvent('avisota_message_preview');
     $eventDispatcher->dispatch(\ContaoCommunityAlliance\Contao\Bindings\ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
     $_SESSION['TL_CONFIRM'][] = sprintf($translator->translate('previewSend', 'avisota_message_preview'), $recipient->getEmail());
     header('Location: ' . $url);
     exit;
 }
예제 #2
0
파일: Subscriber.php 프로젝트: zonky2/core
 /**
  * Retrieve the MetaModel attached to the model condition setting.
  *
  * @param EnvironmentInterface $interface The environment.
  *
  * @return \MetaModels\IMetaModel
  */
 public function getMetaModel(EnvironmentInterface $interface)
 {
     $metaModelId = $this->getDatabase()->prepare('SELECT id FROM tl_metamodel WHERE
             id=(SELECT pid FROM tl_metamodel_dca WHERE
             id=(SELECT pid FROM tl_metamodel_dcasetting WHERE id=?))')->execute(ModelId::fromSerialized($interface->getInputProvider()->getParameter('pid'))->getId());
     return $this->getMetaModelById($metaModelId->id);
 }
예제 #3
0
 /**
  * Get the bread crumb elements.
  *
  * @param GetBreadcrumbEvent $event This event.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.LongVariable)
  */
 public function getBreadCrumb(GetBreadcrumbEvent $event)
 {
     $environment = $event->getEnvironment();
     $dataDefinition = $environment->getDataDefinition();
     $inputProvider = $environment->getInputProvider();
     $translator = $environment->getTranslator();
     $modelParameter = $inputProvider->hasParameter('act') ? 'id' : 'pid';
     if ($dataDefinition->getName() !== 'orm_avisota_salutation' || !$inputProvider->hasParameter($modelParameter)) {
         return;
     }
     $salutationModelId = ModelId::fromSerialized($inputProvider->getParameter($modelParameter));
     if (!in_array($salutationModelId->getDataProviderName(), array('orm_avisota_salutation', 'orm_avisota_salutation_group'))) {
         return;
     }
     $elements = $event->getElements();
     $urlSalutationBuilder = new UrlBuilder();
     $urlSalutationBuilder->setPath('contao/main.php')->setQueryParameter('do', $inputProvider->getParameter('do'))->setQueryParameter('ref', TL_REFERER_ID);
     $elements[] = array('icon' => 'assets/avisota/salutation/images/salutation.png', 'text' => $translator->translate('avisota_salutation.0', 'MOD'), 'url' => $urlSalutationBuilder->getUrl());
     if ($modelParameter === 'pid') {
         $event->setElements($elements);
         return;
     }
     $urlSalutationGroupBuilder = new UrlBuilder();
     $urlSalutationGroupBuilder->setPath('contao/main.php')->setQueryParameter('do', $inputProvider->getParameter('do'))->setQueryParameter('table', $inputProvider->getParameter('table'))->setQueryParameter('pid', $inputProvider->getParameter('pid'))->setQueryParameter('ref', TL_REFERER_ID);
     $salutationGroupModelId = ModelId::fromSerialized($inputProvider->getParameter('pid'));
     $dataProvider = $environment->getDataProvider($salutationGroupModelId->getDataProviderName());
     $model = $dataProvider->fetch($dataProvider->getEmptyConfig()->setId($salutationGroupModelId->getId()));
     $entity = $model->getEntity();
     $elements[] = array('icon' => 'assets/avisota/subscription-recipient/images/recipients.png', 'text' => $entity->getTitle(), 'url' => $urlSalutationGroupBuilder->getUrl());
     $event->setElements($elements);
 }
예제 #4
0
 /**
  * @return MessageCategory|null
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.ShortVariable)
  */
 public static function resolveCategoryFromInput()
 {
     $id = \Input::get('id');
     $pid = \Input::get('pid');
     $modelId = null;
     $parentModelId = null;
     /** @var MessageCategory $category */
     $category = null;
     /** @var Message $message */
     $message = null;
     /** @var MessageContent $content */
     $content = null;
     if ($id) {
         $modelId = ModelId::fromSerialized($id);
     }
     if ($pid) {
         $parentModelId = ModelId::fromSerialized($pid);
     }
     // $id or $pid is a category ID
     if ($modelId && $modelId->getDataProviderName() == 'orm_avisota_message_category') {
         $repository = EntityHelper::getRepository('Avisota\\Contao:MessageCategory');
         $category = $repository->find($modelId->getId());
     } else {
         if ($parentModelId && $parentModelId->getDataProviderName() == 'orm_avisota_message_category') {
             $repository = EntityHelper::getRepository('Avisota\\Contao:MessageCategory');
             $category = $repository->find($parentModelId->getId());
         } else {
             if ($modelId && $modelId->getDataProviderName() == 'orm_avisota_message') {
                 $repository = EntityHelper::getRepository('Avisota\\Contao:Message');
                 $message = $repository->find($modelId->getId());
                 $category = $message->getCategory();
             } else {
                 if ($parentModelId && $parentModelId->getDataProviderName() == 'orm_avisota_message') {
                     $repository = EntityHelper::getRepository('Avisota\\Contao:Message');
                     $message = $repository->find($parentModelId->getId());
                     $category = $message->getCategory();
                 } else {
                     if ($modelId && $modelId->getDataProviderName() == 'orm_avisota_message_content') {
                         $repository = EntityHelper::getRepository('Avisota\\Contao:MessageContent');
                         $content = $repository->find($modelId->getId());
                         $message = $content->getMessage();
                         $category = $message->getCategory();
                     } else {
                         if ($parentModelId && $parentModelId->getDataProviderName() == 'orm_avisota_message_content') {
                             $repository = EntityHelper::getRepository('Avisota\\Contao:MessageContent');
                             $content = $repository->find($parentModelId->getId());
                             $message = $content->getMessage();
                             $category = $message->getCategory();
                         }
                     }
                 }
             }
         }
     }
     return $category;
 }
예제 #5
0
파일: Subscriber.php 프로젝트: zonky2/core
 /**
  * Clear the button if the User is not admin.
  *
  * @param GetOperationButtonEvent $event The event.
  *
  * @return void
  */
 public function getOperationButton(GetOperationButtonEvent $event)
 {
     if ($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel') {
         return;
     }
     $command = $event->getCommand();
     if ($command->getName() == 'dca_combine') {
         $event->setHref(UrlBuilder::fromUrl($event->getHref())->setQueryParameter('id', ModelId::fromValues('tl_metamodel_dca_combine', $event->getModel()->getId())->getSerialized())->getUrl());
     }
 }
예제 #6
0
 /**
  * Load the parent model for the current list.
  *
  * @param InputProviderInterface $input       The input provider.
  *
  * @param EnvironmentInterface   $environment The environment.
  *
  * @return ModelInterface|null
  */
 protected function loadParentModel(InputProviderInterface $input, EnvironmentInterface $environment)
 {
     if (!$input->hasParameter('pid')) {
         return null;
     }
     $pid = ModelId::fromSerialized($input->getParameter('pid'));
     if (!($dataProvider = $environment->getDataProvider($pid->getDataProviderName()))) {
         return null;
     }
     if ($parent = $dataProvider->fetch($dataProvider->getEmptyConfig()->setId($pid->getId()))) {
         return $parent;
     }
     return null;
 }
 /**
  * Get the bread crumb elements.
  *
  * @param GetBreadcrumbEvent $event This event.
  *
  * @return void
  */
 public function getBreadCrumb(GetBreadcrumbEvent $event)
 {
     $environment = $event->getEnvironment();
     $dataDefinition = $environment->getDataDefinition();
     $inputProvider = $environment->getInputProvider();
     $modelParameter = $inputProvider->hasParameter('act') ? 'id' : 'pid';
     if ($dataDefinition->getName() !== 'orm_avisota_recipient_source' || !$inputProvider->hasParameter($modelParameter)) {
         return;
     }
     $modelId = ModelId::fromSerialized($inputProvider->getParameter($modelParameter));
     if ($modelId->getDataProviderName() !== 'orm_avisota_recipient_source') {
         return;
     }
     $elements = $event->getElements();
     $urlBuilder = new UrlBuilder();
     $urlBuilder->setPath('contao/main.php')->setQueryParameter('do', $inputProvider->getParameter('do'))->setQueryParameter('ref', TL_REFERER_ID);
     $elements[] = array('icon' => 'assets/avisota/core/images/recipient_source.png', 'text' => $GLOBALS['TL_LANG']['MOD']['avisota_recipient_source'][0], 'url' => $urlBuilder->getUrl());
     $event->setElements($elements);
 }
예제 #8
0
 /**
  * Get the bread crumb elements.
  *
  * @param GetBreadcrumbEvent $event This event.
  *
  * @return void
  */
 public function getBreadCrumb(GetBreadcrumbEvent $event)
 {
     $environment = $event->getEnvironment();
     $dataDefinition = $environment->getDataDefinition();
     $inputProvider = $environment->getInputProvider();
     if ($dataDefinition->getName() !== 'orm_avisota_transport' || !$inputProvider->hasParameter('id')) {
         return;
     }
     $modelId = ModelId::fromSerialized($inputProvider->getParameter('id'));
     if ($modelId->getDataProviderName() !== 'orm_avisota_transport') {
         return;
     }
     $elements = $event->getElements();
     $urlBuilder = new UrlBuilder();
     $urlBuilder->setPath('contao/main.php')->setQueryParameter('do', 'avisota_transport')->setQueryParameter('ref', TL_REFERER_ID);
     $translator = $environment->getTranslator();
     $elements[] = array('icon' => 'assets/avisota/core/images/transport.png', 'text' => $translator->translate('avisota_transport.0', 'MOD'), 'url' => $urlBuilder->getUrl());
     $event->setElements($elements);
 }
 /**
  * Handle the action.
  *
  * @return mixed
  *
  * @throws DcGeneralRuntimeException When the definition is not creatable.
  */
 public function process()
 {
     $environment = $this->getEnvironment();
     $event = $this->getEvent();
     $definition = $environment->getDataDefinition();
     $basicDefinition = $definition->getBasicDefinition();
     if (!$basicDefinition->isCreatable()) {
         throw new DcGeneralRuntimeException('DataContainer ' . $definition->getName() . ' is not creatable');
     }
     // We only support flat tables, sorry.
     if (BasicDefinitionInterface::MODE_FLAT !== $basicDefinition->getMode()) {
         return;
     }
     $modelId = ModelId::fromSerialized($environment->getInputProvider()->getParameter('id'));
     $dataProvider = $environment->getDataProvider();
     $model = $dataProvider->fetch($dataProvider->getEmptyConfig()->setId($modelId->getId()));
     $clone = $dataProvider->getEmptyModel();
     $editMask = new EditMask($environment, $model, $clone, null, null);
     $event->setResponse($editMask->execute());
 }
 /**
  * Handle the event.
  *
  * @param HandleSubmitEvent $event The event.
  *
  * @return void
  */
 public function handleEvent(HandleSubmitEvent $event)
 {
     $dispatcher = func_get_arg(2);
     $currentUrl = $this->environment->get('uri');
     switch ($event->getButtonName()) {
         case 'save':
             // Could be a create action, always redirect to current page with edit action and id properly set.
             $url = UrlBuilder::fromUrl($currentUrl)->setQueryParameter('act', 'edit')->setQueryParameter('id', ModelId::fromModel($event->getModel())->getSerialized());
             $dispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($url->getUrl()));
             break;
         case 'saveNcreate':
             // We want to create a new model, set create action and pass the current id as "after" to keep sorting.
             $after = ModelId::fromModel($event->getModel());
             $url = UrlBuilder::fromUrl($currentUrl)->unsetQueryParameter('id')->setQueryParameter('act', 'create')->setQueryParameter('after', $after->getSerialized());
             $dispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($url->getUrl()));
             break;
         default:
             // Do nothing.
     }
 }
예제 #11
0
 /**
  * @param EnvironmentInterface $environment
  *
  * @return string
  * @internal param DC_General $dc
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function renderPreviewView(EnvironmentInterface $environment)
 {
     /** @var EventDispatcher $eventDispatcher */
     $eventDispatcher = $GLOBALS['container']['event-dispatcher'];
     $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('avisota_message_preview'));
     $eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('orm_avisota_message'));
     $messageRepository = EntityHelper::getRepository('Avisota\\Contao:Message');
     $messageId = ModelId::fromSerialized(\Input::get('id') ? \Input::get('id') : \Input::get('pid'));
     $message = $messageRepository->find($messageId->getId());
     if (!$message) {
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent(preg_replace('#&(act=preview|id=[a-f0-9\\-]+)#', '', \Environment::get('request'))));
     }
     $modules = new StringBuilder();
     /** @var \Avisota\Contao\Message\Core\Send\SendModuleInterface $module */
     foreach ($GLOBALS['AVISOTA_SEND_MODULE'] as $className) {
         $class = new \ReflectionClass($className);
         $module = $class->newInstance();
         $modules->append($module->run($message));
     }
     $context = array('message' => $message, 'modules' => $modules);
     $template = new \TwigTemplate('avisota/backend/preview', 'html5');
     return $template->parse($context);
 }
예제 #12
0
 /**
  * Retrieve the base data provider config for the current data definition.
  *
  * This includes parent filter when in parented list mode and the additional filters from the data definition.
  *
  * @param ModelIdInterface|null $parentId The parent to use.
  *
  * @return ConfigInterface
  */
 private function buildBaseConfig($parentId)
 {
     $environment = $this->getEnvironment();
     $config = $environment->getDataProvider()->getEmptyConfig();
     $definition = $environment->getDataDefinition();
     $additional = $definition->getBasicDefinition()->getAdditionalFilter();
     // Custom filter common for all modes.
     if ($additional) {
         $config->setFilter($additional);
     }
     if (!$config->getSorting()) {
         /** @var Contao2BackendViewDefinitionInterface $viewDefinition */
         $viewDefinition = $definition->getDefinition(Contao2BackendViewDefinitionInterface::NAME);
         $config->setSorting($viewDefinition->getListingConfig()->getDefaultSortingFields());
     }
     // Special filter for certain modes.
     if ($parentId) {
         $this->addParentFilter($parentId, $config);
     } elseif ($definition->getBasicDefinition()->getMode() == BasicDefinitionInterface::MODE_PARENTEDLIST) {
         $pid = $environment->getInputProvider()->getParameter('pid');
         $pidDetails = ModelId::fromSerialized($pid);
         $this->addParentFilter($pidDetails, $config);
     }
     return $config;
 }
예제 #13
0
 /**
  * {@inheritdoc}
  */
 public function process()
 {
     $event = $this->getEvent();
     if ($event->getAction()->getName() !== 'copy') {
         return;
     }
     $environment = $this->getEnvironment();
     $modelId = ModelId::fromSerialized($environment->getInputProvider()->getParameter('source'));
     $this->guardValidEnvironment($modelId);
     // We want a redirect here if not creatable.
     $this->guardIsCreatable($modelId, true);
     if ($this->isEditOnlyResponse()) {
         return;
     }
     // Manual sorting mode. The ClipboardController should pick it up.
     $manualSortingProperty = ViewHelpers::getManualSortingProperty($environment);
     if ($manualSortingProperty && $this->environment->getDataProvider()->fieldExists($manualSortingProperty)) {
         return;
     }
     $copiedModel = $this->copy($modelId);
     $this->redirect($environment, ModelId::fromModel($copiedModel));
 }
예제 #14
0
 /**
  * Handle the "create variant" event.
  *
  * @param ActionEvent $event The action Event being executed.
  *
  * @return void
  *
  * @throws \RuntimeException When the base model can not be found.
  * @throws \InvalidArgumentException When the view in the environment is incompatible.
  */
 public function handleCreateVariantAction(ActionEvent $event)
 {
     if ($event->getAction()->getName() != 'createvariant') {
         return;
     }
     $environment = $event->getEnvironment();
     $view = $environment->getView();
     $dataProvider = $environment->getDataProvider();
     $inputProvider = $environment->getInputProvider();
     $modelId = $inputProvider->hasParameter('id') ? ModelId::fromSerialized($inputProvider->getParameter('id')) : null;
     /** @var \MetaModels\DcGeneral\Data\Driver $dataProvider */
     $model = $dataProvider->createVariant($dataProvider->getEmptyConfig()->setId($modelId->getId()));
     if ($model == null) {
         throw new \RuntimeException(sprintf('Could not find model with id %s for creating a variant.', $modelId));
     }
     $metaModel = $this->getServiceContainer()->getFactory()->getMetaModel($model->getProviderName());
     if (!$metaModel || !$metaModel->hasVariants()) {
         return;
     }
     $preFunction = function ($environment, $model) {
         /** @var EnvironmentInterface $environment */
         $copyEvent = new PreCreateModelEvent($environment, $model);
         $environment->getEventDispatcher()->dispatch($copyEvent::NAME, $copyEvent);
     };
     $postFunction = function ($environment, $model) {
         /** @var EnvironmentInterface $environment */
         $copyEvent = new PostCreateModelEvent($environment, $model);
         $environment->getEventDispatcher()->dispatch($copyEvent::NAME, $copyEvent);
     };
     if (!$view instanceof BackendViewInterface) {
         throw new \InvalidArgumentException('Invalid view registered in environment.');
     }
     $editMask = new EditMask($view, $model, null, $preFunction, $postFunction, $this->breadcrumb($environment));
     $event->setResponse($editMask->execute());
 }
예제 #15
0
 /**
  * Calculate the href for a command.
  *
  * @param CommandInterface $command The command.
  *
  * @param ModelInterface   $model   The current model.
  *
  * @return string
  */
 private function calculateHref(CommandInterface $command, $model)
 {
     $modelId = ModelId::fromModel($model)->getSerialized();
     $parameters = $this->calculateParameters($command, $modelId);
     $href = '';
     foreach ($parameters as $key => $value) {
         $href .= sprintf('&%s=%s', $key, $value);
     }
     return $this->addToUrl($href);
 }
예제 #16
0
 /**
  * Retrieve a list of html buttons to use in the top panel (submit area).
  *
  * @param ModelInterface $parentModel The parent model.
  *
  * @return null|string
  */
 protected function getHeaderEditButtons($parentModel)
 {
     $environment = $this->getEnvironment();
     $parentDefinition = $environment->getParentDataDefinition();
     if ($parentDefinition && $parentDefinition->getBasicDefinition()->isEditable()) {
         $definition = $environment->getDataDefinition();
         $basicDefinition = $definition->getBasicDefinition();
         $parentName = $basicDefinition->getParentDataProvider();
         $dispatcher = $environment->getEventDispatcher();
         $query = array('do' => $environment->getInputProvider()->getParameter('do'), 'act' => 'edit', 'table' => $parentName, 'id' => ModelId::fromModel($parentModel)->getSerialized());
         $factory = DcGeneralFactory::deriveFromEnvironment($this->environment);
         $factory->setContainerName($parentDefinition->getName());
         $parentContainer = $factory->createContainer();
         if ($parentContainer->getBasicDefinition()->getParentDataProvider()) {
             $container = $this->environment->getDataDefinition();
             $relationship = $container->getModelRelationshipDefinition()->getChildCondition($parentContainer->getBasicDefinition()->getParentDataProvider(), $parentContainer->getName());
             if ($relationship) {
                 $filter = $relationship->getInverseFilterFor($parentModel);
                 $grandParentProvider = $this->environment->getDataProvider($parentContainer->getBasicDefinition()->getParentDataProvider());
                 $config = $grandParentProvider->getEmptyConfig();
                 $config->setFilter($filter);
                 $parents = $grandParentProvider->fetchAll($config);
                 if ($parents->length() == 1) {
                     $query['pid'] = ModelId::fromModel($parents->get(0))->getSerialized();
                 } elseif ($parents->length() > 1) {
                     return null;
                 }
             }
         }
         /** @var GenerateHtmlEvent $imageEvent */
         $imageEvent = $dispatcher->dispatch(ContaoEvents::IMAGE_GET_HTML, new GenerateHtmlEvent('edit.gif', $this->translate('editheader.0', $definition->getName())));
         return sprintf('<a href="%s" title="%s" onclick="Backend.getScrollOffset()">%s</a>', 'contao/main.php?' . str_replace('%3A', ':', http_build_query($query)), specialchars($this->translate('editheader.1', $definition->getName())), $imageEvent->getHtml());
     }
     return null;
 }
예제 #17
0
 /**
  * Retrieve the MetaModel attached to the model filter setting.
  *
  * @param EnvironmentInterface $environment The environment.
  *
  * @return \MetaModels\IMetaModel
  */
 public function getMetaModel(EnvironmentInterface $environment)
 {
     $metaModelId = $this->getDatabase()->prepare('SELECT id FROM tl_metamodel WHERE id=(SELECT pid FROM tl_metamodel_dca WHERE id=?)')->execute(ModelId::fromSerialized($environment->getInputProvider()->getParameter('pid'))->getId());
     /** @noinspection PhpUndefinedFieldInspection */
     return $this->getMetaModelById($metaModelId->id);
 }
예제 #18
0
 /**
  * Handle the submit and determine which button has been triggered.
  *
  * This method will redirect the client.
  *
  * @param ModelInterface $model The model that has been submitted.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 protected function handleSubmit(ModelInterface $model)
 {
     $environment = $this->getEnvironment();
     $dispatcher = $environment->getEventDispatcher();
     $inputProvider = $environment->getInputProvider();
     if ($inputProvider->hasValue('save')) {
         $newUrlEvent = new AddToUrlEvent('act=edit&id=' . ModelId::fromModel($model)->getSerialized());
         $dispatcher->dispatch(ContaoEvents::BACKEND_ADD_TO_URL, $newUrlEvent);
         $dispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($newUrlEvent->getUrl()));
     } elseif ($inputProvider->hasValue('saveNclose')) {
         $this->clearBackendStates();
         $newUrlEvent = new GetReferrerEvent();
         $dispatcher->dispatch(ContaoEvents::SYSTEM_GET_REFERRER, $newUrlEvent);
         $dispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($newUrlEvent->getReferrerUrl()));
     } elseif ($inputProvider->hasValue('saveNcreate')) {
         $this->clearBackendStates();
         $after = ModelId::fromModel($model);
         $newUrlEvent = new AddToUrlEvent('act=create&id=&after=' . $after->getSerialized());
         $dispatcher->dispatch(ContaoEvents::BACKEND_ADD_TO_URL, $newUrlEvent);
         $dispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($newUrlEvent->getUrl()));
     } elseif ($inputProvider->hasValue('saveNback')) {
         $this->clearBackendStates();
         $parentProviderName = $environment->getDataDefinition()->getBasicDefinition()->getParentDataProvider();
         $newUrlEvent = new GetReferrerEvent(false, $parentProviderName);
         $dispatcher->dispatch(ContaoEvents::SYSTEM_GET_REFERRER, $newUrlEvent);
         $dispatcher->dispatch(ContaoEvents::CONTROLLER_REDIRECT, new RedirectEvent($newUrlEvent->getReferrerUrl()));
     }
 }
예제 #19
0
파일: Subscriber.php 프로젝트: zonky2/core
 /**
  * Generate the paste button.
  *
  * @param GetPasteButtonEvent $event The event.
  *
  * @return void
  */
 public function generatePasteButton(GetPasteButtonEvent $event)
 {
     if ($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_filtersetting') {
         return;
     }
     $environment = $event->getEnvironment();
     $model = $event->getModel();
     $clipboard = $environment->getClipboard();
     $filter = new Filter();
     $filter->andModelIs(ModelId::fromModel($model))->andActionIs($clipboard::MODE_CUT);
     // Disable all buttons if there is a circular reference.
     if ($event->isCircularReference() || !$clipboard->isEmpty($filter)) {
         $event->setPasteAfterDisabled(true)->setPasteIntoDisabled(true);
         return;
     }
     $factory = $this->getServiceContainer()->getFilterFactory()->getTypeFactory($model->getProperty('type'));
     // If setting does not support children, omit them.
     if ($model->getId() && !($factory && $factory->isNestedType())) {
         $event->setPasteIntoDisabled(true);
     }
 }
예제 #20
0
 /**
  * Generate the paste button.
  *
  * @param GetPasteButtonEvent $event The event.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 public function generatePasteButton(GetPasteButtonEvent $event)
 {
     if ($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_dcasetting_condition') {
         return;
     }
     $environment = $event->getEnvironment();
     $model = $event->getModel();
     $clipboard = $environment->getClipboard();
     // Disable all buttons if there is a circular reference.
     if ($clipboard->fetch(Filter::create()->andActionIs(ItemInterface::CUT)->andModelIs(ModelId::fromModel($model)))) {
         $event->setPasteAfterDisabled(true)->setPasteIntoDisabled(true);
         return;
     }
     $flags = $GLOBALS['METAMODELS']['inputscreen_conditions'][$model->getProperty('type')];
     // If setting does not support children, omit them.
     if ($model->getId() && !$flags['nestingAllowed']) {
         $event->setPasteIntoDisabled(true);
         return;
     }
     if (isset($flags['maxChildren']) && count($event->getEnvironment()->getController()->assembleAllChildrenFrom($model)) > $flags['maxChildren']) {
         $event->setPasteIntoDisabled(true);
     }
 }
예제 #21
0
 /**
  * Test valid model ids.
  *
  * @param string      $testId    The id to test.
  *
  * @param string|null $exception The name of the expected exception class.
  *
  * @dataProvider idProvider
  *
  * @return void
  */
 public function testValidIds($testId, $exception = null)
 {
     if (null !== $exception) {
         $this->setExpectedException($exception);
     }
     $this->assertEquals($testId, ModelId::fromSerialized($testId)->getSerialized());
 }
 /**
  * Get the parent model id.
  *
  * Returns null if no parent id is given.
  *
  * @return ModelIdInterface|null
  */
 protected function getParentId()
 {
     $parentIdRaw = $this->getEnvironment()->getInputProvider()->getParameter('pid');
     if ($parentIdRaw) {
         $parentId = ModelId::fromSerialized($parentIdRaw);
         return $parentId;
     }
     return null;
 }
 /**
  * Handle "old" add to clipboard actions.
  *
  * @param ActionEvent $event The action event.
  *
  * @return void
  */
 private function addToClipboard(ActionEvent $event)
 {
     $actionName = $event->getAction()->getName();
     $environment = $event->getEnvironment();
     $input = $environment->getInputProvider();
     $clipboard = $environment->getClipboard();
     $parentIdRaw = $input->getParameter('pid');
     if ($parentIdRaw) {
         $parentId = ModelId::fromSerialized($parentIdRaw);
     } else {
         $parentId = null;
     }
     $clipboardActionName = $this->translateActionName($actionName);
     if (!$clipboardActionName) {
         return;
     }
     if ('create' === $actionName) {
         if ($this->isAddingAllowed($environment)) {
             return;
         }
         $providerName = $environment->getDataDefinition()->getBasicDefinition()->getDataProvider();
         $item = new UnsavedItem($clipboardActionName, $parentId, $providerName);
         // Remove other create items, there can only be one create item in the clipboard or many others
         $clipboard->clear();
     } else {
         $modelIdRaw = $input->getParameter('source');
         $modelId = ModelId::fromSerialized($modelIdRaw);
         $filter = new Filter();
         $filter->andActionIs(ItemInterface::CREATE);
         $items = $clipboard->fetch($filter);
         foreach ($items as $item) {
             $clipboard->remove($item);
         }
         // Only push item to clipboard if manual sorting is used.
         if (Item::COPY === $clipboardActionName && !ViewHelpers::getManualSortingProperty($environment)) {
             return;
         }
         // create the new item
         $item = new Item($clipboardActionName, $parentId, $modelId);
     }
     // Let the clipboard save it's values persistent.
     $clipboard->clear()->push($item)->saveTo($environment);
     ViewHelpers::redirectHome($environment);
 }
예제 #24
0
파일: Subscriber.php 프로젝트: zonky2/core
 /**
  * Handle the add all action event.
  *
  * @param ActionEvent $event The event.
  *
  * @return void
  *
  * @throws \RuntimeException When the MetaModel can not be retrieved.
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 public function handleAddAll(ActionEvent $event)
 {
     if ($event->getEnvironment()->getDataDefinition()->getName() !== 'tl_metamodel_dcasetting') {
         return;
     }
     if ($event->getAction()->getName() !== 'dca_addall') {
         return;
     }
     $environment = $event->getEnvironment();
     $dispatcher = $environment->getEventDispatcher();
     $database = $this->getDatabase();
     $input = $environment->getInputProvider();
     $pid = ModelId::fromSerialized($input->getParameter('pid'));
     $dispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('default'));
     $dispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, new LoadLanguageFileEvent('tl_metamodel_dcasetting'));
     $referrer = new GetReferrerEvent(true, 'tl_metamodel_dcasetting');
     $dispatcher->dispatch(ContaoEvents::SYSTEM_GET_REFERRER, $referrer);
     $template = new \BackendTemplate('be_autocreatepalette');
     $template->cacheMessage = '';
     $template->updateMessage = '';
     $template->href = $referrer->getReferrerUrl();
     $template->headline = $GLOBALS['TL_LANG']['tl_metamodel_dcasetting']['addall'][1];
     // Severity is: error, confirm, info, new.
     $messages = array();
     $palette = $database->prepare('SELECT * FROM tl_metamodel_dca WHERE id=?')->execute($pid->getId());
     $metaModel = $this->getMetaModelById($palette->pid);
     if (!$metaModel) {
         throw new \RuntimeException('Could not retrieve MetaModel ' . $palette->pid);
     }
     $alreadyExisting = $database->prepare('SELECT * FROM tl_metamodel_dcasetting WHERE pid=?')->execute($pid->getId());
     $knownAttributes = array();
     $intMax = 128;
     while ($alreadyExisting->next()) {
         $knownAttributes[$alreadyExisting->attr_id] = $alreadyExisting->row();
         if ($intMax < $alreadyExisting->sorting) {
             $intMax = $alreadyExisting->sorting;
         }
     }
     $blnWantPerform = false;
     // Perform the labour work.
     if ($input->getValue('act') == 'perform') {
         $this->perform($metaModel, $knownAttributes, $intMax, $pid->getId(), $messages);
     } else {
         // Loop over all attributes now.
         foreach ($metaModel->getAttributes() as $attribute) {
             if (array_key_exists($attribute->get('id'), $knownAttributes)) {
                 $messages[] = array('severity' => 'info', 'message' => sprintf($GLOBALS['TL_LANG']['tl_metamodel_dcasetting']['addAll_alreadycontained'], $attribute->getName()));
             } else {
                 $messages[] = array('severity' => 'confirm', 'message' => sprintf($GLOBALS['TL_LANG']['tl_metamodel_dcasetting']['addAll_willadd'], $attribute->getName()));
                 $blnWantPerform = true;
             }
         }
     }
     if ($blnWantPerform) {
         $template->action = ampersand(\Environment::get('request'));
         $template->submit = $GLOBALS['TL_LANG']['MSC']['continue'];
     } else {
         $template->action = ampersand($referrer->getReferrerUrl());
         $template->submit = $GLOBALS['TL_LANG']['MSC']['saveNclose'];
     }
     $template->error = $messages;
     $event->setResponse($template->parse());
 }
예제 #25
0
 /**
  * @SuppressWarnings(PHPMD.ShortVariable)
  */
 public function generate()
 {
     $do = \Input::get('do');
     $id = preg_replace('#^avisota_category_(.*)$#', '$1', $do);
     $serializer = new ModelId('orm_avisota_message_category', $id);
     $this->redirect('contao/main.php?do=avisota_newsletter&table=orm_avisota_message&pid=' . $serializer->getSerialized());
 }
예제 #26
0
 /**
  * Create the "new" button.
  *
  * @return null|Command
  */
 protected function getCreateModelCommand()
 {
     $environment = $this->getEnvironment();
     $definition = $environment->getDataDefinition();
     $basicDefinition = $definition->getBasicDefinition();
     $providerName = $environment->getDataDefinition()->getName();
     $mode = $basicDefinition->getMode();
     $config = $this->getEnvironment()->getBaseConfigRegistry()->getBaseConfig();
     if ($serializedPid = $environment->getInputProvider()->getParameter('pid')) {
         $pid = ModelId::fromSerialized($serializedPid);
     } else {
         $pid = null;
     }
     if (!$basicDefinition->isCreatable()) {
         return null;
     }
     $command = new Command();
     $parameters = $command->getParameters();
     $extra = $command->getExtra();
     $extra['class'] = 'header_new';
     $extra['accesskey'] = 'n';
     $extra['attributes'] = 'onclick="Backend.getScrollOffset();"';
     $command->setName('button_new')->setLabel($this->translate('new.0', $providerName))->setDescription($this->translate('new.1', $providerName));
     $this->getPanel()->initialize($config);
     // Add new button.
     if ($mode == BasicDefinitionInterface::MODE_PARENTEDLIST || $mode == BasicDefinitionInterface::MODE_HIERARCHICAL) {
         $filter = new Filter();
         $filter->andModelIsFromProvider($basicDefinition->getDataProvider());
         if ($parentDataProviderName = $basicDefinition->getParentDataProvider()) {
             $filter->andParentIsFromProvider($parentDataProviderName);
         } else {
             $filter->andHasNoParent();
         }
         if ($environment->getClipboard()->isNotEmpty($filter)) {
             return null;
         }
     }
     $parameters['act'] = 'create';
     // Add new button.
     if ($pid) {
         $parameters['pid'] = $pid->getSerialized();
     }
     return $command;
 }
 /**
  * Do deep copy.
  *
  * @param array $deepCopyList The deep copy list.
  *
  * @return void
  */
 protected function doDeepCopy(array $deepCopyList)
 {
     if (empty($deepCopyList)) {
         return;
     }
     $factory = DcGeneralFactory::deriveFromEnvironment($this->getEnvironment());
     $dataDefinition = $this->getEnvironment()->getDataDefinition();
     $modelRelationshipDefinition = $dataDefinition->getModelRelationshipDefinition();
     $childConditions = $modelRelationshipDefinition->getChildConditions($dataDefinition->getName());
     foreach ($deepCopyList as $deepCopy) {
         /** @var ModelInterface $origin */
         $origin = $deepCopy['origin'];
         /** @var ModelInterface $model */
         $model = $deepCopy['model'];
         $parentId = ModelId::fromModel($model);
         foreach ($childConditions as $childCondition) {
             // create new destination environment
             $destinationName = $childCondition->getDestinationName();
             $factory->setContainerName($destinationName);
             $destinationEnvironment = $factory->createEnvironment();
             $destinationDataDefinition = $destinationEnvironment->getDataDefinition();
             $destinationViewDefinition = $destinationDataDefinition->getDefinition(Contao2BackendViewDefinitionInterface::NAME);
             $destinationDataProvider = $destinationEnvironment->getDataProvider();
             $destinationController = $destinationEnvironment->getController();
             /** @var Contao2BackendViewDefinitionInterface $destinationViewDefinition */
             /** @var DefaultController $destinationController */
             $listingConfig = $destinationViewDefinition->getListingConfig();
             $groupAndSortingCollection = $listingConfig->getGroupAndSortingDefinition();
             $groupAndSorting = $groupAndSortingCollection->getDefault();
             // ***** fetch the children
             $filter = $childCondition->getFilter($origin);
             // apply parent-child condition
             $config = $destinationDataProvider->getEmptyConfig();
             $config->setFilter($filter);
             // apply sorting
             $sorting = array();
             foreach ($groupAndSorting as $information) {
                 /** @var GroupAndSortingInformationInterface $information */
                 $sorting[$information->getProperty()] = $information->getSortingMode();
             }
             $config->setSorting($sorting);
             // receive children
             $children = $destinationDataProvider->fetchAll($config);
             // ***** do the deep copy
             $actions = array();
             // build the copy actions
             foreach ($children as $childModel) {
                 $childModelId = ModelId::fromModel($childModel);
                 $actions[] = array('model' => $childModel, 'item' => new Item(ItemInterface::DEEP_COPY, $parentId, $childModelId));
             }
             // do the deep copy
             $childrenModels = $destinationController->doActions($actions, null, null, $parentId);
             // ensure parent-child condition
             foreach ($childrenModels as $childrenModel) {
                 $childCondition->applyTo($model, $childrenModel);
             }
             $destinationDataProvider->saveEach($childrenModels);
         }
     }
 }
예제 #28
0
 /**
  * Handle the show event.
  *
  * @return void
  *
  * @throws DcGeneralRuntimeException  The error.
  */
 public function process()
 {
     $environment = $this->getEnvironment();
     if ($environment->getDataDefinition()->getBasicDefinition()->isEditOnlyMode()) {
         $this->getEvent()->setResponse($environment->getView()->edit($this->getEvent()->getAction()));
         return;
     }
     $translator = $environment->getTranslator();
     $modelId = ModelId::fromSerialized($environment->getInputProvider()->getParameter('id'));
     $dataProvider = $environment->getDataProvider($modelId->getDataProviderName());
     $model = $this->getModel();
     $data = $this->convertModel($model, $environment);
     $headline = $this->getHeadline($model);
     $template = new ContaoBackendViewTemplate('dcbe_general_show');
     $template->set('headline', $headline)->set('arrFields', $data['values'])->set('arrLabels', $data['labels']);
     if ($dataProvider instanceof MultiLanguageDataProviderInterface) {
         $template->set('languages', $environment->getController()->getSupportedLanguages($model->getId()))->set('currentLanguage', $dataProvider->getCurrentLanguage())->set('languageSubmit', specialchars($translator->translate('MSC.showSelected')))->set('backBT', specialchars($translator->translate('MSC.backBT')));
     } else {
         $template->set('languages', null);
     }
     $this->getEvent()->setResponse($template->parse());
 }
예제 #29
0
 /**
  * Handle the action event.
  *
  * @param ActionEvent $event The event to handle.
  *
  * @return void
  *
  * @throws \RuntimeException When the MetaModel could not be determined.
  */
 public function handleActionEvent(ActionEvent $event)
 {
     $environment = $event->getEnvironment();
     if ($environment->getDataDefinition()->getName() !== static::$table) {
         return;
     }
     if ($event->getAction()->getName() !== static::$actionName) {
         return;
     }
     $this->input = $environment->getInputProvider();
     $referrer = new GetReferrerEvent(true, static::$table);
     $this->dispatcher->dispatch(ContaoEvents::SYSTEM_GET_REFERRER, $referrer);
     $this->environment = $environment;
     $this->translator = $environment->getTranslator();
     $pid = ModelId::fromSerialized($this->input->getParameter('pid'))->getId();
     $this->metaModel = $this->getMetaModelById($this->database->prepare('SELECT * FROM ' . static::$ptable . ' WHERE id=?')->execute($pid)->pid);
     if (!$this->metaModel) {
         throw new \RuntimeException('Could not retrieve MetaModel from ' . $this->input->getParameter('pid'));
     }
     $startSort = 0;
     $this->knownAttributes = array();
     $alreadyExisting = $this->database->prepare('SELECT * FROM ' . static::$table . ' WHERE pid=? ORDER BY sorting ASC')->execute($pid);
     while ($alreadyExisting->next()) {
         $this->knownAttributes[$alreadyExisting->attr_id] = $alreadyExisting->row();
         // Keep the sorting value.
         $startSort = $alreadyExisting->sorting;
     }
     if ($this->input->hasValue('add') || $this->input->hasValue('saveNclose')) {
         $this->perform($startSort + 128, $pid);
     }
     if ($this->input->hasValue('saveNclose')) {
         \Controller::redirect($referrer->getReferrerUrl());
     }
     $this->template = new \BackendTemplate('be_addallattributes');
     $this->template->href = $referrer->getReferrerUrl();
     $this->template->backBt = $this->translator->translate('MSC.backBT');
     $this->template->add = $this->translator->translate('MSC.continue');
     $this->template->saveNclose = $this->translator->translate('MSC.saveNclose');
     $this->template->headline = $this->translator->translate('addall.1', static::$table);
     $this->template->selectAll = $this->translator->translate('MSC.selectAll');
     $this->template->cacheMessage = '';
     $this->template->updateMessage = '';
     $this->template->hasCheckbox = false;
     $this->template->fields = $this->generateForm();
     $event->setResponse($this->template->parse());
 }
예제 #30
0
 /**
  * Retrieve a model from a serialized id.
  *
  * Exits the script if no model has been found.
  *
  * @param string $serializedId The serialized id.
  *
  * @return ModelInterface
  */
 protected function getModelFromSerializedId($serializedId)
 {
     $modelId = ModelId::fromSerialized($serializedId);
     $dataProvider = $this->getEnvironment()->getDataProvider($modelId->getDataProviderName());
     $model = $dataProvider->fetch($dataProvider->getEmptyConfig()->setId($modelId->getId()));
     if ($model === null) {
         $event = new LogEvent('A record with the ID "' . $serializedId . '" does not exist in "' . $this->getEnvironment()->getDataDefinition()->getName() . '"', 'Ajax executePostActions()', TL_ERROR);
         $this->getEnvironment()->getEventDispatcher()->dispatch(ContaoEvents::SYSTEM_LOG, $event);
         header('HTTP/1.1 400 Bad Request');
         echo 'Bad Request';
         $this->exitScript();
     }
     return $model;
 }