Example #1
0
/**
 * Файл может содержать ряд пользовательских фунций влияющих на работу движка. 
 * В данном файле можно использовать собственные обработчики 
 * перехватывая функции движка, аналогично работе плагинов.
 * 
 * @author Авдеев Марк <*****@*****.**>
 * @package moguta.cms
 * @subpackage File
 */
function seoMeta($args)
{
    $settings = MG::get('settings');
    $args[0]['title'] = !empty($args[0]['title']) ? $args[0]['title'] : '';
    $title = !empty($args[0]['meta_title']) ? $args[0]['meta_title'] : $args[0]['title'];
    MG::set('metaTitle', $title . ' | ' . $settings['sitename']);
}
Example #2
0
 /**
  * Запускает движок системы.
  *
  * @return array массив с результатами содержащий:
  * -тип файла, который надо открыть
  * -данные для этого файла
  * -вид
  */
 public function run()
 {
     $data = null;
     $view = null;
     $variables = null;
     // Если найден контролер.
     if ($controller = $this->getController()) {
         MG::set('controller', $controller);
         $contr = new $controller();
         $type = 'view';
         $variables = $contr->variables;
         $view = $this->getView();
     } elseif ($data = MG::getPhpContent()) {
         // отключаем вывод шаблона для пользовательских скриптов
         MG::disableTemplate();
         // Если найден пользовательский файл, возвращает его расширение (php||html).
         $ext = explode(".", $data);
         $type = end($ext);
         // если запрошен существуюий файл стилей или js или любое другое расширение кроме html и php,
         // то редиректрим на его настоящее местоположение минуя проверки движка
         if ($type != 'php' && $type != 'html') {
             MG::redirect('/' . $data);
             exit;
         }
         if ($type != 'php') {
             // если файл не исполняемый то считываем его в строку
             $data = file_get_contents($data);
             $type = 'html';
         }
     } elseif ($data = MG::getHtmlContent()) {
         // Если найден статический контент в БД.
         $type = 'html';
     }
     // Если не существует запрашиваемых данных.
     $type = !empty($type) ? $type : '404';
     $result = array('type' => $type, 'data' => $data, 'view' => $view, 'variables' => $variables);
     return $result;
 }
Example #3
0
/**
 * Добавляет переданную строку в секцию <head> </head>
 *
 * @param string $data - строковая переменная, с данными.
 * @param string $onlyController - подключать только для заданного контролера.
 * @return void.
 */
function mgAddMeta($data, $onlyController = 'all')
{
    $register = MG::get('register') ? MG::get('register') : array();
    // Если заголовок нужно подключить только в определенном контролере,
    // то записываем его в  отдельный ключ массива.
    if ($onlyController != 'all') {
        $onlyController = 'controllers_' . $onlyController;
    }
    if (!empty($register[$onlyController])) {
        if (!in_array($data, $register[$onlyController])) {
            $register[$onlyController][] = $data;
        }
    } else {
        $register[$onlyController][] = $data;
    }
    MG::set('register', $register);
    MG::set('userMeta', MG::get('userMeta') . "\n" . $data);
}
Example #4
0
 /**
  * Сохраняет курс валют
  * @return boolean
  */
 public function saveCurrency()
 {
     $this->messageSucces = $this->lang['ACT_SAVE_CURR'];
     $this->messageError = $this->lang['ACT_NOT_SAVE_CURR'];
     foreach ($_POST['data'] as $currency) {
         $currency['iso'] = htmlspecialchars($currency['iso']);
         $currency['short'] = htmlspecialchars($currency['short']);
         $currency['rate'] = (double) $currency['rate'];
         $currencyShopRate[$currency['iso']] = $currency['rate'];
         $currencyShopShort[$currency['iso']] = $currency['short'];
     }
     MG::setOption(array('option' => 'currencyRate', 'value' => addslashes(serialize($currencyShopRate))));
     MG::setOption(array('option' => 'currencyShort', 'value' => addslashes(serialize($currencyShopShort))));
     $settings = MG::get('settings');
     $settings['currencyRate'] = $currencyShopRate;
     $settings['currencyShort'] = $currencyShopShort;
     MG::set('settings', $settings);
     $product = new Models_Product();
     $product->updatePriceCourse(MG::getSetting('currencyShopIso'));
     return true;
 }
