예제 #1
0
 /**
  * Breadcrumbs
  *
  * @param Request $request
  *
  * @return mixed
  */
 public function createBreadcrumbsMenu(Request $request)
 {
     $menu = $this->factory->createItem('root');
     $menu->setUri($request->getRequestUri());
     $menu->addChild($this->translator->trans('Главная'), array('route' => 'homepage'));
     return $menu;
 }
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
         return;
     }
     $request = $event->getRequest();
     $fc_form = $this->form_service->guessFcForm($request);
     if (!$fc_form instanceof FcForm) {
         return;
     }
     if ($fc_form->getAction()) {
         return;
     }
     /** @var FormInterface $form */
     $form = $this->form_service->create($fc_form);
     $form->handleRequest($request);
     if ($form->isValid()) {
         $data = $form->getData();
         $this->form_service->clear($fc_form, array('template' => $data['_template'], 'data' => $this->form_service->initData($data)));
         if ($fc_form->getIsAjax()) {
             return;
         }
         if ($fc_form->getMessage()) {
             $message = $fc_form->getMessage();
         } else {
             $message = $this->translator->trans('fc.message.form.is_valid', array(), 'FenrizbesFormConstructorBundle');
         }
         // TODO: Связывать сообщение с конкретной формой и подчищать старые
         $this->session->getFlashBag()->add('fc_form.success', $message);
         $response = new RedirectResponse($this->router->generate($request->get('_route'), $request->get('_route_params')));
         $event->setResponse($response);
     }
 }
