Esempio n. 1
0
 public function testQuery()
 {
     new Translator(new Container());
     $export = new ProductSEOExport(new Container());
     $data = $export->buildData(Lang::getDefaultLanguage());
     $keys = ["ref", "visible", "product_title", "url", "page_title", "meta_description", "meta_keywords"];
     sort($keys);
     $rawData = $data->getData();
     $max = count($rawData);
     /**
      * If there's more that 50 entries,
      * just pick 50, it would be faster and as tested as if we test 1000 entries.
      */
     if ($max > 50) {
         $max = 50;
     }
     for ($i = 0; $i < $max; ++$i) {
         $row = $rawData[$i];
         $rowKeys = array_keys($row);
         $this->assertTrue(sort($rowKeys));
         $this->assertEquals($keys, $rowKeys);
         $product = ProductQuery::create()->findOneByRef($row["ref"]);
         $this->assertNotNull($product);
         $this->assertEquals($product->getVisible(), $row["visible"]);
         $this->assertEquals($product->getTitle(), $row["product_title"]);
         $this->assertEquals($product->getMetaTitle(), $row["page_title"]);
         $this->assertEquals($product->getMetaDescription(), $row["meta_description"]);
         $this->assertEquals($product->getMetaKeywords(), $row["meta_keywords"]);
         $this->assertEquals($product->getRewrittenUrl("en_US"), $row["url"]);
     }
 }
Esempio n. 2
0
 public function testRenderLoop()
 {
     $customerId = CustomerQuery::create()->findOne()->getId();
     $this->handler->expects($this->any())->method("buildDataSet")->willReturn($this->handler->renderLoop("address", ["customer" => $customerId]));
     $lang = Lang::getDefaultLanguage();
     $loop = $this->handler->buildDataSet($lang);
     $this->assertInstanceOf("Thelia\\Core\\Template\\Loop\\Address", $loop);
     $data = $this->handler->buildData($lang);
     $addresses = AddressQuery::create()->filterByCustomerId($customerId)->find()->toArray("Id");
     foreach ($data->getData() as $row) {
         $this->assertArrayHasKey("id", $row);
         $this->assertArrayHasKey($row["id"], $addresses);
         $this->assertEquals(count($addresses), $row["loop_total"]);
         $address = $addresses[$row["id"]];
         $this->assertEquals($row["address1"], $address["Address1"]);
         $this->assertEquals($row["address2"], $address["Address2"]);
         $this->assertEquals($row["address3"], $address["Address3"]);
         $this->assertEquals($row["cellphone"], $address["Cellphone"]);
         $this->assertEquals($row["city"], $address["City"]);
         $this->assertEquals($row["company"], $address["Company"]);
         $this->assertEquals($row["country"], $address["CountryId"]);
         $this->assertEquals($row["create_date"], $address["CreatedAt"]);
         $this->assertEquals($row["update_date"], $address["UpdatedAt"]);
         $this->assertEquals($row["firstname"], $address["Firstname"]);
         $this->assertEquals($row["lastname"], $address["Lastname"]);
         $this->assertEquals($row["id"], $address["Id"]);
         $this->assertEquals($row["label"], $address["Label"]);
         $this->assertEquals($row["phone"], $address["Phone"]);
         $this->assertEquals($row["title"], $address["TitleId"]);
         $this->assertEquals($row["zipcode"], $address["Zipcode"]);
     }
 }
 public function testImportWorks()
 {
     // Export data
     $data = $this->exportHandler->buildData(Lang::getDefaultLanguage());
     $compareData = array();
     $currentData = $data->getData();
     // Replace the prices
     foreach ($currentData as $key => &$entry) {
         // let  6/10 prices be changed.
         if (rand(1, 100) >= 60) {
             $compareData[$key] = $rand = rand(1, 1000);
             $entry["price"] = $rand;
         } else {
             $compareData[$key] = $entry["price"];
         }
     }
     // Import new prices
     $this->importHandler->retrieveFromFormatterData($data->setData($currentData));
     // Export once again
     $newData = $this->exportHandler->buildData(Lang::getDefaultLanguage());
     $newDataEntries = $newData->getData();
     // Check them
     foreach ($compareData as $key => $price) {
         $this->assertEquals($price, $newDataEntries[$key]["price"]);
     }
 }
