Exemplo n.º 1
0
 /**
  * Сохраняет заказ в базу сайта.
  * Добавляет в массив корзины третий параметр 'цена товара', для сохранения в заказ.
  * Это нужно для тогою чтобы в последствии вывести детальную информацию о заказе.
  * Если оставить только id то информация может оказаться неверной, так как цены меняютcя.
  * @return int $id номер заказа.
  */
 public function addOrder($adminOrder = false)
 {
     $itemPosition = new Models_Product();
     $cart = new Models_Cart();
     $catalog = new Models_Catalog();
     $categoryArray = $catalog->getCategoryArray();
     $this->summ = 0;
     $currencyRate = MG::getSetting('currencyRate');
     $currencyShopIso = MG::getSetting('currencyShopIso');
     // Массив запросов на обновление количества товаров.
     $updateCountProd = array();
     // Добавляем в массив корзины параметр 'цена товара'.
     if ($adminOrder) {
         $this->email = $adminOrder['user_email'];
         $this->phone = $adminOrder['phone'];
         $this->address = $adminOrder['address'];
         $this->delivery = $adminOrder['delivery_id'];
         $this->dateDelivery = $adminOrder['date_delivery'];
         $this->delivery_cost = $adminOrder['delivery_cost'];
         $this->payment = $adminOrder['payment_id'];
         $this->fio = $adminOrder['name_buyer'];
         $formatedDate = date('Y-m-d H:i:s');
         // Форматированная дата ГГГГ-ММ-ДД ЧЧ:ММ:СС.
         foreach ($adminOrder['order_content'] as $item) {
             $product = $itemPosition->getProduct($item['id']);
             $_SESSION['couponCode'] = $item['coupon'];
             $product['category_url'] = $product['category_url'] ? $product['category_url'] : 'catalog';
             $productUrl = $product['category_url'] . '/' . $product['url'];
             $itemCount = $item['count'];
             if (!empty($product)) {
                 $fulPrice = $item['fulPrice'];
                 // полная стоимость без скидки
                 $product['price'] = $item['price'];
                 // $product['price'] = $item['price_course'];
                 //$product['currency_iso'] = $product['currency_iso']?$product['currency_iso']:$currencyShopIso;
                 //$product['price'] *= $currencyRate[$product['currency_iso']];
                 $discount = 0;
                 if (!empty($item['price']) && (!empty($item['coupon']) || stristr($item['discSyst'], 'true') !== false)) {
                     $discount = 100 - $product['price'] * 100 / $fulPrice;
                 }
                 $productPositions[] = array('id' => $product['id'], 'name' => $item['title'], 'url' => $productUrl, 'code' => $item['code'], 'price' => $product['price'], 'count' => $itemCount, 'property' => $item['property'], 'coupon' => $_SESSION['couponCode'], 'discount' => round($discount, 1), 'fulPrice' => $fulPrice, 'weight' => $product['weight'], 'currency_iso' => $currencyShopIso, 'discSyst' => !empty($item['discSyst']) ? $item['discSyst'] : '');
                 $this->summ += $product['price'] * $itemCount;
                 // По ходу формируем массив запросов на обновление количества товаров.
                 if ($item['variant'] == 0) {
                     $product['count'] = $product['count'] - $itemCount >= 0 ? $product['count'] - $itemCount : 0;
                     $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count`= " . DB::quote($product['count']) . " WHERE `id`=" . DB::quote($product['id']) . " AND `count`>0";
                 } else {
                     $count = DB::query('
           SELECT count
           FROM `' . PREFIX . 'product_variant`
           WHERE id = ' . DB::quote($item['variant']));
                     $count = DB::fetchAssoc($count);
                     $product['count'] = $count['count'] - $itemCount >= 0 ? $count['count'] - $itemCount : 0;
                     $updateCountProd[] = "UPDATE `" . PREFIX . "product_variant` SET `count`= " . DB::quote($product['count']) . " WHERE `id`=" . DB::quote($item['variant']) . " AND `count`>0";
                     $variants = $itemPosition->getVariants($product['id']);
                     $firstVariant = reset($variants);
                     if ($firstVariant['id'] == $item['variant']) {
                         // если приобретен вариант товара, то выясним является ли он первым в наборе, если да то обновим информацию в mg_product
                         $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count`= " . DB::quote($product['count']) . " WHERE `id`=" . DB::quote($product['id']) . " AND `count`>0";
                     }
                 }
                 $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count_buy`= `count_buy` + 1 WHERE `id`=" . DB::quote($product['id']);
             }
         }
     } elseif (!empty($_SESSION['cart'])) {
         foreach ($_SESSION['cart'] as $item) {
             $product = $itemPosition->getProduct($item['id']);
             // Дописываем к массиву продуктов данные о выбранных характеристиках из корзины покупок, чтобы приплюсовать к сумме заказа.
             if ($item['id'] == $product['id']) {
                 $product['property_html'] = $item['propertyReal'];
             }
             $variant = null;
             $discount = null;
             $promocode = null;
             if (!empty($item['variantId']) && $item['id'] == $product['id']) {
                 $variants = $itemPosition->getVariants($product['id']);
                 $variant = $variants[$item['variantId']];
                 $product['price'] = $variant['price_course'];
                 $fulPrice = $product['price'];
                 $priceWithCoupon = $cart->applyCoupon($_SESSION['couponCode'], $product['price'], $product);
                 $priceWithDiscount = $cart->applyDiscountSystem($product['price']);
                 //$product['price'] = $priceWithCoupon < $priceWithDiscount['price'] ? $priceWithCoupon : $priceWithDiscount['price'];
                 $product['price'] = $cart->customPrice(array('product' => $product, 'priceWithCoupon' => $priceWithCoupon, 'priceWithDiscount' => $priceWithDiscount['price']));
                 $product['code'] = $variant['code'];
                 $product['count'] = $variant['count'];
                 $product['weight'] = $variant['weight'];
                 $product['title'] .= " " . $variant['title_variant'];
                 $discountSystem = $priceWithDiscount['discounts'];
                 $promocode = $priceWithDiscount['discounts'] != '' ? $priceWithDiscount['promo'] : $_SESSION['couponCode'];
                 //По ходу формируем массив запросов на обновление количества товаров
                 $resCount = $variant['code'];
                 $resCount = $variant['count'] - $item['count'] >= 0 ? $variant['count'] - $item['count'] : 0;
                 $updateCountProd[] = "UPDATE `" . PREFIX . "product_variant` SET `count`= " . DB::quote($resCount) . " WHERE `id`=" . DB::quote($item['variantId']) . " AND `count`>0";
             }
             $product['category_url'] = $product['category_url'] ? $product['category_url'] : 'catalog';
             $productUrl = $product['category_url'] . '/' . $product['url'];
             // Eсли куки не актуальны исключает попадание несуществующего продукта в заказ
             if (!empty($product)) {
                 if (!$variant) {
                     $product['price'] = $product['price_course'];
                     $fulPrice = $product['price'];
                 }
                 $product['price'] = SmalCart::plusPropertyMargin($fulPrice, $product['property_html'], $currencyRate[$product['currency_iso']]);
                 //$product['currency_iso'] = $product['currency_iso']?$product['currency_iso']:$currencyShopIso;
                 //$product['price'] *= $currencyRate[$product['currency_iso']];
                 $fulPrice = $product['price'];
                 $tempPrice = $product['price'];
                 //   if (!$variant) {
                 $priceWithCoupon = $cart->applyCoupon($_SESSION['couponCode'], $product['price'], $product);
                 $priceWithDiscount = $cart->applyDiscountSystem($product['price']);
                 //$product['price'] = $priceWithCoupon < $priceWithDiscount['price'] ? $priceWithCoupon : $priceWithDiscount['price'];
                 $product['price'] = $cart->customPrice(array('product' => $product, 'priceWithCoupon' => $priceWithCoupon, 'priceWithDiscount' => $priceWithDiscount['price']));
                 $discountSystem = $priceWithDiscount['discounts'];
                 $promocode = $priceWithDiscount['discounts'] != '' ? $priceWithDiscount['promo'] : $_SESSION['couponCode'];
                 //    }
                 $discount = 0;
                 if (!empty($tempPrice)) {
                     $discount = 100 - $product['price'] * 100 / $tempPrice;
                 }
                 $productPositions[] = array('id' => $product['id'], 'name' => $product['title'], 'url' => $productUrl, 'code' => $product['code'], 'price' => $product['price'], 'count' => $item['count'], 'property' => $item['property'], 'coupon' => $promocode, 'discount' => round($discount), 'fulPrice' => $fulPrice, 'weight' => $product['weight'], 'currency_iso' => $currencyShopIso, 'discSyst' => $discountSystem ? $discountSystem : '');
                 $this->summ += $product['price'] * $item['count'];
                 if (!$resCount) {
                     $resCount = $product['count'] - $item['count'] >= 0 ? $product['count'] - $item['count'] : 0;
                 }
                 //По ходу формируем массив запросов на обновление количества товаров
                 if (!$variant) {
                     $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count`= " . DB::quote($resCount) . " WHERE `id`=" . DB::quote($product['id']) . " AND `count`>0";
                 } else {
                     $firstVariant = reset($variants);
                     if ($firstVariant['id'] == $item['variantId']) {
                         // если приобретен вариант товара, то выясним является ли он первым в наборе, если да то обновим информацию в mg_product
                         $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count`= " . DB::quote($resCount) . " WHERE `id`=" . DB::quote($product['id']) . " AND `count`>0";
                     }
                 }
                 $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count_buy`= `count_buy` + 1 WHERE `id`=" . DB::quote($product['id']);
                 $resCount = null;
             }
         }
     }
     // Сериализует данные в строку для записи в бд.
     $orderContent = addslashes(serialize($productPositions));
     // Сериализует данные в строку для записи в бд информации об юридическом лице.
     $yurInfo = '';
     if (!empty($adminOrder['yur_info'])) {
         $yurInfo = addslashes(serialize($adminOrder['yur_info']));
     }
     if (!empty($_POST['yur_info'])) {
         $yurInfo = addslashes(serialize($_POST['yur_info']));
     }
     // Создает новую модель корзины, чтобы узнать сумму заказа.
     $cart = new Models_Cart();
     // Генерируем уникальный хэш для подтверждения заказа.
     $hash = $this->_getHash($this->email);
     //Достаем настройки заказов, чтобы установить статус для нового заказа.
     $propertyOrder = MG::getOption('propertyOrder');
     $propertyOrder = stripslashes($propertyOrder);
     $propertyOrder = unserialize($propertyOrder);
     $order_status_id = $this->payment == 3 && $propertyOrder['order_status'] == 1 ? 3 : $propertyOrder['order_status'];
     // Формируем массив параметров для SQL запроса.
     $array = array('user_email' => $this->email, 'summ' => number_format($this->summ, 2, '.', ''), 'order_content' => $orderContent, 'phone' => $this->phone, 'address' => $this->address, 'delivery_id' => $this->delivery, 'delivery_cost' => $this->delivery_cost, 'payment_id' => $this->payment, 'paided' => '0', 'status_id' => $order_status_id, 'confirmation' => $hash, 'yur_info' => $yurInfo, 'name_buyer' => $this->fio, 'date_delivery' => $this->dateDelivery, 'user_comment' => $this->info, 'ip' => $_SERVER['REMOTE_ADDR']);
     // Если заказ оформляется через админку.
     if ($adminOrder) {
         $array['comment'] = $adminOrder['comment'];
         $array['status_id'] = $adminOrder['status_id'];
         $array['add_date'] = $formatedDate;
         $array['date_delivery'] = $adminOrder['date_delivery'];
         DB::buildQuery("INSERT INTO `" . PREFIX . "order` SET ", $array);
     } else {
         // Отдает на обработку  родительской функции buildQuery.
         DB::buildQuery("INSERT INTO `" . PREFIX . "order` SET add_date = now(), ", $array);
     }
     // Заказ номер id добавлен в базу.
     $id = null;
     $id = DB::insertId();
     $_SESSION['usedCouponCode'] = $_SESSION['couponCode'];
     unset($_SESSION['couponCode']);
     $orderNumber = $this->getOrderNumber($id);
     $hashStatus = '';
     $linkToStatus = '';
     if (MG::getSetting('autoRegister') == "false" && !USER::isAuth()) {
         $hashStatus = md5($id . $this->email . rand(9999));
         $linkToStatus = '<a href="' . SITE . '/order?hash=' . $hashStatus . '" target="blank">' . SITE . '/order?hash=' . $hashStatus . '</a>';
     }
     DB::query("UPDATE `" . PREFIX . "order` SET `number`= " . DB::quote($orderNumber) . ", `hash`=" . DB::quote($hashStatus) . " WHERE `id`=" . DB::quote($id) . "");
     // Ссылка для подтверждения заказа
     $link = 'ссылке <a href="' . SITE . '/order?sec=' . $hash . '&id=' . $id . '" target="blank">' . SITE . '/order?sec=' . $hash . '&id=' . $id . '</a>';
     $table = "";
     // Формирование тела письма.
     if ($id) {
         // Уменьшаем количество купленных товаров
         if (!empty($updateCountProd)) {
             foreach ($updateCountProd as $sql) {
                 DB::query($sql);
             }
             foreach ($productPositions as $product) {
                 Storage::clear(md5('ControllersProduct' . $product['url']));
             }
         }
         // Если заказ создался, то уменьшаем количество товаров на складе.
         $settings = MG::get('settings');
         $delivery = $this->getDeliveryMethod(false, $this->delivery);
         $sitename = $settings['sitename'];
         $currency = MG::getSetting('currency');
         $paymentArray = $this->getPaymentMethod($this->payment);
         $subj = 'Оформлена заявка №' . ($orderNumber != "" ? $orderNumber : $id) . ' на сайте ' . $sitename;
         foreach ($productPositions as &$item) {
             foreach ($item as &$v) {
                 $v = rawurldecode($v);
             }
         }
         $paramToMail = array('orderNumber' => $orderNumber, 'siteName' => MG::getSetting('sitename'), 'delivery' => $delivery, 'currency' => MG::getSetting('currency'), 'fio' => $this->fio, 'email' => $this->email, 'phone' => $this->phone, 'address' => $this->address, 'delivery' => $delivery['description'], 'payment' => $paymentArray['name'], 'adminOrder' => $adminOrder, 'result' => $this->summ, 'deliveryCost' => $this->delivery_cost, 'date_delivery' => $this->dateDelivery, 'total' => $this->delivery_cost + $this->summ, 'confirmLink' => $link, 'ip' => $this->ip, 'lastvisit' => $_SESSION['lastvisit'], 'firstvisit' => $_SESSION['firstvisit'], 'supportEmail' => MG::getSetting('noReplyEmail'), 'shopName' => MG::getSetting('shopName'), 'shopPhone' => MG::getSetting('shopPhone'), 'formatedDate' => date('Y-m-d H:i:s'), 'productPositions' => $productPositions, 'couponCode' => $_SESSION['couponCode'], 'toKnowStatus' => $linkToStatus);
         $emailToUser = MG::layoutManager('email_order', $paramToMail);
         $paramToMail['adminMail'] = true;
         $emailToAdmin = MG::layoutManager('email_order', $paramToMail);
         $mails = explode(',', MG::getSetting('adminEmail'));
         foreach ($mails as $mail) {
             if (preg_match('/^[-._a-zA-Z0-9]+@(?:[a-zA-Z0-9][-a-zA-Z0-9]+\\.)+[a-zA-Z]{2,6}$/', $mail)) {
                 Mailer::addHeaders(array("Reply-to" => $this->email));
                 Mailer::sendMimeMail(array('nameFrom' => $this->fio, 'emailFrom' => MG::getSetting('noReplyEmail'), 'nameTo' => $sitename, 'emailTo' => $mail, 'subject' => $subj, 'body' => $emailToAdmin, 'html' => true));
             }
         }
         // Отправка заявки пользователю.
         Mailer::sendMimeMail(array('nameFrom' => $sitename, 'emailFrom' => MG::getSetting('noReplyEmail'), 'nameTo' => $this->fio, 'emailTo' => $this->email, 'subject' => $subj, 'body' => $emailToUser, 'html' => true));
         // Если заказ успешно записан, то очищает корзину.
         if (!$adminOrder) {
             $cart->clearCart();
         }
     }
     $result = array('id' => $id, 'orderNumber' => $orderNumber);
     // Возвращаем номер созданого заказа.
     $args = func_get_args();
     return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args);
 }
