src/Controller/CartController.php line 418

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Pimcore\Controller\FrontendController;
  4. use Pimcore\Model\Asset\Image;
  5. use Pimcore\Mail;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Pimcore\Model\DataObject;
  9. use \Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  10. use PHPExcel_Writer_Excel2007;
  11. use Carbon\Carbon;
  12. use Pimcore\Model\Asset;
  13. use ZipArchive;
  14. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use App\Model\DataObject\BrandExtension;
  17. use PHPExcel;
  18. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  19. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  22. #require 'PHPExcel_1.8.0/Classes/PHPExcel.php';
  23. #require 'PHPExcel_1.8.0/Classes/PHPExcel/Writer/Excel2007.php';
  24. // class CartController extends \Website\Controller\CartAware
  25. /**
  26.      * @Route("/{_locale}/cart")    
  27. */
  28. class CartController extends CartAware
  29. {
  30.     const COMPANY_NAME = "BeamSuntory";
  31.     private $session;
  32.     private $trance;
  33.     public function __construct(SessionInterface $session, TranslatorInterface $trance)
  34.     {
  35.         $this->session = $session;
  36.         $this->trance = $trance;
  37.     }
  38.     /**
  39.      * show top navigation
  40.      */
  41.     public function topNavCartAction(Request $request)
  42.     {
  43.         $params = [];
  44.         $params['language'] = $request->getLocale();
  45.         $session = $request->getSession();
  46.         $authNamespace = $session->getBag('espirit');
  47.         if ($authNamespace->has('customeraccount')) {
  48.             $params['FirstName']  = $authNamespace->get('customeraccount')->getFirstName();
  49.             $params['LastName'] = $authNamespace->get('customeraccount')->getLastName();
  50.         }
  51.         $params['cart'] = $this->getCart();
  52.         return $this->render('Cart/topNavCart.html.twig',$params);
  53.         
  54.     }
  55.     /**
  56.      * show product landing
  57.      */
  58.     public function orderJsonAction(Request $request)
  59.     {
  60.         $orders = array();
  61.         $cart = $this->getCart();
  62.         if(count($cart->getItems()) == 0) {
  63.             echo json_encode($orders);
  64.             return;
  65.         }
  66.         $orderitems = array();
  67.         foreach($cart->getItems() as $item) {
  68.             $orderitems[] = array ( "id" => $item->getProduct()->getId(), "name" => $item->getProduct()->getOSName());
  69.         }
  70.         $orders["orderinfo"] = $orderitems;
  71.         //$authNamespace = new Zend_Session_Namespace('Zend_Auth');
  72.         $authNamespace = $this->get('session')->getBag('espirit');
  73.         if ($authNamespace->get('customeraccount')) {
  74.             $orders["customeraccount"] = $authNamespace->get('customeraccount');
  75.         }
  76.         $orders["downloadlink"] = $this->view->url(array('action' => 'delivery'), 'checkout'); 
  77.         echo @json_encode($orders);
  78.     }
  79.      /**
  80.      * @Route("/download", name="cart-download")
  81.      *
  82.      * @param Request $request
  83.      * 
  84.      */
  85.     public function downloadAction(Request $request)
  86.     {
  87.         
  88.         set_time_limit(6000);
  89.         ini_set('memory_limit', '1024M'); 
  90.         //$this->layout()->setLayout('cart');
  91.         //$this->enableLayout();
  92.         $params = [];
  93.         $params['locale'] = strtolower($request->getLocale());
  94.         $params['hideNav'] = true;
  95.         $cart = $this->getCart();
  96.         $params['cart'] = $cart;
  97.         $defaultCountry = DataObject\AvailabilityCountry::getByPath('/availability-countries/us');
  98.         if(isset($this->country)){
  99.             $availableCountry = $this->country;
  100.         }else{
  101.             $availableCountry = $defaultCountry;
  102.             $params['country'] = $defaultCountry;
  103.         }
  104.         //if cart empty, redirect to cart list
  105.         if(count($cart->getItems()) == 0) {
  106.             //$urlHelper = \Pimcore::getContainer()->get('pimcore.templating.view_helper.pimcore_url');  
  107.             //return $this->redirect($urlHelper(array('action' => 'list', 'prefix' => strtolower($this->locale)), 'cart', true));
  108.             return $this->redirectToRoute('shop-cart-detail');
  109.         }
  110.         $checkoutManager = Factory::getInstance()->getCheckoutManager( $cart );
  111.         $confirmStep = $checkoutManager->getCheckoutStep('confirm');
  112.         $checkoutManager->commitStep($confirmStep, true);
  113.         $order = $checkoutManager->commitOrder();
  114.         
  115.         //$authNamespace = new Zend_Session_Namespace('Zend_Auth');
  116.         //TODO
  117.         $fileformat = 'PNG'; //We will remove this after session implementation
  118.         $session = $request->getSession();
  119.         $authNamespace = $session->getBag('espirit');
  120.         
  121.         if ($authNamespace->get('photographyfileformat') == 'JPG') {
  122.             $fileformat = 'JPG';
  123.         } else {
  124.             $fileformat = 'PNG';
  125.         }
  126.         
  127.         //TODO
  128.         $dim = "original";  //We will remove this after session implementation
  129.         $thumbnail = ["format" => $fileformat]; //We will remove this AFTER fix line no 131
  130.         
  131.         if ($authNamespace->get('photographyfiledimension')) {
  132.             switch ($authNamespace->get('photographyfiledimension')) {
  133.                 case 'eSpirits_1':
  134.                     $thumbnail = ["format" => $fileformat];
  135.                     $dim = "original";
  136.                 break;
  137.                 case 'eSpirits_2':
  138.                     $thumbnail = ["width" => 750, "height" => 1500, "frame" => true, "format" => $fileformat];
  139.                     $dim = "750x1500";
  140.                 break;
  141.                 case 'eSpirits_3':
  142.                     $thumbnail = ["width" => 1000, "height" => 1000, "frame" => true, "format" => $fileformat];
  143.                     $dim = "1000x1000";
  144.                 break;
  145.                 case 'eSpirits_4':
  146.                     $thumbnail = ["width" => 1500, "height" => 1500, "frame" => true, "format" => $fileformat];
  147.                     $dim = "1500x1500";
  148.                 break;
  149.                 case 'eSpirits_5':
  150.                     $thumbnail = ["width" => 2000, "height" => 2000, "frame" => true, "format" => $fileformat];
  151.                     $dim = "2000x2000";
  152.                 break;
  153.                 case 'eSpirits_6':
  154.                     $thumbnail = ["width" => 2500, "height" => 2500, "frame" => true, "format" => $fileformat];
  155.                     $dim = "2500x2500";
  156.                 break;
  157.                 default:
  158.                     $thumbnail = ["format" => $fileformat];
  159.                     $dim = "original";
  160.                 break;
  161.             }
  162.         }
  163.         $order->setcountry($params['country']->getName());
  164.         //TODO
  165.         $order->setcustomer($authNamespace->get('customeraccount'));
  166.         $order->setdatafileformat($authNamespace->get('datafileformat'));
  167.         $order->setotheremail($authNamespace->get('otheremail'));
  168.         $order->setphotographyfileformat($authNamespace->get('photographyfileformat'));
  169.         //$order->setcustomer('Rohit');
  170.         $order->setdatafileformat($fileformat);
  171.         $order->setotheremail('assd.fff');
  172.         $order->setphotographyfileformat($authNamespace->get('photographyfileformat'));
  173.         $order->setphotographyfiledimension($dim);
  174.         $order->setordertype("cart");
  175.         $order->save();
  176.         //Get the order zip file
  177.         //TODO
  178.         
  179.         if ($authNamespace->get('customeraccount')) {
  180.             $params['firstname'] = $authNamespace->get('customeraccount')->getFirstName();
  181.             $params['lastname'] = $authNamespace->get('customeraccount')->getLastName();
  182.         }
  183.         
  184.         $params['firstname'] = '';
  185.         $params['lastname'] = '';
  186.         $excelfile = $this->create_download_file($order);
  187.         $orderdate = $order->getOrderDate();
  188.         $orderdate = Carbon::instance($orderdate);
  189.         //TODO
  190.         $downloadfilename = ((!empty($authNamespace->get('fileDownloadName'))) ? $authNamespace->get('fileDownloadName') : "Beam-Suntory_Product-Data") . "_" . $orderdate->format('Y-M-d') . "_" . $order->getId() . ".zip";
  191.         //$downloadfilename  = "Beam-Suntory_Product-Data" . "_" . $orderdate->format('Y-M-d') . "_" . $order->getId() . ".zip"; //WE will remove after fix LINE NO 196
  192.         $downloadfile = "/downloads/" . $order->getId() . "/{$downloadfilename}";
  193.         //Create the file
  194.         $downloaddir = realpath("downloads");
  195.         $downloadpath = "";
  196.         if (!file_exists($downloaddir . "/" . $order->getId())) {
  197.             mkdir($downloaddir . "/" . $order->getId(), 0777, true);
  198.         }
  199.         $downloadpath = $downloaddir . "/" . $order->getId() . "/{$downloadfilename}";
  200.         if (!empty($downloadpath)) {
  201.             $files_to_zip = array();
  202.             foreach ($order->getItems() as $item) {
  203.                 $product = $item->getProduct();
  204.                 //Get all the lifesize
  205.                 //TODO
  206.                 
  207.                 //Get all the bottle-size photos
  208.                 $sizeVariants = $product->getSizeVariants($this->country);
  209.                 if ($sizeVariants) {
  210.                     foreach($sizeVariants as $variant) {
  211.                         //if ($variant->getBottleSize() == '750 m') {
  212.                             $countries = $variant->getCountryAvailabilityList();
  213.                             $continue = 0;
  214.                             foreach ($countries as $country) {
  215.                                     if ($country->getObject()->getId() == $this->country->getId() && $country->geteSpiritsEnable() == 1) {
  216.                                         $continue = 1;
  217.                                         break;
  218.                                     }
  219.                             }
  220.                             if ($continue == 0) {
  221.                                 continue;
  222.                             }
  223.                             if ($variant->getBottlePhoto()) {
  224.                                 $files_to_zip[] = $variant->getBottlePhoto();
  225.                             }
  226.                             
  227.                             $additionalPhotos = $variant->getAdditionalPhotos();
  228.                     
  229.                             if(!empty($additionalPhotos))
  230.                             {
  231.                                 foreach($additionalPhotos as $a)
  232.                                 { 
  233.                                     $files_to_zip[] = $a['AdditionalPhoto']->getData();
  234.                                 }
  235.                             }
  236.                         }
  237.                     //}
  238.                 }
  239.                 
  240.                 /* Excluding Videos for now        
  241.                 $videos = $product->getVideoList();
  242.             
  243.                 if(!empty($videos))
  244.                 {
  245.                     foreach($videos as $v) //
  246.                     {
  247.                         $files_to_zip[] = sprintf("/website/var/assets%s", $v->getFullPath());
  248.                     }
  249.                 }
  250.                 */
  251.                 
  252.             }
  253.             for($i=0; $i<count($files_to_zip); $i++)
  254.             {
  255.                 {
  256.                     $asset = Asset::getByPath($files_to_zip[$i]);
  257.                     $tn = $asset->getThumbnail($thumbnail, false)->getLocalFile();
  258.                     $files_to_zip[$i] = $tn; // .form-group div -> clear: both; label for picks float: left
  259.                 }
  260.             }
  261.             
  262.             $files_to_zip[] = $excelfile;
  263.             //if true, good; if false, zip creation failed
  264.             if (count($files_to_zip) > 0) {
  265.                 $result = $this->create_zip($files_to_zip,$downloadpath,true);
  266.             }
  267.         }
  268.         
  269.         $params['downloadurl']  = $downloadfile;
  270.         $params['downloadfilename']  = $downloadfilename;
  271.         //Send the Email
  272.         //$params = array();
  273.         $params["order"] = $order;
  274.         $params["customer"] = $order->getCustomer();
  275.         $params["ordernumber"] = $order->getOrdernumber();
  276.         $size = "0. 0 KB";
  277.         if (file_exists($_SERVER['DOCUMENT_ROOT'] . $downloadfile)) {
  278.             $size = $this->filesize_formatted($_SERVER['DOCUMENT_ROOT'] . $downloadfile);
  279.         }
  280.         $params["filesize_formatted"] = $size;
  281.         
  282.         $mail = new Mail(array("document" => "/espirits/" . strtolower($this->locale) . "/emails/download-confirmation", "params" => $params));
  283.         
  284.         if($order->getCustomer()) {
  285.             $mail->setIgnoreDebugMode(true);
  286.             //$mail->setDefaultFrom("contact@beamsuntory.com","eSpirits Portal");
  287.             $mail->subject("Saudi Aramco Document Data Download | " . $order->getOrderDate()->format('YYYY-MM-dd') . " | " . $order->getId());
  288.             $mail->addTo($order->getCustomer()->getEmail());
  289.             //TODO
  290.             if ($authNamespace->get('otheremail')) {
  291.                 $toemails = explode(",", $authNamespace->get('otheremail'));
  292.                 foreach ($toemails as $toemail) {
  293.                     if (!empty( $toemail )) $mail->addTo( $toemail );
  294.                 }
  295.             }
  296.             #fix the email sending
  297.             //****$mail->send();
  298.         } else {
  299.             //TODO    We will be uncomment
  300.             //\Logger::err("No Customer found!");
  301.         }
  302.         // init
  303.         $params["order"] = \Pimcore\Model\DataObject\OnlineShopOrder::getById( $order->getId() );
  304.         //need to revisit
  305.         //**$itemKeyUniversal = \Pimcore\Bundle\EcommerceFrameworkBundle\CheckoutManager\CheckoutManager::TRACK_ECOMMERCE_UNIVERSAL . "_" . $order->getOrdernumber();
  306.         $itemKeyUniversal = 'checkout_trackecommerce_universal' . "_" . $order->getOrdernumber(); 
  307.         $environment = Factory::getInstance()->getEnvironment();
  308.         $codeUniversal = $environment->getCustomItem($itemKeyUniversal);
  309.         if(!empty($codeUniversal)) {
  310.             $params["gacodeUniversal"] = $codeUniversal;
  311.             $environment->removeCustomItem($itemKeyUniversal);
  312.             $environment->save();
  313.         }
  314.         return $this->render('Cart/download.html.twig', $params);
  315.     }
  316.     /**
  317.      * @Route("/list", name="shop-cart-detail", methods={"GET"})
  318.      *
  319.      * @param Request $request
  320.      * @param BreadcrumbHelperService $breadcrumbHelperService
  321.      * @param Factory $ecommerceFactory
  322.      *
  323.      */
  324.     public function listAction(Request $request,  Factory $ecommerceFactory): Response
  325.     {
  326.         // init view
  327.         //$this->layout()->setLayout('cart');
  328.         //$this->enableLayout();
  329.         $params = [];
  330.         $params['hideNav'] = true;
  331.         $params['locale'] = strtolower($request->getLocale());
  332.         $params['params'] = $request->request->all();
  333.         $params['preview'] = $request->get('pimcore_preview',null);
  334.         $defaultCountry = DataObject\AvailabilityCountry::getByPath('/availability-countries/us');
  335.         if(isset($this->country)){
  336.             $availableCountry = $this->country;
  337.         }else{
  338.             $availableCountry = $defaultCountry;
  339.             $params['country'] = $defaultCountry;
  340.         }
  341.         $cart = $this->getCart();
  342.         // sort by item count asc
  343.         //Todo item
  344.         // $cart->sortItems(function (\Pimcore\Bundle\EcommerceFrameworkBundle\CartManager\ICartItem $a, \Pimcore\Bundle\EcommerceFrameworkBundle\CartManager\ICartItem $b) {
  345.         //     return $a->getCount() > $b->getCount();
  346.         // });
  347.             
  348.         $cart = $this->getCart();
  349.         if ($request->getMethod() == Request::METHOD_POST) {
  350.             $items = $request->get('items');
  351.             foreach ($items as $itemKey => $quantity) {
  352.                 if ($cart->getItemCount() > 99) {
  353.                     break;
  354.                 }
  355.                 $product = BrandExtension::getById($itemKey);
  356.                 if ($product instanceof CheckoutableInterface) {
  357.                     $cart->updateItem($itemKey, $product, $quantity, true);
  358.                 }
  359.             }
  360.             $cart->save();
  361.             $trackingManager = $ecommerceFactory->getTrackingManager();
  362.             $trackingManager->trackCartUpdate($cart);
  363.         }
  364.         $params['cart'] = $cart;
  365.         //$breadcrumbHelperService->enrichCartPage();
  366.         //$params = array_merge($request->request->all(), $request->query->all());
  367.         if ($cart->isEmpty()) {
  368.             return $this->render('Cart/list.html.twig', $params);
  369.         } else {
  370.             return $this->render('Cart/list.html.twig', $params);
  371.         }
  372.     }
  373.     /**
  374.      * @Route("/add-to-cart", name="shop-add-to-cart")
  375.      *
  376.      * @param Request $request
  377.      * @param Factory $ecommerceFactory
  378.      *
  379.      * @throws \Exception
  380.      */
  381.     public function addAction(Request $request)
  382.     {
  383.         // add item to cart
  384.         if(($id = $request->get('item')))
  385.         {   
  386.             $product = DataObject\BrandExtension::getById( $id );
  387.             $prefix = $request->get('prefix');
  388.             /* @var \Website\DefaultProduct $product */
  389.             $qty = (int)$request->get('qty', 1);
  390.             if($product)
  391.             {
  392.                 $cart = $this->getCart();
  393.                 $cart->addItem( $product, $qty);
  394.                 $cart->save();
  395.             }
  396.             //$urlHelper = \Pimcore::getKernel()->getContainer()->get('pimcore.templating.view_helper.pimcore_url');
  397.             //$url = $urlHelper(array('action' => 'list'), 'cart');
  398.             //return $this->redirect( $url );
  399.             // $url = $this->generateUrl('shop-cart-detail');
  400.             
  401.             //return $this->redirectToRoute('shop-cart-detail');
  402.             $url = $this->generateUrl('shop-cart-detail');
  403.             
  404.             return $this->redirect($url);
  405.            
  406.         } else {
  407.             throw new \Exception("no item given to add to cart");
  408.         }
  409.     }
  410.     /**
  411.      * @Route("/remove-from-cart", name="shop-remove-from-cart")
  412.      */
  413.     public function removeAction(Request $request)
  414.     {
  415.         // remove item from cart
  416.         if(($id = $request->get('item')))
  417.         {
  418.             $cart = $this->getCart();
  419.             $cart->removeItem( $id );
  420.             $cart->save();
  421.             //$urlHelper = \Pimcore::getContainer()->get('pimcore.templating.view_helper.pimcore_url');  
  422.             //return $this->redirect( $urlHelper(array('action' => 'list'), 'cart') );
  423.             return $this->redirectToRoute('shop-cart-detail');
  424.         } else {
  425.             throw new \Exception("no item given to remove from cart");
  426.         }
  427.     }
  428.      /**
  429.      * @Route("/update", name="cart-update", methods={"GET"})
  430.      *
  431.      * @param Request $request
  432.      * @param Factory $ecommerceFactory
  433.      *
  434.      * @throws \Exception
  435.      */
  436.     public function updateAction(Request $request)
  437.     {
  438.         if($request->get("qty")) {
  439.             $cart = $this->getCart();
  440.             foreach($request->get("qty") as $key => $qty) {
  441.                 $product = Pimcore\Model\Object\Product::getById($key);
  442.                 if($product) {
  443.                     $cart->updateItem($key, $product, intval($qty), true);
  444.                     $cart->save();
  445.                 }
  446.             }
  447.         }
  448.         $url = $this->view->url(array('action' => 'list'), 'cart');
  449.         return $this->redirect( $url );
  450.     }
  451.     /**
  452.      * Adds a voucher token to cart, sets error messages and
  453.      * redirects to list action.
  454.      */
  455.     public function addVoucherAction(Request $request)
  456.     {
  457.         $cart = $this->getCart();
  458.         $voucherError = "";
  459.         if ($token = strip_tags($request->get('voucherToken'))) {
  460.             try {
  461.                 $success = $cart->addVoucherToken($token);
  462.                 if(!$success) {
  463.                     $voucherError = $this->view->t('cart.msg-error-token-couldnt-be-applied');
  464.                 }
  465.             } catch (\Pimcore\Bundle\EcommerceFrameworkBundle\Exception\VoucherServiceException $e) {
  466.                 $voucherError = $this->view->t('cart.msg-error.' . $e->getCode());
  467.             }
  468.         } else {
  469.             $voucherError = $this->view->t('cart.msg-error-token-missing');
  470.         }
  471.         $params = ["action" => "list", "prefix" => $this->locale];
  472.         if($voucherError) {
  473.             $params["voucherError"] = $voucherError;
  474.             $params["voucherToken"] = $token;
  475.         }
  476.         $url = $this->view->url($params, 'cart', true);
  477.         return $this->redirect($url);
  478.     }
  479.     /**
  480.      * Remove a voucher token from cart, sets error messages and
  481.      * redirects to list action.
  482.      */
  483.     public function releaseVoucherAction(Request $request)
  484.     {
  485.         $cart = $this->getCart();
  486.         $voucherError = "";
  487.         if ($code = $request->get('voucherToken')) {
  488.             try {
  489.                 $cart->removeVoucherToken($code);
  490.             } catch (\Pimcore\Bundle\EcommerceFrameworkBundle\Exception\VoucherServiceException $e){
  491.                 $voucherError = $this->view->t('cart.msg-error.' . $e->getCode());
  492.             }
  493.         } else {
  494.             $voucherError = $this->view->t('cart.msg-error-token-missing');
  495.         }
  496.         $url = $this->view->url(array('action' => 'list', 'voucherError' => $voucherError), 'cart');
  497.         return $this->redirect($url);
  498.     }
  499.     private function filesize_formatted($path)
  500.     {
  501.         $size = filesize($path);
  502.         $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  503.         $power = $size > 0 ? floor(log($size, 1024)) : 0;
  504.         return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
  505.     }
  506.     /* creates a compressed zip file */
  507.     function create_zip($files = array(),$destination = '',$overwrite = false) {
  508.         //if the zip file already exists and overwrite is false, return false
  509.         if(file_exists($destination)) { 
  510.             $overwrite = true; 
  511.         } else {
  512.             $overwrite = false; 
  513.         }
  514.         //vars
  515.         $valid_files = array();
  516.         //if files were passed in...
  517.         if(is_array($files)) {
  518.             //cycle through each file
  519.             foreach($files as $file) {
  520.                 //make sure the file exists
  521.                 if(file_exists($file)) {
  522.                     $valid_files[] = $file;
  523.                 }
  524.             }
  525.             
  526.         }
  527.         
  528.         //if we have good files...
  529.         if(count($valid_files)) {
  530.             //create the archive
  531.             $zip = new ZipArchive();
  532.             if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  533.                 return false;
  534.             }
  535.             //add the files
  536.             foreach($valid_files as $file) {
  537.                 $new_filename = substr($file,strrpos($file,'/') + 1);
  538.                 
  539.                 if (preg_match('#xlsx#', $file) === 0) {
  540.                     $new_filename = "assets/" . $new_filename;
  541.                     //$new_filename = "product-media/bottle-photos/" . $new_filename;
  542.                 }
  543.                 if(is_dir($file))
  544.                 {
  545.                     continue;
  546.                 }
  547.                 
  548.                 $zip->addFile($file, $new_filename);
  549.             }
  550.             //debug
  551.             //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  552.           
  553.             //close the zip -- done!
  554.             $zip->close();
  555.             
  556.             //check to make sure the file exists
  557.             return file_exists($destination);
  558.         }
  559.         else
  560.         {
  561.             return false;
  562.         }
  563.     }
  564.     function create_download_file($order) {
  565.         
  566.         //$objPHPExcel = new PHPExcel();
  567.         $objPHPExcel = new Spreadsheet();
  568.         
  569.         // Set properties
  570.         $pr = $objPHPExcel->getProperties();
  571.         $ttl = $this->trance->trans("espirits.export.title");
  572.         
  573.         //$pr->setCreator(self::COMPANY_NAME);
  574.         $pr->setLastModifiedBy(self::COMPANY_NAME);
  575.         $pr->setTitle($ttl);
  576.         $pr->setSubject($ttl);
  577.         $pr->setDescription($ttl);
  578.                 
  579.         // Write product info sheet.
  580.         $objPHPExcel->setActiveSheetIndex(0);
  581.         $sht = $objPHPExcel->getActiveSheet();
  582.         $sht->setTitle($this->trance->trans("espirits.export.Product Info"));
  583.         
  584.         $headers = array("ObjectType", "Brand", "BrandExtensionName", "BrandExtensionNameTrademark", "BottleSize", "BrandExtensionDiscontinued", "ABV", "ShortDescription", "FullDescription", "Aging", "BottlePhoto", "LifestylePhotoList", "OriginCountry", "OriginRegion", "AlcoholType", "FlavoringType", "PricingSegment", "WhyBuy1", "WhyBuy2", "WhyBuy3", "WhyBuy4", "WhyBuy5", "WhyBuy6", "WhyBuy7", "WhyBuy8", "Keywords1", "Keywords2", "Keywords3", "Keywords4", "Keywords5", "Keywords6", "Keywords7", "Keywords8", "Keywords9", "Keywords10", "Keywords11", "Keywords12", "Keywords13", "Keywords14", "Keywords15", "Keywords16", "Keywords17", "Keywords18", "Keywords19", "Keywords20", "Keywords21", "Keywords22", "Keywords23", "Keywords24", "Keywords25", "Keywords26", "Keywords27", "Keywords28", "Keywords29", "Keywords30", "GTIN", "Material", "Height", "Width", "Depth", "Weight", "BSIID", "modificationDate", "creationDate"); 
  585.         $this->country = DataObject\AvailabilityCountry::getByPath('/availability-countries/us');
  586.         //TODO Replace default country by lofined user by country
  587.         
  588.         if($this->country != "DE")
  589.         {
  590.             $headers = array_merge(array_slice($headers, 0, 7), array("Proof"), array_slice($headers, 7));
  591.         }
  592.         
  593.         $this->writeHeaders($sht, $headers);
  594.         
  595.         $counter = 1;
  596.         foreach ($order->getItems() as $item) {
  597.             $counter++;
  598.             $product = $item->getProduct();
  599.             
  600.             if ($this->locale == "de") 
  601.             {
  602.                 $this->create_excel_row_de($objPHPExcel, $product, "BrandExtension", $counter);
  603.             } else 
  604.             {
  605.                 $this->create_excel_row($objPHPExcel, $product, "BrandExtension", $counter);
  606.             }
  607.             
  608.             $sizeVariants = $product->getSizeVariants();
  609.             if ($sizeVariants) {
  610.                 foreach($sizeVariants as $variant) {
  611.                     $countries = $variant->getCountryAvailabilityList();
  612.                     $continue = 0;
  613.                     foreach ($countries as $country) {
  614.                             if ($country->getObjectId() == $this->country->getId() && $country->geteSpiritsEnable() == 1) {
  615.                                 $continue = 1;
  616.                                 break;
  617.                             }
  618.                     }
  619.                     if ($continue == 0) {
  620.                         continue;
  621.                     }
  622.                     $counter++;
  623.                     if ($this->country->getName() == "DE") {
  624.                         $this->create_excel_row_de($objPHPExcel, $variant, "BottleVariant", $counter);
  625.                     } else {
  626.                         $this->create_excel_row($objPHPExcel, $variant, "BottleVariant", $counter);
  627.                     }
  628.                 }
  629.             }
  630.         }
  631.         
  632.         $objPHPExcel->createSheet(1);
  633.         $objPHPExcel->setActiveSheetIndex(1);
  634.         $sht = $objPHPExcel->getActiveSheet();
  635.         $sht->setTitle($this->trance->trans("espirits.export.Recipes"));
  636.         
  637.         $this->writeHeaders($sht, array("Recipe Name", "Brand Extension Name", "Ingredients", "Preparation", "Recipe Image Path"));
  638.         
  639.         $ctr = 2;
  640.         
  641.         foreach($order->getItems() as $item)
  642.         {
  643.             $product = $item->getProduct();        
  644.                         
  645.         }
  646.         $objPHPExcel->setActiveSheetIndex(0);
  647.         
  648.         // Set properties
  649.         
  650.         
  651.         $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
  652.         
  653.         $objWriter->save($_SERVER['DOCUMENT_ROOT'] . "/downloads/excel/Products_Download_" . $order->getId() . ".xlsx");
  654.         return $_SERVER['DOCUMENT_ROOT'] . "/downloads/excel/Products_Download_" . $order->getId() . ".xlsx";
  655.     }
  656.     
  657.     
  658.     public function writeHeaders($sht, $hdrs)
  659.     {
  660.         $kv = "A";
  661.         foreach($hdrs as $h)
  662.         {
  663.             $sht->SetCellValue(sprintf("%s1", $kv), $this->trance->trans(sprintf("espirits.export.%s", $h)));
  664.             $kv++;
  665.         }
  666.     }
  667.     
  668.     public function removeHTML($s)
  669.     {
  670.         $rt = str_replace(array("<p>", "</p>"), array("", "\r\n"), $s);
  671.         $rt = preg_replace("/<\/?.*?>/", "", $rt);
  672.         $rt = html_entity_decode($rt, ENT_COMPAT | ENT_HTML401, "UTF-8");
  673.         
  674.         return $rt;
  675.     }
  676.     function create_excel_row($objPHPExcel, $product, $producttype, $counter)
  677.     {
  678.         $brandname = "";
  679.         $brandextname = "";
  680.         $brandextensionnametrademark = "";
  681.         $bottlesize = "";
  682.         $BrandExtensionDiscontinued = "";
  683.         $proof = "";
  684.         $abv = "";
  685.         $shortdesc = "";
  686.         $fulldesc = "";
  687.         $region  = "";
  688.         $country = "";
  689.         $alcoholtype = "";
  690.         $aging = "";
  691.         $lifestylephotos = "";
  692.         $bottlephotos = "";
  693.         $bottleGTIN = "";
  694.         $bottleBottleMaterial = "";
  695.         $bottleBottleHeight = "";
  696.         $bottleBottleWidth = "";
  697.         $bottleBottleDepth = "";
  698.         $bottleBottleWeight = "";
  699.     $flv = "";
  700.     $seg = "";
  701.         if ($producttype == "BrandExtension") {
  702.             $brandextname = $product->getName();
  703.             $brandextensionnametrademark = $product->getName();
  704.             $brand = $product->getBrand();
  705.             if ($brand) $brandname = $brand[0]->getObject()->getBrandName();
  706.                        
  707.             
  708.             $fulldesc = $product->getContent();
  709.             //Country Origin
  710.             
  711.             
  712.             $categories = $product->getCategories();
  713.             if ($categories) foreach ($categories as $category) {
  714.                 break;
  715.             }
  716.             if ($category) $alcoholtype = $category->getAlcoholType();
  717.             
  718.         } 
  719.         $objPHPExcel->getActiveSheet()->SetCellValue('A' . $counter, $this->trance->trans("espirits.export." . $producttype));
  720.         $objPHPExcel->getActiveSheet()->SetCellValue('B' . $counter, iconv("UTF-8", "ISO-8859-1//IGNORE", $brandname));
  721.         $objPHPExcel->getActiveSheet()->SetCellValue('C' . $counter, iconv("UTF-8", "ISO-8859-1//IGNORE", $brandextname));
  722.         $objPHPExcel->getActiveSheet()->SetCellValue('D' . $counter, iconv("UTF-8", "ISO-8859-1//IGNORE", $brandextensionnametrademark));      
  723.         // Existing code for keywords 1 and 2
  724.         
  725.         $objPHPExcel->getActiveSheet()->SetCellValue('E' . $counter, $product->getId());
  726.         //$create_date = new Zend_Date($product->getcreationDate());
  727.         $create_date = Carbon::createFromTimestamp($product->getcreationDate());
  728.         $create_date = $create_date->format("YYYY/MM/dd");
  729.         //$modify_date = new Zend_Date($product->getmodificationDate());
  730.         $modify_date = Carbon::createFromTimestamp($product->getmodificationDate());
  731.         $modify_date = $modify_date->format("YYYY/MM/dd");
  732.         $objPHPExcel->getActiveSheet()->SetCellValue('F' . $counter, $modify_date);
  733.         $objPHPExcel->getActiveSheet()->SetCellValue('G' . $counter, $create_date);
  734.     }
  735.     function create_excel_row_de($objPHPExcel, $product, $producttype, $counter)
  736.     {
  737.         $brandname = "";
  738.         $brandextname = "";
  739.         $brandextensionnametrademark = "";
  740.         $bottlesize = "";
  741.         $BrandExtensionDiscontinued = "";
  742.         $proof = "";
  743.         $abv = "";
  744.         $shortdesc = "";
  745.         $fulldesc = "";
  746.         $region  = "";
  747.         $country = "";
  748.         $alcoholtype = "";
  749.         $aging = "";
  750.         $lifestylephotos = "";
  751.         $bottlephotos = "";
  752.         $bottleGTIN = "";
  753.         $bottleBottleMaterial = "";
  754.         $bottleBottleHeight = "";
  755.         $bottleBottleWidth = "";
  756.         $bottleBottleDepth = "";
  757.         $bottleBottleWeight = "";
  758.         if ($producttype == "BrandExtension") {
  759.             $brandextname = $product->getBrandExtensionName();
  760.             $brandextensionnametrademark = $product->getBrandExtensionNameTrademark();
  761.             $brand = $product->getBrand();
  762.             if ($brand) $brandname = $brand[0]->getObject()->getBrandName();
  763.             if ($product->getBrandExtensionDiscontinued()) $BrandExtensionDiscontinued = "1";
  764.             $proof = $product->getProof();
  765.             $abv = $product->getABV();
  766.             $shortdesc = $product->getShortDescription();
  767.             $fulldesc = $product->getFullDescription();
  768.             //Country Origin
  769.             $region = $product->getOriginRegion();
  770.             $country = $product->getOriginCountry();
  771.             $countrydic = $product->getClass()->getFieldDefinition("OriginCountry")->getOptions();
  772.             foreach ($countrydic as $countrydicitem) {
  773.                 if ($countrydicitem['value'] == $country) {
  774.                     $country = $countrydicitem['key'];
  775.                     break;
  776.                 }
  777.             }
  778.             //Aging
  779.             $aging = $product->getAging();
  780.             //Pricing Segment
  781.             $segs = $product->PricingSegment;
  782.             if ($segs) foreach ($segs as $seg) {
  783.                 break;
  784.             }
  785.             if ($seg) $seg = $seg->getObject();
  786.             if ($seg) $seg = $seg->getPricingSegment();
  787.             //Flavoring Type
  788.             $flvs = $product->FlavoringType;
  789.             if ($flvs) foreach ($flvs as $flv) {
  790.                 break;
  791.             }
  792.             if ($flv) $flv = $flv->getObject();
  793.             if ($flv) $flv = $flv->getFlavoringType();
  794.             $categories = $product->getCategories();
  795.             if ($categories) foreach ($categories as $category) {
  796.                 break;
  797.             }
  798.             if ($category) $alcoholtype = $category->getAlcoholType();
  799.             //Get all the lifesize
  800.             if ($product->getLifestylePhotoList()) {
  801.                 foreach ($product->getLifestylePhotoList()->getItems() as $item) {
  802.                     if ($item && $item->getPhotoLifestyle() && $item->getPhotoLifestyle()->getFullPath()) {
  803.                         if (!empty($lifestylephotos)) $lifestylephotos .= ",";
  804.                         $lifestylephotos .= $item->getPhotoLifestyle()->getFullPath();
  805.                     }
  806.                 }
  807.             }
  808.         } else {
  809.             $bottlesize = $product->getBottleSize();
  810.             //Get all the bottle-size photos
  811.             $bottlephoto = $product->getBottlePhoto();
  812.             $bottlephotos = "";
  813.             if ($bottlephoto) $bottlephotos = $bottlephoto->getFilename();
  814.             $additionalPhotos = $product->getAdditionalPhotos();
  815.             if (!empty($additionalPhotos)) {
  816.                 foreach ($additionalPhotos as $a) {
  817.                     $bottlephotos .= "," . $a['AdditionalPhoto']->getData()->getFilename();
  818.                 }
  819.             }
  820.             $bottleGTIN = $product->getGTIN();
  821.             $bottleBottleMaterial = $product->getBottleMaterial();
  822.             $bottleBottleHeight = $product->getBottleHeight();
  823.             $bottleBottleWidth = $product->getBottleWidth();
  824.             $bottleBottleDepth = $product->getBottleDepth();
  825.             $bottleBottleWeight = $product->getBottleWeight();
  826.         }
  827.         $objPHPExcel->getActiveSheet()->SetCellValue('A' . $counter, $this->get('translator')->trans("espirits.export." . $producttype));
  828.         $objPHPExcel->getActiveSheet()->SetCellValue('B' . $counter, $brandname);
  829.         $objPHPExcel->getActiveSheet()->SetCellValue('C' . $counter, $brandextname);
  830.         $objPHPExcel->getActiveSheet()->SetCellValue('D' . $counter, $brandextensionnametrademark);
  831.         $objPHPExcel->getActiveSheet()->SetCellValue('E' . $counter, $bottlesize);
  832.         $objPHPExcel->getActiveSheet()->SetCellValue('F' . $counter, $BrandExtensionDiscontinued);
  833.         $objPHPExcel->getActiveSheet()->SetCellValue('G' . $counter, $abv);
  834.         $objPHPExcel->getActiveSheet()->SetCellValue('H' . $counter, $shortdesc);
  835.         $objPHPExcel->getActiveSheet()->SetCellValue('I' . $counter, $fulldesc);
  836.         $objPHPExcel->getActiveSheet()->SetCellValue('J' . $counter, $aging);
  837.         $objPHPExcel->getActiveSheet()->SetCellValue('K' . $counter, $bottlephotos);
  838.         $objPHPExcel->getActiveSheet()->SetCellValue('L' . $counter, $lifestylephotos);
  839.         $objPHPExcel->getActiveSheet()->SetCellValue('M' . $counter, $country);
  840.         $objPHPExcel->getActiveSheet()->SetCellValue('N' . $counter, $region);
  841.         $objPHPExcel->getActiveSheet()->SetCellValue('O' . $counter, $alcoholtype);
  842.         $objPHPExcel->getActiveSheet()->SetCellValue('P' . $counter, $flv);
  843.         $objPHPExcel->getActiveSheet()->SetCellValue('Q' . $counter, $seg);
  844.         $buyAlpha = array("R", "S", "T", "U", "V", "W", "X", "Y");
  845.         for ($i = 1; $i <= 8; $i++) {
  846.             if ($producttype == "BrandExtension") {
  847.                 $whybuy = "getWhyBuy" . $i;
  848.                 $whybuys = $product->$whybuy();
  849.                 if (is_null($whybuys)) {
  850.                     $whybuys = "";
  851.                 }
  852.                 $objPHPExcel->getActiveSheet()->SetCellValue($buyAlpha[$i - 1] . $counter, $whybuys);
  853.             } else {
  854.                 $objPHPExcel->getActiveSheet()->SetCellValue($buyAlpha[$i - 1] . $counter, "");
  855.             }
  856.         }
  857.         $keyAlpha = array("Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI");
  858.         for ($i = 1; $i <= 10; $i++) {
  859.             if ($producttype == "BrandExtension") {
  860.                 $keyword = "Keywords" . $i;
  861.                 $kwords = $product->localizedfields->items[$this->locale->toString()][$keyword];
  862.                 if (is_null($kwords)) {
  863.                     $keywords = "";
  864.                 }
  865.                 $objPHPExcel->getActiveSheet()->SetCellValue($keyAlpha[$i - 1] . $counter, $kwords);
  866.             } else {
  867.                 $objPHPExcel->getActiveSheet()->SetCellValue($keyAlpha[$i - 1] . $counter, "");
  868.             }
  869.         }
  870.         $objPHPExcel->getActiveSheet()->SetCellValue('AJ' . $counter, $bottleGTIN);
  871.         $objPHPExcel->getActiveSheet()->SetCellValue('AK' . $counter, $bottleBottleMaterial);
  872.         $objPHPExcel->getActiveSheet()->SetCellValue('AL' . $counter, $bottleBottleHeight);
  873.         $objPHPExcel->getActiveSheet()->SetCellValue('AM' . $counter, $bottleBottleWidth);
  874.         $objPHPExcel->getActiveSheet()->SetCellValue('AN' . $counter, $bottleBottleDepth);
  875.         $objPHPExcel->getActiveSheet()->SetCellValue('AO' . $counter, $bottleBottleWeight);
  876.         $objPHPExcel->getActiveSheet()->SetCellValue('AP' . $counter, $product->getId());
  877.         //$create_date = new Zend_Date($product->getcreationDate());
  878.         $create_date = Carbon::createFromTimestamp($product->getcreationDate());
  879.         $create_date = $create_date->format("YYYY/MM/dd");
  880.         //$modify_date = new Zend_Date($product->getmodificationDate());
  881.         $modify_date = Carbon::createFromTimestamp($product->getmodificationDate());
  882.         $modify_date = $modify_date->format("YYYY/MM/dd");
  883.         $objPHPExcel->getActiveSheet()->SetCellValue('AQ' . $counter, $modify_date);
  884.         $objPHPExcel->getActiveSheet()->SetCellValue('AR' . $counter, $create_date);
  885.     }
  886. }