Esempio n. 4
0
 /**
  * render the RSS feed
  *
  * @param $context string   The context of the feed : catalog, content. default: catalog
  * @param $lang string      The lang of the feed : fr_FR, en_US, ... default: default language of the site
  * @param $id string        The id of the parent element. The id of the main parent category for catalog context.
  *                          The id of the content folder for content context
  * @return Response
  * @throws \RuntimeException
  */
 public function generateAction($context, $lang, $id)
 {
     /** @var Request $request */
     $request = $this->getRequest();
     // context
     if ("" === $context) {
         $context = "catalog";
     } else {
         if (!in_array($context, array("catalog", "content", "brand"))) {
             $this->pageNotFound();
         }
     }
     // the locale : fr_FR, en_US,
     if ("" !== $lang) {
         if (!$this->checkLang($lang)) {
             $this->pageNotFound();
         }
     } else {
         try {
             $lang = Lang::getDefaultLanguage();
             $lang = $lang->getLocale();
         } catch (\RuntimeException $ex) {
             // @todo generate error page
             throw new \RuntimeException("No default language is defined. Please define one.");
         }
     }
     if (null === ($lang = LangQuery::create()->findOneByLocale($lang))) {
         $this->pageNotFound();
     }
     $lang = $lang->getId();
     // check if element exists and is visible
     if ("" !== $id) {
         if (false === $this->checkId($context, $id)) {
             $this->pageNotFound();
         }
     }
     $flush = $request->query->get("flush", "");
     // check if feed already in cache
     $cacheContent = false;
     $cacheDir = $this->getCacheDir();
     $cacheKey = self::FEED_CACHE_KEY . $lang . $context . $id;
     $cacheExpire = intval(ConfigQuery::read("feed_ttl", '7200')) ?: 7200;
     $cacheDriver = new FilesystemCache($cacheDir);
     if (!($this->checkAdmin() && "" !== $flush)) {
         $cacheContent = $cacheDriver->fetch($cacheKey);
     } else {
         $cacheDriver->delete($cacheKey);
     }
     // if not in cache
     if (false === $cacheContent) {
         // render the view
         $cacheContent = $this->renderRaw("feed", array("_context_" => $context, "_lang_" => $lang, "_id_" => $id));
         // save cache
         $cacheDriver->save($cacheKey, $cacheContent, $cacheExpire);
     }
     $response = new Response();
     $response->setContent($cacheContent);
     $response->headers->set('Content-Type', 'application/rss+xml');
     return $response;
 }
Esempio n. 5
0
 /**
  * Checks if we are the payment module for the order, and if the order is paid,
  * then send a confirmation email to the customer.
  *
  * @params OrderEvent $order
  */
 public function update_status(OrderEvent $event)
 {
     $payzen = new Payzen();
     if ($event->getOrder()->isPaid() && $payzen->isPaymentModuleFor($event->getOrder())) {
         $contact_email = ConfigQuery::read('store_email', false);
         $lang = Lang::getDefaultLanguage();
         $locale = $lang->getLocale();
         Tlog::getInstance()->debug("Sending confirmation email from store contact e-mail {$contact_email}");
         if ($contact_email) {
             $message = MessageQuery::create()->filterByName(Payzen::CONFIRMATION_MESSAGE_NAME)->findOne();
             if (false === $message) {
                 throw new \Exception(sprintf("Failed to load message '%s'.", Payzen::CONFIRMATION_MESSAGE_NAME));
             }
             $order = $event->getOrder();
             $customer = $order->getCustomer();
             $this->parser->assign('order_id', $order->getId());
             $this->parser->assign('order_ref', $order->getRef());
             $this->parser->assign('locale', $locale);
             $message->setLocale($order->getLang()->getLocale());
             $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name'));
             // Build subject and body
             $message->buildMessage($this->parser, $instance);
             $this->getMailer()->send($instance);
             Tlog::getInstance()->debug("Confirmation email sent to customer " . $customer->getEmail());
         }
     } else {
         Tlog::getInstance()->debug("No confirmation email sent (order not paid, or not the proper payment module).");
     }
 }
Esempio n. 6
0
 public function __construct(Request $request)
 {
     if ($request->getSession() != null) {
         $this->locale = $request->getLocale();
     } else {
         $this->locale = Lang::getDefaultLanguage()->getLocale();
     }
 }
Esempio n. 7
0
 protected function buildForm($change_mode = false)
 {
     $name_constraints = array(new Constraints\NotBlank());
     if (!$change_mode) {
         $name_constraints[] = new Constraints\Callback(array("methods" => array(array($this, "checkDuplicateName"))));
     }
     $this->formBuilder->add("name", "text", array("constraints" => $name_constraints, "label" => Translator::getInstance()->trans('Name'), "label_attr" => array("for" => "name", 'help' => Translator::getInstance()->trans("This is an identifier that will be used in the code to get this message")), 'attr' => ['placeholder' => Translator::getInstance()->trans("Mail template name")]))->add("title", "text", array("constraints" => array(new Constraints\NotBlank()), "label" => Translator::getInstance()->trans('Purpose'), "label_attr" => array("for" => "purpose", 'help' => Translator::getInstance()->trans("Enter here the mail template purpose in the default language (%title%)", ['%title%' => Lang::getDefaultLanguage()->getTitle()])), 'attr' => ['placeholder' => Translator::getInstance()->trans("Mail template purpose")]))->add("locale", "hidden", array("constraints" => array(new Constraints\NotBlank())))->add("secured", "hidden", array());
 }
Esempio n. 8
0
 protected function applyUserLocale(Admin $user)
 {
     // Set the current language according to Admin locale preference
     $locale = $user->getLocale();
     if (null === ($lang = LangQuery::create()->findOneByLocale($locale))) {
         $lang = Lang::getDefaultLanguage();
     }
     $this->getSession()->setLang($lang);
 }