Example #5
0
mgSEO(array('meta_title' => 'asf'));
$site = SITE;
$breadcrumbs = <<<EOF
<div class="site-breadcrumbs">
    <ul class="site-breadcrumbs-list">
        <li class="site-breadcrumbs-list-item"><a href="{$site}">Главная</a></li>
        <li class="site-breadcrumbs-list-item separator">/</li>
        <li class="site-breadcrumbs-list-item current">Каталог</li>
        <li class="site-breadcrumbs-list-item separator">/</li>
        <li class="site-breadcrumbs-list-item current">Бренд</li>
    </ul>
</div>
EOF;
MG::set('breadcrumbs', $breadcrumbs);
MG::set('pageTitle', $data['title']);
MG::set('isNotWrapper', true);
?>
<div class="products-wrapper">   
    <?php 
$actionButton = MG::getSetting('actionInCatalog') === "true" ? 'actionBuy' : 'actionView';
$currency = MG::getSetting('currency');
$item = brand::getProductsByBrand($_GET['brand']);
$items = $item['items'];
$brand = $item['brand'];
if (!empty($brand)) {
    ?>
      <h1 class="new-products-title"><?php 
    echo $brand['brand'];
    ?>
</h1> 
      <div class="cat-desc">	        
Example #6
0
 /**
  * Возвращает список товаров и пейджер для постраничной навигации.
  * @param int $countRows - количество возвращаемых записей для одной страницы.
  * @param boolean $mgadmin - откуда вызван метод, из публичной части или панели управления.
  * @param boolean $onlyActive - учитывать только активные продукты.
  * @return type
  */
 public function getList($countRows = 20, $mgadmin = false, $onlyActive = false)
 {
     // Если не удалось получить текущую категорию.
     if (!$this->getCurrentCategory()) {
         echo 'Ошибка получения данных!';
         exit;
     }
     // только для публичной части строим html для фильтров, а ели уже пришел запрос с нее, то получаем результат
     if (!$mgadmin) {
         $onlyInCount = false;
         // ищем все товары
         if (MG::getSetting('printProdNullRem') == "true") {
             $onlyInCount = true;
             // ищем только среди тех которые есть в наличии
         }
         $filterProduct = $this->filterPublic(true, $onlyInCount);
         MG::set('catalogfilter', $filterProduct['filterBarHtml']);
         // return array('catalogItems'=>null, 'pager'=>null, 'filterBarHtml'=>$filter->getHtmlFilter(true), 'userFilter' => $userFilter);
         // если пришел запрос с фильтра со страницы каталога и не используется плагин фильтров
         if (isset($_REQUEST['applyFilter'])) {
             $result = array();
             if (!empty($filterProduct['userFilter'])) {
                 // если при генерации фильтров был построен запрос
                 // по входящим свойствам товара из  гет запроса
                 // то получим все товары  именно по данному запросу, учитвая фильтрацию по характеристикам
                 $result = $this->getListByUserFilter($countRows, $filterProduct['userFilter']);
                 $result['filterBarHtml'] = $filterProduct['filterBarHtml'];
             }
             $args = func_get_args();
             return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args);
         }
     }
     // Страница.
     $page = URL::get("page");
     $sql .= 'SELECT
       DISTINCT p.id,
       CONCAT(c.parent_url,c.url) as category_url,
       p.url as product_url,
       p.*, pv.product_id as variant_exist,
       rate,(p.price_course + p.price_course * (IFNULL(rate,0))) as `price_course`
     FROM `' . PREFIX . 'product` p
     LEFT JOIN `' . PREFIX . 'category` c
       ON c.id = p.cat_id
     LEFT JOIN `' . PREFIX . 'product_variant` pv
       ON p.id = pv.product_id
     LEFT JOIN (
       SELECT pv.product_id, SUM( pv.count ) AS varcount
       FROM  `' . PREFIX . 'product_variant` AS pv
       GROUP BY pv.product_id
     ) AS temp ON p.id = temp.product_id';
     // FIND_IN_SET - учитывает товары, в настройках которых,
     // указано в каких категориях следует их покзывать.
     $this->currentCategory['id'] = $this->currentCategory['id'] ? $this->currentCategory['id'] : 0;
     if (MG::getSetting('productInSubcat') == 'true') {
         $filter = '(p.cat_id IN (' . DB::quote(implode(',', $this->categoryId), 1) . ') ' . 'or FIND_IN_SET(' . DB::quote($this->currentCategory['id'], 1) . ',p.`inside_cat`))';
     } else {
         $filter = '(c.id IN (' . DB::quote($this->currentCategory['id'], 1) . ') ' . 'or FIND_IN_SET(' . DB::quote($this->currentCategory['id'], 1) . ',p.`inside_cat`))';
     }
     if ($mgadmin) {
         $filter = ' (p.cat_id IN (' . DB::quote(implode(',', $this->categoryId), 1) . ') ' . 'or FIND_IN_SET(' . DB::quote($this->currentCategory['id'], 1) . ',p.`inside_cat`))';
         if ($this->currentCategory['id'] == 0) {
             $filter = ' 1=1 ';
         }
     }
     // Запрос вернет общее кол-во продуктов в выбранной категории.
     $sql .= ' WHERE  ' . $filter;
     if ($onlyActive) {
         $sql .= ' AND p.activity = 1';
     }
     if (MG::getSetting('printProdNullRem') == "true" && !$mgadmin) {
         $sql .= " AND (temp.`varcount` > 0 OR temp.`varcount` < 0" . " OR p.count>0 OR p.count<0)";
     }
     $orderBy = ' ORDER BY `sort` ASC ';
     if (FILTER_SORT != 'FILTER_SORT' && !$mgadmin) {
         $parts = explode('|', FILTER_SORT);
         $orderBy = ' ORDER BY `' . DB::quote($parts[0], 1) . '` ' . DB::quote($parts[1], 1);
     }
     $sql .= $orderBy;
     // в админке не используем кэш
     if (!$mgadmin) {
         $result = Storage::get(md5($sql . $page));
     }
     if ($result == null) {
         $navigator = new Navigator($sql, $page, $countRows);
         //определяем класс
         $this->products = $navigator->getRowsSql();
         // добавим к полученым товарам их свойства
         $this->products = $this->addPropertyToProduct($this->products);
         if ($mgadmin) {
             $this->pager = $navigator->getPager('forAjax');
         } else {
             $this->pager = $navigator->getPager();
         }
         $result = array('catalogItems' => $this->products, 'pager' => $this->pager, 'totalCountItems' => $navigator->getNumRowsSql());
         Storage::save(md5($sql . $page), array('catalogItems' => $this->products, 'pager' => $this->pager, 'totalCountItems' => $navigator->getNumRowsSql()));
     }
     if (!empty($filterProduct['filterBarHtml'])) {
         $result['filterBarHtml'] = $filterProduct['filterBarHtml'];
     }
     $args = func_get_args();
     return MG::createHook(__CLASS__ . "_" . __FUNCTION__, $result, $args);
 }
Example #7
0
File: mg.php Project: nellka/mebel
 /**
  * Собирает массив данных, доступных в последствии из шаблоне через масиив $data.
  * @return void
  */
 public static function templateData($content)
 {
     $cart = self::getSmalCart();
     $settings = self::get('settings');
     $data = array('data' => array('cartCount' => $cart['cart_count'], 'cartPrice' => $cart['cart_price'], 'currency' => $settings['currency'], 'cartData' => $cart, 'content' => $content, 'menu' => self::getMenu(), 'thisUser' => User::getThis()));
     MG::set('templateData', $data['data']);
     return $data;
 }