Email edition

@param Request $request
@param string  $emailId
@param string  $lang

@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
@return \Symfony\Component\HttpFoundation\Response
503968
public function editAction(Request $request, $emailId, $lang = null)
    {
        $class = $this->container->getParameter('lexik_mailer.email_entity.class');
        $email = $this->get('doctrine.orm.entity_manager')->find($class, $emailId);

        if (!$email) {
            throw $this->createNotFoundException(sprintf('No email found for id "%d"', $emailId));
        }

        $handler = $this->get('lexik_mailer.form.handler.email');
        $form = $handler->createForm($email, $lang);

        if ($handler->processForm($form, $request)) {
            return $this->redirect($this->generateUrl('lexik_mailer.email_edit', array(
                'emailId' => $email->getId(),
                'lang'    => $handler->getLocale(),
            )));
        }

        return $this->render('LexikMailerBundle:Email:edit.html.twig', array_merge(array(
            'form'          => $form->createView(),
            'layout'        => $this->container->getParameter('lexik_mailer.base_layout'),
            'email'         => $email,
            'lang'          => $handler->getLocale(),
            'displayLang'   => \Locale::getDisplayLanguage($handler->getLocale()),
            'routePattern'  => urldecode($this->generateUrl('lexik_mailer.email_edit', array('emailId' => $email->getId(), 'lang' => '%lang%'), true)),
        ), $this->getAdditionalParameters()));
    }
872055
public function render(string $templateID, string $language, \Swift_Mime_SimpleMessage &$message)
    {
        // Find Template
        $template = $this->entityManager
            ->getRepository(MailTemplate::class)
            ->findOneBy(['templateId' => $templateID, 'status' => true, 'language' => $language]);

        if ((null === $template) && ($language !== $this->defaultLanguage)) {
            return $this->render($templateID, $this->defaultLanguage, $message);
        }

        // Render Template
        if (null !== $template) {
            // Render Body
            try {
                $message->setBody(
                    $this->twig->createTemplate($template->getTemplate())->render(unserialize($message->getBody())),
                    $message->getContentType(),
                    $message->getCharset());
            } catch (\Exception $e) {
            }

            // Set Header
            if (!empty($template->getFromName()) && !empty($template->getFromEmail())) {
                $message->setFrom($template->getFromEmail(), $template->getFromName());
            }

            // Set Subject
            if (!empty($template->getSubject())) {
                $message->setSubject($template->getSubject());
            }

            return true;
        }

        return false;
    }
912134
public static function translateMail(MailInterface $template, $locale, TranslatorInterface $translator = null)
    {
        if (null === $template->getTranslationDomain()) {
            $template = $template->getTranslation($locale);
        } elseif (null !== $translator) {
            static::injectTranslatorValues($translator, $template);
        }

        return $template;
    }
725077
public function invoiceAction(Request $request)
    {
        /** @var \Ekyna\Component\Sale\Order\OrderInterface $order */
        $order = $this->get('ekyna_order.order.repository')->findOneBy([
            'id' => $request->attributes->get('orderId', null), 
            'type' => OrderTypes::TYPE_ORDER
        ]);
        if (null === $order) {
            throw new NotFoundHttpException('Order not found.');
        }

        // Admin or owner security check
        if(!($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $order->getUser() == $this->getUser())) {
            throw new AccessDeniedHttpException('You are not allowed to view this resource.');
        }

        $response = new Response();
        $response->setLastModified($order->getUpdatedAt());
        if ($response->isNotModified($request)) {
            return $response;
        }

        $content = $this->renderView('EkynaOrderBundle:Document:invoice.html.twig', [
            'order' => $order,
        ]);

        $format = $request->attributes->get('_format', 'html');
        if ('html' === $format) {
            $response->setContent($content);
        } elseif ('pdf' === $format) {
            $response->setContent($this->get('knp_snappy.pdf')->getOutputFromHtml($content));
            $response->headers->add(['Content-Type' => 'application/pdf']);
        } else {
            throw new NotFoundHttpException('Unsupported format.');
        }

        if ($request->query->get('_download', false)) {
            $filename = sprintf('order-%s.%s', $order->getNumber(), $format);
            $contentDisposition = $response->headers->makeDisposition(
                ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename
            );
            $response->headers->set('Content-Disposition', $contentDisposition);
        }

        return $response;
    }