Esempio n. 9
0
 public static function addI18nCondition(ModelCriteria $query, $i18nTableName, $tableIdColumn, $i18nIdColumn, $localeColumn, $locale)
 {
     if (null === static::$defaultLocale) {
         static::$defaultLocale = Lang::getDefaultLanguage()->getLocale();
     }
     $locale = static::realEscape($locale);
     $defaultLocale = static::realEscape(static::$defaultLocale);
     $query->_and()->where("CASE WHEN " . $tableIdColumn . " IN" . "(SELECT DISTINCT " . $i18nIdColumn . " " . "FROM `" . $i18nTableName . "` " . "WHERE locale={$locale}) " . "THEN " . $localeColumn . " = {$locale} " . "ELSE " . $localeColumn . " = {$defaultLocale} " . "END");
 }
Esempio n. 10
0
 public function getProduct(ConnectionInterface $con = null, $locale = null)
 {
     $product = parent::getProduct($con);
     $translation = $product->getTranslation($locale);
     if ($translation->isNew()) {
         if (ConfigQuery::getDefaultLangWhenNoTranslationAvailable()) {
             $locale = Lang::getDefaultLanguage()->getLocale();
         }
     }
     $product->setLocale($locale);
     return $product;
 }
 public function testPrices()
 {
     $container = new Container();
     new Translator($container);
     $handler = new ProductTaxedPricesExport($container);
     $lang = Lang::getDefaultLanguage();
     $data = $handler->buildData($lang)->getData();
     foreach ($data as $line) {
         $product = ProductSaleElementsQuery::create()->findOneByRef($line["ref"]);
         $currency = CurrencyQuery::create()->findOneByCode($line["currency"]);
         $this->assertNotNull($product);
         $prices = $product->getPricesByCurrency($currency);
         $this->assertEquals($prices->getPrice(), $line["price"]);
         $this->assertEquals($prices->getPromoPrice(), $line["promo_price"]);
     }
 }
 public function getTaxonomy($langId = null)
 {
     $lang = LangQuery::create()->findOneById($langId);
     if ($lang === null) {
         $lang = Lang::getDefaultLanguage();
     }
     $file = file_get_contents("http://www.google.com/basepages/producttype/taxonomy." . str_replace("_", "-", $lang->getLocale()) . ".txt");
     $rows = explode("\n", $file);
     $cats = [];
     foreach ($rows as $row) {
         $splittedCat = explode('>', $row);
         $name = end($splittedCat);
         $cats[$name] = htmlspecialchars($row);
     }
     return new JsonResponse(['cats' => $cats]);
 }
Esempio n. 13
0
 public function buildModelCriteria()
 {
     $query = GoogleshoppingProductSynchronisationQuery::create()->filterByProductId($this->getProductId());
     if ($this->getCountry()) {
         $targetCountry = $this->getCountry();
     } else {
         $targetCountry = Country::getDefaultCountry()->getIsoalpha2();
     }
     if ($this->getLocale()) {
         $lang = LangQuery::create()->findOneByLocale($this->getLocale())->getCode();
     } else {
         $lang = Lang::getDefaultLanguage()->getCode();
     }
     $query->filterByTargetCountry($targetCountry)->filterByLang($lang);
     return $query;
 }
 public function testPrices()
 {
     new Translator(new Container());
     $export = new ProductTaxedPricesExport(new Container());
     $data = $export->buildData(Lang::getDefaultLanguage());
     $keys = ["attributes", "currency", "ean", "id", "price", "product_id", "promo", "promo_price", "tax_id", "tax_title", "title"];
     $rawData = $data->getData();
     $max = count($rawData);
     /**
      * If there are more than 50 entries, a test on 50 entries will be as efficient
      * and quicker than a test on all the entries
      */
     if ($max > 50) {
         $max = 50;
     }
     for ($i = 0; $i < $max; ++$i) {
         $row = $rawData[$i];
         $rowKeys = array_keys($row);
         $this->assertTrue(sort($rowKeys));
         $this->assertEquals($keys, $rowKeys);
         $pse = ProductSaleElementsQuery::create()->findPk($row["id"]);
         $this->assertNotNull($pse);
         $this->assertEquals($pse->getEanCode(), $row["ean"]);
         $this->assertEquals($pse->getPromo(), $row["promo"]);
         $currency = CurrencyQuery::create()->findOneByCode($row["currency"]);
         $this->assertNotNull($currency);
         $price = $pse->getPricesByCurrency($currency);
         $this->assertEquals(round($price->getPrice(), 3), round($row["price"], 3));
         $this->assertEquals(round($price->getPromoPrice(), 3), round($row["promo_price"], 3));
         $this->assertEquals($pse->getProduct()->getTitle(), $row["title"]);
         $attributeCombinations = $pse->getAttributeCombinations();
         $attributes = [];
         foreach ($attributeCombinations as $attributeCombination) {
             if (!in_array($attributeCombination->getAttributeAv()->getTitle(), $attributes)) {
                 $attributes[] = $attributeCombination->getAttributeAv()->getTitle();
             }
         }
         $rowAttributes = !empty($row["attributes"]) ? explode(",", $row["attributes"]) : [];
         sort($rowAttributes);
         sort($attributes);
         $this->assertEquals($attributes, $rowAttributes);
         $taxId = $pse->getProduct()->getTaxRule()->getId();
         $this->assertEquals($taxId, $row["tax_id"]);
         $taxTitle = $pse->getProduct()->getTaxRule()->getTitle();
         $this->assertEquals($taxTitle, $row["tax_title"]);
     }
 }
