/**
  * populate Source Object with meta data from Resource
  *
  * @param Smarty_Template_Source   $source    source object
  * @param Smarty_Internal_Template $_template template object
  */
 public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
 {
     Enlight()->Events()->notify('Profiler_Smarty_Render', new Enlight_Event_EventArgs(['name' => $source->name]));
     $uid = '';
     $sources = array();
     $components = explode('|', $source->name);
     $exists = true;
     foreach ($components as $component) {
         $s = Smarty_Resource::source(null, $source->smarty, $component);
         if ($s->type == 'php') {
             throw new SmartyException("Resource type {$s->type} cannot be used with the extends resource type");
         }
         $sources[$s->uid] = $s;
         $uid .= $s->filepath;
         if ($_template && $_template->smarty->compile_check) {
             $exists = $exists && $s->exists;
         }
     }
     $source->components = $sources;
     $source->filepath = $s->filepath;
     $source->uid = sha1($uid);
     if ($_template && $_template->smarty->compile_check) {
         $source->timestamp = $s->timestamp;
         $source->exists = $exists;
     }
     // need the template at getContent()
     $source->template = $_template;
 }
Esempio n. 2
0
 public function errorAction()
 {
     $error = $this->Request()->getParam('error_handler');
     if (!empty($error)) {
         if ($this->Front()->getParam('showException')) {
             $paths = array(Enlight()->Path(), Enlight()->AppPath(), Enlight()->OldPath());
             $replace = array('', Enlight()->App() . '/', '');
             $exception = $error->exception;
             $error_file = $exception->getFile();
             $error_file = str_replace($paths, $replace, $error_file);
             $error_trace = $error->exception->getTraceAsString();
             $error_trace = str_replace($paths, $replace, $error_trace);
             $this->View()->assign(array('exception' => $exception, 'error_message' => $exception->getMessage(), 'error_file' => $error_file, 'error_trace' => $error_trace));
         }
         $code = $error->exception->getCode();
         switch ($code) {
             case 404:
             case 401:
                 $this->Response()->setHttpResponseCode($code);
                 break;
             default:
                 $this->Response()->setHttpResponseCode(503);
                 break;
         }
         if ($this->View()->getAssign('success') !== null) {
             $this->Response()->setHttpResponseCode(200);
             $this->View()->clearAssign('exception');
             $this->View()->assign('message', $error->exception->getMessage());
         }
     }
 }
Esempio n. 3
0
 /**
  * @param Logger $log
  * @return mixed
  */
 public function logResults(Logger $log)
 {
     foreach (array_keys($this->results) as $event) {
         if (empty($this->results[$event][0])) {
             unset($this->results[$event]);
             continue;
         }
         $listeners = array();
         foreach (Enlight()->Events()->getListeners($event) as $listener) {
             $listener = $listener->getListener();
             if ($listener[0] === $this) {
                 continue;
             }
             if (is_array($listener) && is_object($listener[0])) {
                 $listener[0] = get_class($listener[0]);
             }
             if (is_array($listener)) {
                 $listener = implode('::', $listener);
             }
             $listeners[] = $listener;
         }
         $this->results[$event] = array(0 => $event, 1 => $this->utils->formatMemory(0 - $this->results[$event][1]), 2 => $this->utils->formatTime(0 - $this->results[$event][2]), 3 => $listeners);
     }
     $this->results = array_values($this->results);
     foreach ($this->results as $result) {
         $order[] = $result[2];
     }
     array_multisort($order, SORT_NUMERIC, SORT_DESC, $this->results);
     array_unshift($this->results, array('name', 'memory', 'time', 'listeners'));
     $label = 'Benchmark Events';
     $table = array($label, $this->results);
     $log->table($table);
 }
Esempio n. 4
0
 /**
  * Shows a category tree
  */
 public function indexAction()
 {
     $categoryTree = Shopware()->Modules()->sCategories()->sGetWholeCategoryTree();
     $additionalTrees = $this->getAdditionalTrees();
     $additionalTrees = Enlight()->Events()->filter('Shopware_Modules_Sitemap_indexAction', $additionalTrees, array('subject' => $this));
     $categoryTree = array_merge($categoryTree, $additionalTrees);
     $this->View()->sCategoryTree = $categoryTree;
 }
 /**
  * perform autocompletion suggestion
  * @param Enlight_Event_EventArgs $arguments
  * @return boolean
  */
 public function ajaxSearch(Enlight_Event_EventArgs $arguments)
 {
     if (!$this->Config()->get('boxalino_search_enabled')) {
         return null;
     }
     $this->init($arguments);
     Enlight()->Plugins()->Controller()->Json()->setPadding();
     $term = $this->getSearchTerm();
     if (empty($term)) {
         return false;
     }
     $requests = array();
     $offset = 0;
     $hitCount = $this->Helper()->getSearchLimit();
     $requests[] = $this->Helper()->newAutocompleteRequest($term, $hitCount);
     $requests = array_merge($requests, $this->createAutocompleteRequests($term, $offset, $hitCount));
     $responses = $this->Helper()->autocompleteAll($requests);
     $suggestions = $this->Helper()->getAutocompleteSuggestions($responses, $hitCount);
     $response = array_shift($responses);
     $sResults = $this->getAjaxResult($response);
     $router = Shopware()->Front()->Router();
     foreach ($sResults as $key => $result) {
         $sResults[$key]['name'] = $result['articleName'];
         $sResults[$key]['link'] = $router->assemble(array('controller' => 'detail', 'sArticle' => $result['articleID'], 'title' => $result['articleName']));
     }
     if (version_compare(Shopware::VERSION, '5.0.0', '>=')) {
         $this->View()->loadTemplate('frontend/search/ajax.tpl');
         $this->View()->addTemplateDir($this->Bootstrap()->Path() . 'Views/');
         $this->View()->extendsTemplate('frontend/ajax.tpl');
     } else {
         $this->View()->addTemplateDir($this->Bootstrap()->Path() . 'Views/');
         $this->View()->loadTemplate('frontend/ajax4.tpl');
     }
     $totalHitCount = count($sResults);
     if (isset($response->prefixSearchResult) && isset($response->prefixSearchResult->totalHitCount)) {
         $totalHitCount = $response->prefixSearchResult->totalHitCount;
     }
     if ($totalHitCount == 0) {
         $totalHitCount = $suggestions[0]['hits'];
     }
     $templateProperties = array_merge(array('sSearchRequest' => array('sSearch' => $term), 'sSearchResults' => array('sResults' => $sResults, 'sArticlesCount' => $totalHitCount, 'sSuggestions' => $suggestions), 'bxHasOtherItemTypes' => !empty($responses)), $this->extractAutocompleteTemplateProperties($responses, $hitCount));
     if ($this->Config()->get('boxalino_categoryautocomplete_enabled')) {
         foreach ($response->propertyResults as $propertyResult) {
             if ($propertyResult->name == 'categories') {
                 $propertyHits = array_map(function ($hit) {
                     $categoryId = preg_replace('/\\/.*/', '', $hit->label);
                     $categoryPath = Shopware()->Modules()->Categories()->sGetCategoryPath($categoryId);
                     return array('value' => $hit->value, 'label' => $hit->label, 'total' => $hit->totalHitCount, 'link' => $categoryPath);
                 }, $propertyResult->hits);
                 $templateProperties = array_merge(array('bxCategorySuggestions' => $propertyHits, 'bxCategorySuggestionTotal' => count($propertyHits)), $templateProperties);
                 break;
             }
         }
     }
     $this->View()->assign($templateProperties);
     return false;
 }
 /**
  * populate Source Object with meta data from Resource
  *
  * @param Smarty_Template_Source   $source    source object
  * @param Smarty_Internal_Template $_template template object
  */
 public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
 {
     Enlight()->Events()->notify('Profiler_Smarty_Render', new Enlight_Event_EventArgs(['name' => $source->name]));
     $source->filepath = $this->buildFilepath($source, $_template);
     if ($source->filepath !== false) {
         if (is_object($source->smarty->security_policy)) {
             $source->smarty->security_policy->isTrustedResourceDir($source->filepath);
         }
         $source->uid = sha1($source->filepath);
         if ($source->smarty->compile_check && !isset($source->timestamp)) {
             $source->timestamp = @filemtime($source->filepath);
             $source->exists = !!$source->timestamp;
         }
     }
 }
 /**
  * Compiles code for the {block} tag
  *
  * @param array  $args     array with attributes from parser
  * @param object $compiler compiler object
  * @return boolean true
  */
 public function compile($args, $compiler)
 {
     Enlight()->Events()->notify('Profiler_Smarty_Render_Block');
     // check and get attributes
     $_attr = $this->getAttributes($compiler, $args);
     $save = array($_attr, $compiler->parser->current_buffer, $compiler->nocache, $compiler->smarty->merge_compiled_includes, $compiler->merged_templates, $compiler->smarty->merged_templates_func, $compiler->template->properties, $compiler->template->has_nocache_code);
     $this->openTag($compiler, 'block', $save);
     if ($_attr['nocache'] == true) {
         $compiler->nocache = true;
     }
     // set flag for {block} tag
     $compiler->inheritance = true;
     // must merge includes
     $compiler->smarty->merge_compiled_includes = true;
     $compiler->parser->current_buffer = new _smarty_template_buffer($compiler->parser);
     $compiler->has_code = false;
     return true;
 }
Esempio n. 8
0
 /**
  * Index action - get searchterm from request (sSearch) and start search
  * @return void
  */
 public function indexAction()
 {
     Enlight()->Plugins()->Controller()->Json()->setPadding();
     $this->View()->loadTemplate('frontend/search/ajax.tpl');
     $term = $this->Request()->getParam('sSearch');
     $term = trim(stripslashes(html_entity_decode($term)));
     if (!$term || strlen($term) < Shopware()->Config()->MinSearchLenght) {
         return false;
     }
     /**@var $context ProductContextInterface*/
     $context = $this->get('shopware_storefront.context_service')->getProductContext();
     $criteria = $this->get('shopware_search.store_front_criteria_factory')->createAjaxSearchCriteria($this->Request(), $context);
     /**@var $result ProductSearchResult*/
     $result = $this->get('shopware_search.product_search')->search($criteria, $context);
     if ($result->getTotalCount() > 0) {
         $articles = $this->convertProducts($result);
         $this->View()->searchResult = $result;
         $this->View()->sSearchRequest = array("sSearch" => $term);
         $this->View()->sSearchResults = array("sResults" => $articles, "sArticlesCount" => $result->getTotalCount());
     }
 }