341446
public function servicoInfo(Request $request, TranslatorInterface $translator)
    {
        $em       = $this->getDoctrine()->getManager();
        $id       = (int) $request->get('id');
        $usuario  = $this->getUser();
        $unidade  = $usuario->getLotacao()->getUnidade();
        $servico  = $em->find(Servico::class, $id);
        $envelope = new Envelope();
        
        if (!$servico) {
            throw new Exception($translator->trans('error.invalid_service', [], self::DOMAIN));
        }
        
        $data = [
            'nome' => $servico->getNome(),
            'descricao' => $servico->getDescricao()
        ];

        // ultima senha
        $atendimento = $em->getRepository(Atendimento::class)->getUltimo($unidade, $servico);
        
        if ($atendimento) {
            $data['senha']   = $atendimento->getSenha()->__toString();
            $data['senhaId'] = $atendimento->getId();
        } else {
            $data['senha']   = '-';
            $data['senhaId'] = '';
        }
        
        // subservicos
        $data['subservicos'] = [];
        $subservicos = $em->getRepository(Servico::class)->getSubservicos($servico);

        foreach ($subservicos as $s) {
            $data['subservicos'][] = $s->getNome();
        }

        $envelope->setData($data);

        return $this->json($envelope);
    }
588248
public function campagne(Request $request)
    {
        // Get campagne
        $campagne = $this->campagne->find($request->input('id'));
        $date     = $request->input('date',null);

        //set or update html
        $html = $this->worker->html($campagne->id);

        $this->mailjet->setList($campagne->newsletter->list_id); // list id

        // Sync html content to api service and send to newsletter list!
        $response = $this->mailjet->setHtml($html,$campagne->api_campagne_id);

        if(!$response)
        {
            throw new \designpond\newsletter\Exceptions\CampagneUpdateException('Problème avec la préparation du contenu');
        }

        /*
         *  Send at specified date or delay for 15 minutes before sending just in case
         */
        $toSend = $date ? \Carbon\Carbon::parse($date) : \Carbon\Carbon::now()->addMinutes(15);
        
        $result = $this->mailjet->sendCampagne($campagne->api_campagne_id, $toSend->toIso8601String());

        if(!$result['success'])
        {
            throw new \designpond\newsletter\Exceptions\CampagneSendException('Problème avec l\'envoi'.$result['info']['ErrorMessage'].'; Code: '.$result['info']['StatusCode']);
        }

        // Update campagne status
        $this->campagne->update(['id' => $campagne->id, 'status' => 'envoyé', 'updated_at' => date('Y-m-d G:i:s'), 'send_at' => $toSend]);

        alert()->success('Campagne envoyé!');

        return redirect('build/newsletter');
    }
1691
public function naoCompareceu(
        Request $request,
        AtendimentoService $atendimentoService,
        TranslatorInterface $translator
    ) {
        $usuario = $this->getUser();
        $unidade = $usuario->getLotacao()->getUnidade();
        $atual   = $atendimentoService->atendimentoAndamento($usuario->getId(), $unidade);

        if (!$atual) {
            throw new Exception(
                $translator->trans('error.attendance.empty', [], self::DOMAIN)
            );
        }
        
        $atendimentoService->naoCompareceu($atual, $usuario);

        $data     = $atual->jsonSerialize();
        $envelope = new Envelope();
        $envelope->setData($data);

        return $this->json($envelope);
    }