예제 #3
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->addEventSubscriber(new CleanFormSubscriber());
     $builder->addEventSubscriber(new FormExitSubscriber('user.user', $options));
     $builder->add('username', 'text', array('label' => 'mautic.core.username', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'preaddon' => 'fa fa-user', 'autocomplete' => 'off')));
     $builder->add('firstName', 'text', array('label' => 'mautic.core.firstname', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control')));
     $builder->add('lastName', 'text', array('label' => 'mautic.core.lastname', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control')));
     $positions = $this->model->getLookupResults('position', null, 0, true);
     $builder->add('position', 'text', array('label' => 'mautic.core.position', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'data-options' => json_encode($positions)), 'required' => false));
     $builder->add('email', 'email', array('label' => 'mautic.core.type.email', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'preaddon' => 'fa fa-envelope')));
     $existing = !empty($options['data']) && $options['data']->getId();
     $placeholder = $existing ? $this->translator->trans('mautic.user.user.form.passwordplaceholder') : '';
     $required = $existing ? false : true;
     $builder->add('plainPassword', 'repeated', array('first_name' => 'password', 'first_options' => array('label' => 'mautic.core.password', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'placeholder' => $placeholder, 'tooltip' => 'mautic.user.user.form.help.passwordrequirements', 'preaddon' => 'fa fa-lock', 'autocomplete' => 'off'), 'required' => $required, 'error_bubbling' => false), 'second_name' => 'confirm', 'second_options' => array('label' => 'mautic.user.user.form.passwordconfirm', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'placeholder' => $placeholder, 'tooltip' => 'mautic.user.user.form.help.passwordrequirements', 'preaddon' => 'fa fa-lock', 'autocomplete' => 'off'), 'required' => $required, 'error_bubbling' => false), 'type' => 'password', 'invalid_message' => 'mautic.user.user.password.mismatch', 'required' => $required, 'error_bubbling' => false));
     $builder->add('timezone', 'timezone', array('label' => 'mautic.core.timezone', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'), 'multiple' => false, 'empty_value' => 'mautic.user.user.form.defaulttimezone'));
     $builder->add('locale', 'choice', array('choices' => $this->supportedLanguages, 'label' => 'mautic.core.language', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'), 'multiple' => false, 'empty_value' => 'mautic.user.user.form.defaultlocale'));
     if (empty($options['in_profile'])) {
         $builder->add($builder->create('role', 'entity', array('label' => 'mautic.user.role', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'), 'class' => 'MauticUserBundle:Role', 'property' => 'name', 'query_builder' => function (EntityRepository $er) {
             return $er->createQueryBuilder('r')->where('r.isPublished = true')->orderBy('r.name', 'ASC');
         })));
         $builder->add('isPublished', 'yesno_button_group');
         $builder->add('buttons', 'form_buttons');
     } else {
         $builder->add('buttons', 'form_buttons', array('save_text' => 'mautic.core.form.apply', 'apply_text' => false));
     }
     if (!empty($options["action"])) {
         $builder->setAction($options["action"]);
     }
 }
예제 #4
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     // Build a list of columns
     $builder->add('column', 'choice', array('choices' => $options['columnList'], 'expanded' => false, 'multiple' => false, 'label' => 'mautic.report.report.label.filtercolumn', 'label_attr' => array('class' => 'control-label'), 'empty_value' => false, 'required' => false, 'attr' => array('class' => 'form-control filter-columns')));
     // Direction
     $builder->add('direction', 'choice', array('choices' => array('ASC' => $this->translator->trans('mautic.report.report.label.tableorder_dir.asc'), 'DESC' => $this->translator->trans('mautic.report.report.label.tableorder_dir.desc')), 'expanded' => false, 'multiple' => false, 'label' => 'mautic.core.order', 'label_attr' => array('class' => 'control-label'), 'empty_value' => false, 'required' => false, 'attr' => array('class' => 'form-control not-chosen')));
 }
예제 #5
0
 /**
  * Permet de retourner une erreur ajax avec le bon message en fonction du code erreur envoyé
  * @param $errorCode
  * @param string $notificationType
  * @param null $infos
  * @param null $specificMessage
  * @return Response
  */
 public function returnAjaxError($errorCode, $notificationType = 'error', $infos = null, $specificMessage = null)
 {
     switch ($errorCode) {
         case 103:
             $message = 'La recherche est vide';
             break;
         case 130:
         case 131:
         case 132:
             $message = 'Vous n\'êtes pas autorisé à accéder à cette page (seulement ROLE_SUPER_ADMIN)';
             break;
         case 200:
             $message = 'Tout a fonctionné correctement';
             break;
         default:
             $message = $this->translator->trans('bo.global.errorProcessing', array(), 'messages');
             break;
     }
     $message .= ' - ' . $errorCode;
     if (null !== $infos) {
         $message .= ' (' . $infos . ')';
     }
     if (null !== $specificMessage) {
         $message = $specificMessage;
     }
     $return = json_encode(array('responseCode' => $errorCode, 'message' => $message, 'notification' => $notificationType));
     return new Response($return, 200, array('Content-Type' => 'application/json'));
 }
예제 #6
0
 public function departmentLabel($code)
 {
     try {
         return $this->departements->getLabel($code, true);
     } catch (\InvalidArgumentException $e) {
         return $this->translator->trans('report.company_departement.unknown');
     }
 }
예제 #7
0
 public function sendWelcomeEmail(User $user)
 {
     $token = $this->tokenGenerator->generateToken();
     $link = $this->router->generate('fos_user_registration_register', array('token' => $token), true);
     $this->mailer->sendMail($this->translator->trans('jwkh.publishers.email.welcome.subject', array(), null, $user->getPublisher()->getCongregation()->getDefaultLocale()), '*****@*****.**', $user->getEmail(), $this->translator->trans('jwkh.publishers.email.welcome.body', array('%link%' => $link), null, $user->getPublisher()->getCongregation()->getDefaultLocale()));
     $user->setConfirmationToken($token);
     $this->userManager->updateUser($user);
 }
예제 #8
0
 public function createMainMenu(Request $request, Translator $translator, SecurityContext $securityContext)
 {
     $menu = $this->factory->createItem('root');
     $menu->setCurrentUri($request->getRequestUri());
     $menu->addChild('bundles', array('route' => 'bundle_list'))->setLabel($translator->trans('menu.bundles'));
     $menu->addChild('users', array('route' => 'user_list'))->setLabel($translator->trans('menu.users'));
     $menu->addChild('evolution', array('route' => 'evolution'))->setLabel($translator->trans('menu.evolution'));
     $menu->addChild('add-bundle', array('route' => 'add_bundle'))->setLabel($translator->trans('menu.addBundleManually'));
     return $menu;
 }
예제 #9
0
 /**
  * @param OAuthEvent $event
  *
  * @throws AccessDeniedException
  */
 public function onPreAuthorizationProcess(OAuthEvent $event)
 {
     if ($user = $this->getUser($event)) {
         //check to see if user has api access
         if (!$this->mauticSecurity->isGranted('api:access:full')) {
             throw new AccessDeniedException($this->translator->trans('mautic.core.error.accessdenied', [], 'flashes'));
         }
         $client = $event->getClient();
         $event->setAuthorizedClient($client->isAuthorizedClient($user, $this->em));
     }
 }
예제 #10
0
 /**
  * Returns a DQL expression that can be used to get a text representation of the given type of entities.
  *
  * @param string      $format    The representation format, for example full, short, etc.
  * @param string|null $locale    The representation locale.
  * @param string      $className The FQCN of the entity
  * @param string      $alias     The alias in SELECT or JOIN statement
  *
  * @return string A DQL expression or FALSE if this provider cannot return reliable result
  */
 public function getNameDQL($format, $locale, $className, $alias)
 {
     if ($className === self::CLASS_NAME) {
         if ($format === self::SHORT) {
             return $alias . 'label';
         } else {
             return sprintf('CONCAT(%s.label, \' %s\')', $alias, $this->translator->trans('oro.email.mailbox.entity_label', [], null, $locale));
         }
     }
     return false;
 }
예제 #11
0
 /**
  * Adds an action to the list of available .
  *
  * @param string $key - a unique identifier; it is recommended that it be namespaced i.e. lead.action
  * @param array $event - can contain the following keys:
  *  'label'           => (required) what to display in the list
  *  'description'     => (optional) short description of event
  *  'template'        => (optional) template to use for the action's HTML in the point builder
  *      i.e AcmeMyBundle:PointAction:theaction.html.php
  *  'formType'        => (optional) name of the form type SERVICE for the action
  *  'formTypeOptions' => (optional) array of options to pass to formType
  *  'callback'        => (required) callback function that will be passed when the action is triggered
  *      The callback function can receive the following arguments by name (via ReflectionMethod::invokeArgs())
  *          Mautic\CoreBundle\Factory\MauticFactory $factory
  *          Mautic\PointBundle\Entity\TriggerEvent  $event
  *          Mautic\LeadBundle\Entity\Lead           $lead
  *
  * @return void
  * @throws InvalidArgumentException
  */
 public function addEvent($key, array $event)
 {
     if (array_key_exists($key, $this->events)) {
         throw new InvalidArgumentException("The key, '{$key}' is already used by another action. Please use a different key.");
     }
     //check for required keys and that given functions are callable
     $this->verifyComponent(array('group', 'label', 'callback'), array('callback'), $event);
     $event['label'] = $this->translator->trans($event['label']);
     $event['group'] = $this->translator->trans($event['group']);
     $event['description'] = isset($event['description']) ? $this->translator->trans($event['description']) : '';
     $this->events[$key] = $event;
 }
예제 #12
0
 /**
  * Adds an action to the list of available .
  *
  * @param string $key    - a unique identifier; it is recommended that it be namespaced i.e. lead.action
  * @param array  $action - can contain the following keys:
  *  'label'           => (required) what to display in the list
  *  'description'     => (optional) short description of event
  *  'template'        => (optional) template to use for the action's HTML in the point builder
  *      i.e AcmeMyBundle:PointAction:theaction.html.php
  *  'formType'        => (optional) name of the form type SERVICE for the action; will use a default form with point change only
  *  'formTypeOptions' => (optional) array of options to pass to formType
  *  'callback'        => (optional) callback function that will be passed when the action is triggered; return true to
  *                       change the configured points or false to ignore the action
  *      The callback function can receive the following arguments by name (via ReflectionMethod::invokeArgs())
  *          Mautic\CoreBundle\Factory\MauticFactory $factory
  *          Mautic\LeadBundle\Entity\Lead $lead
  *          $eventDetails - variable sent from firing function to call back function
  *          array $action = array(
  *              'id' => int
  *              'type' => string
  *              'name' => string
  *              'properties' => array()
  *         )
  *
  * @return void
  * @throws InvalidArgumentException
  */
 public function addAction($key, array $action)
 {
     if (array_key_exists($key, $this->actions)) {
         throw new InvalidArgumentException("The key, '{$key}' is already used by another action. Please use a different key.");
     }
     //check for required keys and that given functions are callable
     $this->verifyComponent(array('group', 'label'), array('callback'), $action);
     //translate the label and group
     $action['label'] = $this->translator->trans($action['label']);
     $action['group'] = $this->translator->trans($action['group']);
     $this->actions[$key] = $action;
 }
예제 #13
0
 /**
  * Adds a submit action to the list of available actions.
  *
  * @param string $key    a unique identifier; it is recommended that it be namespaced i.e. lead.action
  * @param array  $action can contain the following keys:
  *                       $action = [
  *                       'group'              => (required) Label of the group to add this action to
  *                       'label'              => (required) what to display in the list
  *                       'eventName'          => (required) Event dispatched to execute action; it will receive a SubmissionEvent object
  *                       'formType'           => (required) name of the form type SERVICE for the action
  *                       'allowCampaignForm'  => (optional) true to allow this action for campaign forms; defaults to false
  *                       'description'        => (optional) short description of event
  *                       'template'           => (optional) template to use for the action's HTML in the form builder;
  *                       eg AcmeMyBundle:FormAction:theaction.html.php
  *                       'formTypeOptions'    => (optional) array of options to pass to formType
  *                       'formTheme'          => (optional  theme for custom form views
  *                       'validator'          => (deprecated) callback function to validate form results - use addValidator() instead
  *                       'callback'           => (deprecated) callback function that will be passed the results upon a form submit; use eventName instead
  *                       ]
  *
  * @throws InvalidArgumentException
  */
 public function addSubmitAction($key, array $action)
 {
     if (array_key_exists($key, $this->actions)) {
         throw new InvalidArgumentException("The key, '{$key}' is already used by another action. Please use a different key.");
     }
     //check for required keys and that given functions are callable
     $this->verifyComponent(['group', 'label', 'formType', ['eventName', 'callback', 'validator']], $action);
     $action['label'] = $this->translator->trans($action['label']);
     if (!isset($action['description'])) {
         $action['description'] = '';
     }
     $this->actions[$key] = $action;
 }
예제 #14
0
 /**
  * @param PersistentCollection $key
  *
  * @return array|mixed
  */
 public function getConstraints(Attachment $attachment, DimensionContainer $dimensionContainer)
 {
     $constraints = array();
     foreach ($this->constraints as $constraintClass) {
         $constraintClass->setup($attachment, $dimensionContainer);
         $validate = $constraintClass->validate();
         if ($validate && $validate instanceof TranslatorObject) {
             $constraints[] = $this->translator->trans($validate->getId(), $validate->getData());
         }
     }
     if (count($constraints) == 0) {
         return;
     }
     return $constraints;
 }
 public function getClientBillStatusText(User $client, $year, $quarter)
 {
     $status = $this->getClientBillStatus($client, $year, $quarter);
     if ($status < 0) {
         return $this->translator->transChoice('bill.accounts_require_attention', -$status, array('%count%' => -$status));
     }
     return $this->translator->trans('bill.status' . $status);
 }
예제 #16
0
 /**
  * @param string $label
  * @param string $context
  * @param string $type
  *
  * @return string
  */
 public function getLabel($label, $context = '', $type = '')
 {
     $deleteStr = '_delete';
     if ($context == 'breadcrumb' && substr($label, -strlen($deleteStr)) == $deleteStr) {
         return $this->translator->trans('admin.delete', [], 'OctavaAdminBundle');
     }
     if (in_array($label, ['_action', 'Action'])) {
         return $this->translator->trans('admin._action', [], 'OctavaAdminBundle');
     }
     if (in_array($label, ['Actions'])) {
         return $this->translator->trans('Actions', [], 'OctavaAdminBundle');
     }
     if ($label == 'id') {
         return $this->translator->trans('admin.id', [], 'OctavaAdminBundle');
     }
     if (in_array($label, ['created_at', 'createdAt', 'Created At'])) {
         return $this->translator->trans('admin.created_at', [], 'OctavaAdminBundle');
     }
     if (in_array($label, ['updated_at', 'updatedAt', 'Updated At'])) {
         return $this->translator->trans('admin.updated_at', [], 'OctavaAdminBundle');
     }
     $label = str_replace('.', '_', $label);
     $result = preg_replace('/^translation___(.*)___[a-z]{2}$/i', '$1', $label);
     $result = strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $result));
     $result = 'admin.' . $result;
     return $result;
 }
 /**
  * process a task
  *
  * @param integer $jobId the id of the job being processed
  * @param array $parameters an array of parameters
  *
  * @throws TaskException
  * @return void
  */
 public function process($jobId, $parameters = array())
 {
     $territories = $this->entityManager->getRepository('KingdomHallDataBundle:Territory')->findAll();
     $tNotifs = array_filter($territories, function (Territory $territory) {
         return $territory->getStatus() == Territory::TERRITORY_STATUS_WARNING || $territory->getStatus() == Territory::TERRITORY_STATUS_ALERT;
     });
     /** @var Territory $territory */
     foreach ($tNotifs as $territory) {
         if ($territory->getPublisher()->getEmail() && $territory->getNotified() != $territory->getStatus()) {
             $settings = $territory->getCongregation()->getSettings();
             $alertDate = clone $territory->getBorrowDate();
             $alertDate->add(\DateInterval::createFromDateString('+' . $settings->get('territory_max_borrow_time')->getValue()));
             $this->mailer->sendMail($this->translator->trans('jwkh.territories.email.' . $territory->getStatus() . '.subject', array('%number%' => $territory->getNumber() . ' - ' . $territory->getName()), null, $territory->getCongregation()->getDefaultLocale()), '*****@*****.**', $territory->getPublisher()->getEmail(), $this->translator->trans('jwkh.territories.email.' . $territory->getStatus() . '.body', array('%firstName%' => $territory->getPublisher()->getFirstName(), '%number%' => $territory->getNumber() . ' - ' . $territory->getName(), '%date%' => $alertDate->format($settings->get('date_format_twig')->getValue())), null, $territory->getCongregation()->getDefaultLocale()));
             $territory->setNotified($territory->getStatus());
             $this->entityManager->persist($territory);
             $this->entityManager->flush();
         }
     }
 }
