<?php
namespace App\Trinity\WebshopBundle\Controller;
use App\CmsBundle\Controller\StorageController;
use App\Trinity\WebshopBundle\Entity\Cart;
use App\Trinity\WebshopBundle\Entity\CartProduct;
use App\Trinity\WebshopBundle\Entity\Product;
use App\Trinity\WebshopBundle\Entity\ProductList;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Trinity\WebshopBundle\Entity\Settings;
// Custom form elements
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use App\Trinity\WebshopBundle\Entity\GiftCard;
use App\Trinity\WebshopBundle\Entity\Category;
use Symfony\Component\Intl\Countries;
class WebshopController extends StorageController
{
private $WebshopUser = null;
private $passwordEncoder = null;
private function getWebshopUser(){
if($this->getUser()){
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
if(!empty($WebshopUser)){
$this->WebshopUser = $WebshopUser;
}else{
$loginUser = $this->getUser();
$this->WebshopUser = new \App\Trinity\WebshopBundle\Entity\User();
$this->WebshopUser->setUser($loginUser);
if(!empty($this->Webshop)){
$this->WebshopUser->setWebshop($this->Webshop);
}
$em = $this->getDoctrine()->getManager();
$em->persist($this->WebshopUser);
$em->flush();
}
}
return $this->WebshopUser;
}
/**
* @Route("/admin/webshop/webshop", name="admin_mod_webshop_mod_webshop")
* @Template()
*/
public function indexAction( Request $request, $id = null)
{
// Initialize StorageController
parent::init($request);
$this->breadcrumbs->addRouteItem('Nieuwe bundel', 'admin_mod_webshop_mod_webshop');
return $this->attributes([
// Variables
]);
}
/**
* @Route("/betaling/", name="mod_webshop_betaling_redirect")
* @Template()
*/
public function betalingCount( Request $request, $id = null)
{
parent::init($request);
$url = '/';
if(!empty($_GET['refnr'])){
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBySku($_GET['refnr']);
if(!empty($Product)){
$url = $this->host . ($this->WebshopSettings->getUri() ? '/' . $this->WebshopSettings->getUri() : $this->generateUrl('homepage')) . $Product->getCategory()->first()->getCategory()->getUri() . '/' . $Product->getSlug() . '?utm_source=visreactie&utm_medium=email&utm_campaign=';
}
}
return $this->redirect($url);
}
/**
* @Route("/choice-flow/results", name="mod_webshop_choice_flow_results")
* @Template()
*/
public function choiceFlowResults(Request $request): Response
{
parent::init($request);
$specs = ['spec' => []];
$price_range = [0, 10000];
if(!empty($_GET['specs'])){
foreach($_GET['specs'] as $k => $spec_id){
$value_id = $_GET['values'][$k];
if($spec_id == 'price'){
$price_range = explode('-', $value_id);
continue;
}
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
$SpecValue = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->find($value_id);
if(!empty($Spec) && !empty($SpecValue)){
if($SpecValue->getSpec() == $Spec){
$specs['spec'][$Spec->getId()] = $SpecValue->getValue();
}
}
}
}else{
foreach($_POST['specs'] as $k => $spec_id){
$value_id = $_POST['values'][$k];
if($spec_id == 'price'){
$price_range = explode('-', $value_id);
continue;
}
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($spec_id);
$SpecValue = $this->getDoctrine()->getRepository('TrinityWebshopBundle:SpecValue')->find($value_id);
if(!empty($Spec) && !empty($SpecValue)){
if($SpecValue->getSpec() == $Spec){
$specs['spec'][$Spec->getId()] = $SpecValue->getValue();
}
}
}
}
// Fetch products with specs
$products_raw = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findAnyBySpecs($specs, $price_range);
$products = [];
foreach($products_raw as $ProductEntity){
$products[] = $ProductEntity->getJson($this->WebshopSettings, $this->get('router'));
}
return new JsonResponse([
'success' => true,
'products' => $products,
], 200);
}
/**
* @Route("/psku/{slug}", name="webshop_shortlink")
* @Template()
*/
public function shortlink( Request $request, $slug)
{
parent::init($request);
$url = '/';
$Product = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findOneBySlug($slug);
if(!empty($Product)){
$url = $this->host . ($this->WebshopSettings->getUri() ? '/' . $this->WebshopSettings->getUri() : $this->generateUrl('homepage')) . $Product->getCategory()->first()->getCategory()->getUri() . '/' . $Product->getSlug() . '';
}
return $this->redirect($url);
}
/**
* @Route("/webshop_data/productcount", name="mod_webshop_count")
* @Template()
*/
public function productCount( Request $request, $id = null)
{
// Initialize StorageController
parent::init($request);
return $this->attributes([
// Variables
]);
}
/**
* @Route("/webshop_data/primary-address/{id}", name="mod_webshop_primary_address")
* @Template()
*/
public function primaryAddressAction( Request $request, $id = null)
{
parent::init($request);
$em = $this->getDoctrine()->getManager();
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
foreach ($WebshopUser->getAddresses() as $Address) {
if($Address->getId() == $id){
$Address->setPriority(true);
}else{
$Address->setPriority(false);
}
$em->persist($Address);
}
$em->flush();
return new JsonResponse([
'success' => true
]);
}
public function esi_latestAction(Request $request, $config = null, $params = null, $Settings = null){
$Settings = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Settings')->find($Settings);
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_latest | start');
$locale = $Settings->getWebshop()->getLanguage()->getLocale();
$hash = md5(serialize($config) . $locale);
$cache_file = $this->getWidgetCacheFile($hash);
$widgetCache = false;
if($this->WebshopSettings->getWidgetCache()) {
$widgetCache = true;
}
if($widgetCache && file_exists($cache_file) && (((time() - filemtime($cache_file)) / 60) / 60) < 3){
$cache = json_decode(file_get_contents($cache_file), true);
}else{
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$cats = null;
if(!empty($config['category_id']) && is_array($config['category_id'])){
$cats = $config['category_id'];
}
if(!empty($config['all_categories'])){
$cats = [];
}
$filters = [];
if(!empty($config['specs'])){
foreach($config['specs'] as $k => $id){
$filters[$id] = $config['spec_values'][$k];
}
}
// $products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findBy(['webshop' => $Webshop, 'enabled' => true, 'visible' => true], ['id' => 'desc'], (!empty($config['limit']) ? (int)$config['limit'] : null), (!empty($config['offset']) ? (int)$config['offset'] : null));
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(
$Webshop, // Webshop
[
'category' => $cats,
'filters' => $filters,
'price' => 1,
'visible' => true,
], // filters
'date_modified', // order
'desc', // orderDir
false, // noLimit
false, // ignoreStock
1, // page
(!empty($config['limit']) ? (int)$config['limit'] : null) // limit
, 0, true
);
if(isset($products['results'])){
$products = $products['results'];
}
$cache = [
'config' => $config,
'products' => [],
];
foreach($products as $Product){
$ProductCategory = $Product->getCategory()->first();
if(empty($ProductCategory)){
continue;
}
$Category = $ProductCategory->getCategory();
$uri = '';
if(!empty($this->WebshopSettings) && !empty($this->WebshopSettings->getUri())){
$uri = $this->generateUrl('homepage') . $this->WebshopSettings->getUri();
}else{
if(!empty($this->Settings->getBaseuri())){
$uri = str_replace('/', '', $this->Settings->getBaseuri()) . '/';
}
}
if(!empty($Category)){
$uri .= $Category->getUri() . '/';
}
$uri .= $Product->getSlug();
$media = '/bundles/trinitywebshop/img/no-product-image.png';
$media2 = null;
$mediaWebp = null;
$mediaWebp2 = null;
$mediaMime = null;
$mediaMime2 = null;
$mediaBlur = null;
$mediaBlur2 = null;
$mediaBlurWebp = null;
$mediaBlurWebp2 = null;
if(!empty($Product->getMedia()) && !empty($Product->getMedia()->first())){
$pMedia = $Product->getMedia()->first();
$mediaMime = $pMedia->getMime();
$media = '/' . $pMedia->getWebPath('small');
if ($pMedia->hasWebp()) {
$mediaWebp = '/' . $pMedia->getWebpPath('small');
if ($pMedia->hasBlurred()) {
$mediaBlurWebp = $pMedia->getBlurredWebpPath();
}
}
if ($pMedia->hasBlurred()) {
$mediaBlur = $pMedia->getBlurredWebPath();
}
if ($Product->getMedia()->count() > 1) {
$pMedia2 = $Product->getMedia()->next();
$mediaMime2 = $pMedia2->getMime();
$media2 = '/' . $pMedia2->getWebPath('small');
if ($pMedia2->hasWebp()) {
$mediaWebp2 = '/' . $pMedia2->getWebpPath('small');
if ($pMedia->hasBlurred()) {
$mediaBlurWebp2 = $pMedia->getBlurredWebpPath();
}
}
if ($pMedia->hasBlurred()) {
$mediaBlur2 = $pMedia->getBlurredWebPath();
}
}
}else{
if($this->WebshopSettings->getDefaultProductImage()){
$media = $this->WebshopSettings->getDefaultProductImage();
}
}
if($Category->getLabel() != 'Ongesorteerd'){
$cache['products'][] = [
'id' => $Product->getId(),
'number' => $Product->getNumber(),
'uri' => $uri,
'new' => $Product->getNew(),
'hasPromotion' => $Product->hasPromotion(),
'hasCombi' => $Product->hasCombi(),
'exclusive' => $Product->getExclusive(),
'newFrom' => $Product->getNewFrom(),
'canOrder' => $Product->canOrder(),
'newTill' => $Product->getNewTill(),
'priceSale' => $Product->getPriceSale(),
'priceSalePercent' => $Product->getPriceSalePercent(),
'label' => $Product->getLabel(),
'labelSub' => $Product->getLabelSub(),
'brand' => $Product->getBrand(),
'type' => $Product->getType(),
'intro' => $Product->getIntro() ?? '',
'price' => $Product->getDisplayPrice($this->WebshopSettings),
'visible' => $Product->getVisible(),
'enabled' => $Product->getEnabled(),
'mediaMime' => $mediaMime,
'mediaMime2' => $mediaMime2,
'media' => $media,
'media2' => $media2,
'mediaWebp' => $mediaWebp,
'mediaWebp2' => $mediaWebp2,
'mediaBlur' => $mediaBlur,
'mediaBlur2' => $mediaBlur2,
'mediaBlurWebp' => $mediaBlurWebp,
'mediaBlurWebp2' => $mediaBlurWebp2,
'category' => [
'id' => $Category->getId(),
'label' => $Category->getLabel(),
],
];
}
file_put_contents($cache_file, json_encode($cache));
}
}
$this->Timer->mark('WEBSHOP: widget_latest | end');
$response = $this->render('@TrinityWebshop/default/esi_widget_latest.html.twig', $this->attributes([
'config' => $cache['config'],
'params' => $params,
'products' => $cache['products'],
]));
if(!empty($this->cache_widget)){
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
$response->setPublic();
$response->setMaxAge($this->cache_widget);
$response->headers->addCacheControlDirective('must-revalidate');
$response->setVary(array('Accept-Encoding', 'User-Agent'));
$response->headers->addCacheControlDirective('max-age', $this->cache_widget);
$response->setSharedMaxAge($this->cache_widget);
}
return $response;
}
public function widget_latest($config, $params, $Settings, Request $request){
return $this->renderView('@TrinityWebshop/default/widget_latest.html.twig', $this->attributes([
'esi_config' => $config,
'esi_params' => $params,
'esi_Settings' => $Settings->getId(), // For caching an ID is needed
]));
}
public function esi_productsAction(Request $request, $config = null, $params = null, $Settings = null){
$Settings = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Settings')->find($Settings);
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_products | start');
$locale = $Settings->getWebshop()->getLanguage()->getLocale();
$hash = md5(serialize($config) . $locale);
$cache_file = str_replace('src/Trinity/WebshopBundle/Controller', 'var/cache/webshop/', __DIR__) . $hash;
$widgetCache = false;
if($this->WebshopSettings->getWidgetCache()) {
$widgetCache = true;
}
if($widgetCache && file_exists($cache_file) && (((time() - filemtime($cache_file)) / 60) / 60) < 3){
$cache = json_decode(file_get_contents($cache_file), true);
}else{
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$filters = [];
if(!empty($config['specs'])){
foreach($config['specs'] as $k => $id){
$filters[$id] = $config['spec_values'][$k];
}
}
$products = [];
$description = '';
if(!empty($config['category_id'])){
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($Webshop, [
'filters' => $filters,
'price' => 1,
'visible' => true,
'category' => $config['category_id'],
], 'pos', 'desc', false, false, 1, $config['limit'], 0, true);
if(count($config['category_id']) === 1){
$Category = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($config['category_id'][0]);
if(!empty($Category)){
$description = $Category->getDescription();
}
}
}else{
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search($Webshop, [
'filters' => $filters,
'price' => 1,
'visible' => true,
], 'pos', 'desc', false, false, 1, $config['limit'], 0, true);
}
if(isset($products['results'])){
$products = $products['results'];
}
$cache = [
'config' => $config,
'products' => [],
];
foreach($products as $Product){
$ProductCategory = $Product->getCategory()->first();
$Category = $ProductCategory->getCategory();
$uri = '/';
if(!empty($this->WebshopSettings) && !empty($this->WebshopSettings->getUri())){
$uri = $this->generateUrl('homepage') . $this->WebshopSettings->getUri();
}else{
if(!empty($this->Settings->getBaseuri())){
$uri = str_replace('/', '', $this->Settings->getBaseuri()) . '/';
}
}
if(!empty($Category)){
$uri .= $Category->getUri() . '/';
}
$uri .= $Product->getSlug();
$media = '/bundles/trinitywebshop/img/no-product-image.png';
$media2 = null;
$mediaWebp = null;
$mediaWebp2 = null;
$mediaMime = null;
$mediaMime2 = null;
$mediaBlur = null;
$mediaBlur2 = null;
$mediaBlurWebp = null;
$mediaBlurWebp2 = null;
if(!empty($Product->getMedia()) && !empty($Product->getMedia()->first())){
$pMedia = $Product->getMedia()->first();
$mediaMime = $pMedia->getMime();
$media = '/' . $pMedia->getWebPath('small');
if ($pMedia->hasWebp()) {
$mediaWebp = '/' . $pMedia->getWebpPath('small');
if ($pMedia->hasBlurred()) {
$mediaBlurWebp = '/' . $pMedia->getBlurredWebpPath();
}
}
if ($pMedia->hasBlurred()) {
$mediaBlur = '/' . $pMedia->getBlurredWebPath();
}
if ($Product->getMedia()->count() > 1) {
$pMedia2 = $Product->getMedia()->next();
$mediaMime2 = $pMedia2->getMime();
$media2 = '/' . $pMedia2->getWebPath('small');
if ($pMedia2->hasWebp()) {
$mediaWebp2 = '/' . $pMedia2->getWebpPath('small');
if ($pMedia->hasBlurred()) {
$mediaBlurWebp2 = '/' . $pMedia->getBlurredWebpPath();
}
}
if ($pMedia->hasBlurred()) {
$mediaBlur2 = '/' . $pMedia->getBlurredWebPath();
}
}
}else{
if($this->WebshopSettings->getDefaultProductImage()){
$media = $this->WebshopSettings->getDefaultProductImage();
}
}
if($Category->getLabel() != 'Ongesorteerd'){
$cache['products'][] = [
'id' => $Product->getId(),
'uri' => $uri,
'new' => $Product->getNew(),
'hasPromotion' => $Product->hasPromotion(),
'hasCombi' => $Product->hasCombi(),
'exclusive' => $Product->getExclusive(),
'newFrom' => $Product->getNewFrom(),
'canOrder' => $Product->canOrder(),
'newTill' => $Product->getNewTill(),
'priceSale' => $Product->getPriceSale(),
'priceSalePercent' => $Product->getPriceSalePercent(),
'label' => $Product->getLabel(),
'labelSub' => $Product->getLabelSub(),
'brand' => $Product->getBrand(),
'type' => $Product->getType(),
'intro' => $Product->getIntro() ?? '',
'price' => $Product->getDisplayPrice($this->WebshopSettings),
'visible' => $Product->getVisible(),
'enabled' => $Product->getEnabled(),
'mediaMime' => $mediaMime,
'mediaMime2' => $mediaMime2,
'media' => $media,
'media2' => $media2,
'mediaWebp' => $mediaWebp,
'mediaWebp2' => $mediaWebp2,
'mediaBlur' => $mediaBlur,
'mediaBlur2' => $mediaBlur2,
'mediaBlurWebp' => $mediaBlurWebp,
'mediaBlurWebp2' => $mediaBlurWebp2,
'category' => [
'id' => $Category->getId(),
'label' => $Category->getLabel(),
],
];
}
file_put_contents($cache_file, json_encode($cache));
}
}
$this->Timer->mark('WEBSHOP: widget_products | end');
$response = $this->render('@TrinityWebshop/default/esi_widget_products.html.twig', $this->attributes([
'config' => $cache['config'],
'params' => $params,
'description' => '',//$description,
'products' => $cache['products'],
]));
if(!empty($this->cache_widget)){
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
$response->setPublic();
$response->setMaxAge($this->cache_widget);
$response->headers->addCacheControlDirective('must-revalidate');
$response->setVary(array('Accept-Encoding', 'User-Agent'));
$response->headers->addCacheControlDirective('max-age', $this->cache_widget);
$response->setSharedMaxAge($this->cache_widget);
}
return $response;
}
public function widget_products($config, $params, $Settings, Request $request){
return $this->renderView('@TrinityWebshop/default/widget_products.html.twig', $this->attributes([
'esi_config' => $config,
'esi_params' => $params,
'esi_Settings' => $Settings->getId(), // For caching an ID is needed
]));
}
public function esi_subcategoryAction(Request $request, $config = null, $params = null, $Settings = null){
$Settings = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Settings')->find($Settings);
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_subcategory | start');
$locale = $Settings->getWebshop()->getLanguage()->getLocale();
$hash = md5(serialize($config) . $locale);
$cache_file = $this->getWidgetCacheFile($hash);
$widgetCache = false;
if($this->WebshopSettings->getWidgetCache()) {
$widgetCache = true;
}
if($widgetCache && file_exists($cache_file) && (((time() - filemtime($cache_file)) / 60) / 60) < 3 && (((time() - filemtime($cache_file)) / 60) / 60) < 3){
$cache = json_decode(file_get_contents($cache_file), true);
}else{
$cache = [
'config' => $config,
'categories' => [],
];
$C = null;
$counts = [];
if(!empty($config['category_id'])){
if(!is_array($config['category_id'])) $config['category_id'] = [$config['category_id']];
foreach($config['category_id'] as $id){
$cache['categories'] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findSubsWithCounts($id, 0);
/*$C = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findBy();
$n = 1;
foreach($C->getChildren() as $SC){
$categories[$SC->getId()] = $SC;
if(!empty($config['limit']) && $n >= $config['limit']){
break;
}
$n++;
}*/
}
}
file_put_contents($cache_file, json_encode($cache));
}
$this->Timer->mark('WEBSHOP: widget_subcategory | end');
$response = $this->render('@TrinityWebshop/default/esi_widget_subcategory.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
// 'counts' => $counts,
// 'C' => $C,
'categories' => $cache['categories'],
]));
if(!empty($this->cache_widget)){
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
$response->setPublic();
$response->setMaxAge($this->cache_widget);
$response->headers->addCacheControlDirective('must-revalidate');
$response->setVary(array('Accept-Encoding', 'User-Agent'));
$response->headers->addCacheControlDirective('max-age', $this->cache_widget);
$response->setSharedMaxAge($this->cache_widget);
}
return $response;
}
public function widget_subcategory($config, $params, $Settings, Request $request){
return $this->renderView('@TrinityWebshop/default/widget_subcategory.html.twig', $this->attributes([
'esi_config' => $config,
'esi_params' => $params,
'esi_Settings' => $Settings->getId(), // For caching an ID is needed
]));
}
public function widget_searchwithcat($config, $params, $Settings, Request $request){
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_searchwithcat | start');
$categories = [];
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$Categories = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findBy(['webshop' => $Webshop]);
foreach ($Categories as $cat) {
if(empty($cat->getParent())){
array_push($categories, $cat);
}
}
$specs = [];
if(!empty($config['specs'])){
foreach($config['specs'] as $specid){
$specs[$specid] = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->find($specid);
}
}
// $categories = [];
// if(!empty($config['category_id'])){
// if(!is_array($config['category_id'])) $config['category_id'] = [$config['category_id']];
// foreach($config['category_id'] as $id){
// $C = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($id);
// foreach($C->getChildren() as $SC){
// $categories[$SC->getId()] = $SC;
// }
// }
// }
$this->Timer->mark('WEBSHOP: widget_searchwithcat | end');
return $this->renderView('@TrinityWebshop/default/widget_searchwithcat.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'categories' => $categories,
'specs' => $specs,
]));
}
public function widget_categories($config, $params, $Settings, Request $request){
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_categories | start');
$categories = [];
if(!empty($config['category_id'])){
if(!is_array($config['category_id'])) $config['category_id'] = [$config['category_id']];
foreach($config['category_id'] as $id){
$C = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->find($id);
foreach($C->getChildren() as $SC){
$categories[$SC->getId()] = $SC;
}
}
}
$this->Timer->mark('WEBSHOP: widget_categories | end');
return $this->renderView('@TrinityWebshop/default/widget_categories.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'categories' => $categories,
]));
}
public function esi_featuredAction(Request $request, $config = null, $params = null, $Settings = null){
$Settings = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Settings')->find($Settings);
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_featured | start');
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$cats = null;
if(!empty($config['category_id']) && is_array($config['category_id'])){
$cats = $config['category_id'];
}
if(!empty($config['all_categories'])){
$cats = [];
}
$filters = [];
if(!empty($config['specs'])){
foreach($config['specs'] as $k => $id){
$filters[$id] = $config['spec_values'][$k];
}
}
// $products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findBy(['webshop' => $Webshop, 'enabled' => true, 'visible' => true], ['id' => 'desc'], (!empty($config['limit']) ? (int)$config['limit'] : null), (!empty($config['offset']) ? (int)$config['offset'] : null));
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(
$Webshop, // Webshop
[
'category' => $cats,
'filters' => $filters,
'featured' => true,
'visible' => true,
// 'debug' => true,
], // filters
'id', // order
'desc', // orderDir
false, // noLimit
false, // ignoreStock
1, // page
(!empty($config['limit']) ? (int)$config['limit'] : null) // limit
);
if(isset($products['results'])){
$products = $products['results'];
}
$this->Timer->mark('WEBSHOP: widget_featured | end');
$response = $this->render('@TrinityWebshop/default/esi_widget_featured.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'products' => $products,
]));
if(!empty($this->cache_widget)){
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
$response->setPublic();
$response->setMaxAge($this->cache_widget);
$response->headers->addCacheControlDirective('must-revalidate');
$response->setVary(array('Accept-Encoding', 'User-Agent'));
$response->headers->addCacheControlDirective('max-age', $this->cache_widget);
$response->setSharedMaxAge($this->cache_widget);
}
return $response;
}
public function widget_featured($config, $params, $Settings, Request $request){
return $this->renderView('@TrinityWebshop/default/widget_featured.html.twig', $this->attributes([
'esi_config' => $config,
'esi_params' => $params,
'esi_Settings' => $Settings->getId(), // For caching an ID is needed
]));
}
public function esi_discountedAction(Request $request, $config = null, $params = null, $Settings = null){
$Settings = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Settings')->find($Settings);
$this->init($request);
$this->Timer->mark('WEBSHOP: widget_discounted | start');
$cats = null;
if(!empty($config['category_id']) && is_array($config['category_id'])){
$cats = $config['category_id'];
}
if(!empty($config['all_categories'])){
$cats = [];
}
$filters = [];
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->search(
$Webshop, // Webshop
[
'category' => $cats,
'filters' => $filters,
'discount' => true,
'visible' => true,
], // filters
'id', // order
'desc', // orderDir
false, // noLimit
false, // ignoreStock
1, // page
(!empty($config['limit']) ? (int)$config['limit'] : null) // limit
);
if(isset($products['results'])){
$products = $products['results'];
}
$cache = [
'config' => $config,
'products' => [],
];
foreach($products as $Product){
$ProductCategory = $Product->getCategory()->first();
$Category = $ProductCategory->getCategory();
$uri = '';
if(!empty($this->WebshopSettings) && !empty($this->WebshopSettings->getUri())){
$uri = $this->generateUrl('homepage') . $this->WebshopSettings->getUri();
}else{
if(!empty($this->Settings->getBaseuri())){
$uri = str_replace('/', '', $this->Settings->getBaseuri()) . '/';
}
}
if(!empty($Category)){
$uri .= $Category->getUri() . '/';
}
$uri .= $Product->getSlug();
$media = '/bundles/trinitywebshop/img/no-product-image.png';
$media2 = null;
$mediaWebp = null;
$mediaWebp2 = null;
$mediaMime = null;
$mediaMime2 = null;
$mediaBlur = null;
$mediaBlur2 = null;
$mediaBlurWebp = null;
$mediaBlurWebp2 = null;
if(!empty($Product->getMedia()) && !empty($Product->getMedia()->first())){
$pMedia = $Product->getMedia()->first();
$mediaMime = $pMedia->getMime();
$media = '/' . $pMedia->getWebPath('small');
if ($pMedia->hasWebp()) {
$mediaWebp = '/' . $pMedia->getWebpPath('small');
if ($pMedia->hasBlurred()) {
$mediaBlurWebp = '/' . $pMedia->getBlurredWebpPath();
}
}
if ($pMedia->hasBlurred()) {
$mediaBlur = '/' . $pMedia->getBlurredWebPath();
}
if ($Product->getMedia()->count() > 1) {
$pMedia2 = $Product->getMedia()->next();
$mediaMime2 = $pMedia2->getMime();
$media2 = '/' . $pMedia2->getWebPath('small');
if ($pMedia2->hasWebp()) {
$mediaWebp2 = '/' . $pMedia2->getWebpPath('small');
if ($pMedia->hasBlurred()) {
$mediaBlurWebp2 = '/' . $pMedia->getBlurredWebpPath();
}
}
if ($pMedia->hasBlurred()) {
$mediaBlur2 = '/' . $pMedia->getBlurredWebPath();
}
}
}else{
if($this->WebshopSettings->getDefaultProductImage()){
$media = $this->WebshopSettings->getDefaultProductImage();
}
}
if($Category->getLabel() != 'Ongesorteerd'){
$cache['products'][] = [
'id' => $Product->getId(),
'uri' => $uri,
'new' => $Product->getNew(),
'hasPromotion' => $Product->hasPromotion(),
'hasCombi' => $Product->hasCombi(),
'exclusive' => $Product->getExclusive(),
'newFrom' => $Product->getNewFrom(),
'canOrder' => $Product->canOrder(),
'newTill' => $Product->getNewTill(),
'priceSale' => $Product->getPriceSale(),
'priceSalePercent' => $Product->getPriceSalePercent(),
'label' => $Product->getLabel(),
'labelSub' => $Product->getLabelSub(),
'brand' => $Product->getBrand(),
'type' => $Product->getType(),
'intro' => $Product->getIntro() ?? '',
'price' => $Product->getDisplayPrice($this->WebshopSettings),
'visible' => $Product->getVisible(),
'enabled' => $Product->getEnabled(),
'mediaMime' => $mediaMime,
'mediaMime2' => $mediaMime2,
'media' => $media,
'media2' => $media2,
'mediaWebp' => $mediaWebp,
'mediaWebp2' => $mediaWebp2,
'mediaBlur' => $mediaBlur,
'mediaBlur2' => $mediaBlur2,
'mediaBlurWebp' => $mediaBlurWebp,
'mediaBlurWebp2' => $mediaBlurWebp2,
'category' => [
'id' => $Category->getId(),
'label' => $Category->getLabel(),
],
];
}
// file_put_contents($cache_file, json_encode($cache));
}
//$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->getByDiscounted($Webshop, (!empty($config['limit']) ? (int)$config['limit'] : null), $config);
//$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->findBy(['webshop' => $Webshop, 'discount' => true, 'enabled' => true, 'visible' => true], ['label' => 'asc'], (!empty($config['limit']) ? (int)$config['limit'] : null));
// dump($products);die();
$this->Timer->mark('WEBSHOP: widget_discounted | end');
$response = $this->render('@TrinityWebshop/default/esi_widget_discounted.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'products' => $cache['products'],
]));
if(!empty($this->cache_widget)){
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
$response->setPublic();
$response->setMaxAge($this->cache_widget);
$response->headers->addCacheControlDirective('must-revalidate');
$response->setVary(array('Accept-Encoding', 'User-Agent'));
$response->headers->addCacheControlDirective('max-age', $this->cache_widget);
$response->setSharedMaxAge($this->cache_widget);
}
return $response;
}
public function widget_discounted($config, $params, $Settings, Request $request){
return $this->renderView('@TrinityWebshop/default/widget_discounted.html.twig', $this->attributes([
'esi_config' => $config,
'esi_params' => $params,
'esi_Settings' => $Settings->getId(), // For caching an ID is needed
]));
}
public function widget_popular($config, $params, $Settings, Request $request){
parent::init($request);
$this->Timer->mark('WEBSHOP: widget_popular | start');
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$products = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Product')->getBestSoldAllowed($Webshop, (!empty($config['limit']) ? (int)$config['limit'] : null));
$this->Timer->mark('WEBSHOP: widget_popular | end');
return $this->renderView('@TrinityWebshop/default/widget_popular.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'products' => $products,
]));
}
public function widget_homecats($config, $params, $Settings, Request $request){
parent::init($request);
$this->Timer->mark('WEBSHOP: widget_homecats | start');
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$categories = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Category')->findBy(['webshop' => $Webshop, 'homepage' => true], ['position' => 'asc']);
$this->Timer->mark('WEBSHOP: widget_homecats | end');
return $this->renderView('@TrinityWebshop/default/widget_homecats.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'categories' => $categories,
]));
}
public function widget_choice_flow($config, $params, $Settings, Request $request){
parent::init($request);
$this->Timer->mark('WEBSHOP: widget_choice_flow | start');
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$this->Timer->mark('WEBSHOP: widget_choice_flow | end');
$specs = $config['specs'];
// Loop through specs and get spec entities
foreach($specs as $k => $specId){
$Spec = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Spec')->findOneBy(['id' => $specId, 'type' => 'dropdown']);
if(!empty($Spec)){
$specs[$k] = $Spec;
}
}
return $this->renderView('@TrinityWebshop/default/widget_choice_flow.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'specs' => $specs,
]));
}
public function widget_category_masonry($config, $params, $Settings, Request $request){
$this->init($request);
return $this->renderView('@TrinityWebshop/default/widget_category_masonry.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
//
]));
}
/**
* @Route("/webshop_data/order/dl/{id}", name="webshop_order_dl")
*/
public function orderDlAction( Request $request, $id = null)
{
// Initialize StorageController
parent::init($request);
$Order = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find((int)$id);
if($this->getUser() && $Order->getUser()->getId() == $this->getUser()->getId()){
// $tpl = str_replace('/Controller', '/Resources/public/invoice_template.html', __DIR__);
$tplPath = '@TrinityWebshop/invoice_template.html.twig';
$customTplPath = preg_replace('/src\/.*?$/', 'templates/invoice_template.html.twig', __DIR__);
if(file_exists($customTplPath)){
$tplPath = '/invoice_template.html.twig';
}
$tpl = $this->renderView($tplPath, $this->attributes([
'Order' => $Order,
]));
$html = $tpl;
$pdf = $this->container->get("qipsius.tcpdf")->create();
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('invoice_' . $id . '.pdf', 'D');
exit;
}
throw $this->createNotFoundException($this->trans('Het product bestaat niet', [], "webshop"));
}
public function widget_profile_orders($config, $params, $Settings, Request $request, $finish = false){
parent::init($request);
if($params[0] == 'dl'){
// Download file
$OrderProduct = $this->getDoctrine()->getRepository('TrinityWebshopBundle:OrderProduct')->find((int)$params[1]);
if(!empty($OrderProduct)){
$em = $this->getDoctrine()->getManager();
$Order = $OrderProduct->getOrder();
$Product = $OrderProduct->getProduct();
if(!empty($Order) && !empty($Order) && $Order->getUser()->getUser() == $this->getUser()){
$File = $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductFile')->findOneBy(['product' => $Product, 'id' => $params[2]]);
if(!empty($File)){
$previousDownloads = $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductFileDownload')->findBy(['file' => $File, 'order_product' => $OrderProduct]);
$n = count($previousDownloads);
/*if($Product->getDownloadLimit() > 0 && $n >= $Product->getDownloadLimit()){
throw $this->createNotFoundException($this->trans('Het gekozen bestand is niet meer beschikbaar.', [], "webshop"));
}
if($Product->getDownloadDays() > 0){
$days_offset = date('YmdHis', strtotime('-' . $Product->getDownloadDays() . ' day'));
if($Order->getDate()->format('YmdHis') <= $days_offset){
throw $this->createNotFoundException($this->trans('Het gekozen bestand is niet meer beschikbaar.', [], "webshop"));
}
}*/
$h = new \App\Trinity\WebshopBundle\Entity\ProductFileDownload();
$h->setDate(new \DateTime());
$h->setUser($this->getUser());
$h->setOrder($Order);
$h->setOrderProduct($OrderProduct);
$h->setFile($File);
$em->persist($h);
$em->flush();
$file = $File->getMedia()->getAbsolutePath();
$basename = basename($file);
$length = sprintf("%u", filesize($file));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $basename . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
// header('Content-Length: ' . $length);
ob_end_flush(); // <--- instead of ob_clean()
set_time_limit(0);
readfile($file);
return;
}else{
throw $this->createNotFoundException($this->trans('Het gekozen bestand bestaat niet.', [], "webshop"));
}
}else{
throw $this->createNotFoundException($this->trans('Het gekozen bestand bestaat niet.', [], "webshop"));
}
}else{
throw $this->createNotFoundException($this->trans('Het gekozen bestand bestaat niet.', [], "webshop"));
}
}
$Webshop = $request->getSession()->get('webshop');
$Pay = $this->Settings->getPay();
$route = $request->get('_route');
$order_page = null;
$blocks = $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->findByData('TrinityWebshopBundle', 'profile_orders');
foreach($blocks as $Block){
$p = $Block->getWrapper()->getPage();
if($p->getLanguage() == $this->language){
$order_page = $p;
break;
}
}
if(is_numeric($params[0])){
$order = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->find((int)$params[0]);
if(!empty($params[1] == 'payment')){
$Pay->createPayment([
'id' => $order->getOrderId(),
'order_id' => $order->getOrderId(),
'amount' => $order->getTotalPrice(),
'description' => 'Order ' . $order->getHash(),
'redirectUrl' => $this->generateUrl($order->getWebshop()->getSettings()->getCheckoutFinishUri(), array('hash' => $order->getHash()), UrlGeneratorInterface::ABSOLUTE_URL),
'method' => (!empty($params[2]) ? $params[2] : null),
'issuer' => (!empty($params[2]) && !empty($params[3]) ? $params[3] : null),
]);
$em = $this->getDoctrine()->getManager();
$order->setPaymentId($Pay->id);
$order->setPaymentStatus($Pay->status);
$em->persist($order);
// Payment history
$OrderPayment = new \App\Trinity\WebshopBundle\Entity\OrderPayment();
$OrderPayment->setOrder($order);
$OrderPayment->setDate(new \Datetime());
$OrderPayment->setPaymentId($Pay->id);
$OrderPayment->setPaymentStatus($Pay->status);
$OrderPayment->setIp($_SERVER['REMOTE_ADDR']);
// Save order
// Add to payment history
$em->persist($OrderPayment);
// Remove cart
// $em->remove($Cart);
$em->flush();
header('Location:' . $Pay->url);
exit;
}else if(!empty($params[1] == 'dl')){
$pdf = $this->container->get("qipsius.tcpdf")->create();
// dump($pdf);
exit;
}
if($finish){
header('Location: /');
exit;
}
$tax = [];
$tax_total = 0;
/*if($order->getTotalDelivery() > 0){
$tax[21] = (($order->getTotalDelivery() / 100) * 21);
}*/
if(!empty($order->getProducts())){
foreach($order->getProducts() as $Product){
if(!empty($Product->getProduct())){
$Tax = $Product->getProduct()->getTax();
} else {
$Tax = null;
}
if(empty($Tax)){
$Tax = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Tax')->findOneByPercent(21);
}
$percent = $Tax->getPercent();
$price = $Product->getTotalPrice();
// dump($price);
$_tax = (($price / 100) * $percent);
if(!isset($tax[$percent])) $tax[$percent] = 0;
$tax[$percent] += $_tax;
$tax_total += $_tax;
}
}
$delivery = $order->getTotalDelivery();
if(!empty($delivery)){
$t = (($delivery / 100) * 21);
if(!isset($tax[21])) {
$tax[21] = 0;
}
$tax[21] += $t;
// $tax_total += $t;
}
return $this->renderView('@TrinityWebshop/default/widget_profile_orders_view.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'order' => $order,
'tax' => $tax,
'order_page' => $order_page,
'tax_total' => $tax_total,
]));
}else{
if($finish){
header('Location: /');
exit;
}
$page = 1;
if(!empty($_GET['page'])){ $page = $_GET['page']; }
$per_page = 10;
$count = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->count(array(
'user' => $this->getWebshopUser(),
// 'webshop' => $Webshop
));
$pages = ceil($count / $per_page);
$orders = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Order')->findBy(array(
'user' => $this->getWebshopUser(),
// 'webshop' => $Webshop
), array(
'date' => 'desc'
), $per_page, (($page - 1) * $per_page));
return $this->renderView('@TrinityWebshop/default/widget_profile_orders.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'order_page' => $order_page,
'orders' => $orders,
'Pay' => $Pay,
'pages' => $pages,
'page' => $page,
]));
}
}
public function widget_profile_giftcards($config, $params, $Settings, Request $request, $finish = false){
parent::init($request);
$Webshop = $request->getSession()->get('webshop');
$route = $request->get('_route');
$WebshopUser = $this->getWebshopUser();
$giftcard_error = null;
$giftcard_warning = null;
$giftcard_success = null;
if(!empty($_POST['giftcard_code'])){
$code = $_POST['giftcard_code'];
$Giftcard = $this->getDoctrine()->getRepository(Giftcard::class)->findOneBy(['code' => $code]);
if($Giftcard){
if($Giftcard->getUser() != $this->WebshopUser){
$Giftcard->setUser($this->WebshopUser);
$em = $this->getDoctrine()->getManager();
$em->persist($Giftcard);
$em->flush();
$giftcard_success = 'De cadeaukaart is succesvol verzilverd.';
}else{
$giftcard_warning = 'Deze cadeaukaart is al in gebruik.';
}
}else{
$giftcard_error = 'Geen cadeaukaart gevonden met deze code.';
}
}
return $this->renderView('@TrinityWebshop/default/widget_profile_giftcards.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'WebshopUser' => $WebshopUser,
'giftcard_success' => $giftcard_success,
'giftcard_warning' => $giftcard_warning,
'giftcard_error' => $giftcard_error,
]));
}
public function widget_profile_lists($config, $params, $Settings, Request $request){
$this->init($request);
$order_page = null;
$blocks = $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->findByData('TrinityWebshopBundle', 'profile_orders');
foreach($blocks as $Block){
$p = $Block->getWrapper()->getPage();
if($p->getLanguage() == $this->language){
$order_page = $p;
break;
}
}
$Webshop = $request->getSession()->get('webshop');
$WebshopUser = $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
if(!empty($_GET['l']) && !empty($_GET['d'])){
$p = $this->getDoctrine()->getRepository(Product::class)->find($_GET['d']);
$l = $this->getDoctrine()->getRepository(ProductList::class)->find($_GET['l']);
if($l && $p){
$l->removeProduct($p);
$em = $this->getDoctrine()->getManager();
$em->persist($l);
$em->flush();
}
}else if(!empty($_GET['d'])){
$l = $this->getDoctrine()->getRepository(ProductList::class)->find($_GET['d']);
if($l){
$em = $this->getDoctrine()->getManager();
$em->remove($l);
$em->flush();
}
}else if(!empty($_GET['c'])){
$List = $this->getDoctrine()->getRepository(ProductList::class)->find($_GET['c']);
if($List){
$em = $this->getDoctrine()->getManager();
$User = $WebshopUser->getUser();
// Find previous cart(s)
$carts = $em->getRepository(Cart::class)->findBy(['user' => $WebshopUser]);
foreach($carts as $Cart){
// Remove old cart
$em->remove($Cart);
}
// Find previous cart(s)
$carts = $em->getRepository(Cart::class)->findBy(['ip' => $_SERVER['REMOTE_ADDR']]);
foreach($carts as $Cart){
// Remove old cart
$em->remove($Cart);
}
$Cart = new Cart();
$Cart->setWebshop($this->Webshop);
$Cart->setLanguage($this->language);
$Cart->setUser($this->getWebshopUser());
$Cart->setDateStart(new \Datetime());
$Cart->setIp($_SERVER['REMOTE_ADDR']);
$Cart->setFirstname($User->getFirstname());
$Cart->setLastname($User->getLastname());
$Cart->setEmail($User->getEmail());
$em->persist($Cart);
foreach($List->getProducts() as $Product){
if(!empty($Product) && $Product instanceof Product){
$CartProduct = new CartProduct();
$CartProduct->setAmount(1);
$CartProduct->setProduct($Product, $this->WebshopSettings);
$CartProduct->setCart($Cart);
$em->persist($CartProduct);
$Cart->addProduct($CartProduct);
}
}
$Cart->calculate($this->getDoctrine(), $this->Settings);
$em->persist($Cart);
$em->flush();
$request->getSession()->set('cart', $Cart->getId());
header('Location: ' . $this->generateUrl('checkout'));
exit;
}
}
$route = $request->get('_route');
$lists = $this->getDoctrine()->getRepository('TrinityWebshopBundle:ProductList')->findByUser($WebshopUser);
return $this->renderView('@TrinityWebshop/default/widget_profile_lists.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'order_page' => $order_page,
'lists' => $lists,
]));
}
private function postalcodeToAddress($postalcode, $number){
$postalcode = (preg_replace('/[^0-9a-zA-Z]/', '', $postalcode));
if (strlen($postalcode . $number) > 5) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.postcode.nl/rest/addresses/" . $postalcode . "/" . $number);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_USERPWD, "VPoIVrLzyr2nCtBGg3tSuH7JBZ8qHCx458256zgsjgh:e3NH3amIpGTKJEgJQSqXo8Tnn6TbyLQ6b9PntAsqMXeCuzB29M");
// curl_setopt($ch, CURLOPT_HEADER, 1);
$result = json_decode(curl_exec($ch));
curl_close($ch);
if(!isset($result->exception)){
if ($result->street && !empty($result->street)) {
return [
'street' => $result->street,
'number' => $number,
'postalcode' => $postalcode,
'city' => $result->city
];
}
}
}
return null;
}
public function widget_profile($config, $params, $Settings, Request $request){
$this->init($request);
$Webshop = $request->getSession()->get('webshop');
$WebshopUser = $this->getWebshopUser();
$savedProfile = false;
$route = $request->get('_route');
$giftcard_error = null;
$giftcard_warning = null;
$giftcard_success = null;
if(!empty($_POST['giftcard_code'])){
$code = $_POST['giftcard_code'];
$Giftcard = $this->getDoctrine()->getRepository(Giftcard::class)->findOneBy(['code' => $code]);
if($Giftcard){
if($Giftcard->getUser() != $this->WebshopUser){
$Giftcard->setUser($this->WebshopUser);
$em = $this->getDoctrine()->getManager();
$em->persist($Giftcard);
$em->flush();
$giftcard_success = 'De cadeaukaart is succesvol verzilverd.';
}else{
$giftcard_warning = 'Deze cadeaukaart is al in gebruik.';
}
}else{
$giftcard_error = 'Geen cadeaukaart gevonden met deze code.';
}
}
$pwd_error = '';
$pwd_msg = '';
if(!empty($_POST['pwd'])){
if(!empty($_POST['pwd']['first'])){
if($_POST['pwd']['first'] == $_POST['pwd']['second']){
$User = $this->getUser();
$passwordEncoder = $this->containerInterface->get('security.password_encoder');
$User->setPassword($passwordEncoder->encodePassword($User, $_POST['pwd']['first']));
$em = $this->getDoctrine()->getManager();
$em->persist($User);
$em->flush();
$pwd_msg = $this->trans('Het wachtwoord is gewijzigd.', [], "webshop");
}else{
$pwd_error = $this->trans('Het wachtwoord en controle wachtwoord komen niet overeen.', [], "webshop");
}
}else{
$pwd_error = $this->trans('Wachtwoord is niet ingevuld.', [], "webshop");
}
}else{
if($request->request->get('naw')){
// User profile
$naw = $request->request->get('naw');
$User = $this->getUser();
if(isset($naw['company'])){
$User->setCompany($naw['company']);
}
if (isset($naw['companytax'])) {
$User->setCompanyTaxNo($naw['companytax']);
}
if (isset($naw['companycoc'])) {
$User->setCompanyKvk($naw['companycoc']);
}
if(!empty($naw['dateofbirth'])){
// $db = preg_replace('/^(\d+)-(\d+)-(\d+)$/', '$3-$2-$1', $naw['dateofbirth']) . ' 00:00:00';
$db = new \DateTime($naw['dateofbirth'] . ' 00:00:00');
$User->setDateOfBirth($db);
}
if(isset($naw['gender'])){
$User->setGender($naw['gender']);
}
if(isset($naw['firstname'])){
$User->setFirstname($naw['firstname']);
}
if(isset($naw['lastname'])){
$User->setLastname($naw['lastname']);
}
if(isset($naw['street'])){
$User->setStreet($naw['street']);
}
if(isset($naw['number'])){
$User->setNumber($naw['number']);
}
if(isset($naw['number_add'])){
$User->setNumberAdd($naw['number_add']);
}
if(isset($naw['postalcode'])){
$User->setPostalcode($naw['postalcode']);
}
if(isset($naw['city'])){
$User->setCity($naw['city']);
}
if(isset($naw['country'])){
$User->setCountry($naw['country']);
}
if(isset($naw['phone'])){
$User->setPhone($naw['phone']);
}
// $User->setEmail($naw['email']);
$em = $this->getDoctrine()->getManager();
$em->persist($User);
$em->flush();
$savedProfile = true;
}
if(!empty($_GET['delete'])){
$Address = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Address')->find($_GET['delete']);
$em = $this->getDoctrine()->getManager();
$em->remove($Address);
$em->flush();
header('Location:' . $this->generateUrl($route));
exit;
}
if($request->request->get('postalcode') && $request->request->get('number')){
// $parsed_address = $this->postalcodeToAddress($request->request->get('postalcode'), $request->request->get('number'));
// if($parsed_address){
$Address = new \App\Trinity\WebshopBundle\Entity\Address();
$Address->setUser($WebshopUser);
$Address->setStreet($_POST['street']);
$Address->setNumber($_POST['number']);
$Address->setNumberAdd($_POST['number_add']);
$Address->setPostalcode($_POST['postalcode']);
$Address->setPlace($_POST['city']);
$Address->setCountry($_POST['country']);
$em = $this->getDoctrine()->getManager();
if($request->request->get('primary')){
$Address->setPriority(true);
$addresses = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Address')->findBy(['user' => $WebshopUser, 'priority' => true]);
foreach($addresses as $a){
$a->setPriority(false);
$em->persist($a);
}
}
$em->persist($Address);
$em->flush();
header('Location:' . $this->generateUrl($route));
exit;
// }
}
}
$countries_available = $this->getDoctrine()->getRepository('TrinityWebshopBundle:DeliveryMethod')->findAvailableCountries($Settings);
$locale_filter = strtoupper($this->language->getLocale());
if (in_array($locale_filter, $countries_available)) {
$country_list = [Countries::getName(strtoupper($locale_filter)) => $locale_filter];
} else {
$country_list = [];
}
foreach($countries_available as $cc){
if(!in_array($cc, $country_list)){
$country_list[Countries::getName(strtoupper($cc))] = $cc;
}
}
return $this->renderView('@TrinityWebshop/default/widget_profile.html.twig', $this->attributes([
'config' => $config,
'params' => $params,
'route' => $route,
'country_list' => $country_list,
'pwd_error' => $pwd_error,
'pwd_msg' => $pwd_msg,
'savedProfile' => $savedProfile,
'WebshopUser' => $WebshopUser,
'giftcard_success' => $giftcard_success,
'giftcard_warning' => $giftcard_warning,
'giftcard_error' => $giftcard_error,
]));
}
private function getWidgetCacheFile(string $hash) : string
{
$dir = $this->containerInterface->get('kernel')->getProjectDir() . '/var/cache/webshop/';
if(!file_exists($dir)){
mkdir($dir);
}
$subdir = substr($hash, 0, 2);
$dir = $dir . $subdir . '/';
if(!file_exists($dir)){
mkdir($dir);
}
return ($dir . $hash . '.widget.html');
}
/**
* Show bundle content to front
*
* @param array $config Array with configuration options
* @param array $params Additional parameters
*
* @return string HTML
*/
public function showAction($config, $params, Request $request)
{
// Initialize StorageController
parent::init($request);
$Webshop = $this->getDoctrine()->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($this->language, $this->Settings);
$Settings = $Webshop->getSettings();
switch ($config['view']) {
case 'category_masonry': return $this->widget_category_masonry($config, $params, $Settings, $request); break;
case 'products': return $this->widget_products($config, $params, $Settings, $request); break;
case 'newproducts': return $this->widget_newproducts($config, $params, $Settings, $request); break;
case 'subcategory': return $this->widget_subcategory($config, $params, $Settings, $request); break;
case 'categories': return $this->widget_categories($config, $params, $Settings, $request); break;
case 'latest': return $this->widget_latest($config, $params, $Settings, $request); break;
case 'featured': return $this->widget_featured($config, $params, $Settings, $request); break;
case 'discounted': return $this->widget_discounted($config, $params, $Settings, $request); break;
case 'popular': return $this->widget_popular($config, $params, $Settings, $request); break;
case 'searchwithcat': return $this->widget_searchwithcat($config, $params, $Settings, $request); break;
case 'homecats': return $this->widget_homecats($config, $params, $Settings, $request); break;
case 'choice_flow': return $this->widget_choice_flow($config, $params, $Settings, $request); break;
case 'profile': return $this->widget_profile($config, $params, $Settings, $request); break;
case 'profile_giftcards': return $this->widget_profile_giftcards($config, $params, $Settings, $request); break;
case 'profile_orders': return $this->widget_profile_orders($config, $params, $Settings, $request); break;
case 'profile_orders_finish': return $this->widget_profile_orders($config, $params, $Settings, $request, true); break;
case 'profile_lists': return $this->widget_profile_lists($config, $params, $Settings, $request); break;
}
return $this->renderView('@TrinityWebshop/default/front.html.twig', $this->attributes([]));
}
/**
* Return link data when required within the link form
*
* @param object Doctrine object
*
* @return array Array with config options
*/
public function getLinkData($em, $Language, $Container, $Settings){
$Webshop = $em->getRepository('TrinityWebshopBundle:Webshop')->getByLanguageAndSettings($Language, $Settings);
$categories = $em->getRepository('TrinityWebshopBundle:Category')->findByWebshop($Webshop);
$specs = $em->getRepository('TrinityWebshopBundle:Spec')->findBy([], ['label' => 'asc']);
return [
'categories' => $categories,
'Language' => $Language,
'specs' => $specs,
];
}
/**
* Show dashboard blocks
*
* @return array List of blocks
*/
public function dashboardBlocks(){
// Return block data to show on Trinity dashboard in the following format.
// You can do whatever you want in this function, just return data as below.
return [
[
'title' => 'Mijn lege module',
'class' => '',
'content' => '<div style="text-align:center;padding:20px;">Lege module</div>'
]
];
}
public static function resourcesHandler($Settings, array $bundledata, string $projectDir) : ?string
{
$resources = null;
$layoutKey = !empty($Settings->getOverrideKey()) ? trim($Settings->getOverrideKey()) . '/' : '';
$view = '';
if (isset($bundledata['view'])) {
$view = $bundledata['view'];
}
switch($view)
{
case 'categories':
case 'products':
case 'latest':
case 'homecat': // not used
case 'featured':
case 'discounted':
case 'popular':
case 'profile_lists':
$resource_file = 'resources_style_bootstrap.json';
break;
case 'profile':
case 'profile_orders':
case 'profile_orders': // && profile_orders_view && profile_orders_finish
$resource_file = 'resources_style.json';
break;
case 'category_masonry': // not used
case 'searchwithcat':
case 'subcategory':
default:
$resource_file = 'resources_empty.json';
break;
}
// check if file exists or build array in code and return that.
$file = __DIR__ . "/../Resources/views/default/" . $resource_file;
$override = $projectDir . '/public/custom/' . $layoutKey . 'webshop/' . $resource_file;
if (file_exists($override)) {
$resources = $override;
} else if (file_exists($file)) {
$resources = $file;
}
return $resources;
}
}