public function __construct() { mgActivateThisPlugin(__FILE__, array(__CLASS__, 'createDateBase')); mgAddAction(__FILE__, array(__CLASS__, 'pageSettingsPlugin')); if (!URL::isSection('mg-admin')) { mgAddShortcode('sms', array(__CLASS__, 'sendsms')); } }
public function __construct() { mgAddShortcode('feed-back-ajx', array(__CLASS__, 'handleShortCode')); self::$pluginName = PM::getFolderPlugin(__FILE__); self::$path = PLUGIN_DIR . self::$pluginName; if (!URL::isSection('mg-admin')) { mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/feed-back-user.js"></script>'); } }
function __construct() { self::$pluginName = PM::getFolderPlugin(__FILE__); self::$path = PLUGIN_DIR . self::$pluginName; mgAddShortcode('scroll-top', array(__CLASS__, 'showScrollTop')); if (!URL::isSection('mg-admin')) { // подключаем CSS плагина для всех страниц, кроме админки mgAddMeta('<link rel="stylesheet" href="' . SITE . '/' . self::$path . '/css/style.css" type="text/css" />'); mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/scrolltop.js"></script>'); } }
public function __construct() { mgActivateThisPlugin(__FILE__, array(__CLASS__, 'activate')); mgAddAction(__FILE__, array(__CLASS__, 'pageSettingsPlugin')); mgAddShortcode('call-back', array(__CLASS__, 'handleShortCode')); self::$lang = PM::plugLocales(self::$pluginName); self::$path = PLUGIN_DIR . self::$pluginName; if (!URL::isSection('mg-admin')) { mgAddMeta('<link rel="stylesheet" href="' . SITE . '/' . self::$path . '/css/user.css" type="text/css" />'); mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/jquery.maskedinput.min.js"></script>'); mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/user.js"></script>'); } MG::addInformer(array('count' => self::getEntityActive(), 'class' => 'count-wrap', 'classIcon' => 'message-icon', 'isPlugin' => true, 'section' => 'call-back', 'priority' => 80)); }
public function __construct() { mgActivateThisPlugin(__FILE__, array(__CLASS__, 'activate')); mgAddAction(__FILE__, array(__CLASS__, 'pageSettingsPlugin')); mgAddShortcode('slider-images', array(__CLASS__, 'handleShortCode')); self::$pluginName = PM::getFolderPlugin(__FILE__); self::$lang = PM::plugLocales(self::$pluginName); self::$path = PLUGIN_DIR . self::$pluginName; if (!URL::isSection('mg-admin')) { mgAddMeta('<link rel="stylesheet" href="' . SITE . '/' . self::$path . '/css/jquery.bxslider.css" type="text/css" />'); mgAddMeta('<link rel="stylesheet" href="' . SITE . '/' . self::$path . '/css/slider-images-user.css" type="text/css" />'); mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/jquery.bxslider.min.js"></script>'); mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/slider-images-user.js"></script>'); } }
public function __construct() { mgActivateThisPlugin(__FILE__, array(__CLASS__, 'activate')); //Инициализация метода выполняющегося при активации mgAddShortcode('rating', array(__CLASS__, 'showRating')); // Инициализация шорткода [rating] - доступен в любом HTML коде движка. self::$pluginName = PM::getFolderPlugin(__FILE__); self::$lang = PM::plugLocales(self::$pluginName); self::$path = PLUGIN_DIR . self::$pluginName; if (!URL::isSection('mg-admin')) { // подключаем CSS плагина для всех страниц, кроме админки mgAddMeta('<link rel="stylesheet" href="' . SITE . '/' . self::$path . '/css/rateit.css" type="text/css" />'); } mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/rating.js"></script>'); // подключаем плагин для работы с отображение звезд системы рейтинга mgAddMeta('<script type="text/javascript" src="' . SITE . '/' . self::$path . '/js/jquery.rateit.min.js"></script>'); }
/** * Обработчик шотркода вида [slider-action] * выполняется когда при генерации страницы встречается [slider-action] */ static function sliderAction() { if (!URL::isSection('mg-admin')) { $option = MG::getSetting('sliderActionOption'); } else { $option = MG::getOption('sliderActionOption'); } $option = stripslashes($option); $options = unserialize($option); $options["width"] = $options["width"] ? $options["width"] . 'px' : '100%'; $options["height"] = $options["height"] ? $options["height"] . 'px' : 'auto'; if ($options["position"] == 'right') { $options["position"] = "float:right;"; } if ($options["position"] == 'left') { $options["position"] = "float:left;"; } if ($options["position"] == 'center') { $options["position"] = "margin: 0 auto;"; } $slides = self::getEntity(); $html = '<div class="m-p-slider-wrapper" style="width:' . $options["width"] . '; height:' . $options["height"] . '; ' . $options["position"] . '">'; if ($options["titleslider"] != "") { $html .= '<h2>' . $options["titleslider"] . '</h2>'; } $html .= '<div class="m-p-slider-contain">'; foreach ($slides as $slide) { if (!$slide['invisible']) { continue; } if ($slide["type"] == "img" && !empty($slide["href"])) { $slide["value"] = '<a href="' . $slide["href"] . '">' . $slide["value"] . '</a>'; } $html .= "<div class='m-p-slide-unit'>" . $slide["value"]; if ($options["nameaction"] == 'true') { $html .= "<div class='nameaction'>" . $slide["nameaction"] . "</div>"; } $html .= "</div>"; } $html .= "</div>\r\n\t\t\t</div>\r\n <div class='clear fix-slider-block' style='display:inline-block'></div>\r\n "; $options["pause"] = $options["pause"] ? $options["pause"] : '1500'; $options["mode"] = $options["mode"] ? $options["mode"] : 'horizontal'; $options["speed"] = $options["speed"] ? $options["speed"] : '3000'; $html .= ' <script type="text/javascript"> $(document).ready(function() { $(".m-p-slider-contain").bxSlider({ minSlides: 1, maxSlides: 1, pager:true, adaptiveHeight: false, auto:true, pause: ' . $options["pause"] . ', useCSS: false, speed:' . $options["speed"] . ', mode: "' . $options["mode"] . '", }); }); </script> '; $html .= '<div class="after-slider-content"></div>'; return $html; }
/** * Ищет в контенте шорткоды и запускает их обработчики. * Если шотркод не определен или его плагин отключен, он будет возвращен без обработки. * * @param string $content - строка для поиска в ней шорткодов. * @return string исходную строку с результатами выполнения хуков для шорткодов. */ public static function doShortcode($content) { $shortCodes = self::getListShortCode(); if (empty($shortCodes) || URL::isSection('mg-admin')) { return $content; } elseif (substr_count($content, '[') > 400) { echo 'Превышено допустимое количество шорткодов на странице. <br />Пожалуйста, примите меры по уменьшению числа шорткодов'; exit; } // Получает шаблон для поиска шорткодов. $pattern = self::getShortcodeRegex(); return preg_replace_callback("/{$pattern}/s", array(__CLASS__, 'doShortcodeTag'), $content); }
<?php /* Plugin Name: Партнерская программа Description: Устанавливает связь между оплаченными заказами и пользователем, благодаря которому был оплачен заказ. Добавляет страницу /affiliate, на которой необходимо разместить информацию о вашей партнерской программе. Шорт код [data-balance] необходимо разместить на странице личного кабинета в файле 'ваша тема'/views/personal.php , для отображения баланса партнеров. Author: Avdeev Mark Version: 1.1 */ if (URL::isSection('personal') || URL::isSection('affiliate')) { mgAddMeta("<link rel='stylesheet' href='" . SITE . "/mg-plugins/partners-program/css/style.css' type='text/css' />"); } new PartnerProgram(); class PartnerProgram { public static $percent = 20; //процент для партнеров public static $exitMoneyLimit = 50; //минимальная сумма для вывода public function __construct() { mgActivateThisPlugin(__FILE__, array(__CLASS__, 'createDateBase')); mgAddAction(__FILE__, array(__CLASS__, 'pageSettingsPlugin')); mgAddShortcode('data-balance', array(__CLASS__, 'getBalance')); mgAddShortcode('affiliate', array(__CLASS__, 'affiliatePanel')); // установка куки если есть гет параметр if (isset($_GET['partnerId']) && is_numeric($_GET['partnerId'])) { self::setPartnerCookie($_GET['partnerId']); } // при каждом оформлении заказа создавать запись в партнерской таблице mgAddAction('models_order_addorder', array(__CLASS__, 'partnerToOrder'), 1); // ждем когда придет оплата
private function gelLink($class, $numberPage, $type = "getQuery", $ancor = null) { $href = "href='javascript:void(0);'"; if ($type == "forAjax") { $href = "href='javascript:void(0);'"; } if ($type == "getQuery") { $uri = $_SERVER['REQUEST_URI']; if (MG::get('controller') == "controllers_catalog" && MG::getSetting('catalogIndex') == 'true' && (URL::isSection(null) || URL::isSection('index'))) { $uri = substr_count($uri, 'index') ? str_replace('/index', '/catalog', $uri) : str_replace('/', '/catalog', $uri); } $url = str_replace(array('[', ']'), array('[', ']'), URL::add_get($uri, $this->paramName, $numberPage)); $href = "href='" . $url . "'"; } $ancor = $ancor ? $ancor : $numberPage; return "<li><a class='" . $class . " page_" . $numberPage . "' " . $href . " >" . $ancor . "</a></li>"; }
/** * Обработчик шотркода вида [pozvonim] * выполняется когда при генерации страницы встречается [pozvonim] */ static function handleShortCode() { if (!URL::isSection('mg-admin')) { $option = MG::getSetting('pozvonimOption'); } else { $option = MG::getOption('pozvonimOption'); } // преобразование строки опций в массив $option = stripslashes($option); $options = unserialize($option); if (isset($options['key']) && !empty($options['key'])) { return '<script crossorigin="anonymous" async type="text/javascript" src="//api.pozvonim.com/widget/callback/v3/' . $options['key'] . '/connect" id="check-code-pozvonim" charset="UTF-8"></script>'; } return ''; }
function __construct() { $settings = MG::get('settings'); // Если нажата кнопка купить. $_REQUEST['category_id'] = URL::getQueryParametr('category_id'); if (!empty($_REQUEST['inCartProductId'])) { $cart = new Models_Cart(); // Если параметров товара не передано // возможно была нажата кнопка купить из мини карточки, // в этом случае самостоятельно вычисляем набор // параметров, которые были бы указаны при открытии карточки товара. if (empty($_POST) || isset($_POST['updateCart']) && isset($_POST['inCartProductId']) && count($_POST) == 2) { $modelProduct = new Models_Product(); $product = $modelProduct->getProduct($_REQUEST['inCartProductId']); if (empty($product)) { MG::redirect('/404'); exit; } $blockVariants = $modelProduct->getBlockVariants($product['id']); $blockedProp = $modelProduct->noPrintProperty(); $propertyFormData = $modelProduct->createPropertyForm($param = array('id' => $product['id'], 'maxCount' => $product['count'], 'productUserFields' => $product['thisUserFields'], 'action' => "/catalog", 'method' => "POST", 'ajax' => true, 'blockedProp' => $blockedProp, 'noneAmount' => false, 'titleBtn' => MG::getSetting('buttonBuyName'), 'blockVariants' => $blockVariants, 'currency_iso' => $product['currency_iso'])); $_POST = $propertyFormData['defaultSet']; $_POST['inCartProductId'] = $product['id']; } $property = $cart->createProperty($_POST); $cart->addToCart($_REQUEST['inCartProductId'], $_REQUEST['amount_input'], $property); SmalCart::setCartData(); MG::redirect('/cart'); } if (!empty($_REQUEST['fastsearch'])) { $this->getSearchData(); } $countСatalogProduct = $settings['countСatalogProduct']; // Показать первую страницу выбранного раздела. $page = 1; // Запрашиваемая страница. if (isset($_REQUEST['p'])) { $page = $_REQUEST['p']; } $model = new Models_Catalog(); // Если происходит поиск по ключевым словам. $keyword = MG::defenderXss_decode(urldecode(URL::getQueryParametr('search'))); if (!empty($keyword)) { $keyword = $this->convertLang($keyword); $items = $model->getListProductByKeyWord($keyword, false, true, false, 'groupBy'); $searchData = array('keyword' => $keyword, 'count' => $items['numRows']); } else { // Получаем список вложенных категорий, // для вывода всех продуктов, на страницах текущей категории. if (empty($_REQUEST['category_id'])) { $_REQUEST['category_id'] = 0; } $model->categoryId = MG::get('category')->getCategoryList($_REQUEST['category_id']); // В конец списка, добавляем корневую текущую категорию. $model->categoryId[] = $_REQUEST['category_id']; // Записываем в глобальную переменную список всех вложенных категорий, // чтобы использовать в других местах кода, например в фильтре по характеристикам $_REQUEST['category_ids'] = $model->categoryId; // Передаем номер требуемой страницы, и количество выводимых объектов. $countСatalogProduct = $settings['countСatalogProduct']; $items = $model->getList($countСatalogProduct, false, true); } // Если с фильтра пришел запрос только на количество позиций. if (!empty($_REQUEST['getcount']) && !empty($_REQUEST['filter'])) { echo $items['totalCountItems'] ? $items['totalCountItems'] : 0; exit; } $settings = MG::get('settings'); if (empty($items['catalogItems'])) { $items['catalogItems'] = array(); } else { foreach ($items['catalogItems'] as $item) { if ($item['id']) { $productIds[] = $item['id']; } } $product = new Models_Product(); $blocksVariants = empty($productIds) ? null : $product->getBlocksVariantsToCatalog($productIds); $blockedProp = $product->noPrintProperty(); $actionButton = MG::getSetting('actionInCatalog') === "true" ? 'actionBuy' : 'actionView'; foreach ($items['catalogItems'] as $k => $item) { $imagesUrl = explode("|", $item['image_url']); $items['catalogItems'][$k]["image_url"] = ""; if (!empty($imagesUrl[0])) { $items['catalogItems'][$k]["image_url"] = $imagesUrl[0]; } $items['catalogItems'][$k]['title'] = MG::modalEditor('catalog', $item['title'], 'edit', $item["id"]); if ($items['catalogItems'][$k]['count'] == 0) { $buyButton = $items['catalogItems'][$k]['actionView']; } else { $buyButton = $items['catalogItems'][$k][$actionButton]; if (!empty($items['catalogItems'][$k]['variants'])) { foreach ($items['catalogItems'][$k]['variants'] as $variant) { if ($variant['count'] == 0) { $buyButton = $items['catalogItems'][$k]['actionView']; } } } } // Легкая форма без характеристик. $liteFormData = $product->createPropertyForm($param = array('id' => $item['id'], 'maxCount' => $item['count'], 'productUserFields' => null, 'action' => "/catalog", 'method' => "POST", 'ajax' => true, 'blockedProp' => $blockedProp, 'noneAmount' => true, 'titleBtn' => "В корзину", 'blockVariants' => $blocksVariants[$item['id']], 'buyButton' => $buyButton)); $items['catalogItems'][$k]['liteFormData'] = $liteFormData['html']; $buyButton = $items['catalogItems'][$k]['liteFormData']; $items['catalogItems'][$k]['buyButton'] = $buyButton; } } $categoryDesc = MG::get('category')->getDesctiption($_REQUEST['category_id']); if ($_REQUEST['category_id']) { $categoryDesc = MG::inlineEditor(PREFIX . 'category', "html_content", $_REQUEST['category_id'], $categoryDesc); } $catImg = MG::get('category')->getImageCategory($_REQUEST['category_id']); //$model->currentCategory['title'] = $_REQUEST['category_id'] ? $model->currentCategory['title'] : 0, //var_dump($model->currentCategory['title']); $data = array('items' => $items['catalogItems'], 'titeCategory' => $model->currentCategory['title'], 'cat_desc' => $categoryDesc, 'cat_img' => $catImg, 'cat_id' => $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0, 'filterBar' => $items['filterBarHtml'], 'totalCountItems' => $items['totalCountItems'], 'pager' => $items['pager'], 'searchData' => empty($searchData) ? '' : $searchData, 'meta_title' => !empty($model->currentCategory['meta_title']) ? $model->currentCategory['meta_title'] : $model->currentCategory['title'], 'meta_keywords' => !empty($model->currentCategory['meta_keywords']) ? $model->currentCategory['meta_keywords'] : "товары,продукты,изделия", 'meta_desc' => !empty($model->currentCategory['meta_desc']) ? $model->currentCategory['meta_desc'] : "В каталоге нашего магазина есть все.", 'currency' => $settings['currency'], 'actionButton' => $actionButton); if (URL::isSection('catalog') || MG::getSetting('catalogIndex') == 'true' && (URL::isSection('index') || URL::isSection(''))) { $html = MG::get('pages')->getPageByUrl('catalog'); $html['html_content'] = MG::inlineEditor(PREFIX . 'page', "html_content", $html['id'], $html['html_content']); $data['meta_title'] = $html['meta_title'] ? $html['meta_title'] : $html['title']; $data['meta_title'] = $data['meta_title'] ? $data['meta_title'] : $model->currentCategory['title']; $data['meta_keywords'] = $html['meta_keywords']; $data['meta_desc'] = $html['meta_desc']; $data['cat_desc'] = $html['html_content']; $data['titeCategory'] = $html['title']; } if ($keyword) { $data['meta_title'] = 'Поиск по фразе: ' . $keyword; } $this->data = $data; }
/** * Метод для обработки фильтрации товаров в каталоге * @return . */ public function filterPublic($noneAjax = true, $onlyInCount = false, $onlyActive = true, $sortFields = array('price_course|-1' => 'цене, сначала недорогие', 'price_course|1' => 'цене, сначала дорогие', 'id|1' => 'новизне', 'count_buy|1' => 'популярности', 'recommend|1' => 'сначала рекомендуемые', 'new|1' => 'сначала новинки', 'old_price|1' => 'сначала распродажа', 'sort|-1' => 'порядку', 'count|1' => 'наличию'), $baseSort = 'sort|-1') { $orderBy = strtolower(trim(FILTER_SORT)); $compareArray = array("sort|asc" => 'sort|-1', "price_course|asc" => 'price_course|-1', "price_course|desc" => 'price_course|1', "id|desc" => 'id|1', "count_buy|desc" => 'count_buy|1', "recommend|desc" => 'recommend|1', "new|desc" => 'new|1', "old_price|desc" => 'old_price|1', "count|desc" => 'count|1'); $baseSort = $compareArray[$orderBy] ? $compareArray[$orderBy] : 'sort|-1'; $newSortFields[$baseSort] = $sortFields[$baseSort]; unset($sortFields[$baseSort]); $sortFields = array_merge($newSortFields, $sortFields); $lang = MG::get('lang'); $model = new Models_Catalog(); $catalog = array(); if (!empty($_REQUEST['insideCat']) && $_REQUEST['insideCat'] === "false") { $this->categoryId = array(end($this->categoryId)); } $currentCategoryId = $this->currentCategory['id'] ? $this->currentCategory['id'] : 0; $where = ''; $catIds = implode(',', $this->categoryId); if (!empty($catIds) || $catIds === 0) { $where = ' WHERE p.cat_id IN (' . $catIds . ') or FIND_IN_SET(' . $currentCategoryId . ',p.`inside_cat`)'; $rule1 = ' cat_id IN (' . $catIds . ') or FIND_IN_SET(' . $currentCategoryId . ',p.`inside_cat`) '; if ($currentCategoryId == 0) { $where = ' WHERE 1=1 or FIND_IN_SET(' . $currentCategoryId . ',p.`inside_cat`)'; $rule1 = ' 1=1 or FIND_IN_SET(' . $currentCategoryId . ',p.`inside_cat`) '; } } else { $catIds = 0; } $prices = DB::fetchAssoc(DB::query(' SELECT ROUND(MAX((p.price_course + p.price_course * (IFNULL(c.rate,0)))),0) as `max_price`, FLOOR(MIN((p.price_course + p.price_course * (IFNULL(c.rate,0))))) as min_price FROM `' . PREFIX . 'product` as p LEFT JOIN `' . PREFIX . 'category` as c ON c.id = p.cat_id ' . $where)); $maxPrice = $prices['max_price']; $minPrice = $prices['min_price']; $property = array('cat_id' => array('type' => 'hidden', 'value' => $_REQUEST['cat_id']), 'sorter' => array('type' => 'select', 'label' => 'Сортировать по', 'option' => $sortFields, 'selected' => !empty($_REQUEST['sorter']) ? $_REQUEST['sorter'] : 'null', 'value' => !empty($_REQUEST['sorter']) ? $_REQUEST['sorter'] : null), 'price_course' => array('type' => 'beetwen', 'label1' => $lang['PRICE_FROM'], 'label2' => $lang['PRICE_TO'], 'min' => !empty($_REQUEST['price_course'][0]) ? $_REQUEST['price_course'][0] : $minPrice, 'max' => !empty($_REQUEST['price_course'][1]) ? $_REQUEST['price_course'][1] : $maxPrice, 'factMin' => $minPrice, 'factMax' => $maxPrice, 'class' => 'price numericProtection'), 'applyFilter' => array('type' => 'hidden', 'label' => 'флаг примения фильтров', 'value' => 1)); $filter = new Filter($property); $arr = array('(p.price_course + p.price_course * (IFNULL(rate,0)))' => array(!empty($_REQUEST['price_course'][0]) ? $_REQUEST['price_course'][0] : $minPrice, !empty($_REQUEST['price_course'][1]) ? $_REQUEST['price_course'][1] : $maxPrice), 'p.new' => isset($_REQUEST['new']) ? $_REQUEST['new'] : 'null', 'p.recommend' => isset($_REQUEST['recommend']) ? $_REQUEST['recommend'] : 'null', 'rule1' => $rule1); $userFilter = $filter->getFilterSql($arr, array(), $_REQUEST['insideCat']); if (!empty($_REQUEST['prop'])) { $arrayIdsProd = $filter->getProductIdByFilter($_REQUEST['prop']); $listIdsProd = implode(',', $arrayIdsProd); if ($listIdsProd) { $userFilter .= ' AND p.id IN (' . $listIdsProd . ') '; } else { // добавляем заведомо неверное условие к запросу, // чтобы ничего не попало в выдачу, т.к. товаров отвечающих заданым характеристикам ненайдено $userFilter = ' 0 = 1 '; } } $keys = array_keys($sortFields); if (empty($_REQUEST['sorter'])) { $_REQUEST['sorter'] = $keys[0]; } elseif (!URL::isSection('mg-admin') && !in_array($_REQUEST['sorter'], $keys)) { $_REQUEST['sorter'] = $keys[0]; } if (!empty($_REQUEST['sorter']) && !empty($userFilter)) { $sorterData = explode('|', $_REQUEST['sorter']); $field = $sorterData[0]; if ($sorterData[1] > 0) { $dir = 'desc'; } else { $dir = 'asc'; } if ($onlyInCount) { $userFilter .= ' AND (p.count>0 OR p.count<0)'; } if ($onlyActive) { $userFilter .= ' AND p.`activity` = 1'; } if (!empty($userFilter)) { $userFilter .= " ORDER BY `" . DB::quote($field, true) . "` " . $dir; } } return array('filterBarHtml' => $filter->getHtmlFilter($noneAjax), 'userFilter' => $userFilter); }
static function getPanelCode($place = 0) { /* * Выводит в форму html для генерации виджета */ $redirect_uri = urlencode(SITE . '/socialauth?backurl=' . urlencode(ULoginAuth::ulogin_get_current_page_url())); $ulogin_default_options = array(); $ulogin_default_options['display'] = 'small'; $ulogin_default_options['providers'] = 'vkontakte,odnoklassniki,mailru,facebook'; $ulogin_default_options['fields'] = 'first_name,last_name,email,photo,photo_big'; $ulogin_default_options['optional'] = 'sex,bdate,country,city'; $ulogin_default_options['hidden'] = 'other'; $ulogin_options = array(); if (!URL::isSection('mg-admin')) { $option = MG::getSetting('uLoginSettings'); } else { $option = MG::getOption('uLoginSettings'); } $option = stripslashes($option); $options = unserialize($option); $ulogin_options['ulogin_id1'] = $options['uloginid1']; $ulogin_options['ulogin_id2'] = $options['uloginid2']; $default_panel = false; switch ($place) { case 0: $ulogin_id = $ulogin_options['ulogin_id1']; break; case 1: $ulogin_id = $ulogin_options['ulogin_id2']; break; default: $ulogin_id = $ulogin_options['ulogin_id1']; } if (empty($ulogin_id)) { $ul_options = $ulogin_default_options; $default_panel = true; } $panel = ''; $panel .= '<div class="ulogin_panel"'; if ($default_panel) { $ul_options['redirect_uri'] = $redirect_uri; unset($ul_options['label']); $x_ulogin_params = ''; foreach ($ul_options as $key => $value) { $x_ulogin_params .= $key . '=' . $value . ';'; } if ($ul_options['display'] != 'window') { $panel .= ' data-ulogin="******"></div>'; } else { $panel .= ' data-ulogin="******" href="#"><img src="https://ulogin.ru/img/button.png" width=187 height=30 alt="МультиВход"/></div>'; } } else { $panel .= ' data-uloginid="' . $ulogin_id . '" data-ulogin="******"></div>'; } $panel = '<div class="ulogin_block place' . $place . '">' . $panel . '</div><div style="clear:both"></div>'; return $panel; }
/** * Возвращает древовидный список категорий, пригодный для использования в меню. * * @param int $parent id категории, для которой надо вернуть список. * @param int $type тип списка (для публичной части, либо для админки). * @param int $recursion использовать рекурсию. * @return string */ public function getCategoryListUl($parent = 0, $type = 'public', $recursion = true) { // получаем данные об открытых категориях из куков if (empty($this->openedCategory)) { if ('admin' == $type) { $this->openedCategory = json_decode($_COOKIE['openedCategoryAdmin']); } else { $this->openedCategory = json_decode($_COOKIE['openedCategory']); } if (empty($this->openedCategory)) { $this->openedCategory = array(); } } $print = ''; if (empty($this->categories)) { $print = ''; } else { $lang = MG::get('lang'); $categoryArr = $this->categories; //для публичной части убираем из меню закрытые категории if ('public' == $type) { foreach ($categoryArr as $key => $val) { if ($val['invisible'] == 1) { unset($categoryArr[$key]); } } } foreach ($categoryArr as $category) { if (!isset($category['id'])) { break; } //если категории неceotcndetn if ($parent == $category['parent']) { $flag = false; $mover = ''; if ('admin' == $type) { $class = 'active'; $title = $lang['ACT_EXPORT_CAT']; if ($category['export'] == 0) { $class = ''; $title = $lang['ACT_NOT_EXPORT_CAT']; } $export = '<div class="export tool-tip-bottom ' . $class . '" title="' . $title . '" data-category-id="' . $category['id'] . '"></div>'; $class = 'active'; $title = $lang['ACT_V_CAT']; if ($category['invisible'] == 1) { $class = ''; $title = $lang['ACT_UNV_CAT']; } $checkbox = '<input type="checkbox" name="category-check">'; $mover .= $checkbox . '<div class="mover"></div><div class="link-to-site tool-tip-bottom" title="' . $lang['MOVED_TO_CAT'] . '" data-href="' . SITE . '/' . $category['parent_url'] . $category['url'] . '"></div>' . $export . '<div class="visible tool-tip-bottom ' . $class . '" title="' . $title . '" data-category-id="' . $category['id'] . '"></div>'; } $slider = '>' . $mover . $link; foreach ($this->categories as $sub_category) { if ($category['id'] == $sub_category['parent']) { $slider = ' class="slider">' . $mover . '<div class="slider_btn"></div>'; $style = ""; $opened = ""; if (in_array($category['id'], $this->openedCategory)) { $opened = " opened "; $style = ' style="background-position: 0 0"'; } $slider = ' class="slider">' . $mover . '<div class="slider_btn ' . $opened . '" ' . $style . '></div>'; $flag = true; break; } } $rate = ''; if ($category['rate'] > 0) { $rate = '<div class="sticker-menu discount-rate-up" data-cat-id="' . $category['id'] . '"> ' . $lang['DISCOUNT_UP'] . ' +' . $category['rate'] * 100 . '% <div class="discount-mini-control"><span class="discount-apply-follow tool-tip-bottom" title="Применить ко всем вложенным категориям" >↓↓</span> <span class="discount-cansel tool-tip-bottom" title="Отменить">x</span></div></div>'; } if ($category['rate'] < 0) { $rate = '<div class="sticker-menu discount-rate-down" data-cat-id="' . $category['id'] . '"> ' . $lang['DISCOUNT_DOWN'] . ' ' . $category['rate'] * 100 . '% <div class="discount-mini-control"><span class="discount-apply-follow tool-tip-bottom" title="Применить ко всем вложенным категориям">↓↓</span> <span class="discount-cansel tool-tip-bottom" title="Отменить">x</span></div></div>'; } if ('admin' == $type) { $print .= '<li' . $slider . '<a href="javascript:void(0);" onclick="return false;" class="CategoryTree" rel="CategoryTree" id="' . $category['id'] . '" parent_id="' . $category["parent"] . '">' . $category['title'] . '</a> ' . $rate; } else { if ($category['invisible'] != 1) { $active = ''; if (URL::isSection($category['parent_url'] . $category['url'])) { $active = 'class="active"'; } $category['title'] = MG::contextEditor('category', $category['title'], $category["id"], "category"); $print .= '<li' . $slider . '<a href="' . SITE . '/' . $category['parent_url'] . $category['url'] . '"><span ' . $active . '>' . $category['title'] . '</span></a>'; } } if ($flag) { $display = "display:none"; if (in_array($category['id'], $this->openedCategory)) { $display = "display:block"; } // если нужно выводить подкатегории то делаем рекурсию if ($recursion) { $sub_menu = ' <ul class="sub_menu" style="' . $display . '"> [li] </ul>'; $li = $this->getCategoryListUl($category['id'], $type); $print .= strlen($li) > 0 ? str_replace('[li]', $li, $sub_menu) : ""; } $print .= '</li>'; } else { $print .= '</li>'; } } } } $args = func_get_args(); $result = $print; return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
/** * Метод управляющий подключением верстки для писем и HTML блоков движка. * @param string $layout - название файла с версткой * @param string $param - массив переменных, которые будут доступны в layout * @return string html верстка. */ public static function layoutManager($layout, $data) { $content = ""; $path = ''; $layoutPath = PATH_TEMPLATE . '/layout/'; // если идет обращение к лэйауту из админки, например отправка письма // то вместо PATH_TEMPLATE в котором для админки всегда хранится путь к дефолтному шаблону // берем путь до указанного в настройках шаблона, чтобы использовались нужные лайауты if (URL::isSection('mg-admin')) { $selectedTemplate = self::getSetting('templateName'); $layoutPath = 'mg-templates/' . $selectedTemplate . '/layout/'; } if (file_exists($layoutPath . $layout . '.php')) { $path = $layoutPath; } elseif (file_exists(CORE_DIR . 'layout/' . $layout . '.php')) { $path = CORE_DIR . '/layout/'; } if ($path) { //extract($param); ob_start(); include $path . $layout . '.php'; $content = ob_get_contents(); ob_end_clean(); // если в layout для писем не отменен вывод в общем шаблоне. // чтобы отключить вывод в шаблоне, можно прям в layout определить $data['noTemplate'] = true; if (empty($data['noTemplate']) && strpos($layout, 'email_') === 0) { ob_start(); include $path . 'email_template.php'; $content = ob_get_contents(); ob_end_clean(); } } $args = func_get_args(); return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $content, $args); }
/** * Возвращает древовидный список страниц, пригодный для использования в футере. * Вернет заданное количество списков. * @param int $parent id категории, для которой надо вернуть список. * @param int $type тип списка (для публичной части, либо для админки). * @return string */ public function getFooterPagesUl($type = 'public', $column = 3) { $print = ''; if (empty($this->page)) { $print = ''; } else { $lang = MG::get('lang'); $gategoryArr = $this->page; //для публичной части убираем из меню закрытые страницы foreach ($gategoryArr as $key => $val) { if ($val['invisible'] == 1) { unset($gategoryArr[$key]); } } $countPage = 0; foreach ($gategoryArr as $page) { if ($page['parent'] == 0) { $countPage++; } } if ($countPage > 1) { $inColumn = floor($countPage / $column); } $newColumn = true; $i = 0; foreach ($gategoryArr as $page) { if ($page['parent'] == 0) { if ($newColumn == true) { if ($i > 0) { $i = 0; $print .= "</ul><ul class='footer-column'>"; } else { $i = 0; $print .= "<ul class='footer-column'>"; } } if ($i < $inColumn) { $newColumn = false; $i++; } else { $newColumn = true; } $hotFix1 = false; if ($page['parent_url'] == "" && ($page['url'] == 'index' || $page['url'] == 'index.html')) { $hotFix1 = true; } if ($page['invisible'] != 1) { $active = ''; if (URL::isSection($page['parent_url'] . $page['url'])) { $active = 'class="active"'; } $page['title'] = MG::contextEditor('page', $page['title'], $page["id"], "page"); if (strpos($page['url'], 'http://') === false) { $url = SITE . '/' . $page['parent_url'] . $page['url']; } else { $url = $page['url']; } if ($hotFix1) { $print .= '<li><a href="' . SITE . '"><span ' . $active . '>' . $page['title'] . '</span></a>'; } else { $print .= '<li><a href="' . $url . '"><span ' . $active . '>' . $page['title'] . '</span></a>'; } } } } $print .= "</ul>"; } $args = func_get_args(); $result = $print; return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args); }
Оплата Visa и MasterCard </div> </div--> <?php } ?> </div> <div class="center-inner <?php if (MG::get('controller') != 'controllers_index' || MG::getSetting('catalogIndex') == 'true') { ?> inner-page<?php } ?> <?php if (URL::isSection('catalog') && isset($_GET['search'])) { ?> no-filters<?php } ?> "> <?php if (class_exists('trigger') && MG::get('controller') == 'controllers_index') { ?> [trigger-guarantee id="1"] <?php } ?> <?php
<?php /* Plugin Name: Отзывы покупателей Description: Плагин позволяет оставлять отзывы о товарах и статьях сайта. Имеет панель адмнистрирования. Добавить форму отзывов можно вставив шорткод [comments] в любое место страницы. Author: HollowJ и Avdeev Mark Version: 2.1.2 */ $coments = new CommentsToMoguta(); if (URL::isSection('mg-admin')) { MG::addInformer(array('count' => $coments->getNewCommentsCount(), 'class' => 'comment-wrap', 'classIcon' => 'comment-small-icon', 'isPlugin' => true, 'section' => 'comments', 'priority' => 80)); } class CommentsToMoguta { public function __construct() { mgActivateThisPlugin(__FILE__, array(__CLASS__, 'createDataComments')); mgAddAction(__FILE__, array(__CLASS__, 'pagePluginComments')); mgAddShortcode('comments', array(__CLASS__, 'showComments')); mgAddShortcode('wall-comments', array(__CLASS__, 'wallComments')); $meta = '<script src="' . SITE . '/mg-plugins/comments/js/comments.js"></script>' . '<link href="' . SITE . '/mg-plugins/comments/css/style.css" rel="stylesheet" type="text/css">'; mgAddMeta($meta); } // При активации создает таблицу в БД и регистрирует новую опцию static function createDataComments() { $sql = "\r\n \t\t CREATE TABLE IF NOT EXISTS `" . PREFIX . "comments` (\r\n \t\t\t`id` INT AUTO_INCREMENT NOT NULL,\r\n `name` VARCHAR(45) NOT NULL,\r\n `email` VARCHAR(45) NOT NULL,\r\n `comment` TEXT NoT NULL,\r\n `date` TIMESTAMP NOT NULL,\r\n `uri` VARCHAR(255) NOT NULL,\r\n `approved` TINYINT NOT NULL DEFAULT 0, \r\n PRIMARY KEY(`id`)\r\n \t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; DB::query($sql); setOption('countPrintRowsComments', 10); } /**
/** * Метод добавляет к массиву продуктов информацию о характеристиках * для каждого продукта * @param $arrayProducts - массив с продуктами * @return float. */ public function addPropertyToProduct($arrayProducts) { $categoryIds = array(); $whereCat = ''; $idsProduct = array(); $currency = MG::getSetting("currency"); $currencyRate = MG::getSetting('currencyRate'); $currencyShopIso = MG::getSetting('currencyShopIso'); $prod = new Models_Product(); $idsVariantProduct = array(); foreach ($arrayProducts as $key => $product) { $arrayProducts[$key]['category_url'] = SHORT_LINK == '1' && !URL::isSection('mg-admin') ? '' : $arrayProducts[$key]['category_url'] . '/'; $product['category_url'] = SHORT_LINK == '1' ? '' : $product['category_url'] . '/'; if ($product['variant_exist'] && $product['variant_id']) { $variants = $prod->getVariants($product['id']); $variantsKey = array_keys($variants); $product['variant_id'] = $variantsKey[0]; $idsVariantProduct[$product['id']][] = $key; $variant = $variants[$product['variant_id']]; $arrayProducts[$key]['price_course'] = $variant['price_course']; $arrayProducts[$key]['price'] = $variant['price']; $arrayProducts[$key]['image_url'] = $variant['image'] ? $variant['image'] : $arrayProducts[$key]['image_url']; } $idsProduct[$product['id']] = $key; $categoryIds[] = $product['cat_id']; // Назначаем для продукта позьзовательские // характеристики по умолчанию, заданные категорией. $arrayProducts[$key]['thisUserFields'] = MG::get('category')->getUserPropertyCategoryById($product['cat_id']); $arrayProducts[$key]['propertyIdsForCat'] = MG::get('category')->getPropertyForCategoryById($product['cat_id']); $arrayProducts[$key]['currency'] = $currency; // Формируем ссылки подробнее и в корзину. $arrayProducts[$key]['actionBuy'] = '<a href="' . SITE . '/catalog?inCartProductId=' . $product["id"] . '" class="addToCart product-buy" data-item-id="' . $product["id"] . '">' . MG::getSetting('buttonBuyName') . '</a>'; $arrayProducts[$key]['actionCompare'] = '<a href="' . SITE . '/compare?inCompareProductId=' . $product["id"] . '" class="addToCompare" data-item-id="' . $product["id"] . '">' . MG::getSetting('buttonCompareName') . '</a>'; $arrayProducts[$key]['actionView'] = '<a href="' . SITE . '/' . (isset($product["category_url"]) ? $product["category_url"] : 'catalog') . '/' . $product["product_url"] . '" class="product-info">' . MG::getSetting('buttonMoreName') . '</a>'; $arrayProducts[$key]['link'] = SITE . '/' . (isset($product["category_url"]) ? $product["category_url"] : 'catalog/') . $product["product_url"]; if (empty($arrayProducts[$key]['currency_iso'])) { $arrayProducts[$key]['currency_iso'] = $currencyShopIso; } $arrayProducts[$key]['real_old_price'] = $arrayProducts[$key]['old_price']; $arrayProducts[$key]['old_price'] *= $currencyRate[$arrayProducts[$key]['currency_iso']]; $arrayProducts[$key]['real_price'] = $arrayProducts[$key]['price']; $arrayProducts[$key]['price'] = MG::priceCourse($arrayProducts[$key]['price_course']); $imagesConctructions = $prod->imagesConctruction($arrayProducts[$key]['image_url'], $arrayProducts[$key]['image_title'], $arrayProducts[$key]['image_alt']); $arrayProducts[$key]['images_product'] = $imagesConctructions['images_product']; $arrayProducts[$key]['images_title'] = $imagesConctructions['images_title']; $arrayProducts[$key]['images_alt'] = $imagesConctructions['images_alt']; $arrayProducts[$key]['image_url'] = $imagesConctructions['image_url']; $arrayProducts[$key]['image_title'] = $imagesConctructions['image_title']; $arrayProducts[$key]['image_alt'] = $imagesConctructions['image_alt']; $imagesUrl = explode("|", $arrayProducts[$key]['image_url']); $arrayProducts[$key]["image_url"] = ""; if (!empty($imagesUrl[0])) { $arrayProducts[$key]["image_url"] = $imagesUrl[0]; } } $model = new Models_Product(); $arrayVariants = $model->getBlocksVariantsToCatalog(array_keys($idsProduct), true); foreach (array_keys($idsProduct) as $id) { $arrayProducts[$idsProduct[$id]]['variants'] = $arrayVariants[$id]; } // Собираем все ID продуктов в один запрос. if ($prodSet = trim(DB::quote(implode(',', array_keys($idsProduct))), "'")) { // Формируем список id продуктов, к которым нужно найти пользовательские характеристики. $where = ' IN (' . $prodSet . ') '; } else { $where = ' IN (0) '; } //Определяем id категории, в которой находимся $catCode = URL::getLastSection(); $sql = ' SELECT pup.property_id, pup.value, pup.product_id, prop.*, pup.type_view, pup.product_margin FROM `' . PREFIX . 'product_user_property` as pup LEFT JOIN `' . PREFIX . 'property` as prop ON pup.property_id = prop.id '; if ($catSet = trim(DB::quote(implode(',', $categoryIds)), "'")) { $categoryIds = array_unique($categoryIds); $sql .= ' LEFT JOIN `' . PREFIX . 'category_user_property` as cup ON cup.property_id = prop.id '; $whereCat = ' AND cup.category_id IN (' . $catSet . ') '; } $sql .= 'WHERE pup.`product_id` ' . $where . $whereCat; $sql .= 'ORDER BY `sort` DESC'; $res = DB::query($sql); while ($userFields = DB::fetchAssoc($res)) { // viewDAta($userFields['property_id']); // viewDAta($arrayProducts[$key]['propertyIdsForCat']); // Обновляет данные позначениям характеристик, только для тех хар. которые назначены для категории текущего товара. // Это не работает в фильтрах и сравнениях. // if(in_array($userFields['property_id'],$arrayProducts[$key]['propertyIdsForCat'])){ // дописываем в массив пользовательских характеристик, // все переопределенные для каждого тоавара, оставляя при // этом не измененные характеристики по умолчанию $arrayProducts[$idsProduct[$userFields['product_id']]]['thisUserFields'][$userFields['property_id']] = $userFields; // добавляем польз характеристики ко всем вариантам продукта if (!empty($idsVariantProduct[$userFields['product_id']])) { foreach ($idsVariantProduct[$userFields['product_id']] as $keyPages) { $arrayProducts[$keyPages]['thisUserFields'][$userFields['property_id']] = $userFields; } } // } } return $arrayProducts; }
public static function printNews($arg) { $aUri = URL::getSections(); $result = $arg['result']; if ($aUri[1] == 'news' && empty($aUri[2])) { MG::titlePage('Новости'); $listNews = self::getListNews(MG::getOption('countPrintRowsNews')); $result = ' <div class="page-content"> <ul class="breadcrumbs bor-b"> <li><a href="' . SITE . '" class="home">Главная</a></li> <span> / </span> <li>Новости</li> </ul><!-- !ul.breadcrumbs --> <h1 class="title-page">Новости</h1>'; if (!empty($listNews['listNews'])) { foreach ($listNews['listNews'] as $news) { $result .= ' <div class="news-blocks-main"> <div class="title-news-main"> <a href="news/' . $news['url'] . '">' . ucfirst($news['title']) . '</a> </div> <div class="white-box bor-b clearfix"> <img src="' . SITE . '/uploads/news/' . $news['image_url'] . '" alt="' . $news['title'] . '" title="' . $news['title'] . '"> ' . mb_substr(strip_tags(PM::stripShortcodes($news['description'])), 0, 140, 'utf-8') . ' </div><!-- !div.white-box --> </div><!-- !div.news-blocks-main --> '; } $result .= "{$listNews['pagination']}"; } else { $result .= '<div class="white-box bor-b">Новости не найдены</div><!-- !div.page-content-box -->'; } $result .= '</div><!-- !div.page-content -->'; } else { if (URL::isSection('news')) { $news = self::getNewsByUrl(URL::getLastSection()); if (empty($news)) { MG::redirect('/404.html'); } MG::titlePage($news['title']); MG::seoMeta($news); $body = MG::inlineEditor('mpl_news', 'description', $news['id'], $news['description']); $result = ' <div class="page-content"> <ul class="breadcrumbs bor-b"> <li><a href="' . SITE . '" class="home">Главная</a></li> <span> / </span> <li><a href="' . SITE . '/news' . '">Новости</a></li> <span> / </span> <li>' . $news['title'] . '</li> </ul><!-- !ul.breadcrumbs --> <h1 class="title-page">' . $news['title'] . '</h1> <div class="white-box bor-b"> ' . $body . ' </div><!-- !div.page-content-box --> <div class="clearfix static-comments-btn"> <div class="left"> <p>Комментарии:</p> </div> <div class="right"> <a href="#" class="add-cmt jq-add-cmt-static-page">Добавить комментарий</a> </div> </div><!-- !div.clearfix --> [comments] </div><!-- !div.page-content -->'; } } return $result; }
private function gelLink($class, $numberPage, $type = "getQuery", $ancor = null) { $href = "href='javascript:void(0);'"; if ($type == "forAjax") { $href = "href='javascript:void(0);'"; } if ($type == "getQuery") { $uri = $_SERVER['REQUEST_URI']; if (MG::get('controller') == "controllers_catalog" && MG::getSetting('catalogIndex') == 'true' && (URL::isSection(null) || URL::isSection('index'))) { $uri = substr_count($uri, 'index') ? str_replace('/index', '/catalog', $uri) : str_replace('/', '/catalog', $uri); } $part = explode('?', $uri); //var_dump($part); // $part[1]=urlencode($part[1]); $href = "href='" . URL::add_get($part[0] . '?' . $part[1], $this->paramName, $numberPage) . "'"; } $ancor = $ancor ? $ancor : $numberPage; return "<li><a class='" . $class . " page_" . $numberPage . "' " . $href . " >" . $ancor . "</a></li>"; }