247463
public static function processLanguage($request)
    {

        if (LangHelper::countActiveLanguages() > 1)
        {
            //$lang = LangHelper::getFirstActiveLanguageCode(); //!! no
            $lang = Yii::$app->language; // current language

            // Get language from _GET parameter lang=XX if exists.
            // This language has low priority than as URL part: BASE_URL/XX/...
            $get = $request->get();
            if (!empty($get['lang'])) {
                $getLang = $get['lang'];
                if (LangHelper::isValidLangCode($getLang)) {
                    $lang = $getLang;
                }
            }           

            // Get language from URL if exists
            // and correct $request->pathInfo by cutting language part
            $pathInfo0 = $request->getPathInfo(); // pathInfo has not leading '/'
            //echo "orig pathInfo:'$pathInfo'<br>";
            $parts = explode('/', $pathInfo0, 2);
            if (!empty($parts[0])) {
                $langPart = $parts[0];
                if (LangHelper::isValidLangCode($langPart)) {
                    $pathInfo = substr($pathInfo0, strlen($langPart) + 1);
                    $lang = $langPart;
                    $request->setPathInfo($pathInfo);

                    $msg = "corrected pathInfo from '{$pathInfo0}' to '{$pathInfo}'<br>";
                    Yii::trace($msg);
                }
            }

            // Save language
            $lang = LangHelper::normalizeLangCode($lang);
            Yii::$app->language = $lang;
            LangHelper::setDefaultLanguage($lang);
            LangHelper::saveLanguageInSession($lang);

            // Correct $request->url by cutting language part if exists
            $urlManager = Yii::$app->urlManager;
            $baseUrl = $urlManager->showScriptName || !$urlManager->enablePrettyUrl ? $urlManager->getScriptUrl() : $urlManager->getBaseUrl();
            $url0 = $request->getUrl();
            if ($baseUrl !== '' && strpos($url0, $baseUrl) === 0) { // $url0 = $request->url begin with '/'
                $link = substr($url0, strlen($baseUrl));
                if (isset($langPart) && LangHelper::isValidLangCode($langPart)) {
                    $langPart = '/' . $langPart;
                    if (strpos($link, $langPart) === 0) {
                        $link = substr($link, strlen($langPart));
                    }
                    $url = $baseUrl . $link;
                    $request->setUrl($url);
                    $msg = "correct request->url from '{$url0}' to '{$url}'";
                    Yii::trace($msg);
                }
            }
        }    

    }
1126717
public function createByTypeAction($id, Request $request)
    {
        $contentType = $this->contentTypeManager->getContentTypeById($id);

        if ($contentType === null) {
            throw EntityNotFoundException::fromClassNameAndIdentifier(
                $this->configurationManager->getEntityClass('content_type'),
                [$id]
            );
        }

        $contentEntityClass = $this->configurationManager->getEntityClass('content');
        $content = new $contentEntityClass;
        $content->setContentType($contentType);

        $form = $this->createForm(ContentType::class, $content, [
            'action' => $this->generateUrl('sherlockode_acb_content_create_by_type', ['id' => $contentType->getId()]),
            'contentType' => $content->getContentType(),
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->om->persist($content);
            $this->om->flush();

            return $this->redirectToRoute('sherlockode_acb_content_edit', ['id' => $content->getId()]);
        }

        return $this->render('@SherlockodeAdvancedContent/Content/edit_content.html.twig', [
            'form' => $form->createView(),
            'is_ajax' => $request->isXmlHttpRequest(),
        ]);
    }
1330973
public function update(LanguageRequest $request, Language $language)
    {
        $language->update($request->all());
        Session::forget('language_setup', false);

        return redirect()->route('admin.language.index');
    }
530472
public function detailsJSON($lang, $id)
    {
        // check if user has permissions to access this link
        if(\Illuminate\Support\Facades\Auth::user()->userID != $id) {
            if (!User::hasAccess('User', 'read')) {
                return $this->noPermission();
            }
        }

        $user = App\Models\User::with('roles', 'profileImage')->find($id)->appendLanguageKeys();
        $final = [
          'details' => $user,
          'allGroups' => UserGroup::all()
        ];

        // Fire event
        $final['events'] = Event::fire('user:pre_update', [$final]);
        return $final;
    }
1289014
public function newAction(Request $request)
    {
        $entity = new Translation();
        $form = $this->createForm('CoreBundle\Form\TranslationType', $entity);
        
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            //Create entry in DB
            $this->updateTranslation($entity);
            
            $this->get('session')->getFlashBag()->add('success', 'translation.created');
            
            return $this->redirectToRoute('core_translation_index');
        }

        return $this->render('CoreBundle:Translation:new.html.twig', array(
            'translation' => $entity,
            'form' => $form->createView(),
        ));
    }
1168379
public function actionEdit($templateId, $languageId = null)
    {
        $editForm = new EditForm([
            'templateId' => $templateId,
            'languageId' => $languageId
        ]);
        return $this->renderForm($editForm, 'edit');
    }