Esempio n. 15
0
 /**
  * @param ModelCriteria $search
  * @param               $requestedLocale
  * @param array $columns
  * @param null $foreignTable
  * @param string $foreignKey
  * @param bool $forceReturn
  * @param string $forceReturn
  */
 public static function getFrontEndI18n(ModelCriteria &$search, $requestedLocale, $columns, $foreignTable, $foreignKey, $forceReturn = false, $localeAlias = null)
 {
     if (!empty($columns)) {
         if ($foreignTable === null) {
             $foreignTable = $search->getTableMap()->getName();
             $aliasPrefix = '';
         } else {
             $aliasPrefix = $foreignTable . '_';
         }
         if ($localeAlias === null) {
             $localeAlias = $search->getTableMap()->getName();
         }
         $defaultLangWithoutTranslation = ConfigQuery::getDefaultLangWhenNoTranslationAvailable();
         $requestedLocaleI18nAlias = $aliasPrefix . 'requested_locale_i18n';
         $defaultLocaleI18nAlias = $aliasPrefix . 'default_locale_i18n';
         if ($defaultLangWithoutTranslation == Lang::STRICTLY_USE_REQUESTED_LANGUAGE) {
             $requestedLocaleJoin = new Join();
             $requestedLocaleJoin->addExplicitCondition($localeAlias, $foreignKey, null, $foreignTable . '_i18n', 'ID', $requestedLocaleI18nAlias);
             $requestedLocaleJoin->setJoinType($forceReturn === false ? Criteria::INNER_JOIN : Criteria::LEFT_JOIN);
             $defaultLocaleJoin = new Join();
             $defaultLocaleJoin->addExplicitCondition($localeAlias, $foreignKey, null, $foreignTable . '_i18n', 'ID', $defaultLocaleI18nAlias);
             $search->addJoinObject($requestedLocaleJoin, $requestedLocaleI18nAlias)->addJoinCondition($requestedLocaleI18nAlias, '`' . $requestedLocaleI18nAlias . '`.LOCALE = ?', $requestedLocale, null, \PDO::PARAM_STR);
             $search->addJoinObject($defaultLocaleJoin, $defaultLocaleI18nAlias)->addJoinCondition($defaultLocaleI18nAlias, '`' . $defaultLocaleI18nAlias . '`.LOCALE <> ?', $requestedLocale, null, \PDO::PARAM_STR);
             $search->withColumn('NOT ISNULL(`' . $requestedLocaleI18nAlias . '`.`ID`)', $aliasPrefix . 'IS_TRANSLATED');
             foreach ($columns as $column) {
                 $search->withColumn('`' . $requestedLocaleI18nAlias . '`.`' . $column . '`', $aliasPrefix . 'i18n_' . $column);
             }
         } else {
             $defaultLocale = Lang::getDefaultLanguage()->getLocale();
             $defaultLocaleJoin = new Join();
             $defaultLocaleJoin->addExplicitCondition($localeAlias, $foreignKey, null, $foreignTable . '_i18n', 'ID', $defaultLocaleI18nAlias);
             $defaultLocaleJoin->setJoinType(Criteria::LEFT_JOIN);
             $search->addJoinObject($defaultLocaleJoin, $defaultLocaleI18nAlias)->addJoinCondition($defaultLocaleI18nAlias, '`' . $defaultLocaleI18nAlias . '`.LOCALE = ?', $defaultLocale, null, \PDO::PARAM_STR);
             $requestedLocaleJoin = new Join();
             $requestedLocaleJoin->addExplicitCondition($localeAlias, $foreignKey, null, $foreignTable . '_i18n', 'ID', $requestedLocaleI18nAlias);
             $requestedLocaleJoin->setJoinType(Criteria::LEFT_JOIN);
             $search->addJoinObject($requestedLocaleJoin, $requestedLocaleI18nAlias)->addJoinCondition($requestedLocaleI18nAlias, '`' . $requestedLocaleI18nAlias . '`.LOCALE = ?', $requestedLocale, null, \PDO::PARAM_STR);
             $search->withColumn('NOT ISNULL(`' . $requestedLocaleI18nAlias . '`.`ID`)', $aliasPrefix . 'IS_TRANSLATED');
             if ($forceReturn === false) {
                 $search->where('NOT ISNULL(`' . $requestedLocaleI18nAlias . '`.ID)')->_or()->where('NOT ISNULL(`' . $defaultLocaleI18nAlias . '`.ID)');
             }
             foreach ($columns as $column) {
                 $search->withColumn('CASE WHEN NOT ISNULL(`' . $requestedLocaleI18nAlias . '`.ID) THEN `' . $requestedLocaleI18nAlias . '`.`' . $column . '` ELSE `' . $defaultLocaleI18nAlias . '`.`' . $column . '` END', $aliasPrefix . 'i18n_' . $column);
             }
         }
     }
 }
