/** * Сохраняет и обновляет параметры записи. * @return type */ public function saveEntity() { //доступно только модераторам и админам. USER::AccessOnly('1,4', 'exit()'); $this->messageSucces = $this->lang['ENTITY_SAVE']; $this->messageError = $this->lang['ENTITY_SAVE_NOT']; unset($_POST['mguniqueurl']); unset($_POST['pluginHandler']); if (!empty($_POST['id'])) { // если передан ID, то обновляем if (DB::query(' UPDATE `' . PREFIX . $this->pluginName . '-elements` SET ' . DB::buildPartQuery($_POST) . ' WHERE id =' . DB::quote($_POST['id']))) { $this->data['row'] = $_POST; } else { return false; } } else { // если не передан ID, то создаем if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '-elements` SET ', $_POST)) { $_POST['id'] = DB::insertId(); DB::query(' UPDATE `' . PREFIX . $this->pluginName . '-elements` SET `sort`=' . DB::quote($_POST['id']) . ' WHERE id =' . DB::quote($_POST['id'])); $this->data['row'] = $_POST; } else { return false; } } return true; }
/** * Добавляет новость в базу данных. * * @param array $array массив с данными о новости. * @return bool|int в случае успеха возвращает id добавленной новости. */ public function addNews($array) { unset($array['id']); $result = array(); $array['url'] = empty($array['url']) ? MG::translitIt($array['title']) : $array['url']; if (strlen($array['url']) > 60) { $array['url'] = substr($array['url'], 0, 60); } // Исключает дублирование. $dublicatUrl = false; $tempArray = $this->getNewsByUrl($array['url']); if (!empty($tempArray)) { $dublicatUrl = true; } if (DB::buildQuery('INSERT INTO `mpl_news` SET add_date=now(), ', $array)) { $id = DB::insertId(); // Если url дублируется, то дописываем к нему id новости. if ($dublicatUrl) { $this->updateNews(array('id' => $id, 'url' => $array['url'] . '_' . $id)); } $array['id'] = $id; $result = $array; } return $result; }
/** * Сохраняет и обновляет параметры записи. * @return type */ public function saveEntity() { $this->messageSucces = $this->lang['ENTITY_SAVE']; $this->messageError = $this->lang['ENTITY_SAVE_NOT']; unset($_POST['pluginHandler']); if (!empty($_POST['id'])) { // если передан ID, то обновляем if (DB::query(' UPDATE `' . PREFIX . $this->pluginName . '` SET ' . DB::buildPartQuery($_POST) . ' WHERE id = ' . DB::quote($_POST['id']))) { $this->data['row'] = $_POST; $this->data['slider'] = SliderAction::sliderAction(); } else { return false; } } else { // если не передан ID, то создаем if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { $_POST['id'] = DB::insertId(); DB::query(' UPDATE `' . PREFIX . $this->pluginName . '` SET `sort` = `id` WHERE `id` = ' . DB::quote($_POST['id'])); $this->data['row'] = $_POST; $this->data['slider'] = SliderAction::sliderAction(); } else { return false; } } return true; }
/** * Добавление сущности в таблицу БД * @param type $array - массив полей и значений * @return array возвращает входящий массив */ public function addEntity($array) { unset($array['id']); if (DB::buildQuery('INSERT INTO `' . PREFIX . "product_" . $this->pluginName . '` SET ', $array)) { return true; } return false; }
public function editImg() { unset($_POST['pluginHandler']); $id = $_POST['id_cat']; if ($this->isIssetImg($id)) { if (DB::query('UPDATE `' . PREFIX . $this->pluginName . '` SET ' . DB::buildPartQuery($_POST) . ' WHERE `id_cat` = ' . $id)) { return TRUE; } } else { if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { return TRUE; } } }
/** * Добавляет новую учетную запись пользователя в базу сайта. * @param $userInfo - массив значений для вставки в БД [Поле => Значение]. * @return bool */ public static function add($userInfo) { $result = false; // Если пользователя с таким емайлом еще нет. if (!self::getUserInfoByEmail($userInfo['email'])) { $userInfo['pass'] = crypt($userInfo['pass']); foreach ($array as $k => $v) { if ($k !== 'pass') { $array[$k] = htmlspecialchars_decode($v); $array[$k] = htmlspecialchars($v); } } if (DB::buildQuery('INSERT INTO `' . PREFIX . 'user` SET ', $userInfo)) { $id = DB::insertId(); $result = $id; } } else { $result = false; } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
public function handlerCall() { $this->messageSucces = $this->lang['ENTITY_SAVE_SUCCESS']; $this->messageError = $this->lang['ENTITY_SAVE_ERROR']; unset($_POST['pluginHandler']); $conf = $this->getConfigPlugin(); $msg = 'Обр. звонок. ' . $_POST['name'] . ' ' . $_POST['phone']; if (!empty($_POST['comment'])) { $msg .= ' ' . $_POST['comment']; } SMSAlerts::sendsms(null, $msg); if ($conf['send_mail']) { if ($this->sendMail()) { return true; } else { return false; } } else { if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { return true; } } return false; }
/** * Создает новую страницу. * * @param array $array массив с данными о страницах. * @return bool|int в случае успеха возвращает id добавленной страницы. */ public function addPage($array) { unset($array['id']); $result = array(); if (!empty($array['url'])) { $array['url'] = URL::prepareUrl($array['url']); } $maskField = array('title', 'meta_title', 'meta_keywords', 'meta_desc', 'image_title', 'image_alt'); foreach ($array as $k => $v) { if (in_array($k, $maskField)) { $v = htmlspecialchars_decode($v); $array[$k] = htmlspecialchars($v); } } // Исключает дублирование. $dublicatUrl = false; $tempArray = $this->getPageByUrl($array['url'], $array['parent_url']); if (!empty($tempArray)) { $dublicatUrl = true; } $array['sort'] = $array['id']; if (DB::buildQuery('INSERT INTO `' . PREFIX . 'page` SET ', $array)) { $id = DB::insertId(); // Если url дублируется, то дописываем к нему id продукта. if ($dublicatUrl) { $arr = array('id' => $id, 'sort' => $id, 'url' => $array['url'] . '_' . $id); } else { $arr = array('id' => $id, 'sort' => $id, 'url' => $array['url']); } $this->updatePage($arr); $array['id'] = $id; $result = $array; } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
public function addSlide() { $this->messageError = $this->lang['ENTITY_SAVE_ERROR']; $this->messageSucces = $this->lang['ENTITY_SAVE_SUCCESS']; unset($_POST['pluginHandler']); if (!empty($_POST['id'])) { $this->updateSlide($_POST); } else { unset($_POST['id']); if (isset($_POST['type'])) { $_POST['sort'] = $this->getCountSlide(); if ($_POST['type'] == 'img') { $this->data['row']['type'] = $_POST['type']; unset($_POST['type']); if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { $this->data['row']['id'] = DB::insertId(); $this->data['row']['sort'] = $_POST['sort']; $this->data['row']['img'] = SITE . '/' . PLUGIN_DIR . $this->pluginName . '/img/slides/' . $_POST['img']; return true; } } else { if ($_POST['type'] == 'desc') { $this->data['row']['type'] = $_POST['type']; unset($_POST['type']); if (DB::buildQuery('INSERT INTO `' . PREFIX . $this->pluginName . '` SET ', $_POST)) { $this->data['row']['id'] = DB::insertId(); $this->data['row']['name_link'] = $_POST['name_link']; $this->data['row']['url_link'] = $_POST['url_link']; $this->data['row']['desc'] = $_POST['desc']; $this->data['row']['sort'] = $_POST['sort']; $this->data['row']['img'] = SITE . '/' . PLUGIN_DIR . $this->pluginName . '/img/slides/' . $_POST['img']; return true; } } } } } }
/** * Сохраняет заказ в базу сайта. * Добавляет в массив корзины третий параметр 'цена товара', для сохранения в заказ. * Это нужно для тогою чтобы в последствии вывести детальную информацию о заказе. * Если оставить только 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); }
/** * Добавляет товар в базу данных. * @param array $array массив с данными о товаре. * @return bool|int в случае успеха возвращает id добавленного товара. */ public function addProduct($array, $clone = false) { if (empty($array['title'])) { return false; } $userProperty = $array['userProperty']; $variants = !empty($array['variants']) ? $array['variants'] : array(); // варианты товара unset($array['userProperty']); unset($array['variants']); unset($array['id']); $result = array(); $array['url'] = empty($array['url']) ? MG::translitIt($array['title']) : $array['url']; $maskField = array('title', 'meta_title', 'meta_keywords', 'meta_desc', 'image_title', 'image_alt'); foreach ($array as $k => $v) { if (in_array($k, $maskField)) { $v = htmlspecialchars_decode($v); $array[$k] = htmlspecialchars($v); } } if (!empty($array['url'])) { $array['url'] = URL::prepareUrl($array['url']); } // Исключает дублирование. $dublicatUrl = false; $tempArray = $this->getProductByUrl($array['url']); if (!empty($tempArray)) { $dublicatUrl = true; } if (DB::buildQuery('INSERT INTO `' . PREFIX . 'product` SET ', $array)) { $id = DB::insertId(); // Если url дублируется, то дописываем к нему id продукта. if ($dublicatUrl) { $this->updateProduct(array('id' => $id, 'url' => $array['url'] . '_' . $id, 'sort' => $id)); } else { $this->updateProduct(array('id' => $id, 'url' => $array['url'], 'sort' => $id)); } $array['id'] = $id; $array['userProperty'] = $userProperty; $userProp = array(); if ($clone) { if (!empty($userProperty)) { foreach ($userProperty as $property) { $userProp[$property['property_id']] = $property['value']; if (!empty($property['product_margin'])) { $userProp["margin_" . $property['property_id']] = $property['product_margin']; } } $userProperty = $userProp; } } if (!empty($userProperty)) { $this->saveUserProperty($userProperty, $id); } // Обновляем и добавляем варианты продукта. $this->saveVariants($variants, $id); $variants = $this->getVariants($id); foreach ($variants as $variant) { $array['variants'][] = $variant; } $tempProd = $this->getProduct($id); $array['category_url'] = $tempProd['category_url']; $array['product_url'] = $tempProd['product_url']; $result = $array; } $this->updatePriceCourse($currencyShopIso, array($result['id'])); $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
/** * Сохраняет заказ в базу сайта. * Добавляет в массив корзины третий параметр 'цена товара', для сохранения в заказ. * Это нужно для тогою чтобы в последствии вывести детальную информацию о заказе. * Если оставить только 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; // Массив запросов на обновление количества товаров. $updateCountProd = array(); // Добавляем в массив корзины параметр 'цена товара'. if ($adminOrder) { $this->email = $adminOrder['user_email']; $this->phone = $adminOrder['phone']; $this->address = $adminOrder['address']; $this->delivery = $adminOrder['delivery_id']; $this->delivery_cost = $adminOrder['delivery_cost']; $this->payment = $adminOrder['payment_id']; $this->fio = $adminOrder['user_email']; $formatedDate = date('Y-m-d H:i:s'); // Форматированная дата ГГГГ-ММ-ДД ЧЧ:ММ:СС. foreach ($adminOrder['order_content'] as $item) { $product = $itemPosition->getProduct($item['id']); $_SESSION['couponCode'] = $item['coupon']; $productUrl = $product['category_url'] . '/' . $product['url']; $itemCount = $item['count']; if (!empty($product)) { $product['price'] = $item['price']; $product['price'] = $cart->applyCoupon($_SESSION['couponCode'], $product['price'], $product); $discount = 100 - $product['price'] * 100 / $item['price']; $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' => $discount, 'info' => $this->info); $this->summ += $product['price'] * $itemCount; $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"; } } } 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; if (!empty($item['variantId']) && $item['id'] == $product['id']) { $variants = $itemPosition->getVariants($product['id']); $variant = $variants[$item['variantId']]; $product['price'] = $variant['price']; $product['price'] = $cart->applyCoupon($_SESSION['couponCode'], $product['price'], $product); $product['code'] = $variant['code']; $product['count'] = $variant['count']; $product['title'] .= " " . $variant['title_variant']; //По ходу формируем массив запросов на обновление количества товаров $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"; } $productUrl = $product['category_url'] . '/' . $product['url']; // Eсли куки не актуальны исключает попадание несуществующего продукта в заказ if (!empty($product)) { $product['price'] = SmalCart::plusPropertyMargin($product['price'], $product['property_html']); $tempPrice = $product['price']; $product['price'] = $cart->applyCoupon($_SESSION['couponCode'], $product['price'], $product); $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' => $_SESSION['couponCode'], 'discount' => $discount, 'info' => $this->info); $this->summ += $product['price'] * $item['count']; if (!$resCount) { $resCount = $product['count'] - $item['count'] >= 0 ? $product['count'] - $item['count'] : 0; } //По ходу формируем массив запросов на обновление количества товаров $updateCountProd[] = "UPDATE `" . PREFIX . "product` SET `count`= " . DB::quote($resCount) . " WHERE `id`=" . DB::quote($product['id']) . " AND `count`>0"; $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); // Формируем массив параметров для SQL запроса. $array = array('user_email' => $this->email, 'summ' => $this->summ, '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' => '0', 'confirmation' => $hash, 'yur_info' => $yurInfo, 'name_buyer' => $this->fio); // Если заказ оформляется через админку. if ($adminOrder) { $array['comment'] = $adminOrder['comment']; $array['status_id'] = $adminOrder['status_id']; $array['add_date'] = $formatedDate; 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(); unset($_SESSION['couponCode']); // Ссылка для подтверждения заказа $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); } } // Если заказ создался, то уменьшаем количество товаров на складе. $settings = MG::get('settings'); $delivery = $this->getDeliveryMethod(false, $this->delivery); $sitename = $settings['sitename']; $currency = MG::getSetting('currency'); $subj = 'Оформлена заявка №' . $id . ' на сайте ' . $sitename; $subj = str_replace('№', '#', $subj); if ($this->fio) { $table .= '<br/><b>Покупатель:</b> ' . $this->fio; } $table .= '<br/><b>E-mail:</b> ' . $this->email; $table .= '<br/><b>Тел:</b> ' . $this->phone; if ($this->address) { $table .= '<br/><b>Адрес:</b> ' . $this->address; } $table .= '<br/><b>Доставка:</b> ' . $delivery['description']; $paymentArray = $this->getPaymentMethod($this->payment); $table .= '<br/><b>Оплата:</b> ' . $paymentArray['name']; $table .= ' <style> table {border: 4px double black;border-collapse: collapse;} th {text-align: left;background: #ccc;padding: 5px;border: 1px solid black;} td {padding: 5px;border: 1px solid black;} </style>'; $table .= '<br><br><table>'; if (!empty($_SESSION['cart']) || $adminOrder) { $table .= ' <tr> <th>Наименование товара</th> <th>Артикул</th> <th>Стоимость</th> <th>Количество</th> </tr>'; foreach ($productPositions as $product) { $product['property'] = htmlspecialchars_decode(str_replace('&', '&', $product['property'])); $table .= ' <tr> <td>' . $product['name'] . $product['property'] . '</td> <td>' . $product['code'] . '</td> <td>' . $product['price'] . ' ' . $currency . '</td> <td>' . $product['count'] . ' шт.</td> </tr>'; } } $table .= '</table>'; $table .= '<br><b>Итого:</b> ' . $this->summ . ' ' . $currency; $table .= '<br/><b>Стоимость доставки:</b> ' . $this->delivery_cost . " " . $currency; $totalSumm = $this->delivery_cost + $this->summ; $table .= '<br/><b>Всего к оплате:</b> <span style="color:red">' . $totalSumm . ' ' . $currency . '</span>'; $msg = MG::getSetting('orderMessage') . '<br><u>Обязательно подтвердите</u> свой заказ, перейдя по ' . $link . '.<br>' . $table; $msg = str_replace('#ORDER#', $id, $msg); $msg = str_replace('#SITE#', $sitename, $msg); $msg = str_replace('№', '#', $msg); $mails = explode(',', MG::getSetting('adminEmail')); // Отправка заявки админам. // Дополнительная информация для админов. $msgAdmin .= '<br/><br/><b>Покупатель перешел к нам на сайт из: </b><br/>' . $_SESSION['lastvisit'] . '<br/><br/><b>Покупатель впервые перешел к нам на сайт из: </b><br/>' . $_SESSION['firstvisit']; foreach ($mails as $mail) { if (preg_match('/^[-._a-z0-9]+@(?:[a-z0-9][-a-z0-9]+\\.)+[a-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' => $msg . $msgAdmin, 'html' => true)); } } // Добавление в тело письма ссылки для задания пароля. $msg .= '<br>Подтвердите свой заказ, перейдя по ' . $link; // Отправка заявки пользователю. Mailer::sendMimeMail(array('nameFrom' => $sitename, 'emailFrom' => MG::getSetting('noReplyEmail'), 'nameTo' => $this->fio, 'emailTo' => $this->email, 'subject' => $subj, 'body' => $msg, 'html' => true)); // Если заказ успешно записан, то очищает корзину. if (!$adminOrder) { $cart->clearCart(); } } // Возвращаем номер созданого заказа. $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $id, $args); }