116271
public function encerrar(
        Request $request,
        AtendimentoService $atendimentoService,
        TranslatorInterface $translator
    ) {
        $envelope = new Envelope();
        $data     = json_decode($request->getContent());

        $usuario = $this->getUser();
        $unidade = $usuario->getLotacao()->getUnidade();
        $atual   = $atendimentoService->atendimentoAndamento($usuario->getId(), $unidade);

        if (!$atual) {
            throw new Exception(
                $translator->trans('error.attendance.not_in_process', [], self::DOMAIN)
            );
        }

        $servicos   = explode(',', $data->servicos);
        $resolucao  = $data->resolucao;
        $observacao = $data->observacao;
        
        if (empty($servicos)) {
            throw new Exception(
                $translator->trans('error.attendance.no_service', [], self::DOMAIN)
            );
        }
        
        $em = $this->getDoctrine()->getManager();

        $novoUsuario = null;
        $servicoRedirecionado = null;
        
        if ($data->redirecionar) {
            $servicoRedirecionado = $em
                ->getRepository(Servico::class)
                ->find($data->novoServico);
            
            if (isset($data->novoUsuario)) {
                $novoUsuario = $em
                    ->getRepository(Usuario::class)
                    ->find($data->novoServico);
            }
        }
        
        if (in_array($resolucao, [ AtendimentoService::RESOLVIDO, AtendimentoService::PENDENTE ])) {
            $atual->setResolucao($resolucao);
        }
        
        if ($observacao) {
            $atual->setObservacao($observacao);
        }

        $atendimentoService->encerrar($atual, $unidade, $servicos, $servicoRedirecionado, $novoUsuario);

        return $this->json($envelope);
    }
1285969
public function previewAction($emailId, $lang)
    {
        $class = $this->container->getParameter('lexik_mailer.email_entity.class');
        $email = $this->get('doctrine.orm.entity_manager')->find($class, $emailId);

        if (!$email) {
            throw $this->createNotFoundException(sprintf('No email found for id "%d"', $emailId));
        }

        $preview = $this->get('lexik_mailer.message_preview_generator');
        $preview->getTemplatesPreview($email, $lang);

        return $this->render('LexikMailerBundle:Email:preview.html.twig', array_merge(array(
            'content'  => $preview->get('content'),
            'subject'  => $preview->get('subject'),
            'fromName' => $preview->get('fromName'),
            'errors'   => $preview->getErrors(),
        ), $this->getAdditionalParameters()));
    }
693923
public function inlineEditAction(Request $request)
    {
        $id = $request->get('pk');
        $name = $request->get('value');

        /** @var $tag Tag */
        if (!$tag = $this->admin->getObject($id)) {
            throw new NotFoundHttpException('unable to find the tag with the id');
        }

        $tag->setName($name);

        $validator = $this->get('validator');
        $errors = $validator->validate($tag);

        if (count($errors) > 0) {
            $messages = [];
            foreach ($errors as $error) {
                $messages[] = $error->getMessage();
            }

            return new Response(implode(', ', $messages), 400);
        }

        $this->admin->update($tag);

        return $this->renderJson([
            'result' => 'ok',
            'objectId' => $id,
        ]);
    }
83023
public function get($entityId, $lang = 'en') 
    {
        if(!is_qid($entityId)) {
            throw new Exception("First argument in get() must by a valid Wikidata entity ID (e.g.: Q646).", 1);
        }

        $query = '
            SELECT ?item ?itemLabel ?itemDescription ?itemAltLabel ?prop ?propLabel (GROUP_CONCAT(DISTINCT ?valueLabel;separator=", ") AS ?propValue) WHERE { 
                  BIND(wd:'.$entityId.' AS ?item).
                  ?prop wikibase:directClaim ?p .
                  ?item ?p ?value .
                  SERVICE wikibase:label { 
                    bd:serviceParam wikibase:language "'.$lang.'". 
                    ?value rdfs:label ?valueLabel . 
                    ?prop rdfs:label ?propLabel . 
                    ?item rdfs:label ?itemLabel . 
                    ?item skos:altLabel ?itemAltLabel . 
                    ?item schema:description ?itemDescription . 
                  }    
                } group by ?item ?itemLabel ?itemDescription ?itemAltLabel ?prop ?propLabel
        '; 

        $client = new SparqlClient();

        $data = $client->execute($query); 

        if(!$data) {
            return null;
        }

        $entity = new Entity($data, $lang);

        return $entity;
    }