Esempio n. 16
0
 public function parseTemplate($templateType, $template)
 {
     $templateDefinition = new TemplateDefinition($template, $templateType);
     $hooks = array();
     $this->walkDir($templateDefinition->getAbsolutePath(), $hooks);
     // load language message
     $locale = Lang::getDefaultLanguage()->getLocale();
     $this->loadTrans($templateType, $locale);
     $ret = array();
     foreach ($hooks as $hook) {
         try {
             $ret[] = $this->prepareHook($hook);
         } catch (\UnexpectedValueException $ex) {
             Tlog::getInstance()->warning($ex->getMessage());
         }
     }
     return $ret;
 }
Esempio n. 17
0
 public function testQuery()
 {
     new Translator(new Container());
     $export = new ProductPricesExport(new Container());
     $data = $export->buildData(Lang::getDefaultLanguage());
     $keys = ["attributes", "currency", "ean", "id", "price", "product_id", "promo", "promo_price", "title"];
     $rawData = $data->getData();
     $max = count($rawData);
     /**
      * If there's more that 50 entries,
      * just pick 50, it would be faster and as tested as if we test 1000 entries.
      */
     if ($max > 50) {
         $max = 50;
     }
     for ($i = 0; $i < $max; ++$i) {
         $row = $rawData[$i];
         $rowKeys = array_keys($row);
         $this->assertTrue(sort($rowKeys));
         $this->assertEquals($keys, $rowKeys);
         $pse = ProductSaleElementsQuery::create()->findPk($row["id"]);
         $this->assertNotNull($pse);
         $this->assertEquals($pse->getEanCode(), $row["ean"]);
         $this->assertEquals($pse->getPromo(), $row["promo"]);
         $currency = CurrencyQuery::create()->findOneByCode($row["currency"]);
         $this->assertNotNull($currency);
         $price = $pse->getPricesByCurrency($currency);
         // The substr is a patch for php 5.4 float round
         $this->assertEquals(round($price->getPrice(), 3), round($row["price"], 3));
         $this->assertEquals(round($price->getPromoPrice(), 3), round($row["promo_price"], 3));
         $this->assertEquals($pse->getProduct()->getTitle(), $row["title"]);
         $attributeCombinations = $pse->getAttributeCombinations();
         $attributes = [];
         foreach ($attributeCombinations as $attributeCombination) {
             if (!in_array($attributeCombination->getAttributeAv()->getTitle(), $attributes)) {
                 $attributes[] = $attributeCombination->getAttributeAv()->getTitle();
             }
         }
         $rowAttributes = explode(",", $row["attributes"]);
         sort($rowAttributes);
         sort($attributes);
         $this->assertEquals($attributes, $rowAttributes);
     }
 }
Esempio n. 18
0
 public function delete(LangDeleteEvent $event)
 {
     if (null !== ($lang = LangQuery::create()->findPk($event->getLangId()))) {
         if ($lang->getByDefault()) {
             throw new \RuntimeException(Translator::getInstance()->trans('It is not allowed to delete the default language'));
         }
         $lang->setDispatcher($event->getDispatcher())->delete();
         $session = $this->request->getSession();
         // If we've just deleted the current admin edition language, set it to the default one.
         if ($lang->getId() == $session->getAdminEditionLang()->getId()) {
             $session->setAdminEditionLang(LangModel::getDefaultLanguage());
         }
         // If we've just deleted the current admin language, set it to the default one.
         if ($lang->getId() == $session->getLang()->getId()) {
             $session->setLang(LangModel::getDefaultLanguage());
         }
         $event->setLang($lang);
     }
 }
