/** * Returns a product price in the active currency, depending on the * Customer and special offer status. * @param Customer $objCustomer The Customer, or null * @param double $price_options The price for Attributes, * if any, or 0 (zero) * @param integer $count The number of products, defaults * to 1 (one) * @param boolean $ignore_special_offer * If true, special offers are ignored. * This is needed to actually determine * both prices in the products view. * Defaults to false. * @return double The price converted to the active * currency * @author Reto Kohli <*****@*****.**> */ function get_custom_price($objCustomer = null, $price_options = 0, $count = 1, $ignore_special_offer = false) { $normalPrice = $this->price(); $resellerPrice = $this->resellerprice(); $discountPrice = $this->discountprice(); $discount_active = $this->discount_active(); $groupCountId = $this->group_id(); $groupArticleId = $this->article_id(); $price = $normalPrice; if (!$ignore_special_offer && $discount_active == 1 && $discountPrice != 0) { $price = $discountPrice; } else { if ($objCustomer && $objCustomer->is_reseller() && $resellerPrice != 0) { $price = $resellerPrice; } } $price += $price_options; $rateCustomer = 0; if ($objCustomer) { $groupCustomerId = $objCustomer->group_id(); if ($groupCustomerId) { $rateCustomer = Discount::getDiscountRateCustomer($groupCustomerId, $groupArticleId); $price -= $price * $rateCustomer * 0.01; } } $rateCount = 0; if ($count > 0) { $rateCount = Discount::getDiscountRateCount($groupCountId, $count); $price -= $price * $rateCount * 0.01; } $price = Currency::getCurrencyPrice($price); return $price; }
/** * Set up the shop page with products and discounts * * @param array $product_ids The optional array of Product IDs. * Overrides any URL parameters if set * @return boolean True on success, false otherwise * @global ADONewConnection $objDatabase Database connection object * @global array $_ARRAYLANG Language array * @global array $_CONFIG Core configuration array, see {@link /config/settings.php} * @global string(?) $themesPages Themes pages(?) */ static function view_product_overview($product_ids = null) { global $_ARRAYLANG; // activate javascript shadowbox \JS::activate('shadowbox'); $flagSpecialoffer = intval(\Cx\Core\Setting\Controller\Setting::getValue('show_products_default', 'Shop')); if (isset($_REQUEST['cmd']) && $_REQUEST['cmd'] == 'discounts') { $flagSpecialoffer = Products::DEFAULT_VIEW_DISCOUNTS; } $flagLastFive = isset($_REQUEST['lastFive']); $product_id = isset($_REQUEST['productId']) ? intval($_REQUEST['productId']) : null; $cart_id = null; if (isset($_REQUEST['referer']) && $_REQUEST['referer'] == 'cart') { $cart_id = $product_id; $product_id = Cart::get_product_id($cart_id); } $manufacturer_id = isset($_REQUEST['manufacturerId']) ? intval($_REQUEST['manufacturerId']) : null; $term = isset($_REQUEST['term']) ? trim(contrexx_input2raw($_REQUEST['term'])) : null; $category_id = isset($_REQUEST['catId']) ? intval($_REQUEST['catId']) : null; if (!($product_id || $category_id || $manufacturer_id || $term || $cart_id)) { // NOTE: This is different from NULL // in that it enables listing the subcategories $category_id = 0; } // Validate parameters if ($product_id && empty($category_id)) { $objProduct = Product::getById($product_id); if ($objProduct) { $category_id = $objProduct->category_id(); } if (isset($_SESSION['shop']['previous_category_id'])) { $category_id_previous = $_SESSION['shop']['previous_category_id']; foreach (preg_split('/\\s*,\\s*/', $category_id) as $id) { if ($category_id_previous == intval($id)) { $category_id = $category_id_previous; } } } } // Remember visited Products if ($product_id) { self::rememberVisitedProducts($product_id); } $objCategory = null; if ($category_id && empty($product_id)) { $objCategory = ShopCategory::getById($category_id); if (!$objCategory) { $category_id = null; } } $shopMenu = '<form method="post" action="' . \Cx\Core\Routing\Url::fromModuleAndCmd('Shop', '') . '">' . '<input type="text" name="term" value="' . htmlentities($term, ENT_QUOTES, CONTREXX_CHARSET) . '" style="width:150px;" /> ' . '<select name="catId" style="width:150px;">' . '<option value="0">' . $_ARRAYLANG['TXT_ALL_PRODUCT_GROUPS'] . '</option>' . ShopCategories::getMenuoptions($category_id) . '</select> ' . Manufacturer::getMenu('manufacturerId', $manufacturer_id, true) . '<input type="submit" name="bsubmit" value="' . $_ARRAYLANG['TXT_SEARCH'] . '" style="width:66px;" />' . '</form>'; self::$objTemplate->setGlobalVariable($_ARRAYLANG + array('SHOP_MENU' => $shopMenu, 'SHOP_SEARCH_TERM' => htmlentities($term, ENT_QUOTES, CONTREXX_CHARSET), 'SHOP_CATEGORIES_MENUOPTIONS' => ShopCategories::getMenuoptions($category_id, true, 0, true), 'SHOP_MANUFACTURER_MENUOPTIONS' => Manufacturer::getMenuoptions($manufacturer_id, true))); // Only show the cart info when the JS cart is not active! global $_CONFIGURATION; if (empty($_CONFIGURATION['custom']['shopJsCart'])) { self::$objTemplate->setVariable(array('SHOP_CART_INFO' => self::cart_info())); } // Exclude Category list from search results if ($term == '') { self::showCategories($category_id); } if (self::$objTemplate->blockExists('shopNextCategoryLink')) { $nextCat = ShopCategory::getNextShopCategoryId($category_id); $objCategory = ShopCategory::getById($nextCat); if ($objCategory) { self::$objTemplate->setVariable(array('SHOP_NEXT_CATEGORY_ID' => $nextCat, 'SHOP_NEXT_CATEGORY_TITLE' => str_replace('"', '"', $objCategory->name()))); } } $pagingCmd = !empty($_REQUEST['cmd']) ? '&cmd=' . contrexx_input2raw($_REQUEST['cmd']) : ''; $pagingCatId = ''; $pagingManId = ''; $pagingTerm = ''; // TODO: This probably breaks paging in search results! // Should only reset the flag conditionally, but add the URL parameters in // any case, methinks! if ($category_id > 0 && $term == '') { $flagSpecialoffer = false; $pagingCatId = "&catId={$category_id}"; } if ($manufacturer_id > 0) { $flagSpecialoffer = false; $pagingManId = "&manufacturer_id={$manufacturer_id}"; } if ($term != '') { $flagSpecialoffer = false; $pagingTerm = '&term=' . htmlentities($term, ENT_QUOTES, CONTREXX_CHARSET); } // The Product count is passed by reference and set to the total // number of records, though only as many as specified by the core // paging limit are returned in the array. $limit = \Cx\Core\Setting\Controller\Setting::getValue('numof_products_per_page_frontend', 'Shop'); //\DBG::activate(DBG_ERROR_FIREPHP); // Use Sorting class for the Product order $uri = \Html::getRelativeUri_entities(); $arrOrder = array('product.ord' => $_ARRAYLANG['TXT_SHOP_ORDER_PRODUCT_ORD'], 'name' => $_ARRAYLANG['TXT_SHOP_ORDER_PRODUCT_TITLE'], 'code' => $_ARRAYLANG['TXT_SHOP_ORDER_PRODUCT_CODE'], 'price' => $_ARRAYLANG['TXT_SHOP_ORDER_PRODUCT_PRICE'], 'id' => $_ARRAYLANG['TXT_SHOP_ORDER_PRODUCT_DATE'], 'bestseller' => $_ARRAYLANG['TXT_SHOP_ORDER_PRODUCT_BESTSELLER']); $defaultOrder = \Sorting::getFieldindex(Products::$arrProductOrder[\Cx\Core\Setting\Controller\Setting::getValue('product_sorting', 'Shop')]); $objSorting = new \Sorting($uri, $arrOrder, true, 'shop_order_products', $defaultOrder); //\DBG::log("Sorting headers: ".var_export($objSorting->getHeaderArray(), true)); $count = $limit; $arrProduct = array(); if ($product_ids) { $arrProduct = self::getValidProducts($product_ids); $product_id = null; // Suppress meta title from single Product } elseif ($product_id) { $arrProduct = self::getValidProducts(array($product_id)); } else { $arrProduct = Products::getByShopParams($count, \Paging::getPosition(), $product_id, $category_id, $manufacturer_id, $term, $flagSpecialoffer, $flagLastFive, $objSorting->getOrder(), self::$objCustomer && self::$objCustomer->is_reseller()); } // Only show sorting when there's enough to be sorted if ($count > 1) { $objSorting->parseHeaders(self::$objTemplate, 'shop_product_order'); } if ($count == 0 && !ShopCategories::getChildCategoryIdArray($category_id)) { //if ($term != '' || $manufacturer_id != 0 || $flagSpecialoffer) { if (self::$objTemplate->blockExists('no_product')) { self::$objTemplate->touchBlock('no_product'); } return true; } if ($objCategory) { // Only indicate the category name when there are products if ($count) { self::$objTemplate->setVariable(array('SHOP_CATEGORY_CURRENT_NAME' => contrexx_raw2xhtml($objCategory->name()), 'SHOP_PRODUCTS_IN_CATEGORY' => sprintf($_ARRAYLANG['TXT_SHOP_PRODUCTS_IN_CATEGORY'], contrexx_raw2xhtml($objCategory->name())))); } } else { // TODO: There are other cases of flag combinations that are not indivuidually // handled here yet. if ($term == '') { if ($flagSpecialoffer == Products::DEFAULT_VIEW_DISCOUNTS) { self::$objTemplate->setVariable('SHOP_PRODUCTS_IN_CATEGORY', $_ARRAYLANG['TXT_SHOP_PRODUCTS_SPECIAL_OFFER']); } else { if (self::$objTemplate->blockExists('products_in_category')) { self::$objTemplate->hideBlock('products_in_category'); } } } else { self::$objTemplate->setVariable('SHOP_PRODUCTS_IN_CATEGORY', sprintf($_ARRAYLANG['TXT_SHOP_PRODUCTS_SEARCH_RESULTS'], contrexx_raw2xhtml($term))); } } $uri = '&section=Shop' . MODULE_INDEX . $pagingCmd . $pagingCatId . $pagingManId . $pagingTerm; self::$objTemplate->setVariable(array('SHOP_PRODUCT_PAGING' => \Paging::get($uri, '', $count, $limit, $count > 0), 'SHOP_PRODUCT_TOTAL' => $count)); // Global microdata: Seller information $seller_url = \Cx\Core\Routing\Url::fromModuleAndCmd('Shop', '')->toString(); $seller_name = \Cx\Core\Setting\Controller\Setting::getValue('company', 'Shop'); if (empty($seller_name)) { $seller_name = $seller_url; } self::$objTemplate->setVariable(array('SHOP_SELLER_NAME' => $seller_name, 'SHOP_SELLER_URL' => $seller_url)); $formId = 0; $arrDefaultImageSize = $arrSize = null; foreach ($arrProduct as $objProduct) { if (!empty($product_id)) { self::$pageTitle = $objProduct->name(); } $id = $objProduct->id(); $productSubmitFunction = ''; $arrPictures = Products::get_image_array_from_base64($objProduct->pictures()); $havePicture = false; $arrProductImages = array(); foreach ($arrPictures as $index => $image) { $thumbnailPath = $pictureLink = ''; if (empty($image['img']) || $image['img'] == ShopLibrary::noPictureName) { // We have at least one picture on display already. // No need to show "no picture" three times! if ($havePicture) { continue; } $thumbnailPath = self::$defaultImage; $pictureLink = '#'; //"javascript:alert('".$_ARRAYLANG['TXT_NO_PICTURE_AVAILABLE']."');"; if (empty($arrDefaultImageSize)) { $arrDefaultImageSize = getimagesize(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsitePath() . self::$defaultImage); self::scaleImageSizeToThumbnail($arrDefaultImageSize); } $arrSize = $arrDefaultImageSize; } else { $thumbnailPath = \Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesShopWebPath() . '/' . \ImageManager::getThumbnailFilename($image['img']); if ($image['width'] && $image['height']) { $pictureLink = contrexx_raw2encodedUrl(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesShopWebPath() . '/' . $image['img']) . '" rel="shadowbox[' . ($formId + 1) . ']'; // Thumbnail display size $arrSize = array($image['width'], $image['height']); } else { $pictureLink = '#'; if (!file_exists(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsitePath() . $thumbnailPath)) { continue; } $arrSize = getimagesize(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsitePath() . $thumbnailPath); } self::scaleImageSizeToThumbnail($arrSize); // Use the first available picture in microdata, if any if (!$havePicture) { $picture_url = \Cx\Core\Routing\Url::fromCapturedRequest(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesShopWebPath() . '/' . $image['img'], \Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteOffsetPath(), array()); self::$objTemplate->setVariable('SHOP_PRODUCT_IMAGE', $picture_url->toString()); //\DBG::log("Set image to ".$picture_url->toString()); } } $arrProductImages[] = array('THUMBNAIL' => contrexx_raw2encodedUrl($thumbnailPath), 'THUMBNAIL_SIZE' => $arrSize[3], 'THUMBNAIL_LINK' => $pictureLink, 'POPUP_LINK' => $pictureLink, 'POPUP_LINK_NAME' => $_ARRAYLANG['TXT_SHOP_IMAGE'] . ' ' . $index); $havePicture = true; } $i = 1; foreach ($arrProductImages as $arrProductImage) { // TODO: Instead of several numbered image blocks, use a single one repeatedly self::$objTemplate->setVariable(array('SHOP_PRODUCT_THUMBNAIL_' . $i => $arrProductImage['THUMBNAIL'], 'SHOP_PRODUCT_THUMBNAIL_SIZE_' . $i => $arrProductImage['THUMBNAIL_SIZE'])); if (!empty($arrProductImage['THUMBNAIL_LINK'])) { self::$objTemplate->setVariable(array('SHOP_PRODUCT_THUMBNAIL_LINK_' . $i => $arrProductImage['THUMBNAIL_LINK'], 'TXT_SEE_LARGE_PICTURE' => $_ARRAYLANG['TXT_SEE_LARGE_PICTURE'])); } else { self::$objTemplate->setVariable('TXT_SEE_LARGE_PICTURE', contrexx_raw2xhtml($objProduct->name())); } if ($arrProductImage['POPUP_LINK']) { self::$objTemplate->setVariable('SHOP_PRODUCT_POPUP_LINK_' . $i, $arrProductImage['POPUP_LINK']); } self::$objTemplate->setVariable('SHOP_PRODUCT_POPUP_LINK_NAME_' . $i, $arrProductImage['POPUP_LINK_NAME']); ++$i; } $stock = $objProduct->stock_visible() ? $_ARRAYLANG['TXT_STOCK'] . ': ' . intval($objProduct->stock()) : ''; $price = $objProduct->get_custom_price(self::$objCustomer, 0, 1, true); // If there is a discountprice and it's enabled $discountPrice = ''; if ($objProduct->discountprice() > 0 && $objProduct->discount_active()) { $price = '<s>' . $price . '</s>'; $discountPrice = $objProduct->get_custom_price(self::$objCustomer, 0, 1, false); } $groupCountId = $objProduct->group_id(); $groupArticleId = $objProduct->article_id(); $groupCustomerId = 0; if (self::$objCustomer) { $groupCustomerId = self::$objCustomer->group_id(); } self::showDiscountInfo($groupCustomerId, $groupArticleId, $groupCountId, 1); /* OLD $price = Currency::getCurrencyPrice( $objProduct->getCustomerPrice(self::$objCustomer) ); $discountPrice = ''; $discount_active = $objProduct->discount_active(); if ($discount_active) { $discountPrice = $objProduct->discountprice(); if ($discountPrice > 0) { $price = "<s>$price</s>"; $discountPrice = Currency::getCurrencyPrice($discountPrice); } } */ $short = $objProduct->short(); $longDescription = $objProduct->long(); $detailLink = null; // Detaillink is required for microdata (even when longdesc // is empty) $detail_url = \Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'details', FRONTEND_LANG_ID, array('productId' => $objProduct->id()))->toString(); self::$objTemplate->setVariable('SHOP_PRODUCT_DETAIL_URL', $detail_url); if (!$product_id && !empty($longDescription)) { $detailLink = '<a href="' . $detail_url . '"' . ' title="' . $_ARRAYLANG['TXT_MORE_INFORMATIONS'] . '">' . $_ARRAYLANG['TXT_MORE_INFORMATIONS'] . '</a>'; self::$objTemplate->setVariable('SHOP_PRODUCT_DETAILLINK', $detailLink); } // Check Product flags. // Only the meter flag is currently implemented and in use. $flagMeter = $objProduct->testFlag('__METER__'); // Submit button name and function. // Calling productOptions() also sets the $flagMultipart variable // to the appropriate encoding type for the form if // any upload fields are in use. $flagMultipart = false; $productSubmitName = $productSubmitFunction = ''; if (isset($_GET['cmd']) && $_GET['cmd'] == 'details' && isset($_GET['referer']) && $_GET['referer'] == 'cart') { $productSubmitName = "updateProduct[{$cart_id}]"; $productSubmitFunction = self::productOptions($id, $formId, $cart_id, $flagMultipart); } else { $productSubmitName = 'addProduct'; $productSubmitFunction = self::productOptions($id, $formId, $cart_id, $flagMultipart); } $shopProductFormName = "shopProductForm{$formId}"; $row = $formId % 2 + 1; self::$objTemplate->setVariable(array('SHOP_ROWCLASS' => 'row' . $row, 'SHOP_PRODUCT_ID' => $objProduct->id(), 'SHOP_PRODUCT_TITLE' => contrexx_raw2xhtml($objProduct->name()), 'SHOP_PRODUCT_DESCRIPTION' => $short, 'SHOP_PRODUCT_DETAILDESCRIPTION' => $longDescription ? $longDescription : $short, 'SHOP_PRODUCT_FORM_NAME' => $shopProductFormName, 'SHOP_PRODUCT_SUBMIT_NAME' => $productSubmitName, 'SHOP_PRODUCT_SUBMIT_FUNCTION' => $productSubmitFunction, 'SHOP_FORM_ENCTYPE' => $flagMultipart ? ' enctype="multipart/form-data"' : '', 'TXT_SHOP_PRODUCT_COUNT' => $flagMeter ? $_ARRAYLANG['TXT_SHOP_PRODUCT_METER'] : $_ARRAYLANG['TXT_SHOP_PRODUCT_COUNT'], 'SHOP_CURRENCY_CODE' => Currency::getActiveCurrencyCode())); if ($objProduct->code()) { self::$objTemplate->setVariable('SHOP_PRODUCT_CUSTOM_ID', htmlentities($objProduct->code(), ENT_QUOTES, CONTREXX_CHARSET)); } $manufacturer_name = $manufacturer_url = $manufacturer_link = ''; $manufacturer_id = $objProduct->manufacturer_id(); if ($manufacturer_id) { $manufacturer_name = Manufacturer::getNameById($manufacturer_id, FRONTEND_LANG_ID); $manufacturer_url = Manufacturer::getUrlById($manufacturer_id, FRONTEND_LANG_ID); } if (!empty($manufacturer_url) || !empty($manufacturer_name)) { if (empty($manufacturer_name)) { $manufacturer_name = $manufacturer_url; } if (!empty($manufacturer_url)) { $manufacturer_link = '<a href="' . $manufacturer_url . '">' . $manufacturer_name . '</a>'; } // TODO: Test results for any combination of name and url self::$objTemplate->setVariable(array('SHOP_MANUFACTURER_NAME' => $manufacturer_name, 'SHOP_MANUFACTURER_URL' => $manufacturer_url, 'SHOP_MANUFACTURER_LINK' => $manufacturer_link, 'TXT_SHOP_MANUFACTURER_LINK' => $_ARRAYLANG['TXT_SHOP_MANUFACTURER_LINK'])); } // This is the old Product field for the Manufacturer URI. // This is now extended by the Manufacturer table and should thus // get a new purpose. As it is product specific, it could be // renamed and reused as a link to individual Products! $externalLink = $objProduct->uri(); if (!empty($externalLink)) { self::$objTemplate->setVariable(array('SHOP_EXTERNAL_LINK' => '<a href="' . $externalLink . '" title="' . $_ARRAYLANG['TXT_SHOP_EXTERNAL_LINK'] . '" target="_blank">' . $_ARRAYLANG['TXT_SHOP_EXTERNAL_LINK'] . '</a>')); } if ($price) { self::$objTemplate->setGlobalVariable(array('SHOP_PRODUCT_PRICE' => $price, 'SHOP_PRODUCT_PRICE_UNIT' => Currency::getActiveCurrencySymbol())); } // Only show the discount price if it's actually in use, // avoid an "empty <font> tag" HTML warning if ($discountPrice) { self::$objTemplate->setGlobalVariable(array('SHOP_PRODUCT_DISCOUNTPRICE' => $discountPrice, 'SHOP_PRODUCT_DISCOUNTPRICE_UNIT' => Currency::getActiveCurrencySymbol())); if (self::$objTemplate->blockExists('price_discount')) { self::$objTemplate->touchBlock('price_discount'); } } else { if (self::$objTemplate->blockExists('price')) { self::$objTemplate->touchBlock('price'); } } // Special outlet ShopCategory with discounts varying daily. // This should be implemented in a more generic way, in the // Discount class maybe. if ($objProduct->is_outlet()) { self::$objTemplate->setVariable(array('TXT_SHOP_DISCOUNT_TODAY' => $_ARRAYLANG['TXT_SHOP_DISCOUNT_TODAY'], 'SHOP_DISCOUNT_TODAY' => $objProduct->getOutletDiscountRate() . '%', 'TXT_SHOP_PRICE_TODAY' => $_ARRAYLANG['TXT_SHOP_PRICE_TODAY'], 'SHOP_PRICE_TODAY' => Currency::getCurrencyPrice($objProduct->getDiscountedPrice()), 'SHOP_PRICE_TODAY_UNIT' => Currency::getActiveCurrencySymbol())); } if ($objProduct->stock_visible()) { self::$objTemplate->setVariable(array('SHOP_PRODUCT_STOCK' => $stock)); } if ($detailLink) { self::$objTemplate->setVariable(array('SHOP_PRODUCT_DETAILLINK' => $detailLink)); } $distribution = $objProduct->distribution(); $weight = ''; if ($distribution == 'delivery') { $weight = $objProduct->weight(); } // Hide the weight if it is zero or disabled in the configuration if ($weight > 0 && \Cx\Core\Setting\Controller\Setting::getValue('weight_enable', 'Shop')) { self::$objTemplate->setVariable(array('TXT_SHOP_PRODUCT_WEIGHT' => $_ARRAYLANG['TXT_SHOP_PRODUCT_WEIGHT'], 'SHOP_PRODUCT_WEIGHT' => Weight::getWeightString($weight))); } if (Vat::isEnabled()) { self::$objTemplate->setVariable(array('SHOP_PRODUCT_TAX_PREFIX' => Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL'], 'SHOP_PRODUCT_TAX' => Vat::getShort($objProduct->vat_id()))); } // Add flag images for flagged Products $strImage = ''; $strFlags = $objProduct->flags(); $arrVirtual = ShopCategories::getVirtualCategoryNameArray(FRONTEND_LANG_ID); foreach (explode(' ', $strFlags) as $strFlag) { if (in_array($strFlag, $arrVirtual)) { $strImage .= '<img src="images/content/' . $strFlag . '.jpg" alt="' . $strFlag . '" />'; } } if ($strImage) { self::$objTemplate->setVariable('SHOP_PRODUCT_FLAG_IMAGE', $strImage); } $minimum_order_quantity = $objProduct->minimum_order_quantity(); //Activate Quantity-Inputfield when minimum_order_quantity exists if (self::$objTemplate->blockExists('orderQuantity') && $minimum_order_quantity > 0) { self::$objTemplate->setVariable('SHOP_PRODUCT_MINIMUM_ORDER_QUANTITY', contrexx_raw2xhtml($objProduct->minimum_order_quantity())); } elseif (self::$objTemplate->blockExists('orderQuantity') && !$minimum_order_quantity) { self::$objTemplate->hideBlock('orderQuantity'); } if (self::$objTemplate->blockExists('shopProductRow')) { self::$objTemplate->parse('shopProductRow'); } ++$formId; } return true; }
/** * Set up the detail view of the selected order * @access public * @param \Cx\Core\Html\Sigma $objTemplate The Template, by reference * @param boolean $edit Edit if true, view otherwise * @global ADONewConnection $objDatabase Database connection object * @global array $_ARRAYLANG Language array * @return boolean True on success, * false otherwise * @static * @author Reto Kohli <*****@*****.**> (parts) * @version 3.1.0 */ static function view_detail(&$objTemplate = null, $edit = false) { global $objDatabase, $_ARRAYLANG, $objInit; $backend = $objInit->mode == 'backend'; if ($objTemplate->blockExists('order_list')) { $objTemplate->hideBlock('order_list'); } $have_option = false; // The order total -- in the currency chosen by the customer $order_sum = 0; // recalculated VAT total $total_vat_amount = 0; $order_id = intval($_REQUEST['order_id']); if (!$order_id) { return \Message::error($_ARRAYLANG['TXT_SHOP_ORDER_ERROR_INVALID_ORDER_ID']); } if (!$objTemplate) { $template_name = $edit ? 'module_shop_order_edit.html' : 'module_shop_order_details.html'; $objTemplate = new \Cx\Core\Html\Sigma(\Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseModulePath() . '/Shop/View/Template/Backend'); //DBG::log("Orders::view_list(): new Template: ".$objTemplate->get()); $objTemplate->loadTemplateFile($template_name); //DBG::log("Orders::view_list(): loaded Template: ".$objTemplate->get()); } $objOrder = Order::getById($order_id); if (!$objOrder) { //DBG::log("Shop::shopShowOrderdetails(): Failed to find Order ID $order_id"); return \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_ORDER_NOT_FOUND'], $order_id)); } // lsv data $query = "\n SELECT `holder`, `bank`, `blz`\n FROM " . DBPREFIX . "module_shop" . MODULE_INDEX . "_lsv\n WHERE order_id={$order_id}"; $objResult = $objDatabase->Execute($query); if (!$objResult) { return self::errorHandler(); } if ($objResult->RecordCount() == 1) { $objTemplate->setVariable(array('SHOP_ACCOUNT_HOLDER' => contrexx_raw2xhtml($objResult->fields['holder']), 'SHOP_ACCOUNT_BANK' => contrexx_raw2xhtml($objResult->fields['bank']), 'SHOP_ACCOUNT_BLZ' => contrexx_raw2xhtml($objResult->fields['blz']))); } $customer_id = $objOrder->customer_id(); if (!$customer_id) { //DBG::log("Shop::shopShowOrderdetails(): Invalid Customer ID $customer_id"); \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_INVALID_CUSTOMER_ID'], $customer_id)); } $objCustomer = Customer::getById($customer_id); if (!$objCustomer) { //DBG::log("Shop::shopShowOrderdetails(): Failed to find Customer ID $customer_id"); \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_CUSTOMER_NOT_FOUND'], $customer_id)); $objCustomer = new Customer(); // No editing allowed! $have_option = true; } Vat::is_reseller($objCustomer->is_reseller()); Vat::is_home_country(\Cx\Core\Setting\Controller\Setting::getValue('country_id', 'Shop') == $objOrder->country_id()); $objTemplate->setGlobalVariable($_ARRAYLANG + array('SHOP_CURRENCY' => Currency::getCurrencySymbolById($objOrder->currency_id()))); //DBG::log("Order sum: ".Currency::formatPrice($objOrder->sum())); $objTemplate->setVariable(array('SHOP_CUSTOMER_ID' => $customer_id, 'SHOP_ORDERID' => $order_id, 'SHOP_DATE' => date(ASCMS_DATE_FORMAT_INTERNATIONAL_DATETIME, strtotime($objOrder->date_time())), 'SHOP_ORDER_STATUS' => $edit ? Orders::getStatusMenu($objOrder->status(), false, null, 'swapSendToStatus(this.value)') : $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $objOrder->status()], 'SHOP_SEND_MAIL_STYLE' => $objOrder->status() == Order::STATUS_CONFIRMED ? 'display: inline;' : 'display: none;', 'SHOP_SEND_MAIL_STATUS' => $edit ? $objOrder->status() != Order::STATUS_CONFIRMED ? \Html::ATTRIBUTE_CHECKED : '' : '', 'SHOP_ORDER_SUM' => Currency::formatPrice($objOrder->sum()), 'SHOP_DEFAULT_CURRENCY' => Currency::getDefaultCurrencySymbol(), 'SHOP_GENDER' => $edit ? Customer::getGenderMenu($objOrder->billing_gender(), 'billing_gender') : $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->billing_gender())], 'SHOP_COMPANY' => $objOrder->billing_company(), 'SHOP_FIRSTNAME' => $objOrder->billing_firstname(), 'SHOP_LASTNAME' => $objOrder->billing_lastname(), 'SHOP_ADDRESS' => $objOrder->billing_address(), 'SHOP_ZIP' => $objOrder->billing_zip(), 'SHOP_CITY' => $objOrder->billing_city(), 'SHOP_COUNTRY' => $edit ? \Cx\Core\Country\Controller\Country::getMenu('billing_country_id', $objOrder->billing_country_id()) : \Cx\Core\Country\Controller\Country::getNameById($objOrder->billing_country_id()), 'SHOP_PHONE' => $objOrder->billing_phone(), 'SHOP_FAX' => $objOrder->billing_fax(), 'SHOP_EMAIL' => $objOrder->billing_email(), 'SHOP_SHIP_GENDER' => $edit ? Customer::getGenderMenu($objOrder->gender(), 'shipPrefix') : $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHOP_SHIP_COMPANY' => $objOrder->company(), 'SHOP_SHIP_FIRSTNAME' => $objOrder->firstname(), 'SHOP_SHIP_LASTNAME' => $objOrder->lastname(), 'SHOP_SHIP_ADDRESS' => $objOrder->address(), 'SHOP_SHIP_ZIP' => $objOrder->zip(), 'SHOP_SHIP_CITY' => $objOrder->city(), 'SHOP_SHIP_COUNTRY' => $edit ? \Cx\Core\Country\Controller\Country::getMenu('shipCountry', $objOrder->country_id()) : \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHOP_SHIP_PHONE' => $objOrder->phone(), 'SHOP_PAYMENTTYPE' => Payment::getProperty($objOrder->payment_id(), 'name'), 'SHOP_CUSTOMER_NOTE' => $objOrder->note(), 'SHOP_COMPANY_NOTE' => $objCustomer->companynote(), 'SHOP_SHIPPING_TYPE' => $objOrder->shipment_id() ? Shipment::getShipperName($objOrder->shipment_id()) : ' ')); if ($backend) { $objTemplate->setVariable(array('SHOP_CUSTOMER_IP' => $objOrder->ip() ? '<a href="index.php?cmd=NetTools&tpl=whois&address=' . $objOrder->ip() . '" title="' . $_ARRAYLANG['TXT_SHOW_DETAILS'] . '">' . $objOrder->ip() . '</a>' : ' ', 'SHOP_CUSTOMER_HOST' => $objOrder->host() ? '<a href="index.php?cmd=NetTools&tpl=whois&address=' . $objOrder->host() . '" title="' . $_ARRAYLANG['TXT_SHOW_DETAILS'] . '">' . $objOrder->host() . '</a>' : ' ', 'SHOP_CUSTOMER_LANG' => \FWLanguage::getLanguageParameter($objOrder->lang_id(), 'name'), 'SHOP_CUSTOMER_BROWSER' => $objOrder->browser() ? $objOrder->browser() : ' ', 'SHOP_LAST_MODIFIED' => $objOrder->modified_on() && $objOrder->modified_on() != '0000-00-00 00:00:00' ? $objOrder->modified_on() . ' ' . $_ARRAYLANG['TXT_EDITED_BY'] . ' ' . $objOrder->modified_by() : $_ARRAYLANG['TXT_ORDER_WASNT_YET_EDITED'])); } else { // Frontend: Order history ONLY. Repeat the Order, go to cart $objTemplate->setVariable(array('SHOP_ACTION_URI_ENCODED' => \Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'cart'))); } $ppName = ''; $psp_id = Payment::getPaymentProcessorId($objOrder->payment_id()); if ($psp_id) { $ppName = PaymentProcessing::getPaymentProcessorName($psp_id); } $objTemplate->setVariable(array('SHOP_SHIPPING_PRICE' => $objOrder->shipment_amount(), 'SHOP_PAYMENT_PRICE' => $objOrder->payment_amount(), 'SHOP_PAYMENT_HANDLER' => $ppName, 'SHOP_LAST_MODIFIED_DATE' => $objOrder->modified_on())); if ($edit) { // edit order $strJsArrShipment = Shipment::getJSArrays(); $objTemplate->setVariable(array('SHOP_SEND_TEMPLATE_TO_CUSTOMER' => sprintf($_ARRAYLANG['TXT_SEND_TEMPLATE_TO_CUSTOMER'], $_ARRAYLANG['TXT_ORDER_COMPLETE']), 'SHOP_SHIPPING_TYP_MENU' => Shipment::getShipperMenu($objOrder->country_id(), $objOrder->shipment_id(), "calcPrice(0);"), 'SHOP_JS_ARR_SHIPMENT' => $strJsArrShipment, 'SHOP_PRODUCT_IDS_MENU_NEW' => Products::getMenuoptions(null, null, $_ARRAYLANG['TXT_SHOP_PRODUCT_MENU_FORMAT']), 'SHOP_JS_ARR_PRODUCT' => Products::getJavascriptArray($objCustomer->group_id(), $objCustomer->is_reseller()))); } $options = $objOrder->getOptionArray(); if (!empty($options[$order_id])) { $have_option = true; } // Order items $total_weight = $i = 0; $total_net_price = $objOrder->view_items($objTemplate, $edit, $total_weight, $i); // Show VAT with the individual products: // If VAT is enabled, and we're both in the same country // ($total_vat_amount has been set above if both conditions are met) // show the VAT rate. // If there is no VAT, the amount is 0 (zero). //if ($total_vat_amount) { // distinguish between included VAT, and additional VAT added to sum $tax_part_percentaged = Vat::isIncluded() ? $_ARRAYLANG['TXT_TAX_PREFIX_INCL'] : $_ARRAYLANG['TXT_TAX_PREFIX_EXCL']; $objTemplate->setVariable(array('SHOP_TAX_PRICE' => Currency::formatPrice($total_vat_amount), 'SHOP_PART_TAX_PROCENTUAL' => $tax_part_percentaged)); //} else { // No VAT otherwise // remove it from the details overview if empty //$objTemplate->hideBlock('taxprice'); //$tax_part_percentaged = $_ARRAYLANG['TXT_NO_TAX']; //} // Parse Coupon if applicable to this product // Coupon $objCoupon = Coupon::getByOrderId($order_id); if ($objCoupon) { $discount = $objCoupon->discount_amount() != 0 ? $objCoupon->discount_amount() : $total_net_price / 100 * $objCoupon->discount_rate(); $objTemplate->setVariable(array('SHOP_COUPON_NAME' => $_ARRAYLANG['TXT_SHOP_DISCOUNT_COUPON_CODE'], 'SHOP_COUPON_CODE' => $objCoupon->code(), 'SHOP_COUPON_AMOUNT' => Currency::formatPrice(-$discount))); $total_net_price -= $discount; //DBG::log("Order::view_detail(): Coupon: ".var_export($objCoupon, true)); } $objTemplate->setVariable(array('SHOP_ROWCLASS_NEW' => 'row' . (++$i % 2 + 1), 'SHOP_TOTAL_WEIGHT' => Weight::getWeightString($total_weight), 'SHOP_NET_PRICE' => Currency::formatPrice($total_net_price))); $objTemplate->setVariable(array('TXT_PRODUCT_ID' => $_ARRAYLANG['TXT_ID'], 'TXT_TAX_RATE' => Vat::isIncluded() ? $_ARRAYLANG['TXT_TAX_PREFIX_INCL'] : $_ARRAYLANG['TXT_TAX_PREFIX_EXCL'], 'TXT_SHOP_ACCOUNT_VALIDITY' => $_ARRAYLANG['TXT_SHOP_VALIDITY'])); // Disable the "edit" button when there are Attributes if ($backend && !$edit) { if ($have_option) { if ($objTemplate->blockExists('order_no_edit')) { $objTemplate->touchBlock('order_no_edit'); } } else { if ($objTemplate->blockExists('order_edit')) { $objTemplate->touchBlock('order_edit'); } } } return true; }
/** * Handles database errors * * Also migrates old Shop Customers to the User accounts and adds * all new settings * @return boolean false Always! * @throws Cx\Lib\Update_DatabaseException */ static function errorHandler() { // Customer $table_name_old = DBPREFIX . "module_shop_customers"; // If the old Customer table is missing, the migration has completed // successfully already if (!\Cx\Lib\UpdateUtil::table_exist($table_name_old)) { return false; } // Ensure that the ShopSettings (including \Cx\Core\Setting) and Order tables // are ready first! //DBG::log("Customer::errorHandler(): Adding settings"); ShopSettings::errorHandler(); // \Cx\Core\Country\Controller\Country::errorHandler(); // Called by Order::errorHandler(); Order::errorHandler(); Discount::errorHandler(); \Cx\Core\Setting\Controller\Setting::init('Shop', 'config'); $objUser = \FWUser::getFWUserObject()->objUser; // Create new User_Profile_Attributes $index_notes = \Cx\Core\Setting\Controller\Setting::getValue('user_profile_attribute_notes', 'Shop'); if (!$index_notes) { //DBG::log("Customer::errorHandler(): Adding notes attribute..."); // $objProfileAttribute = new \User_Profile_Attribute(); $objProfileAttribute = $objUser->objAttribute->getById(0); //DBG::log("Customer::errorHandler(): NEW notes attribute: ".var_export($objProfileAttribute, true)); $objProfileAttribute->setNames(array(1 => 'Notizen', 2 => 'Notes', 3 => 'Notes', 4 => 'Notes', 5 => 'Notes', 6 => 'Notes')); $objProfileAttribute->setType('text'); $objProfileAttribute->setMultiline(true); $objProfileAttribute->setParent(0); $objProfileAttribute->setProtection(array(1)); //DBG::log("Customer::errorHandler(): Made notes attribute: ".var_export($objProfileAttribute, true)); if (!$objProfileAttribute->store()) { throw new \Cx\Lib\Update_DatabaseException("Failed to create User_Profile_Attribute 'notes'"); } //Re initialize shop setting \Cx\Core\Setting\Controller\Setting::init('Shop', 'config'); //DBG::log("Customer::errorHandler(): Stored notes attribute, ID ".$objProfileAttribute->getId()); if (!(\Cx\Core\Setting\Controller\Setting::set('user_profile_attribute_notes', $objProfileAttribute->getId()) && \Cx\Core\Setting\Controller\Setting::update('user_profile_attribute_notes'))) { throw new \Cx\Lib\Update_DatabaseException("Failed to update User_Profile_Attribute 'notes' setting"); } //DBG::log("Customer::errorHandler(): Stored notes attribute ID setting"); } $index_group = \Cx\Core\Setting\Controller\Setting::getValue('user_profile_attribute_customer_group_id', 'Shop'); if (!$index_group) { // $objProfileAttribute = new \User_Profile_Attribute(); $objProfileAttribute = $objUser->objAttribute->getById(0); $objProfileAttribute->setNames(array(1 => 'Kundenrabattgruppe', 2 => 'Discount group', 3 => 'Kundenrabattgruppe', 4 => 'Kundenrabattgruppe', 5 => 'Kundenrabattgruppe', 6 => 'Kundenrabattgruppe')); $objProfileAttribute->setType('text'); $objProfileAttribute->setParent(0); $objProfileAttribute->setProtection(array(1)); if (!$objProfileAttribute->store()) { throw new \Cx\Lib\Update_DatabaseException("Failed to create User_Profile_Attribute 'notes'"); } //Re initialize shop setting \Cx\Core\Setting\Controller\Setting::init('Shop', 'config'); if (!(\Cx\Core\Setting\Controller\Setting::set('user_profile_attribute_customer_group_id', $objProfileAttribute->getId()) && \Cx\Core\Setting\Controller\Setting::update('user_profile_attribute_customer_group_id'))) { throw new \Cx\Lib\Update_DatabaseException("Failed to update User_Profile_Attribute 'customer_group_id' setting"); } } // For the migration, a temporary flag is needed in the orders table // in order to prevent mixing up old and new customer_id values. $table_order_name = DBPREFIX . "module_shop_orders"; if (!\Cx\Lib\UpdateUtil::column_exist($table_order_name, 'migrated')) { $query = "\n ALTER TABLE `{$table_order_name}`\n ADD `migrated` TINYINT(1) unsigned NOT NULL default 0"; \Cx\Lib\UpdateUtil::sql($query); } // Create missing UserGroups for customers and resellers $objGroup = null; $group_id_customer = \Cx\Core\Setting\Controller\Setting::getValue('usergroup_id_customer', 'Shop'); if ($group_id_customer) { $objGroup = \FWUser::getFWUserObject()->objGroup->getGroup($group_id_customer); } if (!$objGroup || $objGroup->EOF) { $objGroup = \FWUser::getFWUserObject()->objGroup->getGroups(array('group_name' => 'Shop Endkunden')); } if (!$objGroup || $objGroup->EOF) { $objGroup = new \UserGroup(); $objGroup->setActiveStatus(true); $objGroup->setDescription('Online Shop Endkunden'); $objGroup->setName('Shop Endkunden'); $objGroup->setType('frontend'); } //DBG::log("Group: ".var_export($objGroup, true)); if (!$objGroup) { throw new \Cx\Lib\Update_DatabaseException("Failed to create UserGroup for customers"); } //DBG::log("Customer::errorHandler(): Made customer usergroup: ".var_export($objGroup, true)); if (!$objGroup->store() || !$objGroup->getId()) { throw new \Cx\Lib\Update_DatabaseException("Failed to store UserGroup for customers"); } //DBG::log("Customer::errorHandler(): Stored customer usergroup, ID ".$objGroup->getId()); \Cx\Core\Setting\Controller\Setting::set('usergroup_id_customer', $objGroup->getId()); if (!\Cx\Core\Setting\Controller\Setting::update('usergroup_id_customer')) { throw new \Cx\Lib\Update_DatabaseException("Failed to store UserGroup ID for customers"); } $group_id_customer = $objGroup->getId(); $objGroup = null; $group_id_reseller = \Cx\Core\Setting\Controller\Setting::getValue('usergroup_id_reseller', 'Shop'); if ($group_id_reseller) { $objGroup = \FWUser::getFWUserObject()->objGroup->getGroup($group_id_reseller); } if (!$objGroup || $objGroup->EOF) { $objGroup = \FWUser::getFWUserObject()->objGroup->getGroups(array('group_name' => 'Shop Wiederverkäufer')); } if (!$objGroup || $objGroup->EOF) { $objGroup = new \UserGroup(); $objGroup->setActiveStatus(true); $objGroup->setDescription('Online Shop Wiederverkäufer'); $objGroup->setName('Shop Wiederverkäufer'); $objGroup->setType('frontend'); } if (!$objGroup) { throw new \Cx\Lib\Update_DatabaseException("Failed to create UserGroup for resellers"); } //DBG::log("Customer::errorHandler(): Made reseller usergroup: ".var_export($objGroup, true)); if (!$objGroup->store() || !$objGroup->getId()) { throw new \Cx\Lib\Update_DatabaseException("Failed to store UserGroup for resellers"); } \Cx\Core\Setting\Controller\Setting::set('usergroup_id_reseller', $objGroup->getId()); if (!\Cx\Core\Setting\Controller\Setting::update('usergroup_id_reseller')) { throw new \Cx\Lib\Update_DatabaseException("Failed to store UserGroup ID for resellers"); } $group_id_reseller = $objGroup->getId(); $default_lang_id = \FWLanguage::getDefaultLangId(); $query = "\n SELECT `customer`.`customerid`,\n `customer`.`prefix`, `customer`.`firstname`,\n `customer`.`lastname`,\n `customer`.`company`, `customer`.`address`,\n `customer`.`city`, `customer`.`zip`,\n `customer`.`country_id`,\n `customer`.`phone`, `customer`.`fax`,\n `customer`.`email`,\n `customer`.`username`, `customer`.`password`,\n `customer`.`company_note`,\n `customer`.`is_reseller`,\n `customer`.`customer_status`, `customer`.`register_date`,\n `customer`.`group_id`\n FROM `{$table_name_old}` AS `customer`\n ORDER BY `customer`.`customerid` ASC"; $objResult = \Cx\Lib\UpdateUtil::sql($query); while (!$objResult->EOF) { $old_customer_id = $objResult->fields['customerid']; if (empty($objResult->fields['email'])) { $objResult->fields['email'] = $objResult->fields['username']; } $email = $objResult->fields['email']; $objUser = \FWUser::getFWUserObject()->objUser->getUsers(array('email' => array(0 => $email))); // TODO: See whether a User with that username (but different e-mail address) exists! $objUser_name = \FWUser::getFWUserObject()->objUser->getUsers(array('username' => array(0 => $objResult->fields['username']))); if ($objUser && $objUser_name) { $objUser = $objUser_name; } $objCustomer = null; if ($objUser) { $objCustomer = self::getById($objUser->getId()); } if (!$objCustomer) { $lang_id = Order::getLanguageIdByCustomerId($old_customer_id); $lang_id = \FWLanguage::getLangIdByIso639_1($lang_id); if (!$lang_id) { $lang_id = $default_lang_id; } $objCustomer = new Customer(); if (preg_match('/^(?:frau|mad|mme|signora|miss)/i', $objResult->fields['prefix'])) { $objCustomer->gender('gender_female'); } elseif (preg_match('/^(?:herr|mon|signore|mister|mr)/i', $objResult->fields['prefix'])) { $objCustomer->gender('gender_male'); // } else { // Other "genders", like "family", "thing", or "it" won't be matched // and are left on "gender_unknown". //DBG::log("*** Prefix {$objResult->fields['prefix']}, UNKNOWN GENDER!"); } //DBG::log("Prefix {$objResult->fields['prefix']}, made gender ".$objCustomer->gender()); $objCustomer->company($objResult->fields['company']); $objCustomer->firstname($objResult->fields['firstname']); $objCustomer->lastname($objResult->fields['lastname']); $objCustomer->address($objResult->fields['address']); $objCustomer->city($objResult->fields['city']); $objCustomer->zip($objResult->fields['zip']); $objCustomer->country_id($objResult->fields['country_id']); $objCustomer->phone($objResult->fields['phone']); $objCustomer->fax($objResult->fields['fax']); $objCustomer->email($objResult->fields['email']); $objCustomer->companynote($objResult->fields['company_note']); $objCustomer->active($objResult->fields['customer_status']); // Handled by a UserGroup now, see below //$objCustomer->setResellerStatus($objResult->fields['is_reseller']); $objCustomer->register_date($objResult->fields['register_date']); $objCustomer->group_id($objResult->fields['group_id']); // NOTE: Mind that the User class has been modified to accept e-mail addresses // as usernames! $objCustomer->username($objResult->fields['username']); // Copy the md5 hash of the password! $objCustomer->password = $objResult->fields['password']; $objCustomer->setFrontendLanguage($lang_id); } if ($objResult->fields['is_reseller']) { $objCustomer->setGroups($objCustomer->getAssociatedGroupIds() + array($group_id_reseller)); //DBG::log("Customer::errorHandler(): Added reseller: ".$objCustomer->id()); } else { $objCustomer->setGroups($objCustomer->getAssociatedGroupIds() + array($group_id_customer)); //DBG::log("Customer::errorHandler(): Added customer: ".$objCustomer->id()); } if (!$objCustomer->store()) { //DBG::log(var_export($objCustomer, true)); throw new \Cx\Lib\Update_DatabaseException("Failed to migrate existing Customer ID " . $old_customer_id . " to Users (Messages: " . join(', ', $objCustomer->error_msg) . ")"); } // Update the Orders table with the new Customer ID. // Note that we use the ambiguous old customer ID that may // coincide with a new User ID, so to prevent inconsistencies, // migrated Orders are marked as such. $query = "\n UPDATE `{$table_order_name}`\n SET `customer_id`=" . $objCustomer->id() . ",\n `migrated`=1\n WHERE `customer_id`={$old_customer_id}\n AND `migrated`=0"; \Cx\Lib\UpdateUtil::sql($query); // Drop migrated $query = "\n DELETE FROM `{$table_name_old}`\n WHERE `customerid`={$old_customer_id}"; \Cx\Lib\UpdateUtil::sql($query); $objResult->MoveNext(); if (!checkMemoryLimit() || !checkTimeoutLimit()) { return false; } } // Remove the flag, it's no longer needed. // (You could also verify that all records have been migrated by // querying them with "[...] WHERE `migrated`=0", which *MUST* result // in an empty recordset. This is left as an exercise for the reader.) $query = "\n ALTER TABLE `{$table_order_name}`\n DROP `migrated`"; \Cx\Lib\UpdateUtil::sql($query); \Cx\Lib\UpdateUtil::drop_table($table_name_old); //DBG::log("Updated Customer table and related stuff"); // Always return false; }
/** * Store a customer * * Sets a Message according to the outcome. * Note that failure to send the e-mail with login data is not * considered an error and will only produce a warning. * @return integer The Customer ID on success, null otherwise * @author Reto Kohli <*****@*****.**> */ static function storeCustomerFromPost() { global $_ARRAYLANG; $username = trim(strip_tags(contrexx_input2raw($_POST['username']))); $password = trim(strip_tags(contrexx_input2raw($_POST['password']))); $company = trim(strip_tags(contrexx_input2raw($_POST['company']))); $gender = trim(strip_tags(contrexx_input2raw($_POST['gender']))); $firstname = trim(strip_tags(contrexx_input2raw($_POST['firstname']))); $lastname = trim(strip_tags(contrexx_input2raw($_POST['lastname']))); $address = trim(strip_tags(contrexx_input2raw($_POST['address']))); $city = trim(strip_tags(contrexx_input2raw($_POST['city']))); $zip = trim(strip_tags(contrexx_input2raw($_POST['zip']))); $country_id = intval($_POST['country_id']); $phone = trim(strip_tags(contrexx_input2raw($_POST['phone']))); $fax = trim(strip_tags(contrexx_input2raw($_POST['fax']))); $email = trim(strip_tags(contrexx_input2raw($_POST['email']))); $companynote = trim(strip_tags(contrexx_input2raw($_POST['companynote']))); $customer_active = intval($_POST['active']); $is_reseller = intval($_POST['customer_type']); $customer_group_id = intval($_POST['customer_group_id']); // $registerdate = trim(strip_tags(contrexx_input2raw($_POST['registerdate']))); $lang_id = isset($_POST['customer_lang_id']) ? intval($_POST['customer_lang_id']) : FRONTEND_LANG_ID; $customer_id = intval($_REQUEST['customer_id']); $objCustomer = Customer::getById($customer_id); if (!$objCustomer) { $objCustomer = new Customer(); } $objCustomer->gender($gender); $objCustomer->company($company); $objCustomer->firstname($firstname); $objCustomer->lastname($lastname); $objCustomer->address($address); $objCustomer->city($city); $objCustomer->zip($zip); $objCustomer->country_id($country_id); $objCustomer->phone($phone); $objCustomer->fax($fax); $objCustomer->email($email); $objCustomer->companynote($companynote); $objCustomer->active($customer_active); $objCustomer->is_reseller($is_reseller); // Set automatically: $objCustomer->setRegisterDate($registerdate); $objCustomer->group_id($customer_group_id); $objCustomer->username($username); if (isset($_POST['sendlogindata']) && $password == '') { $password = \User::make_password(); } if ($password != '') { $objCustomer->password($password); } $objCustomer->setFrontendLanguage($lang_id); if (!$objCustomer->store()) { foreach ($objCustomer->error_msg as $message) { \Message::error($message); } return null; } \Message::ok($_ARRAYLANG['TXT_DATA_RECORD_UPDATED_SUCCESSFUL']); if (isset($_POST['sendlogindata'])) { // TODO: Use a common sendLogin() method $lang_id = $objCustomer->getFrontendLanguage(); $arrSubs = $objCustomer->getSubstitutionArray(); $arrSubs['CUSTOMER_LOGIN'] = array(0 => array('CUSTOMER_USERNAME' => $username, 'CUSTOMER_PASSWORD' => $password)); //DBG::log("Subs: ".var_export($arrSubs, true)); // Select template for sending login data $arrMailTemplate = array('key' => 'customer_login', 'section' => 'Shop', 'lang_id' => $lang_id, 'to' => $email, 'substitution' => $arrSubs); if (!\Cx\Core\MailTemplate\Controller\MailTemplate::send($arrMailTemplate)) { \Message::warning($_ARRAYLANG['TXT_MESSAGE_SEND_ERROR']); return $objCustomer->id(); } \Message::ok(sprintf($_ARRAYLANG['TXT_EMAIL_SEND_SUCCESSFULLY'], $email)); } return $objCustomer->id(); }