<?php
/**
* Created by PhpStorm.
* User: Matěj Böswart
* Date: 6.11.2017
* Time: 20:34
*/
namespace Kiwi\EshopBundle\Service;
use Kiwi\EshopBundle\Entity\Contingents\ProductRecommended;
use Kiwi\EshopBundle\Entity\Product;
use Kiwi\EshopBundle\Entity\Contingents\ProductParams;
use Kiwi\EshopBundle\Entity\ProductHolders;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\HttpFoundation\Response;
use Kiwi\ImageGalleryBundle\Entity\ImageFolderTree;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Cookie;
class EshopProductsHandle {
protected $em;
protected $languages;
protected $imageGalleryHandle;
protected $eshopCategoriesHandle;
protected $eshopParamsHandle;
protected $eshopCacheHandle;
protected $attachementsHandle;
protected $webHandle;
protected $eshopUsersHandle;
protected $article;
var $controller = null;
var $request = null;
var $root_image_folder_name = '_ESHOP_IMAGES_';
var $root_image_sub_folder_name = '_PRODUCT_IMAGES_';
var $repo = 'Kiwi\EshopBundle\Entity\Product';
var $repo_holders = 'Kiwi\EshopBundle\Entity\ProductHolders';
var $repo_params = 'Kiwi\EshopBundle\Entity\Contingents\ProductParams';
var $repo_categories = 'Kiwi\EshopBundle\Entity\Contingents\ProductCategory';
//var $qr_url_pattern = 'http://dev.effectiveonline.cz:81/qr-%s';
//var $qr_url_pattern = 'http://vape.e-online.cz:4081/qr-%s';
var $qr_url_pattern = 'http://farline-v2.e-online.cz/qr-%s';
var $no_image = '/bundles/Farline/img/logo.svg';
var $cookie_key = 'last_products';
var $log_path = '';
/**
* @var \Kiwi\PageBundle\Twig\PageExtensions
*/
private $pageExtensions;
public function __construct(\Doctrine\ORM\EntityManager $em,
\Kiwi\LanguagesBundle\Service\LanguagesHandle $languages,
\Kiwi\ImageGalleryBundle\Service\ImageGalleryHandle $imageGalleryHandle,
\Kiwi\EshopBundle\Service\EshopCategoriesHandle $eshopCategoriesHandle,
\Kiwi\EshopBundle\Service\EshopParamsHandle $eshopParamsHandle,
\Kiwi\EshopBundle\Service\EshopCacheHandle $eshopCacheHandle,
\Kiwi\EshopBundle\Service\EshopAttachementsHandle $attachementsHandle,
\Security\UserBundle\Service\WebHandle $webHandle,
\Kiwi\EshopBundle\Service\EshopUsersHandle $eshopUsersHandle,
\Kiwi\PageBundle\Twig\PageExtensions $pageExtensions,
\Kiwi\ArticleBundle\Service\ArticleHandle $article) {
$this->em = $em;
$this->languages = $languages;
$this->imageGalleryHandle = $imageGalleryHandle;
$this->eshopCategoriesHandle = $eshopCategoriesHandle;
$this->eshopParamsHandle = $eshopParamsHandle;
$this->eshopCacheHandle = $eshopCacheHandle;
$this->attachementsHandle = $attachementsHandle;
$this->webHandle = $webHandle;
$this->eshopUsersHandle = $eshopUsersHandle;
$this->pageExtensions = $pageExtensions;
$this->article = $article;
$this->log_path = dirname(dirname(dirname(dirname(__DIR__)))).'/tmp/ProductsHandle.log';
//$this->NC1();
//$this->NC2();
}
public function fixCodes() {
foreach ($this->em->getRepository('Kiwi\EshopBundle\Entity\Producers')->findAll() as $producer) {
$producer->setCode($this->pageExtensions->webalizeFunction($producer->getCode()));
$this->em->persist($producer);
$this->em->flush($producer);
}
foreach ($this->em->getRepository('Kiwi\EshopBundle\Entity\KategorieTree')->findAll() as $kategorie) {
$kategorie->setSeoName($this->pageExtensions->webalizeFunction($kategorie->getSeoName()));
$this->em->persist($kategorie);
$this->em->flush($kategorie);
}
foreach ($this->em->getRepository('Kiwi\EshopBundle\Entity\CustomParamsLists')->findAll() as $param) {
$param->setCode($this->pageExtensions->webalizeFunction($param->getCode()));
$this->em->persist($param);
$this->em->flush($param);
}
}
public function setController($controller) {
$this->controller = $controller;
return $this;
}
public function setRequest(Request $request) {
$this->request = $request;
return $this;
}
public function handleProductUpdate(\Kiwi\EshopBundle\Entity\Product $product, Array $update, Array $categories, Array $params, $categories_handle = '_REPLACE_') {
/*
* $categories_handle
* _REPLACE_ = replace current categories (drop current)
* */
//collect data for alter
$multilang_cols = array(
'name',
'name_alt_1',
'name_alt_2',
'description_fast',
'description',
'holder_name',
'actionText',
);
$redirect_call = array(
'setHolderNameHolderId' => function(\Kiwi\EshopBundle\Entity\Product $product, $bs){
$product->setHolder($this->getProduct($bs));
},
'setHolderName' => function(\Kiwi\EshopBundle\Entity\Product $product, $bs){
/*
if(!$product->getHolder()) {
//article for holder
$article = $this->article->createBlankArticle($this->languages->getLangEntry($bs, 'cz'));
//holder
$holder = new ProductHolders();
$holder->setArticle($article);
$holder->setTransportCode(md5($bs));
$this->em->persist($holder);
$this->em->flush($holder);
$this->em->refresh($holder);
$product->setHolder($holder);
}
*/
}
);
$base = array();
foreach($update as $kfd => $fd) {
if(in_array(substr($kfd,0,-3),$multilang_cols)) {
$a_key = substr($kfd,0,-3);
$a_lang = substr(str_replace($a_key,'',$kfd),1);
$base[$a_key][$a_lang] = $fd;
} else {
$base[$kfd] = $fd;
}
}
foreach($base as $kbs => &$bs) {
if(is_array($bs)) {
$a_bs = '';
foreach($bs as $a_lang => $a_content) {
$a_bs = $this->languages->updateLangEntry($a_lang,$a_bs,$a_content);
}
$bs = $a_bs;
}
}
$base = unserialize(serialize($base));
//update obect
foreach($base as $kbs => $bs) {
$method_name = $this->getSetMethodName($kbs);
switch($method_name) {
default:
//echo "method".$method_name."::".$bs."\n";
if(!isset($redirect_call[$method_name])) {
$product->$method_name($bs);
} else {
$redirect_call[$method_name]($product, $bs);
}
break;
case 'setCurrency':
$product->$method_name($this->em->getRepository('Kiwi\EshopBundle\Entity\Currency')->find($bs));
break;
case 'setVat':
$product->$method_name($this->em->getRepository('Kiwi\EshopBundle\Entity\Vat')->find($bs));
break;
case 'setEshop':
$product->$method_name($this->em->getRepository('Kiwi\EshopBundle\Entity\Eshops')->find($bs));
break;
case 'setHolder':
if($bs) {
$product->$method_name($this->em->getRepository('Kiwi\EshopBundle\Entity\ProductHolders')->find($bs));
} else {
$method_name_id = $method_name.'Id';
$product->$method_name(null);
$product->$method_name_id(null);
//var_dump($product->getHolderId()); exit;
}
break;
case 'setUnit':
if($bs) {
$product->$method_name($this->em->getRepository('Kiwi\EshopBundle\Entity\Unit')->find($bs));
} else {
$product->$method_name(null);
}
break;
case 'setProducer':
if($bs) {
$product->$method_name($this->em->getRepository('Kiwi\EshopBundle\Entity\Producers')->find($bs));
} else {
$product->$method_name(null);
}
break;
case 'setProductId':
case 'setRef':
null;
break;
}
}
$product->setCreatedTime(new \DateTime('now'));
$product->setUpdatedTime(new \DateTime('now'));
//$product->setEshop($this->getEshop());
//$this->em->merge($product);
$this->em->persist($product);
$this->em->flush();
//categories
$categories = array_unique($categories);
switch($categories_handle) {
case '_REPLACE_':
foreach($this->eshopCategoriesHandle->getProductCategoriesNoCache($product) as $product_category) {
$this->em->remove($product_category);
$this->em->flush();
}
foreach($categories as $category) {
$category = $this->eshopCategoriesHandle->getCategory($category);
if($category) {
$this->eshopCategoriesHandle->addCategoryProduct(
$category,
$product
);
}
}
break;
}
//params update
$params_processed = [];
foreach($params as $param_id => $param_value) {
$a_param = $this->getProductParam($product->getId(), $param_id);
if(!$a_param) {
$a_param = new ProductParams();
$a_param->setProduct($product);
$a_param->setParam($this->eshopParamsHandle->getCustomParam($param_id));
}
if(is_array($param_value)) {
$a_param->setParamValue(serialize($param_value));
} else {
$a_param->setParamValue($param_value);
}
$this->em->persist($a_param);
$this->em->flush();
$params_processed[] = $param_id;
}
//params cleanup (not processed ones)
$allCustomParams = $this->eshopParamsHandle->getCustomParams();
foreach ($allCustomParams as $acp) {
if(!in_array($acp->getId(), $params_processed)) {
$a_param = $this->getProductParam($product->getId(), $acp->getId());
if($a_param) {
$a_param->setParamValue(serialize(array()));
$this->em->persist($a_param);
$this->em->flush();
}
}
}
$this->eshopCacheHandle->clearCache('vape-eshop-product-'.$product->getId().'-compiled');
$this->eshopCacheHandle->clearCache('eshop-product-'.$product->getId().'-categories');
return $product;
}
public function handleProductsBatchCategoryUpdate(Array $products, Array $categories) {
if($products) {
foreach ($products as $product_id) {
$product = $this->getProduct($product_id);
$this->handleProductUpdate(
$product,
array(),
$categories,
array()
);
}
return true;
} else {
return false;
}
}
public function getProduct($product_id) {
return $this->em->getRepository($this->repo)->find((int)$product_id);
}
public function getHolder($holder_id) {
return $this->em->getRepository($this->repo_holders)->find((int)$holder_id);
}
public function getHolders() {
return $this->em->getRepository($this->repo_holders)->findAll();
}
public function getEshops(Array $eshops = null) {
$ret = array();
$eshops = (count($eshops) >= 1) ? $eshops : $this->em->getRepository('Kiwi\EshopBundle\Entity\Eshops')->findAll();
foreach($eshops as $eshop) {
$web = $this->em->getRepository('Security\UserBundle\Entity\Web')->findOneBy(array('eshop_id' => $eshop->getId()));
if($web) {
$languages = array();
foreach($this->em->getRepository('Kiwi\LanguagesBundle\Entity\Languages')->findBy(array('web_id' => $web->getId())) as $language) {
$languages[] = $language->getCode();
}
$ret[] = array(
'id' => $eshop->getId(),
'name' => $this->languages->getLangEntry($eshop->getName(),$this->languages->getDefaultLang($this->webHandle->getCurrentWeb()->getId())),
'code' => $eshop->getCode(),
'languages' => $languages
);
}
}
return $ret;
}
public function getUsersEshops() {
$user = $this->eshopUsersHandle->getCurrentUser();
if($user) {
$_eshops = array();
foreach($this->eshopUsersHandle->getUsersEshops($user->getId(),true) as $eshop) {
$_eshops[] = $this->em->getRepository('Kiwi\EshopBundle\Entity\Eshops')->find($eshop['id']);
}
return $this->getEshops($_eshops);
} else {
return $this->getEshops();
}
}
public function getEshopById($eshop_id) {
return $this->em->getRepository('Kiwi\EshopBundle\Entity\Eshops')->find((int)$eshop_id);
}
public function getEshop() {
$web = $this->webHandle->getCurrentWeb();
if(!$web)
return null;
return $web->getEshop();
}
public function checkForEshop() {
if(!$this->getEshop()) {
Header('Location: '.
$this->controller->get('router')->generate('admin_webselector'));
exit();
}
}
public function getEshopDefaultLang($eshop_id) {
if($eshop_id >= 1) {
$web = $this->webHandle->getWebByEshopId($eshop_id);
if($web) {
return $this->languages->getDefaultLang($web->getId());
}
}
return null;
}
public function getProductByCode($product_code) {
return $this->em->getRepository($this->repo)->findOneBy(array('code' => addslashes($product_code)));
}
public function getProductImages(\Kiwi\EshopBundle\Entity\Product $product, $lang = 'cz') {
$ret = array();
if($product->getGallery()) {
foreach($this->imageGalleryHandle->getFolderImages($product->getGallery()->getId()) as $image) {
$label = $this->getProductName($product, $lang);
$label_alt = $this->languages->getLangEntry($image->getAltName(),$lang);
$ret[] = array(
'id' => $image->getId(),
'label' => ($label_alt != '') ? $label_alt : $label
);
}
}
return $ret;
}
public function getRecommended(\Kiwi\EshopBundle\Entity\Product $product, $lang = 'cz') {
$recommended = $this->em->getRepository('Kiwi\EshopBundle\Entity\Contingents\ProductRecommended')->findBy(array('product_id' => $product->getId()));
$ret = [];
foreach($recommended as $recommend) {
$ret[] = $this->getProductReturnArrayBlock($recommend->getProductRecommended(), $lang, []);
}
return $ret;
}
//public function getProduct
public function getProductParams($product_id) {
return $this->em->getRepository($this->repo_params)->findBy(array(
'product_id' => (int)$product_id
));
}
public function getProductParam($product_id, $param_id) {
return $this->em->getRepository($this->repo_params)->findOneBy(array(
'product_id' => (int)$product_id,
'param_id' => (int)$param_id
));
}
public function editHolderForm(int $holder_id, $request, $justCreateArticle = false){
$holder = $this->getHolder($holder_id);
$referer = false;
if(isset($_GET['ref'])) {
if($_GET['ref'] != '') {
$referer = urldecode($_GET['ref']);
}
}
if(!$holder->getArticle()) {
$article = $this->article->createBlankArticle($this->languages->getLangEntry($holder->getName(), 'cz'));
$holder->setArticle($article);
$this->em->persist($holder);
$this->em->flush($holder);
$this->em->refresh($holder);
}
if($justCreateArticle) {
return true;
}
$article_forms = $this->article->getArticleUpdateForm($holder->getArticle(),$request,$referer);
$K = $this->controller->get('K');
return $this->controller->get('BL')->setContent($K->getRows(array(
$K->getPageHeader('Editace článku / '.$this->languages->getLangEntry($holder->getArticle()->getName(), 'cz')),
$K->getRow(array(
$K->getBox(
$K->LABEL_HIDE_BOX,
11,
$article_forms,
'Editace článku'
)
),true)
)))->getLayoutResponse();
}
public function getProductForm($product_id = 0, $holder_id = 0) {
$is_product_update = false;
if($product_id >= 1) {
$product = $this->getProduct($product_id);
$is_product_update = true;
} else {
$product = new Product();
$web = $this->controller->get('web_handle')->getCurrentWeb();
$product->setEshop($web->getEshop());
$product->setIsHidden(false);
$product->setIsDeleted(false);
if($holder_id >= 1) {
$product->setHolderId($holder_id);
}
}
$gallery = $this->getProductGallery($product);
if($is_product_update) {
if(!$product->getGallery())
$product->setGallery($gallery);
} else {
$product->setGallery($gallery);
}
$form = $this->controller->get('form.factory')->createNamedBuilder('product_form', FormType::class, array());
$reflect = new \ReflectionClass(new $this->repo);
$tO = new Transformations\ProductFormTransformations();
$tO->setForm($form);
$tO->setFormData($product);
$tO->setController($this->controller);
$tO->setLanguagesHandle($this->languages);
foreach($reflect->getProperties() as $method) {
$method_name = 'fm'.ucfirst($method->name);
if(method_exists($tO, $method_name)) {
$tO->$method_name($method->name);
} else {
$tO->fmDefalut($method->name);
}
}
$form->add('product_id', HiddenType::class, array('data' => $product->getId()));
$form->add('ref', HiddenType::class, array('data' => $this->request->getRequestUri()));
$form->add('save', SubmitType::class, array('label' => 'Uložit / upravit'));
$form = $form->getForm();
$form->handleRequest($this->request);
if($form->isValid()) {
$post_params = (isset($_POST['params'])) ? $_POST['params'] : array();
$this->handleProductUpdate($product, $form->getData(), array_keys($_POST['product_category']), $post_params);
//remove gallery session persister
$session = new Session();
$session->remove('getProductGallery_freelink');
if($this->controller->get( 'kernel' )->getEnvironment() == 'dev') {
Header("Location: /app_dev.php/kiwi/eshop/produkt/edit/".$product->getId());
} else {
Header("Location: /kiwi/eshop/produkt/edit/".$product->getId());
}
exit();
}
$form_v = $form->createView();
//gallery folder
$tnObj = $this->controller->get('ad13_tree_navigation');
$tnObj->setRepository('\Kiwi\ImageGalleryBundle\Entity\ImageFolderTree');
$tnObj->setController($this->controller);
$tnObj->setRequest($this->request);
$tnObj->setLevel($gallery->getId());
$tnObj->setRefreshPath('kiwi_module_image_gallery_folder_level');
$tnObj->setUploadPath('kiwi_module_image_gallery_folder_upload');
$tnObj->setFileDownloadPath('kiwi_module_image_gallery_folder_download_file');
$K = $this->controller->get('K');
$languages_codes = $this->languages->getLanguagesCodes();
//Attachements
$attachements_row = null;
$recommended_row = null;
$holderproducts_row = null;
if($is_product_update) {
$attachements_holders = $this->controller->get('eshop_attachements_handle')->getAttachementsHolders();
$attachements = $this->attachementsHandle->getProductAttachements($product_id);
foreach($attachements_holders as &$ah) {
$ah->current_file = null;
foreach($attachements as $attachement) {
if($ah->getId() == $attachement->getAttachmentId()) {
$ah->current_file = $attachement->getFile();
break;
}
}
}
$attachements_row = $K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
$K->WIDTH_FULL,
'KiwiEshopBundle:Forms:product_attachments.html.twig',
array(
'referer' => '',
'lang' => $this->languages->getDefaultLang(),
'product_id' => $product->getId(),
'attachements_holders' => $attachements_holders
),
'Přílohy'
)
),false);
$form_recommended = $this->controller->get('form.factory')->createNamedBuilder('product_recommended_form', FormType::class, array());
$form_recommended->add('product_name', TextType::class);
$form_recommended->add('product_id', HiddenType::class);
$form_recommended->add('ref', HiddenType::class, array('data' => $this->request->getRequestUri()));
$form_recommended->add('save', SubmitType::class, array('label' => 'Uložit / upravit'));
$form_recommended = $form_recommended->getForm();
$form_recommended->handleRequest($this->request);
if($form_recommended->isValid()) {
$post_params = (isset($_POST['params'])) ? $_POST['params'] : array();
$recommended_obj = new ProductRecommended();
$recommended_obj->setProduct($product);
$recommended_obj->setProductRecommended(
$this->getProduct($form_recommended->getData()['product_id'])
);
$this->em->persist($recommended_obj);
$this->em->flush();
Header("Location: ".$form_recommended->getData()['ref']."#recommended");
exit();
}
$recommended_row = $K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
$K->WIDTH_FULL,
'KiwiEshopBundle:Forms:product_recommended.html.twig',
array(
'form' => $form_recommended->createView(),
'recommended' => $this->getRecommended($product),
'product' => $product,
'ref' => $this->request->getRequestUri()
),
'Doporučené produkty'
)
),false);
if($product->getIsHolder()) {
$search = $this->controller->get('search_handle');
//->setRequest($request)
$search->setFrom('Kiwi\EshopBundle\Entity\Product','p')
->addWhere(sprintf("p.holder_id = '%d'", $product->getId()))
->setOrderBy('p.sort_num', 'ASC')
->setRpp(100);
$inholder_products = [];
foreach ($search->getResult()['data'] as $inholder_product) {
$inholder_products[] = $this->getProductReturnArrayBlock($inholder_product, 'cz', []);
}
$form_inproduct = $this->controller->get('form.factory')->createNamedBuilder('holder_inproducts_form', FormType::class, array());
$form_inproduct->add('product_name', TextType::class);
$form_inproduct->add('product_id', HiddenType::class);
$form_inproduct->add('ref', HiddenType::class, array('data' => $this->request->getRequestUri()));
$form_inproduct->add('save', SubmitType::class, array('label' => 'Uložit'));
$form_inproduct = $form_inproduct->getForm();
$form_inproduct->handleRequest($this->request);
if($form_inproduct->isValid()) {
$formdata = $this->request->get('holder_inproducts_form');
$inproduct_id = (isset($formdata['product_id'])) ? (int)$formdata['product_id'] : 0;
if($inproduct_id >= 1) {
$inproduct = $this->getProduct($inproduct_id);
$inproduct->setHolder($product);
$this->em->persist($inproduct);
$this->em->flush();
}
Header("Location: ".$formdata['ref']."#inholder_products");
exit;
}
$holderproducts_row = $K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
$K->WIDTH_FULL,
'KiwiEshopBundle:Forms:product_holderproducts.html.twig',
array(
'form' => $form_inproduct->createView(),
'products' => $inholder_products,
'ref' => $this->request->getRequestUri()
),
/*
array(
'form' => $form_recommended->createView(),
'recommended' => $this->getRecommended($product),
'product' => $product,
'ref' => $this->request->getRequestUri()
),
*/
'Produkty v holderu'
)
),false);
}
}
$inner_view = $K->getRows(array(
$K->getPageHeader('Vložení nového produktu'),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
7,
'KiwiEshopBundle:Forms:product_main.html.twig',
array('form' => $form_v, 'languages' => $languages_codes),
'Základní parametry produktu'
),
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
5,
'KiwiEshopBundle:Forms:product_price.html.twig',
array('form' => $form_v),
'Cena'
)
),false),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
8,
'KiwiEshopBundle:Forms:product_categories.html.twig',
array('data' => $this->eshopCategoriesHandle->getProductAssociationForm($product)),
'Kategorie'
),
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
4,
'KiwiEshopBundle:Forms:product_flags.html.twig',
array('form' => $form_v),
'Flagy'
)
),false),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
12,
'KiwiEshopBundle:Forms:product_params.html.twig',
array('data' => $this->eshopParamsHandle->getProductParamsForm($product)),
'Volitelné parametry'
)
),false),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
12,
'KiwiEshopBundle:Forms:product_description.html.twig',
array('form' => $form_v, 'languages' => $languages_codes),
'Hlavní popis'
)
),false),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
12,
'KiwiEshopBundle:Forms:product_action.html.twig',
array('form' => $form_v, 'languages' => $languages_codes),
'Akce'
)
),false),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
12,
'KiwiEshopBundle:Forms:product_holder.html.twig',
array('form' => $form_v, 'languages' => $languages_codes, 'product' => $product),
'Vícenásobný produkt'
)
),true),
$K->getRow(array(
$K->getTwigBox(
$K->LABEL_HIDE_BOX,
12,
'KiwiEshopBundle:Forms:product_submit.html.twig',
array('form' => $form_v),
'Uložení / úprava produktu'
)
),true),
$K->getRow(array(
$K->getBox(
$K->LABEL_HIDE_BOX,
$K->WIDTH_FULL,
'<div class="tree_navigator gallery_sortable">'.$this->controller->get('image_gallery_handle')->setRefPath($_SERVER['REQUEST_URI'])->disablePlaceholder()->getFolderBrowser($gallery->getId()).'</div>',
'Galerie'
)
),false),
$K->getRow(array(
$K->getBox(
$K->LABEL_HIDE_BOX,
$K->WIDTH_THIRD,
$tnObj->getUploader(array('{title : "Image files", extensions : "jpg,gif,png"}')),
'Upload souborů do galerie'
),
$K->getBox(
$K->LABEL_HIDE_BOX,
$K->WIDTH_THIRD,
$tnObj->getFileDownloader(),
'Zdroje'
)
),false),
$attachements_row,
$recommended_row,
$holderproducts_row
));
$edit_canvas = $this->controller->get('templating')->render('KiwiEshopBundle:Forms:product_form_holder.html.twig',array(
'form' => $form_v,
'content' => '<script src="\bundles\Kiwi\js\plugins\tinymce\js\tinymce\tinymce.min.js"></script>'.$inner_view
));
return $this->controller->get('BL')
->setContent($edit_canvas,true,true)
->getLayoutResponse();
}
public function dropRecommendedProduct($product_id, $recommended_product_id) {
$recommended_ref = $this->em->getRepository('Kiwi\EshopBundle\Entity\Contingents\ProductRecommended')->findOneBy(array(
'product_id' => $product_id,
'product_recommended_id' => $recommended_product_id
));
$this->em->remove($recommended_ref);
$this->em->flush();
}
public function removeProductHolder($product_id) {
$product = $this->getProduct($product_id);
$product->setHolder(null);
$this->em->persist($product);
$this->em->flush();
}
public function unDropProduct($product_id) {
$product = $this->getProduct($product_id);
$product->setIsDeleted(false);
$this->em->persist($product);
$this->em->flush();
}
public function dropProduct($product_id) {
$product = $this->getProduct($product_id);
$product->setIsDeleted(true);
$this->em->persist($product);
$this->em->flush();
}
public function unInvisibleProduct($product_id) {
$product = $this->getProduct($product_id);
$product->setIsHidden(false);
$this->em->persist($product);
$this->em->flush();
}
public function invisibleProduct($product_id) {
$product = $this->getProduct($product_id);
$product->setIsHidden(true);
$this->em->persist($product);
$this->em->flush();
}
public function getProductGallery(\Kiwi\EshopBundle\Entity\Product $product, $enable_sessions = true) {
$gallery = $product->getGallery();
if(!$gallery) {
//if persist in session, return them instead of create new one
if($enable_sessions) {
$session = new Session();
if($session->get('getProductGallery_freelink'))
return $this->imageGalleryHandle->getFolder($session->get('getProductGallery_freelink'));
}
//find if root folder exists
$root_folder = null;
foreach($this->imageGalleryHandle->getFolderByName($this->root_image_folder_name) as $folder) {
if(!$folder->getParentRow()) {
$root_folder = $folder;
break;
}
}
//create if not
if(!$root_folder) {
$root_folder = new ImageFolderTree();
$root_folder->setName($this->root_image_folder_name);
$root_folder->setPreventChanges(true);
$root_folder->setSystemFolder(true);
$root_folder->setWeb($this->controller->get('web_handle')->getCurrentWeb());
$this->em->persist($root_folder);
$this->em->flush();
}
$gallery = new ImageFolderTree();
$gallery->setName($this->root_image_sub_folder_name.$product->getId());
$gallery->setParentRow($root_folder);
$gallery->setPreventChanges(true);
$gallery->setSystemFolder(true);
//$gallery->setWeb($this->controller->get('web_handle')->getCurrentWeb());
$gallery->setWeb($this->controller->get('web_handle')->getWebByEshopId($product->getEshop()->getId()));
$this->em->persist($gallery);
$this->em->flush();
if($enable_sessions)
$session->set('getProductGallery_freelink',$gallery->getId());
}
return $gallery;
}
private function getProductCategories(\Kiwi\EshopBundle\Entity\Product $product) {
}
private function getSetMethodName($variable_name) {
$get_method = str_replace('_',' ',$variable_name);
$get_method = ucwords($get_method);
$get_method = str_replace(' ','',$get_method);
return 'set'.$get_method;
}
private function getGetMethodName($variable_name) {
$get_method = str_replace('_',' ',$variable_name);
$get_method = ucwords($get_method);
$get_method = str_replace(' ','',$get_method);
return 'get'.$get_method;
}
//partialy frontend methods
private function findNotificationEmails(\Kiwi\EshopBundle\Entity\KategorieTree $kategorieTree,$be_verbose){
$ret = '';
//$kategorieTree = $this->eshopCacheHandle->getHydrated($kategorieTree);
if($be_verbose) {
echo 'looking in '.$kategorieTree->getId().'/'.$kategorieTree->getInfoEmails().'<br>';
}
if($kategorieTree->getInfoEmails()) {
if($kategorieTree->getInfoEmails() != '') {
$ret = $kategorieTree->getInfoEmails();
} else {
$parentRow = $this->eshopCacheHandle->getHydrated($kategorieTree->getParentRow());
if($parentRow) {
$ret = $this->findNotificationEmails($parentRow,$be_verbose);
}
}
} else {
$parentRow = $this->eshopCacheHandle->getHydrated($kategorieTree->getParentRow());
if($parentRow) {
$ret = $this->findNotificationEmails($parentRow,$be_verbose);
}
}
return $ret;
}
public function findProduct($lang, $product_id) {
$product = $this->getProduct($product_id);
//kategorie produktu
$product_categories = array();
$product_order_notifications_emails = array();
foreach($this->controller->get('eshop_categories_handle')->getProductCategories($product) as $product_category) {
$product_categories[] = $product_category->getCategoryId();
$category = $this->eshopCacheHandle->getHydrated($product_category->getCategory());
$emails_raw = $category->getInfoEmails();
$be_verbose = false;
if($emails_raw == '')
$emails_raw = $this->findNotificationEmails($category,$be_verbose);
foreach(explode(',',$emails_raw) as $email) {
if($email != '')
$product_order_notifications_emails[] = str_replace(' ','',$email);
}
$product_order_notifications_emails = array_unique($product_order_notifications_emails);
}
//siblings getter
$siblings = array();
if($product->getHolder()) {
foreach($this->em->getRepository($this->repo)->findBy(array('holder_id' => $product->getHolder()->getId())) as $sibling_product) {
if($sibling_product->getStockAlt() >= 1) {
if($sibling_product->getId() != $product->getId())
$siblings[] = $this->getProductReturnArrayBlock($sibling_product,$lang,array());
}
}
}
//similars getter
$similars = array();
if(count($product_categories) >= 1) {
$qb_similar = $this->em->createQueryBuilder();
$qb_similar->select('p')
->from($this->repo_categories, 'c')
->leftJoin($this->repo, 'p', 'WITH', 'p.id = c.product_id')
->where('p.is_deleted = 0')
->andWhere('p.eshop_id = '.$product->getEshopId())
->andWhere('p.stock_alt >= 1');
if($product->getHolder())
$qb_similar->andWhere('p.holder_id != '.$product->getHolder()->getId());
$qb_similar->andWhere('c.category_id IN ('.implode(",", $product_categories).')')
->orderBy('p.id', 'DESC')
//->groupBy('p.holder_id')
->setMaxResults(10);
foreach($qb_similar->getQuery()->getResult() as $similar_product) {
if($similar_product->getId() != $product->getId())
$similars[] = $this->getProductReturnArrayBlock($similar_product,$lang,array());
}
}
return $this->getProductReturnArrayBlock($product,$lang,$product_categories, $siblings, $similars);
}
public function findProducts($lang, $limit = array(), $eshop = 1, $group_by_holder = false, $minimal_stock = 0) {
$this->logClean();
/*
$list_in_eshops = array($this->getEshop()->getId());
$user = $this->eshopUsersHandle->getCurrentUser();
if($user) {
$list_in_eshops = array();
foreach($this->eshopUsersHandle->getUsersEshops($user->getId(),true) as $a_eshop) {
$list_in_eshops[] = $a_eshop['id'];
}
}
*/
/*
$data = $this->em->getRepository($this->repo)->findBy(
array(),
array(),
99000,
0
);
*/
$eshop = ($eshop >= 1) ? $eshop : 1;
$group_by = ($group_by_holder) ? 'p.holder_id' : 'p.id';
$results_pp = 20;
$results_page = 1;
if(isset($limit['results_page'])) {
if($limit['results_page'] >= 2) {
$results_page = (int)$limit['results_page'];
}
}
if(isset($limit['results_per_page'])) {
if($limit['results_per_page'] >= 1) {
$results_pp = (int)$limit['results_per_page'];
}
}
$dynamic_params_grouped = array();
if(isset($limit['dynamic-params'])) {
if(is_array($limit['dynamic-params'])) {
//group by category
foreach($limit['dynamic-params'] as $dynamic_param) {
$_dynamic_param = explode('@',$dynamic_param);
$dynamic_params_grouped[$_dynamic_param[0]][] = $_dynamic_param[1];
}
}
}
$qb = $this->em->createQueryBuilder();
$qb->select('p')
->from($this->repo_categories, 'c')
->leftJoin($this->repo, 'p', 'WITH', 'p.id = c.product_id')
->leftJoin($this->repo_params, 'params', 'WITH', 'params.product_id = p.id');
//->leftJoin($this->repo_params, 'params', 'WITH', 'params.product_id = p.id AND params.param_id = 8')
if(isset($limit['dynamic-params'])) {
if(is_array($limit['dynamic-params'])) {
foreach($dynamic_params_grouped as $group_id => $group_data) {
$qb->leftJoin($this->repo_params, 'params'.$group_id, 'WITH', 'params'.$group_id.'.product_id = p.id');
}
}
}
$qb->where('p.is_deleted = 0')
//->andwhere('p.eshop_id = '.$this->getEshop()->getId())
//->add('where', $qb->expr()->in('p.eshop_id', $list_in_eshops))
//->add('where', 'p.eshop_id = '.$eshop)
->andWhere('p.eshop_id = '.$eshop)
->andWhere('p.stock_alt >= '.$minimal_stock)
//->orderBy('p.price_with_vat', 'DESC');
->orderBy('p.id', 'DESC')
->groupBy($group_by);
//params.param_value LIKE '%".$limit['fulltext_search']."%' OR
if(isset($limit['fulltext_search'])) {
if($limit['fulltext_search'] != '') {
/*
$xml_part = '\'<?xml version="1.0" encoding="utf-8" ?>%<cz><![CDATA[%'.strtolower($limit['fulltext_search']).'%]]></cz>%</data>\'';
*/
$qb->andWhere("(
p.code LIKE '%".$limit['fulltext_search']."' OR
p.name LIKE '%".$limit['fulltext_search']."%' OR
p.name_alt_1 LIKE '%".$limit['fulltext_search']."%' OR
p.name_alt_2 LIKE '%".$limit['fulltext_search']."%'
)");
/*
params.param_value LIKE '%".$limit['fulltext_search']."%' OR
p.code LIKE '%".$limit['fulltext_search']."%' OR
p.name LIKE $xml_part OR
p.name_alt_1 LIKE $xml_part OR
p.name_alt_2 LIKE $xml_part
*/
}
}
if(isset($limit['category'])) {
if(is_array($limit['category'])) {
$categories = array();
foreach($limit['category'] as $limit_category) {
if($limit_category >= 1) {
$categories[] = $limit_category;
$subcategories = $this->controller->get('eshop_categories_handle')->getCategories($limit_category, true);
if(is_array($subcategories))
$categories = array_merge($categories,$subcategories);
}
}
if(count($categories) >= 1)
$qb->andWhere('c.category_id IN ('.implode(",", $categories).')');
}
}
if(isset($limit['producer'])) {
if(is_array($limit['producer'])) {
$qb->andWhere('p.producer_id IN ('.implode(",", $limit['producer']).')');
}
}
if(isset($limit['dynamic-params'])) {
if(is_array($limit['dynamic-params'])) {
//make groups independent wheres
foreach($dynamic_params_grouped as $group_id => $group_data) {
$dynamic_params_likes = '';
foreach($group_data as $agd) {
if(is_numeric($agd)) {
$dynamic_params_likes .= "params".$group_id.".param_value LIKE '%i:".addslashes($agd)."%' OR ";
} else {
$dynamic_params_likes .= "params".$group_id.".param_value = '".base64_decode($agd)."' OR ";
}
}
if($dynamic_params_likes != '') {
$dynamic_params_likes = substr($dynamic_params_likes,0,-4);
$qb->andWhere("($dynamic_params_likes)");
}
}
}
}
if(isset($limit['holder'])) {
if(is_numeric($limit['holder'])) {
$qb->andWhere('p.holder_id = '.$limit['holder']);
}
}
if(isset($limit['not-holder'])) {
$qb->andWhere('p.is_holder = 0');
}
if(isset($limit['not-holder-member'])) {
$qb->andWhere('p.holder_id IS NULL');
}
if(isset($limit['action'])) {
if(is_numeric($limit['action'])) {
$qb->andWhere('p.is_action = '.$limit['action']);
}
}
$qb_nolimit = clone $qb;
$qb_forcount = clone $qb;
if(isset($limit['letter'])) {
if($limit['letter'] != '') {
$qb->andWhere("p.name_letter = '".$limit['letter']."'");
}
}
//$qb->groupBy('p.holder_id');
$qb->setFirstResult(($results_page*$results_pp)-$results_pp)->setMaxResults($results_pp+1);
$query = $qb->getQuery();
//echo $query->getSQL();
$this->logState($query->getSQL());
//exit;
$data = $query->getResult();
$truncateCzech = function($text){
$prevodni_tabulka = Array(
'ä'=>'a',
'Ä'=>'A',
'á'=>'a',
'Á'=>'A',
'à'=>'a',
'À'=>'A',
'ã'=>'a',
'Ã'=>'A',
'â'=>'a',
'Â'=>'A',
'č'=>'c',
'Č'=>'C',
'ć'=>'c',
'Ć'=>'C',
'ď'=>'d',
'Ď'=>'D',
'ě'=>'e',
'Ě'=>'E',
'é'=>'e',
'É'=>'E',
'ë'=>'e',
'Ë'=>'E',
'è'=>'e',
'È'=>'E',
'ê'=>'e',
'Ê'=>'E',
'í'=>'i',
'Í'=>'I',
'ï'=>'i',
'Ï'=>'I',
'ì'=>'i',
'Ì'=>'I',
'î'=>'i',
'Î'=>'I',
'ľ'=>'l',
'Ľ'=>'L',
'ĺ'=>'l',
'Ĺ'=>'L',
'ń'=>'n',
'Ń'=>'N',
'ň'=>'n',
'Ň'=>'N',
'ñ'=>'n',
'Ñ'=>'N',
'ó'=>'o',
'Ó'=>'O',
'ö'=>'o',
'Ö'=>'O',
'ô'=>'o',
'Ô'=>'O',
'ò'=>'o',
'Ò'=>'O',
'õ'=>'o',
'Õ'=>'O',
'ő'=>'o',
'Ő'=>'O',
'ř'=>'r',
'Ř'=>'R',
'ŕ'=>'r',
'Ŕ'=>'R',
'š'=>'s',
'Š'=>'S',
'ś'=>'s',
'Ś'=>'S',
'ť'=>'t',
'Ť'=>'T',
'ú'=>'u',
'Ú'=>'U',
'ů'=>'u',
'Ů'=>'U',
'ü'=>'u',
'Ü'=>'U',
'ù'=>'u',
'Ù'=>'U',
'ũ'=>'u',
'Ũ'=>'U',
'û'=>'u',
'Û'=>'U',
'ý'=>'y',
'Ý'=>'Y',
'ž'=>'z',
'Ž'=>'Z',
'ź'=>'z',
'Ź'=>'Z'
);
return strtr($text, $prevodni_tabulka);
};
$ret = array();
$ret_nofilter = array();
$ret_nolettermatter = array();
foreach($data as $product) {
$pass_product = true;
$pass_product_by_category = true;
$pass_product_without_letter_matter = true;
//$a_name = $this->languages->getLangEntry($product->getName(),$lang);
//kategorie produktu
$product_categories = array();
$product_order_notifications_emails = array();
foreach($this->controller->get('eshop_categories_handle')->getProductCategories($product) as $product_category) {
$product_categories[] = $product_category->getCategoryId();
$category = $this->eshopCacheHandle->getHydrated($product_category->getCategory());
$emails_raw = $category->getInfoEmails();
$be_verbose = false;
if($emails_raw == '')
$emails_raw = $this->findNotificationEmails($category,$be_verbose);
foreach(explode(',',$emails_raw) as $email) {
if($email != '')
$product_order_notifications_emails[] = str_replace(' ','',$email);
}
$product_order_notifications_emails = array_unique($product_order_notifications_emails);
}
//FILTR -- ceny
if(isset($limit['price_range'])) {
if(is_array($limit['price_range'])) {
$a_price = $product->getPrice();
if($a_price['price_with_vat'] >= $limit['price_range'][0] && $a_price['price_with_vat'] <= $limit['price_range'][1]) {} else {
$pass_product = false;
$pass_product_without_letter_matter = false;
}
}
}
$productArrayBlock = $this->getProductReturnArrayBlock($product,$lang,$product_categories);
//append notifications emails by theirs categories
$productArrayBlock['notifications_emails'] = $product_order_notifications_emails;
if($pass_product) {
$ret[] = $productArrayBlock;
}
if($pass_product_by_category) {
$ret_nofilter[] = $productArrayBlock;
}
if($pass_product_without_letter_matter) {
$ret_nolettermatter[] = $productArrayBlock;
}
}
$sort_name = function($a,$b){
return strcmp($a["name"], $b["name"]);
};
usort($ret,$sort_name);
uasort($ret_nofilter,$sort_name);
uasort($ret_nolettermatter,$sort_name);
$ret = array_values($ret);
$ret_nofilter = array_values($ret_nofilter);
//echo count($qb_forcount->getQuery()->getResult());
//exit();
return array(
'filtered' => array_slice($ret,0,$results_pp),
'nofilter' => $ret_nofilter,
'limit' => $limit,
'results_page' => $results_page,
'has_more_results' => (count($ret) > $results_pp) ? true : false,
'total_results' => count($qb_forcount->getQuery()->getResult()),
'q' => $qb->getDQL()
);
}
public function getProductReturnArrayBlock(\Kiwi\EshopBundle\Entity\Product $product, $lang, $product_categories, $siblings = array(), $similars = array()) {
//$cache = $this->eshopCacheHandle->setCacheKey('farline-eshop-product-'.$lang.'-'.$product->getId().'-compiled');
//if($cache->isKeySet()) {
$cache = false;
if($cache) {
return $cache->getData();
} else {
$images = array();
$images_data = $this->getProductImages($product, $lang);
$images_helper = $this->controller->get('image_twig_extension');
$stockObj = $this->controller->get('eshop_stock_handle');
foreach($images_data as $image) {
$images[] = array(
'id' => $image['id'],
'label' => $image['label'],
'list' => $image['id'],
'full' => $images_helper->imageCutFunction($image['id'],670,0),
'maxi' => $images_helper->imageCutFunction($image['id'],1920,0)
);
}
$attachments = array();
foreach($this->attachementsHandle->getProductAttachements($product->getId()) as $attachement_row) {
$attachments[] = array(
'name' => $this->languages->getLangEntry($attachement_row->getAttachment()->getName(),$lang),
'link' => '/dt/'.$attachement_row->getFile()->getHashName().'.'.$attachement_row->getFile()->getExtension(),
'extension' => $attachement_row->getFile()->getExtension()
);
}
$main_image = $this->no_image;
if(isset($images[0]))
$main_image = $images[0]['list'];
$main_product_image = $this->no_image;
if(isset($images[0]))
$main_product_image = $images[0]['full'];
$unit = false;
if($product->getUnit()) {
$unit = array(
'name' => $this->languages->getLangEntry($product->getUnit()->getName(),$lang),
'code' => $product->getUnit()->getCode(),
);
}
$currency = false;
if($product->getCurrency()) {
$currency = array(
'name' => $this->languages->getLangEntry($product->getCurrency()->getName(),$lang),
'code' => $product->getCurrency()->getCode(),
);
}
$producer = false;
if($product->getProducer()) {
$image = '';
$image2 = '';
if($product->getProducer()->getImage())
$image = '/ds/orig/'.$product->getProducer()->getImage()->getName().'.'.$product->getProducer()->getImage()->getExtension();
if($product->getProducer()->getImage2())
$image2 = '/ds/orig/'.$product->getProducer()->getImage2()->getName().'.'.$product->getProducer()->getImage2()->getExtension();
$eshop_producers_handle = $this->controller->get('eshop_producers_handle');
$producer = array(
'id' => $product->getProducer()->getId(),
'name' => $this->languages->getLangEntry($product->getProducer()->getName(),$lang),
'image' => $image,
'image2' => $image2,
'full_link' => $eshop_producers_handle->getProducerLink($product->getProducer(), $lang)
);
}
$master_category = array(
'id' => 0,
'name' => null,
'title_name' => null
);
$master_category_data = $this->eshopCategoriesHandle->getProductTopCategory($product);
if($master_category_data) {
$master_category['id'] = $master_category_data->getId();
$master_category['name'] = $master_category_data->getName();
$master_category['title_name'] = $master_category_data->getTitle();
}
//return $cache->setData(
return array(
'id' => $product->getId(),
'code' => $product->getCode(),
'name' => $this->getProductName($product, $lang),
//'name_holder' => $this->languages->getLangEntry($product->getHolder()->getArticle()->getName(), $lang),
'name_alt_1' => $this->languages->getLangEntry($product->getNameAlt1(), $lang),
'name_alt_2' => $this->languages->getLangEntry($product->getNameAlt2(), $lang),
'description' => str_replace("\n",'%NEW-LINE%',$this->languages->getLangEntry($product->getDescription(), $lang)),
'price' => $product->getPrice(),
'quantity_in_package' => $product->getQuantityInPackage(),
'main_image' => $main_image,
'main_product_image' => $main_product_image,
'unit' => $unit,
'currency' => $currency,
'producer' => $producer,
'categories' => $product_categories,
'is_action' => $product->getIsAction(),
'action_text' => $this->languages->getLangEntry($product->getActionText(), $lang),
'is_new' => $product->getIsNew(),
'is_tip' => $product->getIsTip(),
'is_selected' => false,
'images' => $images,
'params' => $this->eshopParamsHandle->getParamsCollection($lang, $product, true, true),
'params_entity' => $this->eshopParamsHandle->getParamsCollection($lang, $product, true, true, true),
'params_full' => $this->eshopParamsHandle->getParamsCollection($lang, $product, true, false),
'attachments' => $attachments,
'stock' => ($product->getStockShow()) ? $stockObj->getStock($product->getId())['stock'] : false,
'siblings' => $siblings,
'similars' => $similars,
'detail_url' => $this->getProductUrl($product, 0, $lang),
//'detail_url' => $this->getHolderUrl($product->getHolder(),$lang).'/'.$product->getCode(),
'master_category' => $master_category,
'holder' => $product->getHolder(),
'is_holder' => $product->getIsHolder()
);
//);
}
}
public function getFinder($lang, $limit = array(), $nofilter_products = array()) {
//fulltext_search
$fulltext_search = '';
if(isset($limit['fulltext_search'])) {
$fulltext_search = $limit['fulltext_search'];
}
return array(
'fulltext_search' => array('actual' => $fulltext_search),
'dynamic_model' => $this->eshopParamsHandle->getParamsCollection($lang)
);
}
public function getFinderFull($lang, $current_products, $limit = array()) {
//price range
$min_product_price = 0;
$max_product_price = 0;
foreach($current_products as $product) {
$a_price = $product['price'];
if($min_product_price > $a_price['price_with_vat'])
$min_product_price = $a_price['price_with_vat'];
if($max_product_price < $a_price['price_with_vat'])
$max_product_price = $a_price['price_with_vat'];
}
$a_price_from = $min_product_price;
$a_price_to = $max_product_price;
if(isset($limit['price_range'])) {
if(is_array($limit['price_range'])) {
$a_price_from = $limit['price_range'][0];
$a_price_to = $limit['price_range'][1];
}
}
//fulltext_search
$fulltext_search = '';
if(isset($limit['fulltext_search'])) {
$fulltext_search = $limit['fulltext_search'];
}
return array(
'price_range' => array('actual' => array($a_price_from,$a_price_to), 'data' => array($min_product_price,$max_product_price)),
'fulltext_search' => array('actual' => $fulltext_search),
'dynamic_model' => $this->eshopParamsHandle->getParamsCollection($lang)
);
}
public function getFirstLetter($a_name){
$a_name_low = strtolower($a_name);
$a_name_letter = '';
if(isset($a_name_low[0])) {
$a_name_letter = $a_name_low[0];
if(!$this->isLetter($a_name_letter)) {
for($i = 0; $i < strlen($a_name_low); $i++) {
if($i >= 1) {
$a_name_letter = $a_name_low[$i];
if($this->isLetter($a_name_letter))
break;
}
}
}
}
return $a_name_letter;
}
public function getProductQrCode($product_id) {
require(dirname(__DIR__).'/Lib/phpqrcode/qrlib.php');
$product = $this->getProduct($product_id);
if(!$product)
return false;
$write = sprintf($this->qr_url_pattern,$product->getCode());
$img_path = dirname(__DIR__).'/tmp/qrcode_'.$product_id.'_'.md5($write).'.png';
if(file_exists($img_path))
return $img_path;
\QRcode::png($write, $img_path, 'H', 6, 2);
return $img_path;
}
public function getEshopInitParams($config) {
$uri = explode('?',str_replace('/app_dev.php','',$_SERVER['REQUEST_URI'])); $uri = $uri[0];
$deep = count(explode('/',$uri))-2;
//$deep = $uri;
$request_type = 'category';
//$category = null;
$images_helper = $this->controller->get('image_twig_extension');
$ret = array(
'product' => null,
'products' => null,
'category' => array('deep' => $deep, 'category' => null, 'subcategories' => null),
'request_type' => $request_type
);
$category = $this->eshopCategoriesHandle->getCategoryBySeoName(substr(str_replace('/app_dev.php','',$uri),4));
if($category) {
$ret['category']['category'] = $category;
$ret['category']['subcategories'] = $this->eshopCategoriesHandle->getCategories($category->getId());
} else {
foreach($this->eshopCategoriesHandle->getRouteableCategories() as $category_seo_data) {
if(substr($uri,4,strlen($category_seo_data['link'])) == $category_seo_data['link']) {
$ret['category']['category'] = $category_seo_data['category_obj'];
$ret['category']['subcategories'] = $this->eshopCategoriesHandle->getCategories($category_seo_data['category']['id']);
}
}
}
if($ret['category']['category']) {
$ret['products'] = array();
//test
if($_SERVER["REMOTE_ADDR"] == '81.201.53.119') {
//\Doctrine\Common\Util\Debug::dump($ret['products']);
//\Doctrine\Common\Util\Debug::dump($this->eshopCategoriesHandle->getCategoryProducts($ret['category']['category']->getId(),false));
//echo 'c'.$ret['category']['category']->getId()."\n";
//foreach($this->eshopCategoriesHandle->getCategoryProducts($ret['category']['category']->getId(),false) as $product_category) {
// echo $product_category->getProductId()."\n";
//}
//exit;
}
foreach($this->eshopCategoriesHandle->getCategoryProducts($ret['category']['category']->getId(),false) as $product_category) {
$ret['products'][] = $this->getProductReturnArrayBlock($product_category->getProduct(), 'cz', array());
}
} else {
$ret['category']['subcategories'] = $this->eshopCategoriesHandle->getCategories();
}
if($ret['category']['subcategories']) {
$to_exclude = array();
foreach($ret['category']['subcategories'] as &$subcategory) {
$product_in_category = $this->eshopCategoriesHandle->getCategoryProducts($subcategory['id'],false);
if(count($product_in_category) == 1) {
$product = $this->getProductReturnArrayBlock($product_in_category[0]->getProduct(), 'cz', array());
if($product['main_image'] != $this->no_image)
$subcategory['alt_image'] = $product['main_image'];
if($subcategory['article']) {
if($subcategory['article']->getImage())
$subcategory['alt_image'] = $images_helper->imageCutFunction($subcategory['article']->getImage()->getId(),700,320,'crop-best');
}
$subcategory['full_link'] = str_replace('/cz/','',$product['detail_url']);
}
if(count($product_in_category) == 0) {
$to_exclude[] = $subcategory['id'];
}
}
//exclude empty
//$r_c_s_temp = $ret['category']['subcategories'];
//$ret['category']['subcategories'] = [];
//foreach($r_c_s_temp as $subcategory) {
//if(!in_array($subcategory['id'],$to_exclude))
//$ret['category']['subcategories'][] = $subcategory;
//}
//echo count($product_in_category).'<br>';
//\Doctrine\Common\Util\Debug::dump($to_exclude);
//exit();
}
if($ret['category']['category']) {
$this->controller->get('page_frontend_handle')->setPageMeta(
'F.a.r.line - '.$ret['category']['category']->getName()
);
}
//\Doctrine\Common\Util\Debug::dump($ret['category']['subcategories']);
//exit();
if($_SERVER["REMOTE_ADDR"] == '81.201.53.119') {
//\Doctrine\Common\Util\Debug::dump($ret['products']);
//exit;
}
return $ret;
}
public function getEshopInitProduct($config) {
$uri = explode('?',str_replace('/app_dev.php','',$_SERVER['REQUEST_URI'])); $uri = $uri[0];
$route_url_split = explode('/',$uri);
$product_id = (int)end($route_url_split);
if($product_id >= 1) {
$product = $this->getProduct($product_id);
if($product) {
$product_full = $this->getProductReturnArrayBlock($product,'cz',array());
$this->controller->get('page_frontend_handle')->setPageMeta(
'F.a.r.line - '.$product_full['name'],
$product_full['main_product_image']
);
return $product_full;
}
}
exit('Produkt nenalezen');
}
public function getEshopInitParamsOld($config) {
$uri = explode('?',str_replace('/app_dev.php','',$_SERVER['REQUEST_URI'])); $uri = $uri[0];
$request_type = null;
$product_url_prefix = array('product/');
$product = null;
$ret = array(
'product_id' => 0,
'product' => null,
'categories' => array(),
'category' => array('category' => null, 'subcategories' => null),
'set_categories' => array()
);
//product url
foreach($product_url_prefix as $pp) {
if(strpos($uri, $pp) !== false) {
$request_type = 'product';
}
}
//product dynamic url
if(!$request_type) {
$l1_match = false;
$l2_match = false;
foreach($this->eshopCategoriesHandle->getRouteableCategories() as $category_seo_data) {
if(substr($uri,4,strlen($category_seo_data['link'])) == $category_seo_data['link']) {
$l1_match = true;
$ret['category']['category'] = $category_seo_data['category_obj'];
$ret['category']['subcategories'] = $this->eshopCategoriesHandle->getCategories($category_seo_data['category']['id']);
}
}
if($l1_match) {
$uri_explode = explode('/',$uri);
$code = $uri_explode[count($uri_explode)-1];
$product = $this->getProductByCode($code);
if($product)
$l2_match = true;
}
if($l1_match && $l2_match) {
$request_type = 'product';
} else {
if($l1_match)
$request_type = 'category-direct';
}
}
$category = $this->eshopCategoriesHandle->getCategoryBySeoName(substr(str_replace('/app_dev.php','',$uri),4));
if($category) {
$request_type = 'category';
}
switch($request_type) {
default:
break;
case 'product':
$uri_explode = explode('/',$uri);
$code = $uri_explode[count($uri_explode)-1];
if(!$product)
$product = $this->getProductByCode($code);
if($product) {
$ret['product_id'] = $product->getId();
$ret['product'] = $product;
$product_full = $this->getProductReturnArrayBlock($product,'cz',array());
$this->controller->get('page_frontend_handle')->setPageMeta(
$product_full['name'].' '.$product_full['master_category']['title_name'],
$product_full['main_product_image']
);
}
break;
case 'category':
$sub_categories = $this->eshopCategoriesHandle->getCategories($category->getId());
if($category->getParentRow()) {
$this->controller->get('page_frontend_handle')->setPageMeta(
ucfirst($category->getName()).' '.$category->getParentRow()->getTitle().' - Katalog F.A.R. Line'
);
} else {
$this->controller->get('page_frontend_handle')->setPageMeta(
ucfirst($category->getTitle()).' - Katalog F.A.R. Line'
);
}
//if has subcategories -> include them
if(is_array($sub_categories)) {
foreach($sub_categories as $sc) {
$ret['set_categories'][] = $sc['id'];
}
} else {
$ret['set_categories'] = array($category->getId());
}
break;
}
//eshop categories
$ret['categories'] = $this->eshopCategoriesHandle->getCategories(0);
$ret['dynamic_model'] = $this->eshopParamsHandle->getParamsCollection('cz');
//print_r($ret);
//exit();
return $ret;
}
public function getEshopTopProducts($config) {
return $this->findProducts($config['lang'],array('results_per_page' => 20),1,true,1);
}
private function isLetter($letter) {
if(preg_match("/^[a-z]$/", $letter))
return true;
return false;
}
private function getProductName(\Kiwi\EshopBundle\Entity\Product $product, $lang) {
//name constructor
$name = '';
if($product->getQuantityInPackage() >= 2)
$name .= $product->getQuantityInPackage().'x ';
$name .= $this->languages->getLangEntry($product->getName(),$lang);
return $name;
}
private function getProductUrl(\Kiwi\EshopBundle\Entity\Product $product = null, $product_id = 0, $lang) {
$url = $this->controller->get('page_twig_extension')->kpathFunction(3, $lang);
$category = null;
foreach($this->controller->get('eshop_categories_handle')->getProductCategories($product) as $product_category) {
if($product_category->getCategory()->getParentRow()) {
$category = $product_category->getCategory();
break;
}
}
if($category)
{
if($category->getParentRow())
{
if($category->getParentRow()->getParentRow())
{
if($category->getParentRow()->getParentRow()->getParentRow())
{
$url .= $category->getParentRow()->getParentRow()->getParentRow()->getName().'/';
}
$url .= $category->getParentRow()->getParentRow()->getName().'/';
}
$url .= $category->getParentRow()->getName().'/';
}
$url .= $category->getName().'/';
$url .= str_replace(array(' '),' ',$this->getProductName($product, $lang)).'/';
$url .= $product->getId();
}
else
{
$url .= 'produkt/';
$url .= str_replace(array(' '),' ',$this->getProductName($product, $lang)).'/';
$url .= $product->getId();
}
$url = str_replace('app_dev-php','app_dev.php',$this->pageExtensions->webalizeFunction($url));
return $url;
}
private function getHolderUrl(ProductHolders $holder, $lang) {
$dev_prefix = '';
$url = '/'.$lang.'/';
if($this->controller->get( 'kernel' )->getEnvironment() == 'dev')
$dev_prefix = '/app_dev.php';
/*
$category = null;
foreach($this->controller->get('eshop_categories_handle')->getProductCategories($product) as $product_category) {
if($product_category->getCategory()->getParentRow()) {
$category = $product_category->getCategory();
break;
}
}
if($category)
{
if($category->getParentRow())
{
if($category->getParentRow()->getParentRow())
{
if($category->getParentRow()->getParentRow()->getParentRow())
{
$url .= $category->getParentRow()->getParentRow()->getParentRow()->getName().'/';
}
$url .= $category->getParentRow()->getParentRow()->getName().'/';
}
$url .= $category->getParentRow()->getName().'/';
}
$url .= $category->getName().'/';
$url .= str_replace(array(' '),' ',$this->getProductName($product, $lang)).'/';
$url .= $product->getId();
}
else
{
$url .= 'produkt/'; //$category->GetName().'/';//'drevene-podlahy/';//$category->getName().'/';
$url .= str_replace(array(' '),' ',$this->getProductName($product, $lang)).'/';
$url .= $product->getId();
}
*/
$url .= 'produkt/';
$product = $this->em->getRepository('Kiwi\EshopBundle\Entity\Product')->findOneBy(array(
'holder_id' => $holder->getId()
));
if($product) {
foreach($this->eshopCategoriesHandle->getProductCategoriesNoCache($product) as $product_category) {
if($product_category->getCategory()) {
$url .= $product_category->getCategory()->getSeoName()."/";
}
}
}
$url .= $this->languages->getLangEntry($holder->getArticle()->getName(), $lang).'/';
$url .= $holder->getTransportCode();
$url = $dev_prefix.$this->pageExtensions->webalizeFunction($url);
return $url;
}
public function storeCookieProductReference($product_id, Request $request, Response $response) {
$current = [];
if($request->cookies->has($this->cookie_key)) {
$current = explode(',',$request->cookies->get($this->cookie_key));
}
$current = array_merge([$product_id], $current);
$cookie = new Cookie($this->cookie_key, join(",",$current), time()+(86400*7));
$response->headers->setCookie($cookie);
}
public function getCookieProduct(Request $request, $lang) {
$current = [];
if($request->cookies->has($this->cookie_key)) {
$current = explode(',',$request->cookies->get($this->cookie_key));
$current = array_unique($current);
$slice = array_slice($current,0,10);
$out = [];
foreach ($slice as $product_id) {
$out[] = $this->findProduct($lang, $product_id);
}
return $out;
}
return $current;
}
//debug
private function logClean() {
file_put_contents($this->log_path, '');
}
private function logState($s) {
file_put_contents($this->log_path, $s."\n", FILE_APPEND);
}
}