Exemplo n.º 2
0
 /**
  * Парсинг XML и импортв БД товаров.
  * @param $filename - путь к файлу архива с данными.
  */
 public function processImportXml($filename)
 {
     $importOnlyNew = false;
     $sep = DIRECTORY_SEPARATOR;
     $dirname = dirname(__FILE__);
     $realDocumentRoot = str_replace($sep . 'mg-core' . $sep . 'controllers', '', $dirname);
     $lastPositionProduct = $_SESSION['lastCountProduct1cImport'];
     $lastPositionOffer = $_SESSION['lastCountOffer1cImport'];
     $xml = $this->getImportXml($filename);
     if ($xml && $filename == 'import.xml') {
         foreach ($xml->Каталог->attributes() as $key => $val) {
             if ($key == 'СодержитТолькоИзменения' && $val == "true") {
                 $importOnlyNew = true;
             }
         }
         if (isset($xml->Каталог->СодержитТолькоИзменения)) {
             $importOnlyNew = $xml->Каталог->СодержитТолькоИзменения[0] == 'true' ? true : false;
         }
         if (empty($lastPositionProduct) && $importOnlyNew == false) {
             // если установлена директива CLEAR_CATALOG = 1 в config.ini, то удаляем товары перед синхронизацией с 1с
             if (CLEAR_1С_CATALOG != 'CLEAR_1С_CATALOG' && CLEAR_1С_CATALOG != 0) {
                 DB::query('DELETE FROM `' . PREFIX . 'product` WHERE 1');
                 DB::query('DELETE FROM `' . PREFIX . 'category` WHERE 1');
             }
         }
         $category = $this->groupsGreate($xml->Классификатор, $category, 0);
         $this->propertyСreate($xml->Классификатор->Свойства);
         $model = new Models_Product();
         $currentPosition = 0;
         foreach ($xml->Каталог->Товары[0] as $item) {
             $currentPosition++;
             if ($currentPosition <= $lastPositionProduct) {
                 continue;
             }
             // Добавляем изображение товара в папку uploads
             $imageUrl = array();
             if (isset($item->Картинка)) {
                 foreach ($item->Картинка as $img) {
                     $path = $item->Картинка;
                     $image = basename($item->Картинка);
                     if (!empty($image) && is_file($path)) {
                         copy($path, $realDocumentRoot . $sep . 'uploads' . $sep . $image);
                         $widthPreview = MG::getSetting('widthPreview') ? MG::getSetting('widthPreview') : 200;
                         $widthSmallPreview = MG::getSetting('widthSmallPreview') ? MG::getSetting('widthSmallPreview') : 50;
                         $heightPreview = MG::getSetting('heightPreview') ? MG::getSetting('heightPreview') : 100;
                         $heightSmallPreview = MG::getSetting('heightSmallPreview') ? MG::getSetting('heightSmallPreview') : 50;
                         $upload = new Upload(false);
                         $upload->_reSizeImage('70_' . $image, $realDocumentRoot . $sep . 'uploads' . $sep . $image, $widthPreview, $heightPreview);
                         // миниатюра по размерам из БД (150*100)
                         $upload->_reSizeImage('30_' . $image, $realDocumentRoot . $sep . 'uploads' . $sep . $image, $widthSmallPreview, $heightSmallPreview);
                     }
                     $imageUrl[] = $image;
                 }
             }
             $imageUrl = implode($imageUrl, "|");
             $id = (string) $item->Группы->Ид[0];
             $name = (string) $item->Наименование[0];
             $description = '';
             if (isset($item->Описание)) {
                 $description = nl2br((string) $item->Описание[0], true);
             }
             foreach ($item->ЗначенияРеквизитов->ЗначениеРеквизита as $row) {
                 if ($row->Наименование == 'Полное наименование') {
                     $name = $row->Значение;
                 }
             }
             $code = !empty($item->Артикул[0]) ? $item->Артикул[0] : $item->ШтрихКод[0];
             $id_1c = (string) $item->Ид[0];
             $dataProd = array('title' => $name, 'url' => str_replace('\\', '-', URL::prepareUrl(MG::translitIt($name), true)), 'code' => $code, 'price' => 0, 'description' => $description, 'old_price' => '', 'image_url' => $imageUrl, 'count' => 0, 'cat_id' => $category[$id]['category_id'], 'meta_title' => $name, 'meta_keywords' => $name, 'meta_desc' => MG::textMore($description, 157), 'recommend' => 0, 'activity' => 1, 'new' => 0, 'related' => '', 'inside_cat' => '', '1c_id' => $id_1c, 'weight' => '0');
             if ($importOnlyNew) {
                 unset($dataProd['description']);
                 unset($dataProd['image_url']);
                 unset($dataProd['meta_title']);
                 unset($dataProd['meta_keywords']);
                 unset($dataProd['recommend']);
                 unset($dataProd['activity']);
                 unset($dataProd['new']);
                 unset($dataProd['related']);
                 unset($dataProd['inside_cat']);
                 unset($dataProd['weight']);
             }
             //MG::loger(print_r($dataProd,1));
             $res = DB::query('SELECT * 
       FROM ' . PREFIX . 'product WHERE `1c_id`=' . DB::quote($id_1c));
             if ($row = DB::fetchAssoc($res)) {
                 DB::query('
        UPDATE `' . PREFIX . 'product`
        SET ' . DB::buildPartQuery($dataProd) . '
        WHERE `1c_id`=' . DB::quote($id_1c));
             } else {
                 $model->addProduct($dataProd);
             }
             // Привязываем свойства.
             if (isset($item->ЗначенияСвойств)) {
                 foreach ($item->ЗначенияСвойств->ЗначенияСвойства as $prop) {
                     $this->propertyConnect($id_1c, $prop->Ид, $prop->Значение, $category[$id]['category_id']);
                 }
             }
             $execTime = microtime(true) - $this->startTime;
             if ($execTime + 1 >= $this->maxExecTime) {
                 header("Content-type: text/xml; charset=utf-8");
                 echo "";
                 echo "progress\r\n";
                 echo "Выгружено товаров: {$currentPosition}";
                 $_SESSION['lastCountProduct1cImport'] = $currentPosition;
                 exit;
             }
         }
         if ($this->unlinkFile) {
             unlink($filename);
         }
         $_SESSION['lastCountProduct1cImport'] = 0;
     } elseif ($xml && $filename == 'offers.xml') {
         $currentPosition = 0;
         foreach ($xml->ПакетПредложений[0]->Предложения[0] as $item) {
             $currentPosition++;
             if ($currentPosition <= $lastPositionOffer) {
                 continue;
             }
             $id = (string) $item->Ид[0];
             $price = (string) $item->Цены->Цена->ЦенаЗаЕдиницу[0];
             $count = (string) $item->Количество[0];
             $partProd = array('price' => $price, 'count' => $count, 'price_course' => $price);
             DB::query('
        UPDATE `' . PREFIX . 'product`
        SET ' . DB::buildPartQuery($partProd) . '
        WHERE 1c_id = ' . DB::quote($id) . '
     ');
             $execTime = microtime(true) - $this->startTime;
             if ($execTime + 1 >= $this->maxExecTime) {
                 header("Content-type: text/xml; charset=utf-8");
                 echo "";
                 echo "progress\r\n";
                 echo "Выгружено предложений: {$currentPosition}";
                 $_SESSION['lastCountOffer1cImport'] = $currentPosition;
                 exit;
             }
         }
         if ($this->unlinkFile) {
             unlink($filename);
         }
         $_SESSION['lastCountOffer1cImport'] = 0;
         Storage::clear();
     } else {
         echo "Ошибка загрузки XML\n";
         foreach (libxml_get_errors() as $error) {
             echo "\t", $error->message;
             exit;
         }
     }
 }
Exemplo n.º 3
0
 /**
  * Парсинг XML и импортв БД товаров.
  * @param $filename - путь к файлу архива с данными.
  */
 public function processImportXml($filename)
 {
     $importOnlyNew = false;
     $sep = DIRECTORY_SEPARATOR;
     $dirname = dirname(__FILE__);
     $realDocumentRoot = str_replace($sep . 'mg-core' . $sep . 'controllers', '', $dirname);
     $lastPositionProduct = $_SESSION['lastCountProduct1cImport'];
     $lastPositionOffer = $_SESSION['lastCountOffer1cImport'];
     $xml = $this->getImportXml($filename);
     if ($xml && $filename == 'import.xml') {
         foreach ($xml->Каталог->attributes() as $key => $val) {
             if ($key == 'СодержитТолькоИзменения' && $val == "true") {
                 $importOnlyNew = true;
             }
         }
         if (isset($xml->Каталог->СодержитТолькоИзменения)) {
             $importOnlyNew = $xml->Каталог->СодержитТолькоИзменения[0] == 'true' ? true : false;
         }
         if (empty($lastPositionProduct) && $importOnlyNew == false) {
             // если установлена директива CLEAR_CATALOG = 1 в config.ini, то удаляем товары перед синхронизацией с 1с
             if (CLEAR_1С_CATALOG != 'CLEAR_1С_CATALOG' && CLEAR_1С_CATALOG != 0) {
                 DB::query('DELETE FROM `' . PREFIX . 'product` WHERE 1');
                 DB::query('DELETE FROM `' . PREFIX . 'category` WHERE 1');
                 DB::query('DELETE FROM `' . PREFIX . 'product_variant` WHERE 1');
             }
         }
         $category = $this->groupsGreate($xml->Классификатор, $category, 0);
         $this->propertyСreate($xml->Классификатор->Свойства);
         $model = new Models_Product();
         $currentPosition = 0;
         $upload = new Upload(false);
         $widthPreview = MG::getSetting('widthPreview') ? MG::getSetting('widthPreview') : 200;
         $widthSmallPreview = MG::getSetting('widthSmallPreview') ? MG::getSetting('widthSmallPreview') : 50;
         $heightPreview = MG::getSetting('heightPreview') ? MG::getSetting('heightPreview') : 100;
         $heightSmallPreview = MG::getSetting('heightSmallPreview') ? MG::getSetting('heightSmallPreview') : 50;
         foreach ($xml->Каталог->Товары[0] as $item) {
             $currentPosition++;
             if ($currentPosition <= $lastPositionProduct) {
                 continue;
             }
             // Добавляем изображение товара в папку uploads
             $imageUrl = array();
             $realImgPath = array();
             if (isset($item->Картинка)) {
                 foreach ($item->Картинка as $img) {
                     $path = 'tempcml' . $sep . $img;
                     $realImgPath[] = $path;
                     $image = basename($img);
                     $imageUrl[] = $image;
                 }
             }
             $imageUrl = implode($imageUrl, "|");
             $id = (string) $item->Группы->Ид[0];
             $name = (string) $item->Наименование[0];
             $description = '';
             $desExist = false;
             if (isset($item->Описание)) {
                 $description = nl2br((string) $item->Описание[0], true);
                 $desExist = true;
             }
             foreach ($item->ЗначенияРеквизитов->ЗначениеРеквизита as $row) {
                 if ($row->Наименование == 'Полное наименование') {
                     // если в файле нет специального тега с описанием, то берем из полного наименования
                     if (!$desExist) {
                         $description = (string) $row->Значение ? (string) $row->Значение : $description;
                         $description = nl2br($description, true);
                     } else {
                         // иначе полное наименование подставляем в title товара
                         $name = (string) $row->Значение ? (string) $row->Значение : $name;
                     }
                 }
             }
             $code = !empty($item->Артикул[0]) ? $item->Артикул[0] : $item->ШтрихКод[0];
             $id_1c = (string) $item->Ид[0];
             $dataProd = array('title' => $name, 'url' => str_replace('\\', '-', URL::prepareUrl(MG::translitIt($name), true)), 'code' => $code, 'price' => 0, 'description' => $description, 'old_price' => '', 'image_url' => $imageUrl, 'count' => 0, 'cat_id' => $category[$id]['category_id'], 'meta_title' => $name, 'meta_keywords' => $name, 'meta_desc' => MG::textMore($description, 157), 'recommend' => 0, 'activity' => 1, 'new' => 0, 'related' => '', 'inside_cat' => '', '1c_id' => $id_1c, 'weight' => '0');
             if ($importOnlyNew) {
                 unset($dataProd['description']);
                 unset($dataProd['image_url']);
                 unset($dataProd['meta_title']);
                 unset($dataProd['meta_keywords']);
                 unset($dataProd['recommend']);
                 unset($dataProd['activity']);
                 unset($dataProd['new']);
                 unset($dataProd['related']);
                 unset($dataProd['inside_cat']);
                 unset($dataProd['weight']);
             }
             $res = DB::query('SELECT * 
       FROM ' . PREFIX . 'product WHERE `1c_id`=' . DB::quote($id_1c));
             if ($row = DB::fetchAssoc($res)) {
                 DB::query('
        UPDATE `' . PREFIX . 'product`
        SET ' . DB::buildPartQuery($dataProd) . '
        WHERE `1c_id`=' . DB::quote($id_1c));
                 $productId = $row['id'];
             } else {
                 $newProd = $model->addProduct($dataProd);
                 $productId = $newProd['id'];
             }
             $arImgPath = explode('/', $realImgPath[0]);
             array_pop($arImgPath);
             $path = implode($sep, $arImgPath);
             $imageUrl = explode('|', $imageUrl);
             $dir = floor($productId / 100) . '00';
             if (!empty($realImgPath)) {
                 foreach ($realImgPath as $cell => $image) {
                     if (!empty($image) && is_file($image)) {
                         $upload->_reSizeImage('70_' . $imageUrl[$cell], $realDocumentRoot . $sep . $image, $widthPreview, $heightPreview, 'PROPORTIONAL', 'uploads' . $sep . $addPath . 'thumbs' . $sep);
                         $upload->_reSizeImage('30_' . $imageUrl[$cell], $realDocumentRoot . $sep . $image, $widthSmallPreview, $heightSmallPreview, 'PROPORTIONAL', 'uploads/' . $addPath . 'thumbs/');
                     }
                 }
                 $model->movingProductImage($imageUrl, $productId, $path);
             }
             // Привязываем свойства.
             if (isset($item->ЗначенияСвойств)) {
                 foreach ($item->ЗначенияСвойств->ЗначенияСвойства as $prop) {
                     $propVal = '';
                     $tempProp = '' . $prop->Значение[0];
                     if (!empty($_SESSION['variant_value'][$tempProp])) {
                         $propVal = $_SESSION['variant_value'][$tempProp];
                     }
                     if (empty($propVal)) {
                         $propVal = '';
                         $idVal = '' . $prop->ИдЗначения;
                         if (!empty($_SESSION['variant_value'][$idVal])) {
                             $propVal = $_SESSION['variant_value'][$idVal];
                         }
                     }
                     $this->propertyConnect($id_1c, $prop->Ид, $propVal, $category[$id]['category_id']);
                 }
             }
             $execTime = microtime(true) - $this->startTime;
             if ($execTime + 1 >= $this->maxExecTime) {
                 header("Content-type: text/xml; charset=utf-8");
                 echo "";
                 echo "progress\r\n";
                 echo "Выгружено товаров: {$currentPosition}";
                 $_SESSION['lastCountProduct1cImport'] = $currentPosition;
                 exit;
             }
         }
         if ($this->unlinkFile) {
             unlink($realDocumentRoot . '/tempcml/' . $filename);
         }
         $_SESSION['lastCountProduct1cImport'] = 0;
     } elseif ($xml && $filename == 'offers.xml') {
         $currentPosition = 0;
         $model = new Models_Product();
         $currencyRate = MG::getSetting('currencyRate');
         $currencyShort = MG::getSetting('currencyShort');
         foreach ($xml->ПакетПредложений[0]->Предложения[0] as $item) {
             $currentPosition++;
             if ($currentPosition <= $lastPositionOffer) {
                 continue;
             }
             $id = (string) $item->Ид[0];
             $price = (string) $item->Цены->Цена->ЦенаЗаЕдиницу[0];
             $iso = $this->getIsoByCode((string) $item->Цены->Цена->Валюта[0]);
             if ($iso == 'NULL') {
                 $iso = substr(MG::translitIt((string) $item->Цены->Цена->Валюта[0]), 0, 3);
             }
             $count = (string) $item->Количество[0];
             // если валюта товара не задана ранее в магазине, то добавим ее. (Курс нужно будет установить вручную в настройках)
             $currency = array();
             if (empty($currencyRate[$iso])) {
                 $currency['iso'] = htmlspecialchars($iso);
                 $currency['short'] = $currency['iso'];
                 $currency['rate'] = 1;
                 $currencyRate[$currency['iso']] = $currency['rate'];
                 $currencyShort[$currency['iso']] = $currency['short'];
                 MG::setOption(array('option' => 'currencyRate', 'value' => addslashes(serialize($currencyRate))));
                 MG::setOption(array('option' => 'currencyShort', 'value' => addslashes(serialize($currencyShort))));
             }
             $partProd = array('price' => $price, 'count' => $count < 0 ? 0 : $count, 'currency_iso' => $iso);
             // проверяем, вдруг это предложение является вариантом для товара
             $ids1c = explode('#', (string) $item->Ид[0]);
             $variantId = '';
             // если id варианта не найден
             if (empty($ids1c[1])) {
                 // просто товар, не вариант
                 DB::query('
          UPDATE `' . PREFIX . 'product`
          SET ' . DB::buildPartQuery($partProd) . ' , `price_course` = ROUND(' . DB::quote($price * $currencyRate[$iso], TRUE) . ',2) 
          WHERE 1c_id = ' . DB::quote($ids1c[0]) . '
       ');
             } else {
                 // если товарное предложение является вариантом для продукта
                 $productId = '';
                 $variantId = $ids1c[1];
                 $variant = array();
                 $dbRes = DB::query('
         SELECT id FROM `' . PREFIX . 'product`          
         WHERE 1c_id = ' . DB::quote($ids1c[0]) . '
       ');
                 if ($row = DB::fetchArray($dbRes)) {
                     $productId = $row['id'];
                     $name = array();
                     foreach ($item->ХарактеристикиТовара->ХарактеристикаТовара as $prop) {
                         $name[] = $prop->Значение;
                     }
                     $name = implode(', ', $name);
                     $titleVariant = $name;
                     $variant = array('title_variant' => $titleVariant, 'code' => $item->Артикул[0], 'price' => $price, 'old_price' => '', 'image' => '', 'count' => $count < 0 ? 0 : $count, '1c_id' => $variantId, 'weight' => '0', 'activity' => 1, 'currency_iso' => $iso);
                     // ******
                     //  ищем варианты для этого товара
                     $dbRes = DB::query('
           SELECT id FROM `' . PREFIX . 'product_variant`           
           WHERE product_id = ' . DB::quote($productId) . '
         ');
                     // если еще ни одного небыло, то создаем и обновляем в таблице product значения по первому варианту
                     if ($row != DB::fetchArray($dbRes)) {
                         DB::query('
            UPDATE `' . PREFIX . 'product`
            SET ' . DB::buildPartQuery($partProd) . ' , `price_course` = ROUND(' . DB::quote($price * $currencyRate[$iso], TRUE) . ',2) 
            WHERE 1c_id = ' . DB::quote($ids1c[0]) . '
           ');
                     }
                     // ******
                     // проверяем, импортирован ли ранее этот вариант
                     $dbRes = DB::query('
           SELECT id FROM `' . PREFIX . 'product_variant`           
           WHERE 1c_id = ' . DB::quote($ids1c[1]) . '
         ');
                     // если еще нет, то получаем массив всех имеющихся вариантов по этому продукту,
                     // добавляем к нему новый вариант и обновляем массив вариантов стандартными средствами
                     if (!($row = DB::fetchArray($dbRes))) {
                         $arrVariants = array();
                         $res = DB::query('
               SELECT  pv.*
               FROM `' . PREFIX . 'product_variant` pv    
               WHERE pv.product_id = ' . DB::quote($productId) . '
               ORDER BY sort
             ');
                         if (!empty($res)) {
                             while ($var = DB::fetchAssoc($res)) {
                                 $arrVariants[$var['id']] = $var;
                             }
                         }
                         $variant['price_course'] = round($price * $currencyRate[$iso], 2);
                         $arrVariants[] = $variant;
                         $model->saveVariants($arrVariants, $productId);
                     } else {
                         // обновить вариант
                         DB::query('
            UPDATE `' . PREFIX . 'product_variant`
            SET ' . DB::buildPartQuery($variant) . ',`price_course` = ROUND(' . DB::quote($price * $currencyRate[$iso], TRUE) . ',2)
            WHERE 1c_id = ' . DB::quote($ids1c[0]) . '
           ');
                     }
                 }
             }
             $execTime = microtime(true) - $this->startTime;
             if ($execTime + 1 >= $this->maxExecTime) {
                 header("Content-type: text/xml; charset=utf-8");
                 echo "";
                 echo "progress\r\n";
                 echo "Выгружено предложений: {$currentPosition}";
                 $_SESSION['lastCountOffer1cImport'] = $currentPosition;
                 exit;
             }
         }
         if ($this->unlinkFile) {
             unlink($realDocumentRoot . '/tempcml/' . $filename);
         }
         $_SESSION['lastCountOffer1cImport'] = 0;
         Storage::clear();
     } else {
         echo "Ошибка загрузки XML\n";
         foreach (libxml_get_errors() as $error) {
             echo "\t", $error->message;
             exit;
         }
     }
 }
Exemplo n.º 4
0
 /**
  * Очишает таблицу с кэшем объектов
  * @return boolean
  */
 public function clearСache()
 {
     Storage::clear();
     return true;
 }
Exemplo n.º 5
0
 /**
  * Сортировка по порядку добавления категорий на сайт.
  */
 public function sortToAdd()
 {
     $res = DB::query('
     UPDATE `' . PREFIX . 'category` 
     SET  `sort` = `id`');
     Storage::clear(md5('category'));
 }