예제 #18
0
 /**
  * @return array
  */
 protected function getRows()
 {
     $rows = array();
     $columns = $this->columns();
     $accessor = PropertyAccess::createPropertyAccessor();
     $rowProcessor = $this->getRowProcessor();
     foreach ($this->data as $data) {
         $cells = [];
         foreach ($columns->getColumns() as $col) {
             try {
                 $val = null;
                 switch (strtolower($col['type'])) {
                     case 'template':
                         break;
                     case 'action':
                         $actions = array();
                         if ($columns->getActionColumn()) {
                             foreach ($columns->getActionColumn()['options']['actions'] as $action) {
                                 if (is_callable($action['route_params'])) {
                                     $action['route_params'] = call_user_func($action['route_params'], $data);
                                 }
                                 $actions[$action['group']][] = $action;
                             }
                         }
                         $col['options']['actions'] = $actions;
                         break;
                     case 'text':
                     case 'datetime':
                         $val = $accessor->getValue($data, $col['options']['property']);
                         if ($col['type'] === 'text') {
                             if ($this->translator && $col['options']['translate'] !== false) {
                                 $val = $this->translator->trans($val, $col['options']['translation_params'], $col['options']['translation_domain']);
                             }
                         } else {
                             if ($col['type'] === 'datetime') {
                                 if ($val instanceof \DateTime && isset($col['options']['format'])) {
                                     $val = date_format($val, $col['options']['format']);
                                 }
                             }
                         }
                         break;
                 }
                 $cells[] = array_merge($col, ['value' => $val]);
             } catch (UnexpectedTypeException $e) {
                 $cells[] = array_merge($col, ['value' => null]);
             }
         }
         $row = array('data' => $data, 'columns' => $this->columns, 'cells' => $cells, 'attributes' => [], 'template' => $this->rowTemplate);
         if ($rowProcessor) {
             $row = $rowProcessor($row, $this);
         }
         $rows[] = $row;
     }
     return $rows;
 }