Esempio n. 9
0
 /**
  * Search for $term with shopware default search object
  * @param $term
  * @return bool Successfully ?
  */
 public function doSearch($term)
 {
     $adapter = Enlight()->Events()->filter('Shopware_Controllers_Frontend_Search_SelectAdapter', null);
     if (empty($adapter)) {
         $adapter = new Shopware_Components_Search_Adapter_Default(Shopware()->Db(), Shopware()->Cache(), new Shopware_Components_Search_Result_Default(), Shopware()->Config());
     }
     $search = new Shopware_Components_Search($adapter);
     $searchResults = $search->search($term, $this->getConfig());
     if ($searchResults !== false) {
         $resultCount = $searchResults->getResultCount();
         $resultArticles = $searchResults->getResult();
     } else {
         return false;
     }
     $basePath = $this->Request()->getScheme() . '://' . $this->Request()->getHttpHost() . $this->Request()->getBasePath();
     if (!empty($resultArticles)) {
         foreach ($resultArticles as &$result) {
             if (empty($result['type'])) {
                 $result['type'] = 'article';
             }
             if (!empty($result["mediaId"])) {
                 /**@var $mediaModel \Shopware\Models\Media\Media*/
                 $mediaModel = Shopware()->Models()->find('Shopware\\Models\\Media\\Media', $result["mediaId"]);
                 if ($mediaModel != null) {
                     $result["thumbNails"] = array_values($mediaModel->getThumbnails());
                     //deprecated just for the downward compatibility use the thumbNail Array instead
                     $result["image"] = $result["thumbNails"][1];
                 }
             }
             $result['link'] = $this->Front()->Router()->assemble(array('controller' => 'detail', 'sArticle' => $result['articleID'], 'title' => $result['name']));
         }
     }
     // Set result & count of result
     $this->setResults($resultArticles);
     $this->setCountResults($resultCount);
     return true;
 }
Esempio n. 10
0
    /**
     * Search for $term with shopware default search object
     * @param $term
     * @return bool Successfully ?
     */
    public function doSearch($term)
    {
        $adapter = Enlight()->Events()->filter('Shopware_Controllers_Frontend_Search_SelectAdapter',null);
        if (empty($adapter)){
            $adapter = new Shopware_Components_Search_Adapter_Default(Shopware()->Db(), Shopware()->Cache(), new Shopware_Components_Search_Result_Default(), Shopware()->Config());
        }
        $search = new Shopware_Components_Search($adapter);
        $searchResults = $search->search($term, $this->getConfig());

        if ($searchResults !== false) {
            $resultCount = $searchResults->getResultCount();
            $resultArticles = $searchResults->getResult();
        } else {
            return false;
        }

        $basePath = $this->Request()->getScheme() . '://' . $this->Request()->getHttpHost() . $this->Request()->getBasePath();

        if (!empty($resultArticles)) {
            foreach ($resultArticles as &$result) {
                if (empty($result['type'])) $result['type'] = 'article';
                if (!empty($result['image'])) {
                    $result['image'] = $basePath
                                     . '/media/image/thumbnail/' . $result['image']
                                     . '_57x57.'
                                     . $result['extension'];
                }
                $result['link'] = $this->Front()->Router()->assemble(array('controller' => 'detail', 'sArticle' => $result['articleID'], 'title' => $result['name']));
            }
        }

        // Set result & count of result
        $this->setResults($resultArticles);
        $this->setCountResults($resultCount);
        return true;
    }
Esempio n. 11
0
 /**
  * Logout account by ajax request
  */
 public function ajaxLogoutAction()
 {
     Enlight()->Plugins()->Controller()->Json()->setPadding();
     Shopware()->Session()->unsetAll();
     $this->refreshBasket();
 }
Esempio n. 12
0
 /**
  * listing action for asynchronous fetching listing pages
  * by infinite scrolling plugin
  */
 public function ajaxListingAction()
 {
     Enlight()->Plugins()->Controller()->Json()->setPadding();
     $categoryId = $this->Request()->getParam('sCategory');
     $pageIndex = $this->Request()->getParam('sPage');
     $context = $this->get('shopware_storefront.context_service')->getProductContext();
     $productStreamId = $this->findStreamIdByCategoryId($categoryId);
     if ($productStreamId) {
         /** @var \Shopware\Components\ProductStream\CriteriaFactoryInterface $factory */
         $factory = $this->get('shopware_product_stream.criteria_factory');
         $criteria = $factory->createCriteria($this->Request(), $context);
         /** @var \Shopware\Components\ProductStream\RepositoryInterface $streamRepository */
         $streamRepository = $this->get('shopware_product_stream.repository');
         $streamRepository->prepareCriteria($criteria, $productStreamId);
     } else {
         $criteria = $this->get('shopware_search.store_front_criteria_factory')->createAjaxListingCriteria($this->Request(), $context);
     }
     $articles = Shopware()->Modules()->Articles()->sGetArticlesByCategory($categoryId, $criteria);
     $articles = $articles['sArticles'];
     $this->View()->loadTemplate('frontend/listing/listing_ajax.tpl');
     $layout = Shopware()->Modules()->Categories()->getProductBoxLayout($categoryId);
     $this->View()->assign(array('sArticles' => $articles, 'pageIndex' => $pageIndex, 'productBoxLayout' => $layout));
 }
Esempio n. 13
0
 /**
  * Constructor
  */
 public function __construct($environment, $options = null)
 {
     Enlight($this);
     parent::__construct($environment, $options);
 }