Esempio n. 19
0
 /**
  *
  * in this function you add all the fields you need for your Form.
  * Form this you have to call add method on $this->formBuilder attribute :
  *
  * $this->formBuilder->add("name", "text")
  *   ->add("email", "email", array(
  *           "attr" => array(
  *               "class" => "field"
  *           ),
  *           "label" => "email",
  *           "constraints" => array(
  *               new \Symfony\Component\Validator\Constraints\NotBlank()
  *           )
  *       )
  *   )
  *   ->add('age', 'integer');
  *
  * @return null
  */
 protected function buildForm()
 {
     /**
      * Get information
      */
     if (ShoppingFluxConfigQuery::getDefaultLang() !== null) {
         $langId = ShoppingFluxConfigQuery::getDefaultLang()->getId();
     } else {
         $langId = Lang::getDefaultLanguage()->getId();
     }
     $langsId = LangQuery::create()->select("Id")->find()->toArray();
     $langsId = array_flip($langsId);
     $deliveryModulesId = ModuleQuery::create()->filterByType(AbstractDeliveryModule::DELIVERY_MODULE_TYPE)->filterByActivate(1)->select("Id")->find()->toArray();
     $deliveryModulesId = array_flip($deliveryModulesId);
     $taxesId = TaxQuery::create()->filterByType("Thelia\\TaxEngine\\TaxType\\FixAmountTaxType")->select("Id")->find()->toArray();
     $taxesId = array_flip($taxesId);
     $translator = Translator::getInstance();
     /**
      * Then build the form
      */
     $this->formBuilder->add("token", "text", array("label" => $translator->trans("ShoppingFlux Token", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_token"], "constraints" => [], "required" => true, "data" => ShoppingFluxConfigQuery::getToken()))->add("prod", "checkbox", array("label" => $translator->trans("In production", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_prod"], "required" => false, "data" => ShoppingFluxConfigQuery::getProd()))->add("delivery_module_id", "choice", array("label" => $translator->trans("Delivery module", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_delivery_module_id"], "required" => true, "multiple" => false, "choices" => $deliveryModulesId, "data" => ShoppingFluxConfigQuery::getDeliveryModuleId()))->add("lang_id", "choice", array("label" => $translator->trans("Language", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_lang"], "required" => true, "multiple" => false, "choices" => $langsId, "data" => $langId))->add("ecotax_id", "choice", array("label" => $translator->trans("Ecotax rule", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_ecotax"], "required" => true, "choices" => $taxesId, "multiple" => false, "data" => ShoppingFluxConfigQuery::getEcotaxRuleId()))->add("action_type", "choice", array("required" => true, "choices" => ["save" => 0, "export" => 1], "multiple" => false));
 }
Esempio n. 20
0
 public function sendEmailForAdmin($emails, $productIds)
 {
     $contactEmail = ConfigQuery::read('store_email');
     if ($contactEmail) {
         $message = MessageQuery::create()->filterByName('stockalert_administrator')->findOne();
         if (null === $message) {
             throw new \Exception("Failed to load message 'stockalert_administrator'.");
         }
         $locale = Lang::getDefaultLanguage()->getLocale();
         $this->parser->assign('locale', $locale);
         $this->parser->assign('products_id', $productIds);
         $message->setLocale($locale);
         $instance = \Swift_Message::newInstance();
         $instance->addFrom($contactEmail, ConfigQuery::read('store_name'));
         foreach ($emails as $email) {
             $instance->addTo($email);
         }
         // Build subject and body
         $message->buildMessage($this->parser, $instance);
         $this->mailer->send($instance);
         Tlog::getInstance()->debug("Stock Alert sent to administrator " . implode(', ', $emails));
     } else {
         Tlog::getInstance()->debug("Stock Alert sent to administrator " . implode(', ', $emails));
     }
 }
Esempio n. 21
0
 public function registerHooks()
 {
     $moduleHooks = $this->getHooks();
     if (is_array($moduleHooks) && !empty($moduleHooks)) {
         $allowedTypes = (array) TemplateDefinition::getStandardTemplatesSubdirsIterator();
         $defaultLang = Lang::getDefaultLanguage();
         $defaultLocale = $defaultLang->getLocale();
         $dispatcher = $this->container->get("event_dispatcher");
         foreach ($moduleHooks as $hook) {
             $isValid = is_array($hook) && isset($hook["type"]) && array_key_exists($hook["type"], $allowedTypes) && isset($hook["code"]) && is_string($hook["code"]) && !empty($hook["code"]);
             if (!$isValid) {
                 Tlog::getInstance()->notice("The module " . $this->getCode() . " tried to register an invalid hook");
                 continue;
             }
             /**
              * Create or update hook db entry.
              */
             list($hookModel, $updateData) = $this->createOrUpdateHook($hook, $dispatcher, $defaultLocale);
             /**
              * Update translations
              */
             $event = new HookUpdateEvent($hookModel->getId());
             foreach ($updateData as $locale => $data) {
                 $event->setCode($hookModel->getCode())->setNative($hookModel->getNative())->setByModule($hookModel->getByModule())->setActive($hookModel->getActivate())->setBlock($hookModel->getBlock())->setNative($hookModel->getNative())->setType($hookModel->getType())->setLocale($locale)->setChapo($data["chapo"])->setTitle($data["title"])->setDescription($data["description"]);
                 $dispatcher->dispatch(TheliaEvents::HOOK_UPDATE, $event);
             }
         }
     }
 }
Esempio n. 22
0
 protected function applyUserLocale(UserInterface $user, Session $session)
 {
     // Set the current language according to locale preference
     $locale = $user->getLocale();
     if (null === ($lang = LangQuery::create()->findOneByLocale($locale))) {
         $lang = Lang::getDefaultLanguage();
     }
     $session->setLang($lang);
 }
 public function toggleProductSync($id)
 {
     if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('GoogleShopping'), AccessManager::UPDATE))) {
         return $response;
     }
     if ($this->getRequest()->query->get('target_country')) {
         $targetCountry = CountryQuery::create()->findOneByIsoalpha2($this->getRequest()->get('target_country'));
     } else {
         $targetCountry = Country::getDefaultCountry();
     }
     if ($this->getRequest()->query->get('locale')) {
         $lang = LangQuery::create()->findOneByLocale($this->getRequest()->query->get('locale'));
     } else {
         $lang = Lang::getDefaultLanguage();
     }
     $product = ProductQuery::create()->findPk($id);
     $googleProductEvent = new GoogleProductEvent($product);
     $googleProductEvent->setTargetCountry($targetCountry)->setLang($lang);
     $this->getDispatcher()->dispatch(GoogleShoppingEvents::GOOGLE_PRODUCT_TOGGLE_SYNC, $googleProductEvent);
 }