예제 #19
0
 /**
  * @return array
  */
 public function getField()
 {
     $container = isset($this->options['container']) ? $this->options['container'] : null;
     $ids = array();
     $height = array();
     $width = array();
     $helpMessage = array();
     foreach ($this->field->getDimensions() as $dimension) {
         $height[] = (int) $dimension->getMinHeight();
         $height[] = (int) $dimension->getFixedHeight();
         $width[] = (int) $dimension->getMinWidth();
         $width[] = (int) $dimension->getFixedWidth();
         $ids[] = $dimension->getId();
     }
     $helpMessage[] = $this->field->getDescription();
     if (count($height) > 0) {
         $helpMessage[] = $this->translator->trans('bigfish.media.help.sizes', array('%height%' => max($height), '%width%' => max($width)));
     }
     return array('identifier' => $this->field->getIdentifier(), 'formType' => $this->field->getFormType(), 'formAttributes' => array('container' => $container, 'field' => $this->field, 'label' => $this->field->getName(), 'attr' => array('data-dimensions' => implode(',', $ids), 'class' => 'uploadValue', 'help_text' => ltrim(implode('<BR>', $helpMessage), '<BR>'))));
 }
예제 #20
0
 /**
  * @param Config $config
  */
 private function setConfig(Config $config)
 {
     $this->config = $config;
     $this->logger->info(sprintf("Loading catalogues from \"%s\"", $config->getTranslationsDir()));
     $this->existingCatalogue = new MessageCatalogue();
     // load external resources, so current translations can be reused in the final translation
     foreach ($config->getLoadResources() as $resource) {
         $this->existingCatalogue->merge($this->loader->loadFromDirectory($resource, $config->getLocale()));
     }
     $this->existingCatalogue->merge($this->loader->loadFromDirectory($config->getTranslationsDir(), $config->getLocale()));
     $this->extractor->reset();
     $this->extractor->setDirectories($config->getScanDirs());
     $this->extractor->setExcludedDirs($config->getExcludedDirs());
     $this->extractor->setExcludedNames($config->getExcludedNames());
     $this->extractor->setEnabledExtractors($config->getEnabledExtractors());
     $this->logger->info("Extracting translation keys");
     $this->scannedCatalogue = $this->extractor->extract();
     $this->scannedCatalogue->setLocale($config->getLocale());
     // merge existing messages into scanned messages
     foreach ($this->scannedCatalogue->getDomains() as $domainCatalogue) {
         foreach ($domainCatalogue->all() as $message) {
             if (!$this->existingCatalogue->has($message)) {
                 continue;
             }
             $existingMessage = clone $this->existingCatalogue->get($message->getId(), $message->getDomain());
             $existingMessage->mergeScanned($message);
             $this->scannedCatalogue->set($existingMessage, true);
         }
     }
     if ($this->config->isKeepOldMessages()) {
         foreach ($this->existingCatalogue->getDomains() as $domainCatalogue) {
             foreach ($domainCatalogue->all() as $message) {
                 if ($this->scannedCatalogue->has($message)) {
                     continue;
                 }
                 $this->scannedCatalogue->add($message);
             }
         }
     }
     //keep old translations translated
     if ($this->config->isKeepOldTranslationMessages()) {
         $locale = $this->scannedCatalogue->getLocale();
         /** @var MessageCatalogue $domainCatalogue */
         foreach ($this->scannedCatalogue->getDomains() as $domainCatalogue) {
             /** @var Message $message */
             foreach ($domainCatalogue->all() as $message) {
                 $translated = $this->translator->trans($message->getId(), array(), $message->getDomain(), $locale);
                 $message->setLocaleString($translated);
                 $message->setNew(false);
             }
         }
     }
 }