Esempio n. 14
0
    /**
     * Default search
     */
    public function defaultSearchAction()
    {
        $term = urldecode(trim(strip_tags(htmlspecialchars_decode(stripslashes($this->Request()->sSearch)))));

        // Load search configuration
        $config = $this->getSearchConfiguration($term);

        // Check if we have a one to one match for ordernumber, then redirect
        $location = $this->searchFuzzyCheck($term);
        if (!empty($location)) {
            return $this->redirect($location);
        }

        $this->View()->loadTemplate('frontend/search/fuzzy.tpl');

        // Prepare links for template
        $links = $this->searchDefaultPrepareLinks($config);

        $minLengthSearchTerm = Shopware()->Config()->sMINSEARCHLENGHT;

        // Check if search term met minimum length
        if (strlen($term) >= (int)$minLengthSearchTerm) {
            // Configure search adapter
            $adapter = Enlight()->Events()->filter('Shopware_Controllers_Frontend_Search_SelectAdapter',null);
            if (empty($adapter)){
                $adapter = new Shopware_Components_Search_Adapter_Default(Shopware()->Db(), Shopware()->Cache(), new Shopware_Components_Search_Result_Default(), Shopware()->Config());
            }

            $search = new Shopware_Components_Search($adapter);
            // Submit search request
            $searchResults = $search->search($term, $config);
            // Initiate variables
            $resultCount = 0;
            $resultArticles = array();
            $resultSuppliersAffected = array();
            $resultPriceRangesAffected = array();
            $resultCurrentCategory = array();

            // If search has results
            if ($searchResults !== false) {
                $resultCount = $searchResults->getResultCount();
                $resultArticles = $searchResults->getResult();
                $resultSuppliersAffected = $searchResults->getAffectedSuppliers();
                $resultPriceRangesAffected = $searchResults->getAffectedPriceRanges();
                $resultAffectedCategories = $searchResults->getAffectedCategories();
                $resultCurrentCategory = $searchResults->getCurrentCategoryFilter();
            }

            // Update search statistics
            $this->updateSearchStatistics($term, $resultCount);

            // Generate page array
            $sPages = $this->generatePagesResultArray($resultCount, $config['resultsPerPage'], $config["currentPage"]);

            // Get additional information for each search result
            $articles = array();
            foreach ($resultArticles as $article) {
                $article = Shopware()->Modules()->Articles()->sGetPromotionById('fix', 0, (int)$article["articleID"]);
                if (!empty($article['articleID'])) {
                    $articles[] = $article;
                }
            }

            // todo@all Build old template base compatibility array
            $resultSmartyArray = array(
                'sArticles' => $articles,
                'sArticlesCount' => $resultCount,
                'sSuppliers' => $resultSuppliersAffected,
                'sPrices' => $resultPriceRangesAffected,
                'sCategories' => $resultAffectedCategories,
                'sLastCategory' => $resultCurrentCategory
            );


            // Assign result to template
            $this->View()->sRequests = $config;
            $this->View()->sSearchResults = $resultSmartyArray;
            $this->View()->sPerPage = array_values(explode("|", Shopware()->Config()->sFUZZYSEARCHSELECTPERPAGE));
            $this->View()->sLinks = $links;
            $this->View()->sPages = $sPages;
            $this->View()->sPriceFilter = $search->getAdapter()->getPriceRanges();

            Enlight()->Events()->notify('Shopware_Controllers_Frontend_Search_ModifySearchResult',array("subject" => $this,"search"=>$search,"result"=>$searchResults));

            $this->View()->sCategoriesTree = $this->getCategoryTree(
                $resultCurrentCategory, $config['restrictSearchResultsToCategory']
            );
        }
    }
 /**
  * Export the order
  */
 protected function exportOrder()
 {
     $VariantResource = self::getVariantApi();
     // Build the Request
     $Request_AddOrders = new PlentySoapRequest_AddOrders();
     $Request_AddOrders->Orders = array();
     //
     $Object_Order = new PlentySoapObject_Order();
     //
     $methodOfPayment = $this->getMethodOfPaymentId();
     if ($methodOfPayment == MOP_AMAZON_PAYMENT) {
         $externalOrderID = sprintf('Swag/%d/%s/%s', $this->Order->getId(), $this->Order->getNumber(), $this->Order->getTransactionId());
     } else {
         $externalOrderID = sprintf('Swag/%d/%s', $this->Order->getId(), $this->Order->getNumber());
     }
     $isOrderNet = (bool) $this->Order->getNet() || (bool) $this->Order->getTaxFree();
     // Order head
     $Object_OrderHead = new PlentySoapObject_OrderHead();
     $Object_OrderHead->Currency = PlentymarketsMappingController::getCurrencyByShopwareID($this->Order->getCurrency());
     $Object_OrderHead->CustomerID = $this->PLENTY_customerID;
     $Object_OrderHead->DeliveryAddressID = $this->PLENTY_addressDispatchID;
     $Object_OrderHead->ExternalOrderID = $externalOrderID;
     $Object_OrderHead->IsNetto = $isOrderNet;
     $Object_OrderHead->Marking1ID = PlentymarketsConfig::getInstance()->getOrderMarking1(null);
     $Object_OrderHead->MethodOfPaymentID = $this->getMethodOfPaymentId();
     $Object_OrderHead->OrderTimestamp = $this->getOrderTimestamp();
     $Object_OrderHead->OrderType = 'order';
     $Object_OrderHead->ResponsibleID = PlentymarketsConfig::getInstance()->getOrderUserID(null);
     $Object_OrderHead->ShippingCosts = $this->getShippingCosts();
     $Object_OrderHead->ShippingProfileID = $this->getParcelServicePresetId();
     $Object_OrderHead->StoreID = $this->getShopId();
     $Object_OrderHead->ReferrerID = $this->getReferrerId();
     $Object_Order->OrderHead = $Object_OrderHead;
     // Order infos
     $Object_OrderHead->OrderInfos = array();
     if ($Object_OrderHead->MethodOfPaymentID == MOP_DEBIT) {
         $Customer = $this->Order->getCustomer();
         if ($Customer) {
             $Debit = $Customer->getDebit();
             if ($Debit && $Debit->getAccountHolder()) {
                 $info = 'Account holder: ' . $Debit->getAccountHolder() . chr(10);
                 $info .= 'Bank name: ' . $Debit->getBankName() . chr(10);
                 $info .= 'Bank code: ' . $Debit->getBankCode() . chr(10);
                 $info .= 'Account number: ' . $Debit->getAccount() . chr(10);
                 $Object_OrderInfo = new PlentySoapObject_OrderInfo();
                 $Object_OrderInfo->Info = $info;
                 $Object_OrderInfo->InfoCustomer = 0;
                 $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
                 $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
             }
             $PaymentInstances = $Customer->getPaymentInstances();
             if ($PaymentInstances) {
                 foreach ($PaymentInstances as $PaymentInstance) {
                     if ($this->Order->getId() === $PaymentInstance->getOrder()->getId()) {
                         $Object_BankData = new PlentySoapObject_BankData();
                         $Object_BankData->OwnerFirstname = $PaymentInstance->getFirstName();
                         $Object_BankData->OwnerLastname = $PaymentInstance->getLastName();
                         $Object_BankData->BankName = $PaymentInstance->getBankName();
                         $Object_BankData->IBAN = $PaymentInstance->getIban();
                         $Object_BankData->BIC = $PaymentInstance->getBic();
                         $Object_SetBankCreditCardData = new PlentySoapObject_SetBankCreditCardData();
                         $Object_SetBankCreditCardData->CustomerID = $this->PLENTY_customerID;
                         $Object_SetBankCreditCardData->BankData = $Object_BankData;
                         $Request_SetBankCreditCardData = new PlentySoapRequest_SetBankCreditCardData();
                         $Request_SetBankCreditCardData->CustomerData[] = $Object_SetBankCreditCardData;
                         $Response_SetBankCreditCardData = PlentymarketsSoapClient::getInstance()->SetBankCreditCardData($Request_SetBankCreditCardData);
                         if (!$Response_SetBankCreditCardData->Success) {
                             // Set the error end quit
                             $this->setError(self::CODE_ERROR_SOAP);
                             throw new PlentymarketsExportEntityException('The order with the number »' . $this->Order->getNumber() . '« could not be exported');
                         }
                     }
                 }
             }
         }
     }
     if ($this->Order->getInternalComment()) {
         $Object_OrderInfo = new PlentySoapObject_OrderInfo();
         $Object_OrderInfo->Info = $this->Order->getInternalComment();
         $Object_OrderInfo->InfoCustomer = 0;
         $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
         $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
     }
     if ($this->Order->getCustomerComment()) {
         $Object_OrderInfo = new PlentySoapObject_OrderInfo();
         $Object_OrderInfo->Info = $this->Order->getCustomerComment();
         $Object_OrderInfo->InfoCustomer = 1;
         $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
         $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
     }
     if ($this->Order->getComment()) {
         $Object_OrderInfo = new PlentySoapObject_OrderInfo();
         $Object_OrderInfo->Info = $this->Order->getComment();
         $Object_OrderInfo->InfoCustomer = 1;
         $Object_OrderInfo->InfoDate = $this->getOrderTimestamp();
         $Object_OrderHead->OrderInfos[] = $Object_OrderInfo;
     }
     $Object_Order->OrderItems = array();
     /** @var Shopware\Models\Order\Detail $Item */
     foreach ($this->Order->getDetails() as $Item) {
         $number = $Item->getArticleNumber();
         $itemText = '';
         // Variant
         try {
             $itemId = null;
             try {
                 // get the detail id by the order number
                 $articleDetailID = $VariantResource->getIdFromNumber($Item->getArticleNumber());
             } catch (Exception $E) {
                 $articleDetailID = -1;
             }
             // get the sku from the detail id
             $sku = PlentymarketsMappingController::getItemVariantByShopwareID($articleDetailID);
         } catch (PlentymarketsMappingExceptionNotExistant $E) {
             // Base item
             try {
                 $itemId = PlentymarketsMappingController::getItemByShopwareID($Item->getArticleId());
                 $sku = null;
             } catch (PlentymarketsMappingExceptionNotExistant $E) {
                 $itemId = -2;
                 $sku = null;
                 // Mandatory because there will be no mapping to any item
                 $itemText = $Item->getArticleName();
             }
         }
         //
         if ($itemId > 0 || !empty($sku)) {
             if (PlentymarketsConfig::getInstance()->getOrderItemTextSyncActionID(EXPORT_ORDER_ITEM_TEXT_SYNC) == EXPORT_ORDER_ITEM_TEXT_SYNC) {
                 $itemText = $Item->getArticleName();
             } else {
                 $itemText = null;
             }
         }
         // Coupon
         if ($Item->getMode() == 2) {
             $itemId = -1;
             $rowType = 'Coupon';
         }
         // Additional coupon identifiers für 3rd party plugins
         $couponIdentifiers = PyConf()->get('OrderAdditionalCouponIdentifiers', '');
         $couponIdentifiers = explode('|', $couponIdentifiers);
         if (in_array($number, $couponIdentifiers)) {
             $itemId = -1;
             $rowType = 'Coupon';
         } else {
             // PAYONE fix
             if ($number == 'SHIPPING' && !$Object_OrderHead->ShippingCosts) {
                 $Object_OrderHead->ShippingCosts = $Item->getPrice();
                 continue;
             }
             $discountNumber = Shopware()->Config()->get('discountnumber');
             $surchargeNumber = Shopware()->Config()->get('surchargenumber');
             $paymentSurchargeNumber = Shopware()->Config()->get('paymentsurchargenumber');
             $paymentSurchargeAbsoluteNumber = Shopware()->Config()->get('paymentSurchargeAbsoluteNumber');
             $shippingDiscountNumber = Shopware()->Config()->get('shippingdiscountnumber');
             switch ($number) {
                 case $paymentSurchargeNumber:
                 case $paymentSurchargeAbsoluteNumber:
                     $rowType = 'SurchargeForPaymentMethod';
                     break;
                 case $discountNumber:
                     $rowType = 'Discount';
                     break;
                 case $surchargeNumber:
                     $rowType = 'Surcharge';
                     break;
                 case $shippingDiscountNumber:
                     $rowType = 'SurchargeForShippingMethod';
                     break;
                 default:
                     $rowType = 'Default';
                     break;
             }
         }
         if ($isOrderNet) {
             // Calculate the gross amount (needed by plentymakets even though it is a net sales order)
             $itemPrice = $Item->getPrice() * ((100 + (double) $Item->getTaxRate()) / 100);
         } else {
             $itemPrice = $Item->getPrice();
         }
         $Object_OrderItem = new PlentySoapObject_OrderItem();
         $Object_OrderItem->ExternalOrderItemID = $number;
         $Object_OrderItem->ItemID = $itemId;
         $Object_OrderItem->ReferrerID = $Object_OrderHead->ReferrerID;
         $Object_OrderItem->ItemText = $itemText;
         $Object_OrderItem->Price = $itemPrice;
         $Object_OrderItem->Quantity = $Item->getQuantity();
         $Object_OrderItem->SKU = $sku;
         $Object_OrderItem->VAT = $Item->getTaxRate();
         $Object_OrderItem->RowType = $rowType;
         $Object_Order->OrderItems[] = $Object_OrderItem;
     }
     $Request_AddOrders->Orders[] = $Object_Order;
     // Allow plugins to change the data
     $Request_AddOrders = Enlight()->Events()->filter('PlentyConnector_ExportEntityOrder_BeforeAddOrders', $Request_AddOrders, array('subject' => $this, 'order' => $this->Order));
     // Do the request
     $Response_AddOrders = PlentymarketsSoapClient::getInstance()->AddOrders($Request_AddOrders);
     if (!$Response_AddOrders->Success) {
         // Set the error end quit
         $this->setError(self::CODE_ERROR_SOAP);
         throw new PlentymarketsExportEntityException('The order with the number »' . $this->Order->getNumber() . '« could not be exported', 4010);
     }
     //
     $plentyOrderID = null;
     $plentyOrderStatus = 0.0;
     foreach ($Response_AddOrders->ResponseMessages->item[0]->SuccessMessages->item as $SuccessMessage) {
         switch ($SuccessMessage->Key) {
             case 'OrderID':
                 $plentyOrderID = (int) $SuccessMessage->Value;
                 break;
             case 'Status':
                 $plentyOrderStatus = (double) $SuccessMessage->Value;
                 break;
         }
     }
     if ($plentyOrderID && $plentyOrderStatus) {
         $this->setSuccess($plentyOrderID, $plentyOrderStatus);
     } else {
         // Set the error end quit
         $this->setError(self::CODE_ERROR_SOAP);
         throw new PlentymarketsExportEntityException('The order with the number »' . $this->Order->getNumber() . '« could not be exported (no order id or order status respectively)', 4020);
     }
     $paymentStatusPaid = explode('|', PlentymarketsConfig::getInstance()->getOrderPaidStatusID(12));
     // Directly book the incoming payment
     if ($this->Order->getPaymentStatus() && in_array($this->Order->getPaymentStatus()->getId(), $paymentStatusPaid)) {
         // May throw an exception
         $IncomingPayment = new PlentymarketsExportEntityOrderIncomingPayment($this->Order->getId());
         $IncomingPayment->book();
     }
 }
