public function transliterate($text, $separator = '-') { // table of convert letters from current language to latin letters $convertTable = array('а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'ts', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya'); $text = strtr(trim(mb_strtolower($text, 'UTF-8')), $convertTable); return Urlizer::urlize($text, $separator); }
protected function updateSlugsForEntity($output, $entityName) { $em = $this->getEntityManager(); /** @var TranslationRepository $translationRepository */ $translationRepository = $this->getTranslationRepository(); $entities = $em->getRepository($entityName)->findAll(); $output->writeln(sprintf(' > Updating slugs for <info>%s</info>', $entityName)); /** @var ProgressHelper $progress */ $progress = $this->getHelperSet()->get('progress'); $progress->start($output, count($entities)); foreach ($entities as $entity) { $entity->setSlug(null); $translations = $translationRepository->findTranslations($entity); foreach ($translations as $locale => $values) { if (isset($values['name'])) { $slug = Urlizer::transliterate($values['name']); $slug = Urlizer::urlize($slug); if (function_exists('mb_strtolower')) { $slug = mb_strtolower($slug); } else { $slug = strtolower($slug); } $translationRepository->translate($entity, 'slug', $locale, $slug); } } $em->persist($entity); $progress->advance(); } $em->flush(); $em->clear(); $progress->finish(); }
/** * Add child nodes * * Recursively called. Take only the current version of a current page * on Camdram. */ private function add_child_nodes($dm, $em, $parent_id, $parent) { $pages = $em->createQuery('SELECT p FROM ActsCamdramLegacyBundle:Page p WHERE p.parent_id = :pid AND p.ghost = 0')->setParameter('pid', $parent_id)->getResult(); foreach ($pages as $page) { $cms_page = new CmsPage(); $title = $page->getFullTitle(); if ($title != '') { $cms_page->setSlug(Sluggable\Urlizer::urlize($title, '-')); $cms_page->setTitle($title); $cms_page->setParent($parent); $text = $page->getHelp(); if ($text == '') { /* The page's content comes from a knowledgebase page. * This has been reverse engineered from v1. */ $kb_repo = $em->getRepository('ActsCamdramLegacyBundle:KnowledgeBaseRevision'); $kb_page = $kb_repo->findOneBy(array('page_id' => $page->getId()), array('id' => 'DESC')); $text = $kb_page->getText(); } $cms_page->setContent($text); $dm->persist($cms_page); $dm->flush(); } // Recurse $this->add_child_nodes($dm, $em, $page->getId(), $cms_page); } }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { $reserved_words = array_merge($constraint->words, $this->additionnal_words); if (in_array(Urlizer::urlize($value), $reserved_words)) { $this->context->addViolation($constraint->message, ['%word%' => $value]); } }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { foreach ($options['variable']->getOptions() as $i => $option) { $builder->add(Urlizer::urlize($option->getName()), sprintf('sylius_%s_option_value_choice', $this->variableName), ['label' => $option->getPresentation(), 'option' => $option, 'property_path' => '[' . $i . ']']); } $builder->addModelTransformer(new VariantToCombinationTransformer($options['variable'])); }
protected function setSlug($estate) { $originalAddress = $estate->getAddress(); $estate->setTranslatableLocale('en'); $_manager = $this->getConfigurationPool()->getContainer()->get('Doctrine')->getManager(); $_manager->refresh($estate); $slug = $estate->getAddress() ? $estate->getAddress() : $originalAddress; $slug = Sluggable\Urlizer::transliterate($slug, '_'); $estate->setSlug(Sluggable\Urlizer::urlize($slug, '_')); $_manager->persist($estate); $_manager->flush(); }
public function testExecute() { $transliterate = new Transliterate(); $book = new Book(); $book->setTitle("Unit test book " . date('d-m-Y-H-i-s')); $book->setSlug(Sluggable\Urlizer::urlize($transliterate->transliterate($book->getTitle(), 'ru'), '-')); $book->setAuthors('Authors'); $book->setIsbn('111-1111-1111-1'); $createETBFile = new CreateETBFile(); $createETBFile->setBook($book); $createETBFile->execute(); }
public function prePersist(Show $show, LifecycleEventArgs $event) { if (!$show->getPrimaryRef()) { $refname = Sluggable\Urlizer::urlize($show->getName(), '_'); if ($show->getStartAt()) { $year = $show->getStartAt()->format('y'); $refname = $year . '/' . $refname; } $ref = new ShowRef(); $ref->setShow($show); $ref->setRef($refname); $show->setPrimaryRef($ref); } }
/** * @param FileInterface $file * @param mixed $data * @param bool $unaccent * * @throws \RuntimeException * * @return StreamedFileResponse */ protected function createResponse(FileInterface $file, $data, $unAccent = true) { if (null === $file->getFilename()) { throw new \RuntimeException('Filename must be set'); } $response = new StreamedFileResponse(Urlizer::urlize($file->getFilename()) . $this->getFileExtension()); if (true === $unAccent) { foreach ($data as $rowIndex => $row) { foreach ($row as $dataIndex => $dataValue) { $data[$rowIndex][$dataIndex] = Urlizer::unaccent($dataValue); } } } return $response->writeContent($file, $data); }
/** * @param callable $formatter * * @throws \Nuxia\Component\FileUtils\Exception\FileIteratorMissingException */ public function setDynamicColumnNames(\Closure $formatter = null) { if (null === $this->iterator) { throw new FileIteratorMissingException($this); } if (null === $formatter) { $formatter = function ($element) { return trim(Urlizer::urlize($element, '_')); }; } $buffer = []; foreach ($this->getIterator()->current() as $element) { $buffer[] = $formatter($element); } $this->setColumnNames($buffer); }
/** * {@inheritDoc} */ public function validate($value, Constraint $constraint) { $url = Urlizer::urlize($value->getUrl()); $pages = $this->pageManager->findBy(array('url' => $url, 'parent' => $value->getParent(), 'locale' => $value->getLocale())); if ($value->getParent()) { $url = $value->getParent()->getFullPath() . $url; } if (count($pages) > 0) { foreach ($pages as $page) { /** @var \Networking\InitCmsBundle\Model\PageInterface $page */ if ($page->getId() != $value->getId()) { $this->context->addViolationAt('url', $constraint->message, array('{{ value }}' => $url)); return false; } } } return true; }
/** * {@inheritdoc} */ public function load($resource, $type = null) { $processor = new Processor(); $configurationDefinition = new Configuration(); $configuration = Yaml::parse($resource); $configuration = $processor->processConfiguration($configurationDefinition, ['routing' => $configuration]); if (!empty($configuration['only']) && !empty($configuration['except'])) { throw new \InvalidArgumentException('You can configure only one of "except" & "only" options.'); } $routesToGenerate = ['show', 'index', 'create', 'update', 'delete']; if (!empty($configuration['only'])) { $routesToGenerate = $configuration['only']; } if (!empty($configuration['except'])) { $routesToGenerate = array_diff($routesToGenerate, $configuration['except']); } $isApi = $type === 'sylius.resource_api'; /** @var MetadataInterface $metadata */ $metadata = $this->resourceRegistry->get($configuration['alias']); $routes = $this->routeFactory->createRouteCollection(); $rootPath = sprintf('/%s/', isset($configuration['path']) ? $configuration['path'] : Urlizer::urlize($metadata->getPluralName())); if (in_array('index', $routesToGenerate)) { $indexRoute = $this->createRoute($metadata, $configuration, $rootPath, 'index', ['GET'], $isApi); $routes->add($this->getRouteName($metadata, $configuration, 'index'), $indexRoute); } if (in_array('create', $routesToGenerate)) { $createRoute = $this->createRoute($metadata, $configuration, $isApi ? $rootPath : $rootPath . 'new', 'create', $isApi ? ['POST'] : ['GET', 'POST'], $isApi); $routes->add($this->getRouteName($metadata, $configuration, 'create'), $createRoute); } if (in_array('update', $routesToGenerate)) { $updateRoute = $this->createRoute($metadata, $configuration, $isApi ? $rootPath . '{id}' : $rootPath . '{id}/edit', 'update', $isApi ? ['PUT', 'PATCH'] : ['GET', 'PUT', 'PATCH'], $isApi); $routes->add($this->getRouteName($metadata, $configuration, 'update'), $updateRoute); } if (in_array('show', $routesToGenerate)) { $showRoute = $this->createRoute($metadata, $configuration, $rootPath . '{id}', 'show', ['GET'], $isApi); $routes->add($this->getRouteName($metadata, $configuration, 'show'), $showRoute); } if (in_array('delete', $routesToGenerate)) { $deleteRoute = $this->createRoute($metadata, $configuration, $rootPath . '{id}', 'delete', ['DELETE'], $isApi); $routes->add($this->getRouteName($metadata, $configuration, 'delete'), $deleteRoute); } return $routes; }
public function testExecute() { $transliterate = new Transliterate(); $bookTitle = "Unit test book " . date('d-m-Y-H-i-s'); $bookSlug = Sluggable\Urlizer::urlize($transliterate->transliterate($bookTitle, 'ru'), '-'); $book = new Book(); $book->setTitle($bookTitle); $book->setSlug($bookSlug); $book->setAuthors('Author'); $book->setIsbn('111-1111-1111-2'); $createETBFile = new CreateETBFile(); $createETBFile->setBook($book); $createETBFile->execute(); $book->setAuthors('Author, Author'); $book->setTitle('With module'); $updateETBFile = new UpdateETBFile(); $updateETBFile->setBook($book); $updateETBFile->addModule('New module'); $updateETBFile->execute(); }
/** * Execute * * @param InputInterface $input input * @param OutputInterface $output output */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<info>Update department slug</info>'); try { $em = $this->getEntityManager(); /** @var ProgressHelper $progress */ $progress = $this->getHelperSet()->get('progress'); /** @var DepartmentRepository $departmentRepo */ $departmentRepo = $this->getRepository('SehBundle:Department'); $entities = $departmentRepo->findAll(); $langs = array('en', 'de', 'es', 'it', 'nl'); $progress->start($output, count($entities)); /** @var Department $entity */ foreach ($entities as $entity) { foreach ($langs as $lang) { $entity->setTranslatableLocale($lang); $em->refresh($entity); $slug = $entity->getName(); $entity->setSlug(null); $slug = Urlizer::transliterate($slug); $slug = Urlizer::urlize($slug); if (function_exists('mb_strtolower')) { $slug = mb_strtolower($slug); } else { $slug = strtolower($slug); } $entity->setSlug($slug); $em->persist($entity); $em->flush(); } $progress->advance(); } $progress->finish(); $output->writeln(' > <info>Flushing</info>'); $em->flush(); $em->clear(); $output->writeln(' > <comment>OK</comment>'); } catch (Exception $e) { $output->writeln(' > <error>Erreur : ' . $e->getMessage() . '</error>'); } }
/** * Execute * * @param InputInterface $input input * @param OutputInterface $output output */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<info>Update hotels slug</info>'); try { $entityManager = $this->getEntityManager(); $progress = $this->getHelperSet()->get('progress'); $hotelRepo = $this->getRepository('SehBundle:Hotel'); $entities = $hotelRepo->findAll(); $progress->start($output, count($entities)); foreach ($entities as $entity) { $exists = $hotelRepo->findBy(array("name" => $entity->getName())); if (count($exists) > 1) { echo "\n" . $entity->getName(); $slug = $entity->getName() . "-" . $entity->getZipCode(); } else { $slug = $entity->getName(); } $entity->setSlug(null); $slug = Urlizer::transliterate($slug); $slug = Urlizer::urlize($slug); if (function_exists('mb_strtolower')) { $slug = mb_strtolower($slug); } else { $slug = strtolower($slug); } $entity->setSlug($slug); $entityManager->persist($entity); $progress->advance(); } $progress->finish(); $output->writeln(' > <info>Flushing</info>'); $entityManager->flush(); $entityManager->clear(); $output->writeln(' > <comment>OK</comment>'); } catch (Exception $e) { $output->writeln(' > <error>Erreur : ' . $e->getMessage() . '</error>'); } }
/** * Get taxes percent * * @param tax_names array if present shows only percent of those taxes * @return integer total percent of taxes to apply */ public function getTaxesPercent($tax_names = array()) { $tax_names = is_array($tax_names) ? array_map(array('Gedmo\\Sluggable\\Util\\Urlizer', 'urlize'), $tax_names) : array(Urlizer::urlize($tax_names)); $total = 0; foreach ($this->getTaxes() as $tax) { if (count($tax_names) == 0 || in_array(Urlizer::urlize(str_replace(' ', '', $tax->getName())), $tax_names)) { $total += $tax->getValue(); } } return $total; }
/** * Generate url key from product name and identifier. * The identifier is included to make sure the url_key is unique, as required in Prestashop. * * If name is localized, the default locale is used to get the value. * * @param ProductInterface $product * @param MappingCollection $attributeCodeMapping * @param string $localeCode * @param string $scopeCode * @param boolean $skuFirst * * @return string */ protected function generateUrlKey(ProductInterface $product, MappingCollection $attributeCodeMapping, $localeCode, $scopeCode, $skuFirst = false) { $identifier = $product->getIdentifier(); $nameAttribute = $attributeCodeMapping->getSource(self::NAME); $name = $product->getValue($nameAttribute, $localeCode, $scopeCode); if (false === $skuFirst) { $url = Urlizer::urlize($name . '-' . $identifier); } else { $url = Urlizer::urlize($identifier . '-' . $name); } return $url; }
/** * slug * * @param string $text * @param string $glue * * @return string */ public static function slug($text, $glue = '-') { return Urlizer::urlize($text, $glue); }
/** * @param ProductInterface $product * @param ProductValueInterface $value * * @return string */ public function generateFilenamePrefix(ProductInterface $product, ProductValueInterface $value) { return sprintf('%s-%s-%s-%s-%s-%s', $product->getId(), Urlizer::urlize($product->getIdentifier(), '_'), $value->getAttribute()->getCode(), $value->getLocale(), $value->getScope(), time()); }
/** * Return a json array with the calculated path for a page object * * @param Request $request * @internal param string $path * @return Response */ public function getPathAction(Request $request) { $id = $request->get('page_id'); $getPath = $request->get('path'); $object = $this->admin->getObject($id); if ($id && $object) { $path = $object->getFullPath(); } else { $path = '/'; } $getPath = Urlizer::urlize($getPath); return $this->renderJson(array('path' => $path . $getPath)); }
public function slugUpdate($incident) { $incident->setSlug(Sluggable\Urlizer::urlize($incident->getHostAddress() . " " . $incident->getType()->getSlug() . " " . $incident->getDate()->format('Y-m-d'), '_')); }
/** * Create a safe file name for the uploaded file, so that it can be saved safely on the disk. * * @return string */ public function getSafeFileName() { $fileExtension = pathinfo($this->file->getClientOriginalName(), PATHINFO_EXTENSION); $mimeTypeExtension = $this->file->guessExtension(); $newExtension = !empty($mimeTypeExtension) ? $mimeTypeExtension : $fileExtension; $baseName = !empty($fileExtension) ? basename($this->file->getClientOriginalName(), $fileExtension) : $this->file->getClientOriginalName(); $safeBaseName = Urlizer::urlize($baseName); return $safeBaseName . (!empty($newExtension) ? '.' . $newExtension : ''); }
protected function importLang($brand, $lang) { $translationRepository = $this->getTranslationRepository(); $translationDir = $this->getContainer()->getParameter('translation_dir') . '/lot_5/'; $defaultLang = 'en'; $em = $this->getEntityManager(); $translationfiles = scandir($translationDir . strtoupper($lang) . '/'); $exclude = array('.', '..'); $translationfiles = array_diff($translationfiles, $exclude); foreach (array_values($translationfiles) as $translationFile) { $file = $translationDir . strtoupper($lang) . '/' . $translationFile; $handle = fopen($file, "r"); while (($line = fgetcsv($handle)) !== false) { if ($line) { list($brandId, $regionId, $pageName, $pageTitle, $pageDescription, $block1Title, $block1Description, $block2Title, $block2Description, $block3Title, $block3Description, $block4Title, $block4Description, $block5Title, $block5Description, $imageTitle1, $imageTitle2, $imageTitle3) = $line; $name = sprintf('[%s] Region hotelier - %s [%s]', $brandId, $pageName, $regionId); $page = $em->getRepository('BigfootContentBundle:Page\\Template\\TitleDescMediaBlockSidebar')->createQueryBuilder('p')->where('p.name LIKE :name')->setParameter(':name', sprintf('%%[%s]%%', $regionId))->getQuery()->setHint(\Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE, 'en')->getOneOrNullResult(); if (!$page) { $page = new Page\Template\TitleDescMediaBlockSidebar(); $page->setTemplate('title_desc_media_block_sidebar_edito'); $page->setActive(true); } if ($lang != $defaultLang) { $translationRepository->translate($page, 'name', $lang, $name); $translationRepository->translate($page, 'title', $lang, $pageTitle); $translationRepository->translate($page, 'description', $lang, $pageDescription); $slug = Urlizer::transliterate(sprintf('%s Region hotelier %s', $brandId, $pageName)); $slug = Urlizer::urlize($slug); if (function_exists('mb_strtolower')) { $slug = mb_strtolower($slug); } else { $slug = strtolower($slug); } $translationRepository->translate($page, 'slug', $lang, $slug); } else { $page->setName($name); $page->setTitle($pageTitle); $page->setDescription($pageDescription); $slug = Urlizer::transliterate(sprintf('%s Region hotelier %s', $brandId, $pageName)); $slug = Urlizer::urlize($slug); if (function_exists('mb_strtolower')) { $slug = mb_strtolower($slug); } else { $slug = strtolower($slug); } $page->setSlug($slug); } $em->persist($page); for ($i = 1; $i < 6; $i++) { $title = sprintf('block%sTitle', $i); $desc = sprintf('block%sDescription', $i); if (${$title} or ${$desc}) { $blockName = sprintf('[%s] Region hotelier - %s - Bloc %s [%s]', $brandId, $pageName, $i, $regionId); $block = $em->getRepository('BigfootContentBundle:Block\\Template\\TitleDescMedia')->createQueryBuilder('b')->where('b.name LIKE :name')->setParameter(':name', sprintf('%%%s [%s]%%', $i, $regionId))->getQuery()->setHint(\Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE, 'en')->getOneOrNullResult(); if (!$block) { $block = new TitleDescMedia(); $block->setTemplate('title_desc_media_editorialLeft'); $block->setActive(true); } if ($lang != $defaultLang) { $translationRepository->translate($block, 'name', $lang, $blockName); $translationRepository->translate($block, 'title', $lang, ${$title}); $translationRepository->translate($block, 'description', $lang, ${$desc}); $slug = Urlizer::transliterate($blockName); $slug = Urlizer::urlize($slug); if (function_exists('mb_strtolower')) { $slug = mb_strtolower($slug); } else { $slug = strtolower($slug); } $translationRepository->translate($block, 'slug', $lang, $slug); } else { $block->setName($blockName); $block->setTitle(${$title}); $block->setDescription(${$desc}); $pageBlock = new Page\Block(); $pageBlock->setBlock($block); $pageBlock->setPage($page); $pageBlock->setPosition($i); $pageBlock->setTemplate('title_desc_media_editorialLeft'); $page->addBlock($pageBlock); $em->persist($pageBlock); } $em->persist($block); } } $em->flush(); } } } }
/** * Sets the subject * * @param string $subject */ public function setSubject($subject) { $this->subject = $subject; $this->setSlug(Urlizer::urlize($this->getSubject())); }
/** * Creates the slug for object being flushed * * @param SluggableAdapter $ea * @param object $object * @throws UnexpectedValueException - if parameters are missing * or invalid * @return void */ private function generateSlug(SluggableAdapter $ea, $object) { $om = $ea->getObjectManager(); $meta = $om->getClassMetadata(get_class($object)); $uow = $om->getUnitOfWork(); $changeSet = $ea->getObjectChangeSet($uow, $object); $config = $this->getConfiguration($om, $meta->name); foreach ($config['slugs'] as $slugField => $options) { $options['useObjectClass'] = $config['useObjectClass']; $fields = $options['fields']; //$slugFieldConfig = $config['slugFields'][$slugField]; // collect the slug from fields $slug = ''; $needToChangeSlug = false; foreach ($options['fields'] as $sluggableField) { if (isset($changeSet[$sluggableField])) { $needToChangeSlug = true; } $slug .= $meta->getReflectionProperty($sluggableField)->getValue($object) . ' '; } // if slug is changed, do further processing if ($needToChangeSlug) { $mapping = $meta->getFieldMapping($slugField); if (!strlen(trim($slug)) && (!isset($mapping['nullable']) || !$mapping['nullable'])) { throw new \Gedmo\Exception\UnexpectedValueException("Unable to find any non empty sluggable fields for slug [{$slugField}] , make sure they have something at least."); } // build the slug $slug = call_user_func_array($this->transliterator, array($slug, $options['separator'], $object)); $slug = Util\Urlizer::urlize($slug, $options['separator']); // stylize the slug switch ($options['style']) { case 'camel': $slug = preg_replace_callback('/^[a-z]|' . $options['separator'] . '[a-z]/smi', function ($m) { return strtoupper($m[0]); }, $slug); break; default: // leave it as is break; } // cut slug if exceeded in length if (isset($mapping['length']) && strlen($slug) > $mapping['length']) { $slug = substr($slug, 0, $mapping['length']); } if (isset($mapping['nullable']) && $mapping['nullable'] && !$slug) { $slug = null; } // make unique slug if requested if ($options['unique'] && !is_null($slug)) { $this->exponent = 0; $slug = $this->makeUniqueSlug($ea, $object, $slug, false, $options); } // set the final slug $meta->getReflectionProperty($slugField)->setValue($object, $slug); // recompute changeset $ea->recomputeSingleObjectChangeSet($uow, $meta, $object); } } }
/** * Transliterates the slug and prefixes the slug * by collection of parent slugs * * @param string $text * @param string $separator * @param object $object * @return string */ public function transliterate($text, $separator, $object) { $slug = call_user_func_array($this->originalTransliterator, array($text, $separator, $object)); // For tree slugs, we "urlize" each part of the slug before appending "/" $slug = Urlizer::urlize($slug, $separator); if (strlen($this->parentSlug)) { $slug = $this->parentSlug . $this->usedPathSeparator . $slug; } $this->sluggable->setTransliterator($this->originalTransliterator); return $slug; }
/** * Generate url key for category name and code * The code is included to make sure the url_key is unique, as required in Prestashop. * * @param CategoryInterface $category * @param string $localeCode * * @return string */ protected function generateUrlKey(CategoryInterface $category, $localeCode) { $code = $category->getCode(); $label = $this->getCategoryLabel($category, $localeCode); $url = Urlizer::urlize($label . '-' . $code); return $url; }
/** * Manages the copying of the file to the relevant place on the server * @throws EmptyFileException when no file has been uploaded * @return $this */ public function upload() { // the file property cannot be empty if (null === $this->getFile()) { throw new EmptyFileException("File is empty"); } // Sanitize the filename $this->filename = Urlizer::transliterate($this->getFile()->getClientOriginalName()); // check upload dir $this->checkUploadDir(); // change filename if a file with the same name exists if (file_exists($this->getPath())) { $i = 1; $originalFilename = $this->filename; do { $this->filename = $i++ . '_' . $originalFilename; if ($i > 3) { $this->filename = uniqid(); } } while (file_exists($this->getPath())); } // move the file to the upload dir $this->getFile()->move($this->getDirectoryPath(), $this->filename); // file property cleaned, not needed anymore $this->setFile(null); return $this; }
/** * @ORM\PrePersist() * @ORM\PreUpdate() */ public function preUpdate() { if ('' == trim($this->getSlug())) { $this->setSlug(\Gedmo\Sluggable\Util\Urlizer::urlize($this->getName())); } }
/** * Handle the form submission * * @param Request $request * * @Route("/addFormAnswerAction", name="victoire_contact_form_result") * @return array */ public function addFormAnswerAction(Request $request) { $emailSend = false; $regexErrors = []; if ($request->getMethod() != "POST" && $request->getMethod() != "PUT") { throw $this->createNotFoundException(); } $_taintedValues = $this->getRequest()->request->all()['cms_form_content']; /** @var WidgetForm $widget */ $widget = $this->get('doctrine.orm.entity_manager')->getRepository('VictoireWidgetFormBundle:WidgetForm')->find($_taintedValues['id']); foreach ($_taintedValues['questions'] as $question) { if (in_array($question['type'], array("text", "textarea", "email")) && !empty($question[0])) { $data[] = array('label' => $question["label"], 'value' => $question[0]); if (isset($question['regex']) && !empty($question['regex'])) { $regex = $question['regex']; $regexTitle = null; $regex = "/" . $regex . "/"; $isValid = preg_match($regex, $question[0]); if (isset($question['regexTitle']) && !empty($question['regexTitle'])) { $regexTitle = $question['regexTitle']; } if ($isValid !== 1) { $regexErrors[] = $regexTitle; } } } elseif (in_array($question['type'], array("checkbox", "radio")) && !empty($question['proposal'][0])) { $checkboxValues = $question['proposal']; $data[] = array('label' => $question["label"], 'value' => implode(', ', $checkboxValues)); } elseif ($question['type'] == "date" && !empty($question['Day']) && !empty($question['Month']) && !empty($question['Year'])) { $label = $question["label"]; $data[] = array('label' => $label, 'value' => $question['Day'] . " " . $question['Month'] . " " . $question['Year']); } else { if ($question['type'] == "boolean") { $label = "victoire_widget_form.boolean.false"; if (!empty($question[0])) { $label = "victoire_widget_form.boolean.true"; } $data[] = array('label' => $question["label"], 'value' => $this->get('translator')->trans($label)); } } } ///////////////////////// SEND EMAIL TO ADMIN (set in the form or default one) ////////////////////////////////////////// //$isSpam = $this->testForSpam($taintedValues, $request); $mailer = 'mailer'; $subject = $widget->getTitle(); $targetEmail = $widget->getTargetEmail() ? $widget->getTargetEmail() : $this->container->getParameter('victoire_widget_form.default_email_address'); if ($errors = $this->get('validator')->validateValue($widget->getTargetEmail(), new EmailConstraint())) { try { $from = array($this->container->getParameter('victoire_widget_form.default_email_address') => $this->container->getParameter('victoire_widget_form.default_email_label')); array_push($data, array('label' => 'ip', 'value' => $_SERVER['REMOTE_ADDR'])); $body = $this->renderView('VictoireWidgetFormBundle::managerMailTemplate.html.twig', array('title' => $widget->getTitle(), 'url' => $request->headers->get('referer'), 'data' => $data)); if (sizeof($regexErrors) == 0) { $emailSend = true; $this->createAndSendMail($subject, $from, $targetEmail, $body, 'text/html', null, array(), $mailer); } } catch (\Exception $e) { echo $e->getTraceAsString(); } } ///////////////////////// AUTOANSWER (if email field exists and is filled properly) ////////////////////////////////////////// $email = null; foreach ($_taintedValues['questions'] as $question) { if ($question['label'] == "Email" || $question['label'] == "email") { $email = $question[0]; } } if ($widget->isAutoAnswer() === true && $email) { if ($errors = $this->get('validator')->validateValue($widget->getTargetEmail(), new EmailConstraint())) { try { $urlizer = new Urlizer(); $body = $widget->getMessage(); preg_match_all("/{{(.*?)}}/", $body, $variables); foreach ($variables[1] as $index => $variable) { $pattern = "/" . $variables[0][$index] . "/"; foreach ($_taintedValues["questions"] as $_question) { //Allow exact and urlized term (ex: for a field named Prénom => prenom, Prénom, Prenom are ok) if ($_question['label'] === $variable || $urlizer->urlize($_question['label']) === $urlizer->urlize($variable)) { switch ($_question['type']) { case 'radio': $body = preg_replace($pattern, $_question["proposal"][0], $body); break; case 'checkbox': $body = preg_replace($pattern, implode(', ', $_question["proposal"]), $body); break; case 'date': $body = preg_replace($pattern, $_question['Day'] . " " . $_question['Month'] . " " . $_question['Year'], $body); break; default: //text, textarea $replacement = $_question[0]; $body = preg_replace($pattern, $replacement, $body); } } } //If we didn't found the variable in any field, we cleanup by removing the variable in the body to not appear like buggy to the final user $body = preg_replace($pattern, "", $body); } //Send an email to the customer AND to the specified email target $from = array($this->container->getParameter('victoire_widget_form.default_email_address') => $this->container->getParameter('victoire_widget_form.default_email_label')); $body = $this->renderView('VictoireWidgetFormBundle::customerMailTemplate.html.twig', array('message' => $body)); $attachments = array(); foreach (array('attachmentUrl', 'attachmentUrl2', 'attachmentUrl3', 'attachmentUrl4', 'attachmentUrl5', 'attachmentUrl6', 'attachmentUrl7') as $field) { $getAttachment = 'get' . ucfirst($field); /** @var Media $attachment */ if ($attachment = $widget->{$getAttachment}()) { $filePath = $this->container->getParameter('kernel.root_dir') . '/../web' . $attachment->getUrl(); $attachment = new UploadedFile($filePath, $attachment->getName()); $attachments[] = $attachment; } } if (sizeof($regexErrors) == 0) { $emailSend = true; $this->createAndSendMail($widget->getSubject(), $from, $email, $body, 'text/html', $widget->getTargetemail(), $attachments, $mailer); } } catch (\Exception $exc) { echo $exc->getTraceAsString(); } } } ///////////////////////// BUILD REDIRECT URL ACCORDING TO SUCCESS CALLBACK ///////////////////////////////////// $redirectUrl = null; if ($emailSend) { if ($widget->getSuccessCallback() == 'notification') { $message = $widget->getSuccessMessage() != "" ? $widget->getSuccessMessage() : $this->get('translator')->trans('victoire_widget_form.alert.send.email.success.label'); $this->container->get('appventus_alertifybundle.helper.alertifyhelper')->congrat($message); } else { if ($link = $widget->getLink()) { $redirectUrl = $this->get('victoire_widget.twig.link_extension')->victoireLinkUrl($link->getParameters()); } } } else { if ($widget->getErrorNotification() == true) { $message = $widget->getErrorMessage() != "" ? $widget->getErrorMessage() : $this->get('translator')->trans('victoire_widget_form.alert.send.email.error.label'); $this->container->get('appventus_alertifybundle.helper.alertifyhelper')->scold($message); } } foreach ($regexErrors as $key => $error) { if ($error != '') { $this->container->get('appventus_alertifybundle.helper.alertifyhelper')->scold($error); } } $redirectUrl = $redirectUrl ?: $request->headers->get('referer'); return $this->redirect($redirectUrl); }