예제 #21
0
 /**
  * @see \Symfony\Component\Translation\Translator::trans()
  */
 public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
 {
     if (null === $locale) {
         $locale = $this->getLocale();
     }
     $message = $this->getMessage($id, $domain, $parameters, $locale);
     if ($message->getContent()) {
         // return entity translation
         return strtr($message->getContent(), $parameters);
     }
     // else return translation handled by sf
     return parent::trans($id, $parameters, $domain, $locale);
 }
예제 #22
0
    /**
     * @param array $config
     * @return string
     */
    public function button($config)
    {
        $path = $this->router->generate($config['route'], $config['route_params']);
        $class = $config['class'];
        $icon = $config['icon'] ? "<i class=\"fa fa-{$config['icon']} fa-fw\"></i> " : '';
        $label = $icon . $this->translator->trans($config['label']);
        $attributes = implode(' ', array_map(function ($key, $val) {
            return sprintf('%s="%s"', $key, $val);
        }, array_keys($config['attributes']), $config['attributes']));
        return <<<HTML
            <a href="{$path}" class="btn btn-sm btn-{$class}" {$attributes}>{$label}</a>
HTML;
    }
예제 #23
0
 /**
  * Retrieve entity based on id/alias slugs
  *
  * @param string $slug
  *
  * @return object|bool
  */
 public function getEntityBySlugs($slug)
 {
     $slugs = explode('/', $slug);
     $idSlug = '';
     $category = null;
     $lang = null;
     $slugCount = count($slugs);
     $locales = Intl::getLocaleBundle()->getLocaleNames();
     switch (true) {
         case $slugCount === 3:
             list($lang, $category, $idSlug) = $slugs;
             break;
         case $slugCount === 2:
             list($category, $idSlug) = $slugs;
             // Check if the first slug is actually a locale
             if (isset($locales[$category])) {
                 $lang = $category;
                 $category = null;
             }
             break;
         case $slugCount === 1:
             $idSlug = $slugs[0];
             break;
     }
     // Check for uncategorized
     if ($this->translator->trans('mautic.core.url.uncategorized') == $category) {
         $category = null;
     }
     if (null === $lang) {
         // Default to en
         $lang = 'en';
     } elseif (!isset($locales[$lang])) {
         // Language doesn't exist so return false
         return false;
     }
     if (strpos($idSlug, ':') !== false) {
         $parts = explode(':', $idSlug);
         if (count($parts) == 2) {
             $entity = $this->getEntity($parts[0]);
             if (!empty($entity)) {
                 return $entity;
             }
         }
     } else {
         $entity = $this->getRepository()->findOneBySlugs($idSlug, $category, $lang);
         if (!empty($entity)) {
             return $entity;
         }
     }
     return false;
 }