Esempio n. 16
0
 /**
  * Insert basket discount
  * Used only internally in sBasket::sGetBasket()
  */
 public function sInsertDiscount()
 {
     // Get possible discounts
     $getDiscounts = $this->db->fetchAll('
         SELECT basketdiscount, basketdiscountstart
             FROM s_core_customergroups_discounts
             WHERE groupID = ?
             ORDER BY basketdiscountstart ASC', array($this->sSYSTEM->sUSERGROUPDATA["id"]));
     $this->db->query('DELETE FROM s_order_basket WHERE sessionID = ? AND modus = 3', array($this->session->get('sessionId')));
     // No discounts
     if (!count($getDiscounts)) {
         return;
     }
     $sql = 'SELECT SUM(quantity*(floor(price * 100 + .55)/100)) AS totalAmount
           FROM s_order_basket
           WHERE sessionID = ? AND modus != 4
           GROUP BY sessionID';
     $params = array($this->session->get('sessionId'));
     $sql = Enlight()->Events()->filter('Shopware_Modules_Basket_InsertDiscount_FilterSql_BasketAmount', $sql, array('subject' => $this, 'params' => $params));
     $basketAmount = $this->db->fetchOne($sql, $params);
     // If no articles in basket, return
     if (!$basketAmount) {
         return;
     }
     // Iterate through discounts and find nearly one
     foreach ($getDiscounts as $discountRow) {
         if ($basketAmount < $discountRow["basketdiscountstart"]) {
             break;
         } else {
             $basketDiscount = $discountRow["basketdiscount"];
         }
     }
     if (!$basketDiscount) {
         return;
     }
     $discount = $basketAmount / 100 * $basketDiscount;
     $discount = $discount * -1;
     $discount = round($discount, 2);
     $taxMode = $this->config->get('sTAXAUTOMODE');
     if (!empty($taxMode)) {
         $tax = $this->getMaxTax();
     } else {
         $tax = $this->config->get('sDISCOUNTTAX');
     }
     $taxAutoMode = $this->config->get("sTAXAUTOMODE");
     if (!empty($taxAutoMode)) {
         $tax = $this->getMaxTax();
     }
     if (!$tax) {
         $tax = 19;
     }
     if (!$this->sSYSTEM->sUSERGROUPDATA["tax"] && $this->sSYSTEM->sUSERGROUPDATA["id"]) {
         $discountNet = $discount;
     } else {
         $discountNet = round($discount / (100 + $tax) * 100, 3);
     }
     $this->sSYSTEM->sUSERGROUPDATA["basketdiscount"] = $basketDiscount;
     $discountNumber = $this->config->get('sDISCOUNTNUMBER');
     $name = isset($discountNumber) ? $discountNumber : "DISCOUNT";
     $discountName = -$basketDiscount . ' % ' . $this->snippetManager->getNamespace('backend/static/discounts_surcharges')->get('discount_name');
     $this->db->insert('s_order_basket', array('sessionID' => $this->session->get('sessionId'), 'articlename' => $discountName, 'articleID' => 0, 'ordernumber' => $name, 'quantity' => 1, 'price' => $discount, 'netprice' => $discountNet, 'tax_rate' => $tax, 'datum' => date("Y-m-d H:i:s"), 'modus' => 3, 'currencyFactor' => $this->sSYSTEM->sCurrency["factor"]));
 }
Esempio n. 17
0
 /**
  * @param array $element
  * @param Repository $repository
  * @param int $categoryId
  * @return array
  */
 protected function handleElement(array &$element, Repository $repository, $categoryId)
 {
     $component = $element['component'];
     $elementQuery = $repository->getElementDataQuery($element['id'], $element['componentId']);
     $componentData = $elementQuery->getArrayResult();
     $data = array();
     $data["objectId"] = md5($element["id"]);
     //we have to iterate the component data to decode the values.
     foreach ($componentData as $entry) {
         switch (strtolower($entry['valueType'])) {
             case "json":
                 if ($entry['value'] != '') {
                     $value = Zend_Json::decode($entry['value']);
                 } else {
                     $value = null;
                 }
                 break;
             case "string":
             default:
                 $value = $entry['value'];
                 break;
         }
         $data[$entry['name']] = $value;
     }
     $data = Enlight()->Events()->filter('Shopware_Controllers_Widgets_Emotion_AddElement', $data, array('subject' => $this, 'element' => $element));
     if (!empty($component['convertFunction'])) {
         $convertFunction = $component['convertFunction'];
         $data = $this->{$convertFunction}($data, $categoryId, $element);
     }
     return $data;
 }
Esempio n. 18
0
 /**
  * Validates the shipping informations
  *
  * @return array - shipping data with error flags and msg
  */
 public function validateShipping()
 {
     $countryData = $this->admin->sGetCountryList();
     $countryIds = array_column($countryData, 'id');
     $rules = array('salutation' => array('required' => 1), 'company' => array('required' => 0), 'firstname' => array('required' => 1), 'lastname' => array('required' => 1), 'street' => array('required' => 1), 'streetnumber' => array('required' => 1), 'zipcode' => array('required' => 1), 'city' => array('required' => 1), 'department' => array('required' => 0), 'text1' => array('required' => 0), 'text2' => array('required' => 0), 'text3' => array('required' => 0), 'text4' => array('required' => 0), 'text5' => array('required' => 0), 'text6' => array('required' => 0));
     if (Shopware()->Config()->get('sCOUNTRYSHIPPING')) {
         $rules['country'] = array('required' => 1, 'in' => $countryIds);
         // Check if state selection is required
         if (!empty($this->post["shipping"]["country"])) {
             $stateSelectionRequired = Shopware()->Db()->fetchRow("SELECT display_state_in_registration, force_state_in_registration\n                    FROM s_core_countries WHERE id = ?", array($this->post["shipping"]["country"]));
             if ($stateSelectionRequired["display_state_in_registration"]) {
                 $countryDataIndex = array_search($this->post["shipping"]["country"], $countryIds);
                 $statesIds = array_column($countryData[$countryDataIndex]['states'], 'id');
                 // if not required, allow empty values
                 if (!$stateSelectionRequired["force_state_in_registration"]) {
                     $statesIds[] = "";
                 }
                 $rules["stateID"] = array("required" => $stateSelectionRequired["force_state_in_registration"], 'in' => $statesIds);
             }
             $this->post["shipping"]["stateID"] = $this->post["shipping"]["country_shipping_state_" . $this->post["shipping"]["country"]];
             unset($this->post["shipping"]["country_shipping_state_" . $this->post["shipping"]["country"]]);
         }
     }
     $rules = Enlight()->Events()->filter('Shopware_Controllers_Frontend_Register_validateShipping_FilterRules', $rules, array('subject' => $this));
     $this->admin->sSYSTEM->_POST = $this->post['shipping'];
     $checkData = $this->admin->sValidateStep2ShippingAddress($rules);
     return $checkData;
 }
Esempio n. 19
0
    /**
     * The getEmotions function selects all emotions for the passed category id
     * and sets the result into the view variable "sEmotions".
     */
    public function indexAction()
    {
        /**@var $repository \Shopware\Models\Emotion\Repository*/
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Emotion\Emotion');
        $emotions = $this->getEmotion($repository);
        //iterate all emotions to select the element data.

        foreach ($emotions as &$emotion) {
            //for each emotion we have to iterate the elements to get the element data.
            foreach ($emotion['elements'] as &$element) {
                $component = $element['component'];
                $elementQuery = $repository->getElementDataQuery($element['id'], $element['componentId']);
                $componentData = $elementQuery->getArrayResult();
                $data = array();
                $data["objectId"] = md5($element["id"]);
                //we have to iterate the component data to decode the values.
                foreach ($componentData as $entry) {
                    $value = '';
                    switch (strtolower($entry['valueType'])) {
                        case "json":
                            $value = Zend_Json::decode($entry['value']);
                            break;
                        case "string":
                        default:
                            $value = $entry['value'];
                            break;
                    }
                    $data[$entry['name']] = $value;
                }

                // todo@all Event setzen für Custom-Elements ?
                $data = Enlight()->Events()->filter('Shopware_Controllers_Widgets_Emotion_AddElement', $data, array('subject' => $this, 'element' => $element));

                if (!empty($component['convertFunction'])) {
                    $data = $this->$component['convertFunction']($data, $this->Request()->getParam('categoryId'), $element);
                }

                $element['data'] = $data;

            }
            //print_r($emotions);exit;
        }

        $this->View()->assign('categoryId', (int)$this->Request()->getParam('categoryId'));
        $this->View()->assign('sEmotions', $emotions, true);
        $this->View()->assign('Controller', (string)$this->Request()->getParam('controllerName'));
    }
Esempio n. 20
0
 /**
  * Get all pictures from a certain article
  * @param        $sArticleID
  * @param bool $onlyCover
  * @param int $pictureSize | unused variable
  * @param string $ordernumber
  * @param bool $allImages | unused variable
  * @param bool $realtime | unused variable
  * @param bool $forceMainImage | will return the main image no matter which variant restriction is set
  * @return array
  */
 public function sGetArticlePictures($sArticleID, $onlyCover = true, $pictureSize = 0, $ordernumber = null, $allImages = false, $realtime = false, $forceMainImage = false)
 {
     static $articleAlbum;
     if ($articleAlbum === null) {
         //now we search for the default article album of the media manager, this album contains the thumbnail configuration.
         /**@var $model \Shopware\Models\Media\Album*/
         $articleAlbum = $this->getMediaRepository()->getAlbumWithSettingsQuery(-1)->getOneOrNullResult();
     }
     //first we convert the passed article id into an integer to prevent sql injections
     $articleId = (int) $sArticleID;
     Enlight()->Events()->notify('Shopware_Modules_Articles_GetArticlePictures_Start', array('subject' => $this, 'id' => $articleId));
     //first we get the article cover
     if ($forceMainImage) {
         $cover = $this->getArticleMainCover($articleId, $articleAlbum);
     } else {
         $cover = $this->getArticleCover($articleId, $ordernumber, $articleAlbum);
     }
     if ($onlyCover) {
         $cover = Enlight()->Events()->filter('Shopware_Modules_Articles_GetArticlePictures_FilterResult', $cover, array('subject' => $this, 'id' => $articleId));
         return $cover;
     }
     //now we select all article images of the passed article id.
     $articleImages = $this->getArticleRepository()->getArticleImagesQuery($articleId)->getArrayResult();
     //if an order number passed to the function, we have to select the configured variant images
     $variantImages = array();
     if (!empty($ordernumber)) {
         $variantImages = $this->getArticleRepository()->getVariantImagesByArticleNumberQuery($ordernumber)->getArrayResult();
     }
     //we have to collect the already added image ids, otherwise the images
     //would be displayed multiple times.
     $addedImages = array($cover['id']);
     $images = array();
     //first we add all variant images, this images has a higher priority as the normal article images
     foreach ($variantImages as $variantImage) {
         //if the image wasn't added already, we can add the image
         if (!in_array($variantImage['id'], $addedImages)) {
             //first we have to convert the image data, to resolve the image path and get the thumbnail configuration
             $image = $this->getDataOfArticleImage($variantImage, $articleAlbum);
             //after the data was converted we add the image to the result array and add the id to the addedImages array
             $images[] = $image;
             $addedImages[] = $variantImage['id'];
         }
     }
     //after the variant images added, we can add the normal images, this images has a lower priority as the variant images
     foreach ($articleImages as $articleImage) {
         //add only normal images without any configuration
         //if the image wasn't added already, we can add the image
         if (!in_array($articleImage['id'], $addedImages)) {
             //first we have to convert the image data, to resolve the image path and get the thumbnail configuration
             $image = $this->getDataOfArticleImage($articleImage, $articleAlbum);
             //after the data was converted we add the image to the result array and add the id to the addedImages array
             $images[] = $image;
             $addedImages[] = $articleImage['id'];
         }
     }
     $images = Enlight()->Events()->filter('Shopware_Modules_Articles_GetArticlePictures_FilterResult', $images, array('subject' => $this, 'id' => $articleId));
     return $images;
 }
Esempio n. 21
0
 /**
  * Generic error handling controller action
  */
 public function genericErrorAction()
 {
     $response = $this->Response();
     $errorCode = $this->Request()->getParam('code', 503);
     $response->setHttpResponseCode($errorCode);
     $error = $this->Request()->getParam('error_handler');
     /**
      * If the system is configured to display the exception data, we need
      * to pass it to the template
      */
     if ($this->Front()->getParam('showException') || $this->Request()->getModuleName() == 'backend') {
         $paths = array(Enlight()->Path(), Enlight()->AppPath(), Enlight()->OldPath());
         $replace = array('', Enlight()->App() . '/', '');
         $exception = $error->exception;
         $error_file = $exception->getFile();
         $error_file = str_replace($paths, $replace, $error_file);
         $error_trace = $error->exception->getTraceAsString();
         $error_trace = str_replace($paths, $replace, $error_trace);
         $this->View()->assign(array('exception' => $exception, 'error_message' => $exception->getMessage(), 'error_file' => $error_file, 'error_trace' => $error_trace));
     } else {
         /**
          * Prevent sending error code 503 because of an exception,
          * if it's not configured that way
          */
         $response->unsetExceptions();
     }
     if ($this->View()->getAssign('success') !== null) {
         $this->Response()->setHttpResponseCode(200);
         $this->View()->clearAssign('exception');
         $this->View()->assign('message', $error->exception->getMessage());
     }
 }
Esempio n. 22
0
 /**
  * Recreate shopware search index
  *
  * @param Shopware_Components_Cron_CronJob $job
  * @return void
  */
 public function onCronJobSearch(Shopware_Components_Cron_CronJob $job)
 {
     $adapter = Enlight()->Events()->filter('Shopware_Controllers_Frontend_Search_SelectAdapter', null);
     if (empty($adapter)) {
         $adapter = new Shopware_Components_Search_Adapter_Default(Shopware()->Db(), Shopware()->Cache(), new Shopware_Components_Search_Result_Default(), Shopware()->Config());
     }
     //$adapter = new Shopware_Components_Search_Adapter_Default(Shopware()->Db(), Shopware()->Cache(), new Shopware_Components_Search_Result_Default(), Shopware()->Config());
     $adapter->buildSearchIndex();
 }
Esempio n. 23
0
    /**
     *  Saves current order
     *
     * @return String
     */
    public function mySaveOrder() {
        $myComment = stripslashes(Shopware()->Session()->sOrderVariables['sComment']);
        $myComment = stripcslashes($myComment);
        $shopid = Shopware()->Shop()->getId();
        $sql = "SELECT isocode FROM s_core_multilanguage WHERE id = ?";
        $isocode = Shopware()->Db()->fetchOne($sql, array((int)$shopid));
        $sql = "SELECT defaultcurrency FROM s_core_multilanguage WHERE id = ?";
        $currencyid = Shopware()->Db()->fetchOne($sql, array((int)$shopid));
        $sql = "SELECT currency FROM s_core_currencies WHERE id = ?";
        $currency = Shopware()->Db()->fetchOne($sql, array((int)$currencyid));
        $sql = "SELECT factor FROM s_core_currencies WHERE id = ?";
        $faktor = Shopware()->Db()->fetchOne($sql, array((int)$currencyid));
        $pi_paymorrow_user = $this->getUser();
        $pi_paymorrow_basket = $this->getBasket();
        if (!$pi_paymorrow_basket["sShippingcostsWithTax"]) $pi_paymorrow_basket["sShippingcostsWithTax"] = "0";
        if (!$pi_paymorrow_basket["sShippingcostsNet"]) $pi_paymorrow_basket["sShippingcostsNet"] = "0";
        if (!$pi_paymorrow_basket["AmountNumeric"]) $pi_paymorrow_basket["AmountNumeric"] = $pi_paymorrow_basket["AmountNetNumeric"];
        $pi_paymorrow_basket["AmountNetNumeric"] = round($pi_paymorrow_basket["AmountNetNumeric"], 2);
        // Check if tax-free        
        $sqlData = "SELECT id, tax FROM s_core_customergroups WHERE groupkey = ?";
        $dataUserGroups = Shopware()->Db()->fetchRow($sqlData, array($pi_paymorrow_user["additional"]["user"]["customergroup"]));
        $net = $dataUserGroups['tax'];
        $id = $dataUserGroups['id'];
        
        
        if ((Shopware()->Config()->Articlesoutputnetto && !$net) || (!$net && $id)) {
            $taxfree = "0";
            if (!$net) {
                // Complete net delivery
                $net = "1";
                $pi_paymorrow_basket["AmountNumeric"] = $pi_paymorrow_basket["AmountNetNumeric"];
                $pi_paymorrow_basket["sShippingcostsWithTax"] = $pi_paymorrow_basket["sShippingcostsNet"];
                $taxfree = "1";
            }
        }
        else {
            $net = "0";
            $taxfree = "0";
        }

        //unset($this->sSYSTEM->_SESSION["sPartner"]);
        if (empty(Shopware()->Session()->sOrderVariables['sPartner'])) {
            //"additional"]["user"]
            $pid = $pi_paymorrow_user["additional"]["user"]["affiliate"];

            if (!empty($pid) && $pid != "0") {
                // Get Partner code
                $partner = Shopware()->Db()->fetchOne("
                    SELECT idcode FROM s_emarketing_partner WHERE id = ?
                    ", array($pid)
                );
            }
            else {
                $partner = "";
            }
        }
        else {
            $partner = Shopware()->Session()->sOrderVariables['sPartner'];
        }
        if (Shopware()->Session()->sOrderVariables['sDispatch']['id']) {
            $dispatchId = Shopware()->Session()->sOrderVariables['sDispatch']['id'];
        }
        else {
            $dispatchId = "0";
        }
       if(!Shopware()->Session()->sOrderVariables['sReferer'])Shopware()->Session()->sOrderVariables['sReferer']="";

       $sql = "
          INSERT INTO s_order (
            ordernumber, 
            userID, 
            invoice_amount,
            invoice_amount_net, 
            invoice_shipping,
            invoice_shipping_net, 
            ordertime, 
            status, 
            cleared, 
            paymentID, 
            transactionID, 
            customercomment, 
            net,
            taxfree, 
            partnerID,
            temporaryID,
            referer,
            language,
            dispatchID,
            currency,
            currencyFactor,
            subshopID,
            remote_addr)
          VALUES (
          ".Shopware()->Db()->quote((string) Shopware()->Session()->orderNumber).",
           ".$pi_paymorrow_user["additional"]["user"]["id"].",
           ".$pi_paymorrow_basket["AmountNumeric"].",
           ".$pi_paymorrow_basket["AmountNetNumeric"].",
           ".floatval($pi_paymorrow_basket["sShippingcostsWithTax"]).",
           ".floatval($pi_paymorrow_basket["sShippingcostsNet"]).",
           now(),
           -1,
           -1,
           ".$pi_paymorrow_user["additional"]["user"]["paymentID"].",
           '',
           ".Shopware()->Db()->quote($myComment).",
           $net,
           $taxfree,
           ".Shopware()->Db()->quote((string) $partner).",
           ".Shopware()->Db()->quote((string) Shopware()->Session()->hash).",
           ".Shopware()->Db()->quote((string) Shopware()->Session()->sOrderVariables['sReferer']).",
           '".$isocode."',
           '$dispatchId',
           'EUR',
           '".$faktor."',
           '".Shopware()->Shop()->getId()."',
           ".Shopware()->Db()->quote((string) $_SERVER['REMOTE_ADDR'])."
          )
        ";
        Shopware()->Db()->query($sql);
        $insertedOrderId = Shopware()->Db()->lastInsertId('s_order');
        //new attribute table with shopware 4
        $attributeSql = "INSERT INTO s_order_attributes (orderID, attribute1, attribute2, attribute3, attribute4, attribute5, attribute6)
                VALUES (
                    " . $insertedOrderId  .",
                    ".Shopware()->Db()->quote((string) '').",
                    ".Shopware()->Db()->quote((string) '').",
                    ".Shopware()->Db()->quote((string) '').",
                    ".Shopware()->Db()->quote((string) '').",
                    ".Shopware()->Db()->quote((string) '').",
                    ".Shopware()->Db()->quote((string) '')."
                )";
        $attributeSql = Enlight()->Events()->filter('Shopware_Modules_Order_SaveOrderAttributes_FilterSQL', $attributeSql, array('subject'=>$this));
            
        Shopware()->Db()->exec($attributeSql);
        
        $position = 0;
        foreach ($pi_paymorrow_basket["content"] as $basketRow) {
            $position++;
            $amountRow = $this->myFormatPrice($basketRow["priceNumeric"] * $basketRow["quantity"]);

            if (!$basketRow["price"]) $basketRow["price"] = "0,00";
            if (!$amountRow) $amountRow = "0,00";

            $basketRow["articlename"] = str_replace("<br />", "\n", $basketRow["articlename"]);
            $basketRow["articlename"] = html_entity_decode($basketRow["articlename"]);
            $basketRow["articlename"] = strip_tags($basketRow["articlename"]);

            if (!$basketRow["itemInfo"]) {
                $priceRow = $basketRow["price"];
            }
            else {
                $priceRow = $basketRow["itemInfo"];
            }

            //Bundle-Article
            if ($basketRow["modus"] == 10) {
                $sqlBundleTax = "
                    SELECT `taxID`
                    FROM `s_articles_bundles`
                    WHERE `ordernumber` = ?
                ";
                $bundleTax = Shopware()->Db()->fetchOne($sqlBundleTax, array($basketRow["ordernumber"]));
                if (!empty($bundleTax)) $basketRow["taxID"] = $bundleTax;
            }

            $basketRow["articlename"] = $this->myOptimizeText($basketRow["articlename"]);

            if (!$basketRow["esdarticle"]) {
                $basketRow["esdarticle"] = "0";
            }
            if (!$basketRow["modus"]) {
                $basketRow["modus"] = "0";
            }
            if (!$basketRow["taxID"]) {
                $basketRow["taxID"] = "0";
            }
            if ($net == true) {
                $basketRow["taxID"] = "0";
            }
            $orderIdSql = "SELECT id FROM s_order WHERE ordernumber  = ?";
            $orderID = Shopware()->Db()->fetchOne($orderIdSql, array(Shopware()->Session()->orderNumber));
            $orderNumber = Shopware()->Session()->orderNumber;
            $sql = "
               INSERT INTO s_order_details
                (orderID,
                ordernumber,
                articleID,
                articleordernumber,
                price,
                quantity,
                name,
                status,
                releasedate,
                modus,
                esdarticle,
                taxID
                )
                VALUES (
                $orderID,
                ".Shopware()->Db()->quote((string) $orderNumber).",
                {$basketRow["articleID"]},
                '{$basketRow["ordernumber"]}',
                {$basketRow["priceNumeric"]},
                {$basketRow["quantity"]},
                '".addslashes($basketRow["articlename"])."',
                0,
                '0000-00-00',
                {$basketRow["modus"]},
                {$basketRow["esdarticle"]},
                {$basketRow["taxID"]}
               )";
            $sql = Enlight()->Events()->filter('Shopware_Modules_Order_SaveOrder_FilterDetailsSQL', $sql, array(
                'subject' => $this,
                'row' => $basketRow,
                'user' => $pi_paymorrow_user,
                'order' => array(
                    "id" => $orderID,
                    "number" => $orderNumber
            )));
                        
            // Check for individual voucher - code
            if ($basketRow["modus"] == 2) {
                // $basketRow["articleID"] => s_emarketing_voucher_codes.id
                // $basketRow["ordernumber"] => Check mode
                $getVoucher = Shopware()->Db()->fetchRow("
                    SELECT modus,id FROM s_emarketing_vouchers
                    WHERE ordercode=?
                    ", array($basketRow["ordernumber"])
                );

                if ($getVoucher["modus"] == 1) {
                    // Update Voucher - Code
                    $updateVoucher = Shopware()->Db()->query("
                        UPDATE s_emarketing_voucher_codes
                        SET cashed = 1, userID= ?
                        WHERE id = ?
                        ", array($pi_paymorrow_user["additional"]["user"]["id"], $basketRow["articleID"])
                    );
                }
            }

            if ($basketRow["esdarticle"]) $esdOrder = true;

            Shopware()->Db()->query($sql);
            
            $orderdetailsID = Shopware()->Db()->lastInsertId('s_order_details');
            //new attribute tables
            $attributeSql = "INSERT INTO s_order_details_attributes (detailID, attribute1, attribute2, attribute3, attribute4, attribute5, attribute6)
                             VALUES ("
                             .$orderdetailsID. "," .
                             Shopware()->Db()->quote((string) $basketRow["ob_attr1"]).",".
                             Shopware()->Db()->quote((string) $basketRow["ob_attr2"]).",".
                             Shopware()->Db()->quote((string) $basketRow["ob_attr3"]).",".
                             Shopware()->Db()->quote((string) $basketRow["ob_attr4"]).",".
                             Shopware()->Db()->quote((string) $basketRow["ob_attr5"]).",".
                             Shopware()->Db()->quote((string) $basketRow["ob_attr6"]).
            ")";
            $attributeSql = Enlight()->Events()->filter('Shopware_Modules_Order_SaveOrderAttributes_FilterDetailsSQL', 
                $attributeSql, 
                array('subject'=>$this,'row'=>$basketRow,'user'=>$pi_paymorrow_user,'order'=>array("id"=>$orderID,"number"=>$orderNumber)));
            Shopware()->Db()->exec($attributeSql);

            // Update sales and stock
            if ($basketRow["priceNumeric"] >= 0 && !$basketRow["esdarticle"]) {
                $sql =  "UPDATE s_articles_details
                    SET sales   = sales + ?,
                        instock = instock - ?
                    WHERE ordernumber = ?";
                Shopware()->Db()->query($sql, array( $basketRow["quantity"], $basketRow["quantity"], $basketRow["ordernumber"]));
            }
            $deactivateInstock = Shopware()->Config()->deactivateNoInStock;
            
            if (!empty($basketRow["laststock"]) && !empty($deactivateInstock) && !empty($basketRow['articleID'])) {
                $sql = 'SELECT MAX(instock) as max_instock FROM s_articles_details WHERE articleID=?';
                $max_instock = Shopware()->Db()->fetchOne($sql, array($basketRow['articleID']));
                $max_instock = (int) $max_instock;
                if ($max_instock <= 0) {
                    $sql = 'UPDATE s_articles SET active=0 WHERE id=?';
                    Shopware()->Db()->query($sql, array($basketRow['articleID']));
                    // Ticket #5517
                    Shopware()->Db()->query("
                        UPDATE s_articles_details SET active = 0 WHERE ordernumber = ?
                        ", array($basketRow['ordernumber'])
                    );
                }
            }

            // For esd-articles, assign serialnumber if needed
            // Check if this article is esd-only (check in variants, too -> later)
            if ($basketRow["esdarticle"]) {
                Shopware()->Modules()->Order()->sManageEsdOrder($basketRow, $orderID, $orderdetailsID);
            } // If article is marked as esd-article
        } // For every artice in basket
        Enlight()->Events()->notify('Shopware_Modules_Order_SaveOrder_ProcessDetails', array(
            'subject' => $this,
            'details' => $pi_paymorrow_basket["content"]
        ));
    }
Esempio n. 24
0
 /**
  * Get list of all promotions from a certain category
  * @param int $category category id
  * @access public
  * @return array
  */
 public function sGetPromotions($category)
 {
     $category = intval($category);
     $sToday = date("Y-m-d");
     $sql = "\n\t\t\tSELECT category,mode, TRIM(ordernumber) as ordernumber, link, description, link_target, img\n\t\t\tFROM s_emarketing_promotions\n\t\t\tWHERE category={$category} AND ((TO_DAYS(valid_from) <= TO_DAYS('{$sToday}') AND\n\t\t\tTO_DAYS(valid_to) >= TO_DAYS('{$sToday}')) OR\n\t\t\t(valid_from='0000-00-00' AND valid_to='0000-00-00')) ORDER BY position ASC\n\t\t";
     $sql = Enlight()->Events()->filter('Shopware_Modules_Articles_GetPromotions_FilterSQL', $sql, array('subject' => $this, 'category' => $category));
     $getAffectedPromitions = $this->sSYSTEM->sDB_CONNECTION->GetAll($sql);
     // Clearing cache
     unset($this->sCachePromotions);
     if (count($getAffectedPromitions)) {
         foreach ($getAffectedPromitions as $promotion) {
             switch ($promotion["mode"]) {
                 case "random":
                     $promotion = $this->sGetPromotionById("random", $category);
                     if (count($promotion) > 1) {
                         $promote[] = $promotion;
                     }
                     break;
                 case "fix":
                     $promotion = $this->sGetPromotionById("fix", 0, $promotion["ordernumber"]);
                     if (count($promotion) > 1) {
                         $promote[] = $promotion;
                     }
                     break;
                 case "new":
                     $promotion = $this->sGetPromotionById("new", $category);
                     if (count($promotion) > 1) {
                         $promote[] = $promotion;
                     }
                     break;
                 case "top":
                     $promotion = $this->sGetPromotionById("top", $category);
                     if (count($promotion) > 1) {
                         $promote[] = $promotion;
                     }
                     break;
                 case "gfx":
                     $promotion = $this->sGetPromotionById("gfx", $category, $promotion);
                     if (count($promotion) > 1) {
                         $promote[] = $promotion;
                     }
                     break;
                 case "livefix":
                     break;
                 case "liverand":
                     break;
                 case "liverandcat":
                     break;
             }
             // end switch
         }
         // end foreach
         $promote = Enlight()->Events()->filter('Shopware_Modules_Articles_GetPromotions_FilterResult', $promote, array('subject' => $this, 'category' => $category));
         return $promote;
     }
     // end if
 }
 /**
  * Set the base details
  */
 protected function setDetails()
 {
     // Shipping time
     $shippingTime = PlentymarketsUtils::getShippingTimeByAvailabilityId($this->ItemBase->Availability->AvailabilityID);
     // Active
     $active = $this->ItemBase->Availability->Inactive == 0 && $this->ItemBase->Availability->Webshop == 1;
     $details = array('active' => $active, 'ean' => $this->ItemBase->EAN1, 'minPurchase' => null, 'purchaseSteps' => null, 'maxPurchase' => null, 'purchaseUnit' => null, 'referenceUnit' => null, 'shippingtime' => $shippingTime, 'packUnit' => trim($this->ItemBase->PriceSet->Unit1), 'releaseDate' => $this->ItemBase->Published == 0 ? null : date('c', $this->ItemBase->Published), 'weight' => null, 'width' => null, 'len' => null, 'height' => null, 'attribute' => null);
     if (PlentymarketsConfig::getInstance()->getItemFreetextsImportActionID(IMPORT_ITEM_FREETEXTS) == 1) {
         $details['attribute'] = array('attr1' => $this->ItemBase->FreeTextFields->Free1, 'attr2' => $this->ItemBase->FreeTextFields->Free2, 'attr3' => $this->ItemBase->FreeTextFields->Free3, 'attr4' => $this->ItemBase->FreeTextFields->Free4, 'attr5' => $this->ItemBase->FreeTextFields->Free5, 'attr6' => $this->ItemBase->FreeTextFields->Free6, 'attr7' => $this->ItemBase->FreeTextFields->Free7, 'attr8' => $this->ItemBase->FreeTextFields->Free8, 'attr9' => $this->ItemBase->FreeTextFields->Free9, 'attr10' => $this->ItemBase->FreeTextFields->Free10, 'attr11' => $this->ItemBase->FreeTextFields->Free11, 'attr12' => $this->ItemBase->FreeTextFields->Free12, 'attr13' => $this->ItemBase->FreeTextFields->Free13, 'attr14' => $this->ItemBase->FreeTextFields->Free14, 'attr15' => $this->ItemBase->FreeTextFields->Free15, 'attr16' => $this->ItemBase->FreeTextFields->Free16, 'attr17' => $this->ItemBase->FreeTextFields->Free17, 'attr18' => $this->ItemBase->FreeTextFields->Free18, 'attr19' => $this->ItemBase->FreeTextFields->Free19, 'attr20' => $this->ItemBase->FreeTextFields->Free20);
     }
     if ($this->ItemBase->Availability->MinimumSalesOrderQuantity > 0) {
         $details['minPurchase'] = $this->ItemBase->Availability->MinimumSalesOrderQuantity;
     }
     if ($this->ItemBase->Availability->IntervalSalesOrderQuantity > 0) {
         $details['purchaseSteps'] = $this->ItemBase->Availability->IntervalSalesOrderQuantity;
     }
     if ($this->ItemBase->Availability->MaximumSalesOrderQuantity > 0) {
         $details['maxPurchase'] = $this->ItemBase->Availability->MaximumSalesOrderQuantity;
     }
     if ($this->ItemBase->PriceSet->Lot > 0) {
         $details['purchaseUnit'] = $this->ItemBase->PriceSet->Lot;
     }
     if ($this->ItemBase->PriceSet->PackagingUnit > 0) {
         $details['referenceUnit'] = $this->ItemBase->PriceSet->PackagingUnit;
     }
     if ($this->ItemBase->PriceSet->WeightInGramm > 0) {
         $details['weight'] = $this->ItemBase->PriceSet->WeightInGramm / 1000;
     }
     if ($this->ItemBase->PriceSet->WidthInMM > 0) {
         $details['width'] = $this->ItemBase->PriceSet->WidthInMM / 10;
     }
     if ($this->ItemBase->PriceSet->LengthInMM > 0) {
         $details['len'] = $this->ItemBase->PriceSet->LengthInMM / 10;
     }
     if ($this->ItemBase->PriceSet->HeightInMM > 0) {
         $details['height'] = $this->ItemBase->PriceSet->HeightInMM / 10;
     }
     if (strlen($this->ItemBase->PriceSet->Unit)) {
         try {
             $details['unitId'] = PlentymarketsMappingController::getMeasureUnitByPlentyID($this->ItemBase->PriceSet->Unit);
         } catch (PlentymarketsMappingExceptionNotExistant $E) {
             $details['unitId'] = null;
         }
     }
     // Allow plugins to change the details
     $details = Enlight()->Events()->filter('PlentyConnector_ImportEntityItem_AfterSetDetails', $details, array('subject' => $this, 'itembase' => $this->ItemBase, 'shop' => $this->Shop));
     $this->details = $details;
 }
Esempio n. 26
0
 /**
  * Commit form via email (default) or database (ticket  system)
  *
  * @throws Enlight_Exception
  * @return void
  */
 public function commitForm()
 {
     /** @var Enlight_Components_Mail $mail */
     $mail = $this->get('mail');
     //Email field available check
     foreach ($this->_elements as $element) {
         if ($element['typ'] == "email") {
             $postEmail = $this->_postData[$element['id']];
             $postEmail = trim($postEmail);
         }
     }
     if (!empty($postEmail)) {
         $mail->setReplyTo($postEmail);
     }
     $content = $this->View()->sSupport;
     $mailBody = $content["email_template"];
     foreach ($this->_postData as $key => $value) {
         if ($this->_elements[$key]['typ'] == "text2") {
             $names = explode(";", $this->_elements[$key]['name']);
             $mailBody = str_replace("{sVars." . $names[0] . "}", $value[0], $mailBody);
             $mailBody = str_replace("{sVars." . $names[1] . "}", $value[1], $mailBody);
         } else {
             $mailBody = str_replace("{sVars." . $this->_elements[$key]['name'] . "}", $value, $mailBody);
         }
     }
     $mailBody = str_replace("{sIP}", $_SERVER['REMOTE_ADDR'], $mailBody);
     $mailBody = str_replace("{sDateTime}", date("d.m.Y h:i:s"), $mailBody);
     $mailBody = str_replace('{$sShopname}', Shopware()->Config()->shopName, $mailBody);
     $mailBody = strip_tags($mailBody);
     $mail->setFrom(Shopware()->Config()->Mail);
     $mail->clearRecipients();
     $mail->addTo($content["email"]);
     $mail->setBodyText($mailBody);
     $mail->setSubject($content["email_subject"]);
     $mail = Enlight()->Events()->filter('Shopware_Controllers_Frontend_Forms_commitForm_Mail', $mail, array('subject' => $this));
     if (!$mail->send()) {
         throw new Enlight_Exception("Could not send mail");
     }
 }
Esempio n. 27
0
 /**
  * Get current amount from cart via ajax to display in realtime
  */
 public function ajaxAmountAction()
 {
     Enlight()->Plugins()->Controller()->Json()->setPadding();
     $this->View()->sBasketQuantity = $this->basket->sCountBasket();
     $amount = $this->basket->sGetAmount();
     $quantity = $this->basket->sCountBasket();
     $this->View()->sBasketQuantity = $quantity;
     $this->View()->sBasketAmount = empty($amount) ? 0 : array_shift($amount);
     if (Shopware()->Shop()->getTemplate()->getVersion() >= 3) {
         $this->Front()->Plugins()->ViewRenderer()->setNoRender();
         $this->Response()->setBody(json_encode(['amount' => Shopware()->Template()->fetch('frontend/checkout/ajax_amount.tpl'), 'quantity' => $quantity]));
     }
 }
Esempio n. 28
0
 /**
  * Add product to cart
  * @param int $id ordernumber (s_order_details.ordernumber)
  * @param int $quantity amount
  * @access public
  * @deprecated
  * @return void
  */
 public function sAddArticle($id, $quantity = 1)
 {
     if ($this->sSYSTEM->sBotSession) {
         return false;
     }
     if (empty($this->sSYSTEM->sSESSION_ID)) {
         return false;
     }
     $quantity = empty($quantity) || !is_numeric($quantity) ? 1 : (int) $quantity;
     if ($quantity <= 0) {
         $quantity = 1;
     }
     if (Enlight()->Events()->notifyUntil('Shopware_Modules_Basket_AddArticle_Start', array('subject' => $this, 'id' => $id, "quantity" => $quantity))) {
         return false;
     }
     $sql = "\n\t\t\tSELECT s_articles.id AS articleID, name AS articleName, taxID, additionaltext, s_articles_details.shippingfree,laststock,instock, s_articles_details.id as articledetailsID, ordernumber\n\t\t\tFROM s_articles, s_articles_details \n\t\t\tWHERE s_articles_details.ordernumber=?\n\t\t\tAND s_articles_details.articleID=s_articles.id\n\t\t\tAND s_articles.active = 1\n\t\t\tAND (\n\t\t\t\tSELECT articleID \n\t\t\t\tFROM s_articles_avoid_customergroups \n\t\t\t\tWHERE articleID = s_articles.id AND customergroupID = " . $this->sSYSTEM->sUSERGROUPDATA["id"] . "\n\t\t\t) IS NULL\n\t\t";
     $getArticle = $this->sSYSTEM->sDB_CONNECTION->GetRow($sql, array($id));
     $getName = $this->sSYSTEM->sMODULES["sArticles"]->sGetArticleNameByOrderNumber($getArticle["ordernumber"], true);
     if (!empty($getName)) {
         $getArticle["articleName"] = $getName["articleName"];
         $getArticle["additionaltext"] = $getName["additionaltext"];
     }
     if (!count($getArticle)) {
         //$this->sSYSTEM->E_CORE_WARNING ("BASKET-INSERT #00","Article $id not found");
         //unset($this->sSYSTEM->_GET["sAdd"]);
         return false;
     } else {
         // Check if article is already in basket
         $sql = "\n\t\t\tSELECT id, quantity FROM s_order_basket WHERE articleID=? AND sessionID=? AND\n\t\t\tordernumber=?";
         $chkBasketForArticle = $this->sSYSTEM->sDB_CONNECTION->GetRow($sql, array($getArticle["articleID"], $this->sSYSTEM->sSESSION_ID, $getArticle["ordernumber"]));
         // Shopware 3.5.0 / sth / laststock - instock check
         if (!empty($chkBasketForArticle["id"])) {
             if ($getArticle["laststock"] == true && $getArticle["instock"] < $chkBasketForArticle["quantity"] + $quantity) {
                 $quantity -= $chkBasketForArticle["quantity"];
             }
         } else {
             if ($getArticle["laststock"] == true && $getArticle["instock"] <= $quantity) {
                 $quantity = $getArticle["instock"];
                 if ($quantity <= 0) {
                     return;
                 }
             }
         }
         // --
         $insertTime = date("Y-m-d H:i:s");
         if ($chkBasketForArticle && empty($sUpPriceValues)) {
             // Article is already in basket, update quantity
             $quantity += $chkBasketForArticle["quantity"];
             $this->sUpdateArticle($chkBasketForArticle["id"], $quantity);
             return $chkBasketForArticle["id"];
         } else {
             // Read price from default-price-table
             $sql = "SELECT price,s_core_tax.tax AS tax FROM s_articles_prices,s_core_tax WHERE\n                s_articles_prices.pricegroup=?\n                AND s_articles_prices.articledetailsID=?\n                AND s_core_tax.id=?\n                ";
             $getPrice = $this->sSYSTEM->sDB_CONNECTION->GetRow($sql, array($this->sSYSTEM->sUSERGROUP, $getArticle["articledetailsID"], $getArticle["taxID"]));
             if (empty($getPrice["price"])) {
                 $sql = "SELECT price,s_core_tax.tax AS tax FROM s_articles_prices,s_core_tax WHERE\n                    s_articles_prices.pricegroup='EK'\n                    AND s_articles_prices.articledetailsID=?\n                    AND s_core_tax.id=?\n                    ";
                 $getPrice = $this->sSYSTEM->sDB_CONNECTION->GetRow($sql, array($getArticle["articledetailsID"], $getArticle["taxID"]));
             }
             if (!$getPrice["price"] && !$getArticle["free"]) {
                 // No price could acquired
                 $this->sSYSTEM->E_CORE_WARNING("BASKET-INSERT #01", "No price acquired");
                 return;
             } else {
                 // If configuration article
                 if ($this->sSYSTEM->sCONFIG['sARTICLESOUTPUTNETTO'] && !$this->sSYSTEM->sUSERGROUPDATA["tax"] || !$this->sSYSTEM->sUSERGROUPDATA["tax"] && $this->sSYSTEM->sUSERGROUPDATA["id"]) {
                     // If netto set both values to net-price
                     $getPrice["price"] = $this->sSYSTEM->sMODULES['sArticles']->sCalculatingPriceNum($getPrice["price"], $getPrice["tax"], false, false, $getArticle["taxID"], false);
                     $getPrice["netprice"] = $getPrice["price"];
                 } else {
                     // If brutto, save net
                     $getPrice["netprice"] = $getPrice["price"];
                     $getPrice["price"] = $this->sSYSTEM->sMODULES['sArticles']->sCalculatingPriceNum($getPrice["price"], $getPrice["tax"], false, false, $getArticle["taxID"], false);
                 }
                 // For variants, extend the article-name
                 if ($getArticle["additionaltext"]) {
                     $getArticle["articleName"] .= " " . $getArticle["additionaltext"];
                 }
                 if (!$getArticle["shippingfree"]) {
                     $getArticle["shippingfree"] = "0";
                 }
                 // Check if article is an esd-article
                 // - add flag to basket
                 $sqlGetEsd = "\n\t\t\t\t\tSELECT s_articles_esd.id AS id, serials FROM s_articles_esd,s_articles_details WHERE s_articles_esd.articleID=?\n\t\t\t\t\tAND s_articles_esd.articledetailsID=s_articles_details.id AND s_articles_details.ordernumber=?\n\t\t\t\t\t";
                 $getEsd = $this->sSYSTEM->sDB_CONNECTION->GetRow($sqlGetEsd, array($getArticle["articleID"], $getArticle["ordernumber"]));
                 if ($getEsd["id"]) {
                     $sEsd = "1";
                 } else {
                     $sEsd = "0";
                 }
                 $quantity = (int) $quantity;
                 $sql = "\n\t\t\t\t\t\tINSERT INTO s_order_basket (id,sessionID,userID,articlename,articleID,\n\t\t\t\t\t\tordernumber, shippingfree, quantity, price, netprice, datum, esdarticle, partnerID, config)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )\n\t\t\t\t\t";
                 $params = array('', (string) $this->sSYSTEM->sSESSION_ID, (string) $this->sSYSTEM->_SESSION['sUserId'], $getArticle["articleName"], $getArticle["articleID"], (string) $getArticle["ordernumber"], $getArticle["shippingfree"], $quantity, $getPrice["price"], $getPrice["netprice"], (string) $insertTime, $sEsd, (string) $this->sSYSTEM->_SESSION["sPartner"], empty($sUpPriceValues) ? "" : serialize($sUpPriceValues));
                 $sql = Enlight()->Events()->filter('Shopware_Modules_Basket_AddArticle_FilterSql', $sql, array('subject' => $this, "article" => $getArticle, "price" => $getPrice, "esd" => $sEsd, "quantity" => $quantity, "partner" => $this->sSYSTEM->_SESSION["sPartner"]));
                 $rs = $this->sSYSTEM->sDB_CONNECTION->Execute($sql, $params);
                 if (!$rs) {
                     $this->sSYSTEM->E_CORE_WARNING("BASKET-INSERT #02", "SQL-Error" . $sql);
                 }
                 $insertId = $this->sSYSTEM->sDB_CONNECTION->Insert_ID();
                 $sql = "INSERT INTO s_order_basket_attributes (basketID, attribute1) VALUES (" . $insertId . ", " . $this->sSYSTEM->sDB_CONNECTION->qstr(implode($pictureRelations, "\$\$")) . ")";
                 $this->sSYSTEM->sDB_CONNECTION->Execute($sql);
                 $this->sUpdateArticle($insertId, $quantity);
             }
             // If - Price was found
         }
         // If - Article is not in basket
     }
     // If - Article was found
     return $insertId;
 }
Esempio n. 29
0
 /**
  * Sends this email using the given transport or a previously
  * set DefaultTransport or the internal mail function if no
  * default transport had been set.
  *
  * @param  Zend_Mail_Transport_Abstract $transport
  * @return Zend_Mail                    Provides fluent interface
  * @events  Enlight_Components_Mail_Send
  */
 public function send($transport = null)
 {
     Enlight()->Events()->notify('Enlight_Components_Mail_Send', array('mail' => $this, 'transport' => $transport));
     return parent::send($transport);
 }
Esempio n. 30
0
 public function sMailCampaignsGetDetail($id)
 {
     $sql = "\n        SELECT * FROM s_campaigns_mailings\n        WHERE id={$id}\n        ";
     $getCampaigns = $this->sSYSTEM->sDB_CONNECTION->GetRow($sql);
     if (!$getCampaigns["id"]) {
         return false;
     } else {
         // Fetch all positions
         $sql = "\n            SELECT id, type, description, value FROM s_campaigns_containers\n            WHERE promotionID={$id}\n            ORDER BY position\n            ";
         $sql = Enlight()->Events()->filter('Shopware_Modules_Marketing_MailCampaignsGetDetail_FilterSQL', $sql, array('subject' => $this, 'id' => $id));
         $getCampaignContainers = $this->sSYSTEM->sDB_CONNECTION->GetAll($sql);
         foreach ($getCampaignContainers as $campaignKey => $campaignValue) {
             switch ($campaignValue["type"]) {
                 case "ctBanner":
                     // Query Banner
                     $getBanner = $this->sSYSTEM->sDB_CONNECTION->GetRow("\n                        SELECT image, link, linkTarget, description FROM s_campaigns_banner\n                        WHERE parentID={$campaignValue["id"]}\n                        ");
                     // Rewrite banner
                     if ($getBanner["image"]) {
                         $getBanner["image"] = $this->sSYSTEM->sPathBanner . $getBanner["image"];
                     }
                     if (!preg_match("/http/", $getBanner["link"]) && $getBanner["link"]) {
                         $getBanner["link"] = "http://" . $getBanner["link"];
                     }
                     $getCampaignContainers[$campaignKey]["description"] = $getBanner["description"];
                     $getCampaignContainers[$campaignKey]["data"] = $getBanner;
                     break;
                 case "ctLinks":
                     // Query links
                     $getLinks = $this->sSYSTEM->sDB_CONNECTION->GetAll("\n                        SELECT description, link, target FROM s_campaigns_links\n                        WHERE parentID={$campaignValue["id"]}\n                        ORDER BY position\n                        ");
                     $getCampaignContainers[$campaignKey]["data"] = $getLinks;
                     break;
                 case "ctArticles":
                     $sql = "\n                        SELECT articleordernumber, type FROM s_campaigns_articles\n                        WHERE parentID={$campaignValue["id"]}\n                        ORDER BY position\n                        ";
                     $getArticles = $this->sSYSTEM->sDB_CONNECTION->GetAll($sql);
                     unset($articleData);
                     foreach ($getArticles as $article) {
                         if ($article["type"]) {
                             $category = $this->sSYSTEM->_GET["sCategory"] ? $this->sSYSTEM->_GET["sCategory"] : $this->sSYSTEM->sLanguageData[$this->sSYSTEM->sLanguage]["parentID"];
                             $tmpContainer = $this->sSYSTEM->sMODULES['sArticles']->sGetPromotionById($article["type"], $category, $article['articleordernumber']);
                             if (count($tmpContainer) && isset($tmpContainer["articleName"])) {
                                 $articleData[] = $tmpContainer;
                             }
                         }
                     }
                     $getCampaignContainers[$campaignKey]["data"] = $articleData;
                     break;
                 case "ctText":
                 case "ctVoucher":
                     $getText = $this->sSYSTEM->sDB_CONNECTION->GetRow("\n                            SELECT headline, html,image,alignment,link FROM s_campaigns_html\n                            WHERE parentID={$campaignValue["id"]}\n                        ");
                     if ($getText["image"]) {
                         $getText["image"] = $this->sSYSTEM->sPathBanner . $getText["image"];
                     }
                     if (!preg_match("/http/", $getText["link"]) && $getText["link"]) {
                         $getText["link"] = "http://" . $getText["link"];
                     }
                     $getCampaignContainers[$campaignKey]["description"] = $getText["headline"];
                     $getCampaignContainers[$campaignKey]["data"] = $getText;
                     break;
             }
         }
         $getCampaigns["containers"] = $getCampaignContainers;
         return $getCampaigns;
     }
 }