Esempio n. 24
0
 public function setUp()
 {
     new Translator(new Container());
     $this->lang = Lang::getDefaultLanguage();
     $this->handler = new ContentExport(new Container());
 }
Esempio n. 25
0
 /**
  * Get the current lang used or if not present the default lang for the shop
  *
  * @return \Thelia\Model\Lang
  */
 protected function getLang()
 {
     if (null === $this->lang) {
         $this->lang = $this->getSession() ? $this->getSession()->getLang(true) : ($this->lang = Lang::getDefaultLanguage());
     }
     return $this->lang;
 }
Esempio n. 26
0
 protected function buildForm()
 {
     $this->doBuildForm(Translator::getInstance()->trans('Enter here the sale name in the default language (%title%)', ['%title%' => Lang::getDefaultLanguage()->getTitle()]));
 }
Esempio n. 27
0
 /**
  * Create a SwiftMessage instance from a given message code.
  *
  * @param  string $messageCode
  * @param  array  $from              From addresses. An array of (name => email-address)
  * @param  array  $to                To addresses. An array of (name => email-address)
  * @param  array  $messageParameters an array of (name => value) parameters that will be available in the message.
  * @param string  $locale. If null, the default store locale is used.
  *
  * @return \Swift_Message the generated and built message.
  */
 public function createEmailMessage($messageCode, $from, $to, $messageParameters = [], $locale = null)
 {
     if (null !== ($message = MessageQuery::getFromName($messageCode))) {
         if ($locale == null) {
             $locale = Lang::getDefaultLanguage()->getLocale();
         }
         $message->setLocale($locale);
         // Assign parameters
         foreach ($messageParameters as $name => $value) {
             $this->parser->assign($name, $value);
         }
         $this->parser->assign('locale', $locale);
         $instance = \Swift_Message::newInstance();
         // Add from addresses
         foreach ($from as $address => $name) {
             $instance->addFrom($address, $name);
         }
         // Add to addresses
         foreach ($to as $address => $name) {
             $instance->addTo($address, $name);
         }
         $message->buildMessage($this->parser, $instance);
         return $instance;
     }
     throw new \RuntimeException(Translator::getInstance()->trans("Failed to load message with code '%code%', propably because it does'nt exists.", ['%code%' => $messageCode]));
 }
Esempio n. 28
0
 /**
  * @param  Request                 $request
  * @return null|\Thelia\Model\Lang
  */
 protected function detectLang(Request $request)
 {
     $lang = null;
     //first priority => lang parameter present in request (get or post)
     if ($request->query->has("lang")) {
         $lang = LangQuery::create()->findOneByCode($request->query->get("lang"));
         if (is_null($lang)) {
             return Lang::getDefaultLanguage();
         }
         //if each lang has its own domain, we redirect the user to the good one.
         if (ConfigQuery::isMultiDomainActivated()) {
             //if lang domain is different from actuel domain, redirect to the good one
             if (rtrim($lang->getUrl(), "/") != $request->getSchemeAndHttpHost()) {
                 // TODO : search if http status 302 is the good one.
                 $redirect = new RedirectResponse($lang->getUrl(), 302);
                 return $redirect;
             } else {
                 //the user is actually on the good domain, nothing to change
                 return null;
             }
         } else {
             //one domain for all languages, the lang is set into session
             return $lang;
         }
     }
     //check if lang is not defined. If not we have to search the good one.
     if (null === $request->getSession()->getLang(false)) {
         if (ConfigQuery::isMultiDomainActivated()) {
             //find lang with domain
             return LangQuery::create()->filterByUrl($request->getSchemeAndHttpHost(), ModelCriteria::LIKE)->findOne();
         }
         //find default lang
         return Lang::getDefaultLanguage();
     }
 }