예제 #24
0
 /**
  * @Route("/remove-user/{projectId}/{email}", name="users_remove_user")
  * @Template()
  * @ParamConverter("project", class="TranslationsBundle:Project", options={"id" = "projectId"})
  */
 public function removeUserAction(Project $project, $email, Request $request)
 {
     $session = $request->getSession();
     $this->init();
     /** @var Permission $permission */
     $permission = $this->translationsManager->getPermissionForUserAndProject($this->user, $project);
     if (!$permission || $permission->getPermissions(Permission::GENERAL_KEY) != Permission::OWNER) {
         throw new AclException($this->translator->trans('error.acl.not_enough_permissions_to_manage_this_project'));
     }
     $user = $this->getUserRepository()->findOneBy(array('email' => $email));
     if (!$user) {
         $this->addNoticeFlash("User doesn't exists yet in our system");
     } else {
         $managedLocales = explode(',', $project->getManagedLocales());
         /** @var Permission[] $permissions */
         $permissions = $this->getPermissionRepository()->findBy(array('project' => $project));
         $usersData = array();
         $exists = false;
         foreach ($permissions as $perm) {
             $currentUser = $perm->getUser();
             if ($currentUser->getEmail() != $email) {
                 /*
                                     $usersData[] = array(
                                         'id'          => $currentUser->getId(),
                                         'name'        => $currentUser->getName(),
                                         'email'       => $currentUser->getEmail(),
                                         'createdAt'   => $currentUser->getCreatedAt(),
                                         'active'      => $currentUser->getActive(),
                                         'permissions' => $this->expandPermissions($managedLocales, $perm->getPermissions()),
                                     );*/
             } else {
                 $exists = true;
                 $this->em->remove($perm);
             }
         }
         if ($exists) {
             $this->em->flush();
         }
     }
     // ldd($usersData, $permission->getPermissions());
     return $this->redirect($this->generateUrl('users_index', array('projectId' => $project->getId())));
     //        return array(
     //            'action'         => 'users',
     //            'project'        => $project,
     //            'permissions'    => $permission->getPermissions(),
     //            'users'          => $usersData,
     //            'managedLocales' => $managedLocales,
     //        );
 }