Esempio n. 29
0
 /**
  * Manage how a file collection has to be saved
  *
  * @param  int      $parentId       Parent id owning files being saved
  * @param  string   $parentType     Parent Type owning files being saved (product, category, content, etc.)
  * @param  string   $objectType     Object type, e.g. image or document
  * @param  array    $validMimeTypes an array of valid mime types. If empty, any mime type is allowed.
  * @param  array    $extBlackList   an array of blacklisted extensions.
  * @return Response
  */
 public function saveFileAjaxAction($parentId, $parentType, $objectType, $validMimeTypes = array(), $extBlackList = array())
 {
     if (null !== ($response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE))) {
         return $response;
     }
     $this->checkXmlHttpRequest();
     if ($this->getRequest()->isMethod('POST')) {
         /** @var UploadedFile $fileBeingUploaded */
         $fileBeingUploaded = $this->getRequest()->files->get('file');
         $fileManager = $this->getFileManager();
         // Validate if file is too big
         if ($fileBeingUploaded->getError() == 1) {
             $message = $this->getTranslator()->trans('File is too large, please retry with a file having a size less than %size%.', array('%size%' => ini_get('upload_max_filesize')), 'core');
             return new ResponseRest($message, 'text', 403);
         }
         $message = null;
         $realFileName = $fileBeingUploaded->getClientOriginalName();
         if (!empty($validMimeTypes)) {
             $mimeType = $fileBeingUploaded->getMimeType();
             if (!isset($validMimeTypes[$mimeType])) {
                 $message = $this->getTranslator()->trans('Only files having the following mime type are allowed: %types%', ['%types%' => implode(', ', $validMimeTypes)]);
             }
             $regex = "#^(.+)\\.(" . implode("|", $validMimeTypes[$mimeType]) . ")\$#i";
             if (!preg_match($regex, $realFileName)) {
                 $message = $this->getTranslator()->trans("There's a conflict between your file extension \"%ext\" and the mime type \"%mime\"", ['%mime' => $mimeType, '%ext' => $fileBeingUploaded->getClientOriginalExtension()]);
             }
         }
         if (!empty($extBlackList)) {
             $regex = "#^(.+)\\.(" . implode("|", $extBlackList) . ")\$#i";
             if (preg_match($regex, $realFileName)) {
                 $message = $this->getTranslator()->trans('Files with the following extension are not allowed: %extension, please do an archive of the file if you want to upload it', ['%extension' => $fileBeingUploaded->getClientOriginalExtension()]);
             }
         }
         if ($message !== null) {
             return new ResponseRest($message, 'text', 415);
         }
         $fileModel = $fileManager->getModelInstance($objectType, $parentType);
         $parentModel = $fileModel->getParentFileModel();
         if ($parentModel === null || $fileModel === null || $fileBeingUploaded === null) {
             return new Response('', 404);
         }
         $defaultTitle = $parentModel->getTitle();
         if (empty($defaultTitle)) {
             $defaultTitle = $fileBeingUploaded->getClientOriginalName();
         }
         $fileModel->setParentId($parentId)->setLocale(Lang::getDefaultLanguage()->getLocale())->setTitle($defaultTitle);
         $fileCreateOrUpdateEvent = new FileCreateOrUpdateEvent($parentId);
         $fileCreateOrUpdateEvent->setModel($fileModel);
         $fileCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
         $fileCreateOrUpdateEvent->setParentName($parentModel->getTitle());
         // Dispatch Event to the Action
         $this->dispatch(TheliaEvents::IMAGE_SAVE, $fileCreateOrUpdateEvent);
         $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, $this->getTranslator()->trans('Saving %obj% for %parentName% parent id %parentId%', array('%parentName%' => $fileCreateOrUpdateEvent->getParentName(), '%parentId%' => $fileCreateOrUpdateEvent->getParentId(), '%obj%' => $objectType)));
         return new ResponseRest(array('status' => true, 'message' => ''));
     }
     return new Response('', 404);
 }
Esempio n. 30
0
 /**
  * @param  TheliaRequest $request
  * @return null|\Thelia\Model\Lang
  */
 protected function detectLang(TheliaRequest $request)
 {
     // first priority => lang parameter present in request (get or post)
     if ($request->query->has("lang")) {
         // The lang parameter may contains a lang code (fr, en, ru) for Thelia < 2.2,
         // or a locale (fr_FR, en_US, etc.) for Thelia > 2.2.beta1
         $requestedLangCodeOrLocale = $request->query->get("lang");
         if (strlen($requestedLangCodeOrLocale) > 2) {
             $lang = LangQuery::create()->findOneByLocale($requestedLangCodeOrLocale);
         } else {
             $lang = LangQuery::create()->findOneByCode($requestedLangCodeOrLocale);
         }
         if (is_null($lang)) {
             return Lang::getDefaultLanguage();
         }
         // if each lang has its own domain, we redirect the user to the proper one.
         if (ConfigQuery::isMultiDomainActivated()) {
             $domainUrl = $lang->getUrl();
             if (!empty($domainUrl)) {
                 // if lang domain is different from current domain, redirect to the proper one
                 if (rtrim($domainUrl, "/") != $request->getSchemeAndHttpHost()) {
                     // TODO : search if http status 302 is the good one.
                     return new RedirectResponse($domainUrl, 302);
                 } else {
                     //the user is currently on the proper domain, nothing to change
                     return null;
                 }
             }
             Tlog::getInstance()->warning("The domain URL for language " . $lang->getTitle() . " (id " . $lang->getId() . ") is not defined.");
             return Lang::getDefaultLanguage();
         } else {
             // one domain for all languages, the lang has to be set into session
             return $lang;
         }
     }
     // Next, check if lang is defined in the current session. If not we have to set one.
     if (null === $request->getSession()->getLang(false)) {
         if (ConfigQuery::isMultiDomainActivated()) {
             // find lang with domain
             return LangQuery::create()->filterByUrl($request->getSchemeAndHttpHost(), ModelCriteria::LIKE)->findOne();
         }
         // At this point, set the lang to the default one.
         return Lang::getDefaultLanguage();
     }
     return null;
 }