예제 #25
0
 /**
  * @Route("/story/html/{story}", name="user_story_load_html", 
  *  requirements={"story"="\d+"})
  * @Method({"POST"})
  */
 public function loadStoryHtmlAction(Request $request, $story)
 {
     if ($request->isXmlHttpRequest()) {
         $story = $this->em->getRepository('WebffilmBaseBundle:Story')->find($story);
         if (!$story) {
             return new JsonResponse(array('success' => false, 'msg' => $this->translator->trans('h1.story.is.not.found')));
         } else {
             $this->return['story'] = $story;
             $html = $this->container->get('templating')->render('WebffilmUserBundle:Story:storyHtml.html.twig', $this->return);
             return new JsonResponse(array('success' => true, 'html' => $html));
         }
     } else {
         exit('Only ajax requests are accepted');
     }
 }
예제 #26
0
 /**
  * Build the menu
  *
  * @param ContentInterface $content
  *
  * @return \Knp\Menu\MenuItem
  */
 public function build(ContentInterface $content)
 {
     $menu = null;
     if (count($this->locales) > 1) {
         $factory = new MenuFactory();
         $menu = $factory->createItem('ContentMenu', $this->locales);
         $menu->addChild('default', ['uri' => $this->router->generate('opifer.cms.content.edit', ['id' => $content->getId() ? $content->getId() : 0, 'locale' => null]), 'label' => $this->translator->trans('Default')]);
         foreach ($this->locales as $plocale) {
             if ($plocale === $this->defaultLocale) {
                 continue;
             }
             $menu->addChild($plocale, ['uri' => $this->router->generate('opifer.cms.content.edit', ['id' => $content->getId() ? $content->getId() : 0, 'locale' => $plocale]), 'label' => $this->translator->trans($plocale)]);
         }
         foreach ($menu->getChildren() as $menuChild) {
             if ($menuChild->getName() == $locale) {
                 $menuChild->setCurrent(true);
             }
             if ($menuChild->getName() == 'default' && $locale == null) {
                 $menuChild->setCurrent(true);
             }
         }
     }
     return $menu;
 }
예제 #27
0
 public function prepareIncomingCallNote(Call $call)
 {
     $status = $this->translator->trans('activity.status.' . $call->getHangupEvent()->getStatus());
     $note = $this->translator->trans('activity.note.datetime', array('%dateTime%' => $call->getEndTalk()->format('d.m.Y H:i')));
     $note .= $this->translator->trans('activity.note.status', array('%status%' => $status));
     if ($call->getStartTalk() && $call->getEndTalk()) {
         $note .= $this->translator->trans('activity.note.duration', array('%duration%' => $call->getStartTalk()->diff($call->getEndTalk())->format('%H:%I:%S')));
     }
     $note .= $this->translator->trans('activity.note.manager', array('%manager%' => $call->getUser()->getFullName(), '%phone%' => $call->getAnswerEvent()->getDstNumber()));
     $call->getActivity()->setNote($note);
 }
예제 #28
0
 /**
  * @Route("/disapprove-translation/{translationId}/{locale}", name="disapprove_translation")
  * @Method("POST")
  * @ ParamConverter("translation", class="TranslationsBundle:Translation", options={"id" = "translationId"})
  */
 public function disapproveMessageAction($translationId, $locale)
 {
     $this->init();
     $translation = $this->getTranslationRepository()->find($translationId);
     if (!$translation) {
         return $this->restService->exception($this->translator->trans('message.translation_not_found'));
     }
     if ($this->checkPermission($locale, Permission::ADMIN_PERM)) {
         $translations = $translation->getTranslations();
         if (isset($translations[$locale])) {
             $translations[$locale]['approved'] = false;
             $translation->setTranslations($translations);
             $this->dm->persist($translation);
             $this->dm->flush($translation);
             $this->restService->resultOk(array('message' => $translations[$locale]['message'], 'approved' => false, 'id' => $translationId, 'locale' => $locale));
         } else {
             $this->restService->exception($this->translator->trans('message.inexistent_locale_to_approve'));
         }
     } else {
         $this->restService->exception($this->translator->trans('message.without_permissions_to_approve'));
     }
 }
예제 #29
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('parent', 'entity', ['label' => $this->translator->trans('directory.parent.label'), 'class' => 'Opifer\\CmsBundle\\Entity\\Directory', 'property' => 'name', 'required' => false, 'empty_value' => $this->translator->trans('directory.parent.empty'), 'empty_data' => null, 'attr' => ['help_text' => $this->translator->trans('directory.parent.help_text')]])->add('name', 'text', ['label' => $this->translator->trans('form.name'), 'attr' => ['help_text' => $this->translator->trans('directory.name.help_text')]])->add('slug', 'slug')->add('save', 'submit', ['label' => $this->translator->trans('directory.submit')]);
 }
 /**
  * (non-PHPdoc)
  * @see Azine\EmailBundle\Services.NotifierServiceInterface::sendNewsletter()
  */
 public function sendNewsletter(array &$failedAddresses)
 {
     // params array for all recipients
     $params = array();
     // set a default subject
     $params['subject'] = $this->translatorService->trans("_az.email.newsletter.subject");
     // get the the non-recipient-specific contentItems of the newsletter
     $params[self::CONTENT_ITEMS] = $this->getNonRecipientSpecificNewsletterContentItems();
     // get recipientIds for the newsletter
     $recipientIds = $this->recipientProvider->getNewsletterRecipientIDs();
     $newsletterTemplate = $this->configParameter[AzineEmailExtension::TEMPLATES . "_" . AzineEmailExtension::NEWSLETTER_TEMPLATE];
     foreach ($recipientIds as $recipientId) {
         $failedAddress = $this->sendNewsletterFor($recipientId, $params, $newsletterTemplate);
         if ($failedAddress != null) {
             $failedAddresses[] = $failedAddress;
         }
     }
     return sizeof($recipientIds) - sizeof($failedAddresses);
 }