Сортировка товаров
maiborodava
21 ноября 2018 г.
Добрый вечер, помогите разобраться, почему не работает стандартный код сортировки товаров по цене, точнее он работает но как то странно если я нахожусь в какой то из корневых категорий то сортировка не работает и поля «Цена от» и «Цена до» не проставляется (https://disk.yandex.ru/i/2OMfcvfxgChbfA ), если перейти дальше по каталогу то все работает (https://disk.yandex.ru/i/shGvcBXlf57wfw ).
Используется этот код:
if (Core::moduleIsActive('shop') && isset(Core_Page::instance()->libParams['shopId']))
{
$oShop = Core_Entity::factory('Shop', Core_Page::instance()->libParams['shopId']);
$Shop_Controller_Show = new Shop_Controller_Show($oShop);
$Shop_Controller_Show
->xsl(
Core_Entity::factory('Xsl')->getByName('МагазинФильтр')
)
->groupsMode('tree')
->limit(0)
->itemsProperties(TRUE);
if (is_object(Core_Page::instance()->object)
&& get_class(Core_Page::instance()->object) == 'Shop_Controller_Show')
{
$Shop_Controller_Show->group(Core_Page::instance()->object->group);
$iCurrentShopGroup = Core_Page::instance()->object->group;
}
else
{
$iCurrentShopGroup = 0;
}
$price_from = intval(Core_Array::getGet('price_from'));
$price_to = intval(Core_Array::getGet('price_to'));
if ($price_from)
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_from')->value($price_from)
);
$Shop_Controller_Show->addCacheSignature('price_from=' . $price_from);
}
if ($price_to)
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_to')->value($price_to)
);
$Shop_Controller_Show->addCacheSignature('price_to=' . $price_to);
}
//Sorting
if (Core_Array::getGet('sorting'))
{
$sorting = intval(Core_Array::getGet('sorting'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('sorting')->value($sorting)
);
$Shop_Controller_Show->addCacheSignature('sorting=' . $sorting);
}
//Producers
if (Core_Array::getGet('producer_id'))
{
$iProducerId = intval(Core_Array::getGet('producer_id'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('producer_id')->value($iProducerId)
);
$Shop_Controller_Show->addCacheSignature('producer_id=' . $iProducerId);
}
// Additional properties
$oShop_Item_Property_List = Core_Entity::factory('Shop_Item_Property_List', $oShop->id);
$aProperties = $oShop_Item_Property_List->Properties->findAll();
$aTmpProperties = array();
foreach ($aProperties as $oProperty)
{
// Св-во может иметь несколько значений
$aPropertiesValue = Core_Array::getGet('property_' . $oProperty->id);
if ($aPropertiesValue)
{
!is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
foreach ($aPropertiesValue as $sPropertyValue)
{
$aTmpProperties[] = array($oProperty, strval($sPropertyValue));
}
}
elseif (!is_null(Core_Array::getGet('property_' . $oProperty->id . '_from')))
{
$tmpFrom = Core_Array::getGet('property_' . $oProperty->id . '_from');
$tmpTo = Core_Array::getGet('property_' . $oProperty->id . '_to');
!is_array($tmpFrom) && $tmpFrom = array($tmpFrom);
!is_array($tmpTo) && $tmpTo = array($tmpTo);
// From ... to ...
foreach ($tmpFrom as $iKey => $sValue)
{
$to = Core_Array::get($tmpTo, $iKey);
$aTmpProperties[] = array($oProperty, array(
'from' => $sValue != ''
? ($oProperty->type == 11 ? floatval($sValue) : intval($sValue))
: '',
'to' => $to != ''
? ($oProperty->type == 11 ? floatval($to) : intval($to))
: ''
));
}
}
}
if (count($aTmpProperties))
{
reset($aTmpProperties);
while(list(, list($oProperty, $propertyValue)) = each($aTmpProperties))
{
$tableName = $oProperty->createNewValue(0)->getTableName();
$Shop_Controller_Show->shopItems()->queryBuilder()
->where('shop_item_properties.property_id', '=', $oProperty->id);
if (!is_array($propertyValue))
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id)->value($propertyValue)
);
$Shop_Controller_Show->addCacheSignature("property{$oProperty->id}={$propertyValue}");
}
else
{
$from = trim(Core_Array::get($propertyValue, 'from'));
$to = trim(Core_Array::get($propertyValue, 'to'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_from')->value($from)
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_to')->value($to)
);
$Shop_Controller_Show
->addCacheSignature("property{$oProperty->id}_from={$from}")
->addCacheSignature("property{$oProperty->id}_to={$to}");
}
}
}
$Shop_Controller_Show
->group($iCurrentShopGroup)
->addMinMaxPrice()
->show();
}
Используется этот код:
if (Core::moduleIsActive('shop') && isset(Core_Page::instance()->libParams['shopId']))
{
$oShop = Core_Entity::factory('Shop', Core_Page::instance()->libParams['shopId']);
$Shop_Controller_Show = new Shop_Controller_Show($oShop);
$Shop_Controller_Show
->xsl(
Core_Entity::factory('Xsl')->getByName('МагазинФильтр')
)
->groupsMode('tree')
->limit(0)
->itemsProperties(TRUE);
if (is_object(Core_Page::instance()->object)
&& get_class(Core_Page::instance()->object) == 'Shop_Controller_Show')
{
$Shop_Controller_Show->group(Core_Page::instance()->object->group);
$iCurrentShopGroup = Core_Page::instance()->object->group;
}
else
{
$iCurrentShopGroup = 0;
}
$price_from = intval(Core_Array::getGet('price_from'));
$price_to = intval(Core_Array::getGet('price_to'));
if ($price_from)
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_from')->value($price_from)
);
$Shop_Controller_Show->addCacheSignature('price_from=' . $price_from);
}
if ($price_to)
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_to')->value($price_to)
);
$Shop_Controller_Show->addCacheSignature('price_to=' . $price_to);
}
//Sorting
if (Core_Array::getGet('sorting'))
{
$sorting = intval(Core_Array::getGet('sorting'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('sorting')->value($sorting)
);
$Shop_Controller_Show->addCacheSignature('sorting=' . $sorting);
}
//Producers
if (Core_Array::getGet('producer_id'))
{
$iProducerId = intval(Core_Array::getGet('producer_id'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('producer_id')->value($iProducerId)
);
$Shop_Controller_Show->addCacheSignature('producer_id=' . $iProducerId);
}
// Additional properties
$oShop_Item_Property_List = Core_Entity::factory('Shop_Item_Property_List', $oShop->id);
$aProperties = $oShop_Item_Property_List->Properties->findAll();
$aTmpProperties = array();
foreach ($aProperties as $oProperty)
{
// Св-во может иметь несколько значений
$aPropertiesValue = Core_Array::getGet('property_' . $oProperty->id);
if ($aPropertiesValue)
{
!is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
foreach ($aPropertiesValue as $sPropertyValue)
{
$aTmpProperties[] = array($oProperty, strval($sPropertyValue));
}
}
elseif (!is_null(Core_Array::getGet('property_' . $oProperty->id . '_from')))
{
$tmpFrom = Core_Array::getGet('property_' . $oProperty->id . '_from');
$tmpTo = Core_Array::getGet('property_' . $oProperty->id . '_to');
!is_array($tmpFrom) && $tmpFrom = array($tmpFrom);
!is_array($tmpTo) && $tmpTo = array($tmpTo);
// From ... to ...
foreach ($tmpFrom as $iKey => $sValue)
{
$to = Core_Array::get($tmpTo, $iKey);
$aTmpProperties[] = array($oProperty, array(
'from' => $sValue != ''
? ($oProperty->type == 11 ? floatval($sValue) : intval($sValue))
: '',
'to' => $to != ''
? ($oProperty->type == 11 ? floatval($to) : intval($to))
: ''
));
}
}
}
if (count($aTmpProperties))
{
reset($aTmpProperties);
while(list(, list($oProperty, $propertyValue)) = each($aTmpProperties))
{
$tableName = $oProperty->createNewValue(0)->getTableName();
$Shop_Controller_Show->shopItems()->queryBuilder()
->where('shop_item_properties.property_id', '=', $oProperty->id);
if (!is_array($propertyValue))
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id)->value($propertyValue)
);
$Shop_Controller_Show->addCacheSignature("property{$oProperty->id}={$propertyValue}");
}
else
{
$from = trim(Core_Array::get($propertyValue, 'from'));
$to = trim(Core_Array::get($propertyValue, 'to'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_from')->value($from)
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_to')->value($to)
);
$Shop_Controller_Show
->addCacheSignature("property{$oProperty->id}_from={$from}")
->addCacheSignature("property{$oProperty->id}_to={$to}");
}
}
}
$Shop_Controller_Show
->group($iCurrentShopGroup)
->addMinMaxPrice()
->show();
}
e-mail: webmaster@maiboroda.pro / maiboroda.pro / Создание и поддержка сайтов / г. Ставрополь
Seri
22 ноября 2018 г.
maiborodava писал(а):
Судя по скриншоту, товары отображаются со всех категорий и подкатегорий текущего раздела.
Похоже в самом ТДС ИМ стандартный контроллер Shop_Controller_Show унаследован и переделан.
Приведенный вами выше код это стандартный ТДС блок фильтра с XSL шаблоном МагазинФильтр. Для того что бы добиться решение, вам необходимо ТДС блока фильтра также унаследовать с тем что есть в ТДС ИМ.
Как например работает на Демо сайтеhttp://demoshop.hostcms.ru/shop/
Судя по скриншоту, товары отображаются со всех категорий и подкатегорий текущего раздела.
Похоже в самом ТДС ИМ стандартный контроллер Shop_Controller_Show унаследован и переделан.
Приведенный вами выше код это стандартный ТДС блок фильтра с XSL шаблоном МагазинФильтр. Для того что бы добиться решение, вам необходимо ТДС блока фильтра также унаследовать с тем что есть в ТДС ИМ.
Как например работает на Демо сайте
E-mail: info@syrbek.ru / телега: @syrbek /skype: activexm / syrbek.ru / Поддержка сайтов / г. Москва [HTML, CSS (Bootstrap), JS(JQuery, ExtJS), PHP, MySQL, MSSql, Posgres, Git, SVN, Redmine]
maiborodava
23 ноября 2018 г.
Да вроде все стандартно, вот код ТДС ИМ.
<?php
$oShop = Core_Entity::factory('Shop', Core_Array::get(Core_Page::instance()->libParams, 'shopId'));
$Shop_Controller_Show = new Shop_Controller_Show($oShop);
/* Количество */
$on_page = intval(Core_Array::getGet('on_page'));
if ($on_page > 0 && $on_page < 150)
{
$limit = $on_page;
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('on_page')->value($on_page)
);
}
else
{
$limit = $oShop->items_on_page;
}
$Shop_Controller_Show
->limit($limit)
->parseUrl();
// Обработка скачивания файла электронного товара
$guid = Core_Array::getGet('download_file');
if (strlen($guid))
{
$oShop_Order_Item_Digital = Core_Entity::factory('Shop_Order_Item_Digital')->getByGuid($guid);
if (!is_null($oShop_Order_Item_Digital) && $oShop_Order_Item_Digital->Shop_Order_Item->Shop_Order->shop_id == $oShop->id)
{
$iDay = 7;
// Проверяем, доступна ли ссылка (Ссылка доступна в течение недели после оплаты)
if (Core_Date::sql2timestamp($oShop_Order_Item_Digital->Shop_Order_Item->Shop_Order->payment_datetime) > time() - 24 * 60 * 60 * $iDay)
{
$oShop_Item_Digital = $oShop_Order_Item_Digital->Shop_Item_Digital;
if ($oShop_Item_Digital->filename != '')
{
Core_File::download($oShop_Item_Digital->getFullFilePath(), $oShop_Item_Digital->filename);
exit();
}
}
else
{
Core_Message::show(Core::_('Shop_Order_Item_Digital.time_is_up', $iDay));
}
}
Core_Page::instance()->response->status(404)->sendHeaders()->showBody();
exit();
}
// Сравнение товаров
if (Core_Array::getRequest('compare'))
{
$shop_item_id = intval(Core_Array::getRequest('compare'));
if (Core_Entity::factory('Shop_Item', $shop_item_id)->shop_id == $oShop->id)
{
Core_Session::start();
if (isset($_SESSION['hostcmsCompare'][$oShop->id][$shop_item_id]))
{
unset($_SESSION['hostcmsCompare'][$oShop->id][$shop_item_id]);
}
else
{
$_SESSION['hostcmsCompare'][$oShop->id][$shop_item_id] = 1;
}
}
Core_Page::instance()->response
->status(200)
->header('Pragma', "no-cache")
->header('Cache-Control', "private, no-cache")
->header('Vary', "Accept")
->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
->header('X-Powered-By', 'HostCMS')
->header('Content-Disposition', 'inline; filename="files.json"');
Core_Page::instance()->response
->body(json_encode('OK'))
->header('Content-type', 'application/json; charset=utf-8');
Core_Page::instance()->response
->sendHeaders()
->showBody();
exit();
}
// Избранное
/*if (Core_Array::getRequest('favorite'))
{
$shop_item_id = intval(Core_Array::getRequest('favorite'));
if (Core_Entity::factory('Shop_Item', $shop_item_id)->shop_id == $oShop->id)
{
Core_Session::start();
Core_Session::setMaxLifeTime(86400 * 30);
if (isset($_SESSION['hostcmsFavorite'][$oShop->id]) && in_array($shop_item_id, $_SESSION['hostcmsFavorite'][$oShop->id]))
{
unset($_SESSION['hostcmsFavorite'][$oShop->id][
array_search($shop_item_id, $_SESSION['hostcmsFavorite'][$oShop->id])
]);
}
else
{
$_SESSION['hostcmsFavorite'][$oShop->id][] = $shop_item_id;
}
}
Core_Page::instance()->response
->status(200)
->header('Pragma', "no-cache")
->header('Cache-Control', "private, no-cache")
->header('Vary', "Accept")
->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
->header('X-Powered-By', 'HostCMS')
->header('Content-Disposition', 'inline; filename="files.json"');
Core_Page::instance()->response
->body(json_encode('OK'))
->header('Content-type', 'application/json; charset=utf-8');
Core_Page::instance()->response
->sendHeaders()
->showBody();
exit();
}*/
// Viewed items
if ($Shop_Controller_Show->item && $Shop_Controller_Show->viewed)
{
$Shop_Controller_Show->addIntoViewed();
}
if (!is_null(Core_Array::getGet('vote')))
{
$oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
$entity_id = intval(Core_Array::getGet('id'));
if ($entity_id && !is_null($oSiteuser))
{
$entity_type = strval(Core_Array::getGet('entity_type'));
$vote = intval(Core_Array::getGet('vote'));
$oObject = Vote_Controller::instance()->getVotedObject($entity_type, $entity_id);
if (!is_null($oObject))
{
$oVote = $oObject->Votes->getBySiteuser_Id($oSiteuser->id);
$vote_value = $vote ? 1 : -1;
$deleteVote = 0;
// Пользователь не голосовал ранее
if (is_null($oVote))
{
$oVote = Core_Entity::factory('Vote');
$oVote->siteuser_id = $oSiteuser->id;
$oVote->value = $vote_value;
$oObject->add($oVote);
}
// Пользователь голосовал ранее, но поставил противоположную оценку
elseif ($oVote->value != $vote_value)
{
$oVote->value = $vote_value;
$oVote->save();
}
// Пользователь голосовал ранее и поставил такую же оценку как и ранее, обнуляем его голосование, как будто он вообще не голосовал
else
{
$deleteVote = 1;
$oVote->delete();
}
$aVotingStatistic = Vote_Controller::instance()->getRate($entity_type, $entity_id);
Core_Page::instance()->response
->body(
json_encode(array('value' => $oVote->value, 'item' => $oObject->id, 'entity_type' => $entity_type,
'likes' => $aVotingStatistic['likes'], 'dislikes' => $aVotingStatistic['dislikes'],
'rate' => $aVotingStatistic['rate'], 'delete_vote' => $deleteVote)
)
);
}
}
Core_Page::instance()->response
->status(200)
->header('Pragma', "no-cache")
->header('Cache-Control', "private, no-cache")
->header('Vary', "Accept")
->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
->header('X-Powered-By', 'HostCMS')
->header('Content-Disposition', 'inline; filename="files.json"');
if (strpos(Core_Array::get($_SERVER, 'HTTP_ACCEPT', ''), 'application/json') !== FALSE)
{
Core_Page::instance()->response->header('Content-type', 'application/json; charset=utf-8');
}
else
{
Core_Page::instance()->response
->header('X-Content-Type-Options', 'nosniff')
->header('Content-type', 'text/plain; charset=utf-8');
}
if(Core_Array::getRequest('_'))
{
Core_Page::instance()->response
->sendHeaders()
->showBody();
exit();
}
}
// Текстовая информация для указания номера страницы, например "страница"
$pageName = Core_Array::get(Core_Page::instance()->libParams, 'page')
? Core_Array::get(Core_Page::instance()->libParams, 'page')
: 'страница';
// Разделитель в заголовке страницы
$pageSeparator = Core_Array::get(Core_Page::instance()->libParams, 'separator')
? Core_Page::instance()->libParams['separator']
: ' / ';
$aTitle = array($oShop->name);
$aDescription = array($oShop->name);
$aKeywords = array($oShop->name);
if (!is_null($Shop_Controller_Show->tag) && Core::moduleIsActive('tag'))
{
$oTag = Core_Entity::factory('Tag')->getByPath($Shop_Controller_Show->tag);
if ($oTag)
{
$aTitle[] = $oTag->seo_title != ''
? $oTag->seo_title
: Core::_('Shop.tag', $oTag->name);
$aDescription[] = $oTag->seo_description != ''
? $oTag->seo_description
: $oTag->name;
$aKeywords[] = $oTag->seo_keywords != ''
? $oTag->seo_keywords
: $oTag->name;
}
}
if ($Shop_Controller_Show->group)
{
$oShop_Group = Core_Entity::factory('Shop_Group', $Shop_Controller_Show->group);
$bGroupTitle = $oShop_Group->seo_title != '';
$bGroupDescription = $oShop_Group->seo_description != '';
$bGroupKeywords = $oShop_Group->seo_keywords != '';
if (!$Shop_Controller_Show->item)
{
$bGroupTitle && Core_Page::instance()->title($oShop_Group->seo_title);
$bGroupDescription && Core_Page::instance()->description($oShop_Group->seo_description);
$bGroupKeywords && Core_Page::instance()->keywords($oShop_Group->seo_keywords);
}
do {
($Shop_Controller_Show->item || !$bGroupTitle) && $aTitle[] = $oShop_Group->name;
($Shop_Controller_Show->item || !$bGroupDescription) && $aDescription[] = $oShop_Group->name;
($Shop_Controller_Show->item || !$bGroupKeywords) && $aKeywords[] = $oShop_Group->name;
} while($oShop_Group = $oShop_Group->getParent());
}
if ($Shop_Controller_Show->item)
{
$oShop_Item = Core_Entity::factory('Shop_Item', $Shop_Controller_Show->item);
$oShop_Item->seo_title != ''
? Core_Page::instance()->title($oShop_Item->seo_title)
: $aTitle[] = $oShop_Item->name;
$oShop_Item->seo_description != ''
? Core_Page::instance()->description($oShop_Item->seo_description)
: $aDescription[] = $oShop_Item->name;
$oShop_Item->seo_keywords != ''
? Core_Page::instance()->keywords($oShop_Item->name)
: $aKeywords[] = $oShop_Item->name;
}
if ($Shop_Controller_Show->producer)
{
$oShop_Producer = Core_Entity::factory('Shop_Producer', $Shop_Controller_Show->producer);
$aKeywords[] = $aDescription[] = $aTitle[] = $oShop_Producer->name;
}
if ($Shop_Controller_Show->page)
{
array_unshift($aTitle, $pageName . ' ' . ($Shop_Controller_Show->page + 1));
}
if (count($aTitle) > 1)
{
$aTitle = array_reverse($aTitle);
$aDescription = array_reverse($aDescription);
$aKeywords = array_reverse($aKeywords);
Core_Page::instance()->title(implode($pageSeparator, $aTitle));
Core_Page::instance()->description(implode($pageSeparator, $aDescription));
Core_Page::instance()->keywords(implode($pageSeparator, $aKeywords));
}
Core_Page::instance()->object = $Shop_Controller_Show;
$oShop = Core_Entity::factory('Shop', Core_Array::get(Core_Page::instance()->libParams, 'shopId'));
$Shop_Controller_Show = new Shop_Controller_Show($oShop);
/* Количество */
$on_page = intval(Core_Array::getGet('on_page'));
if ($on_page > 0 && $on_page < 150)
{
$limit = $on_page;
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('on_page')->value($on_page)
);
}
else
{
$limit = $oShop->items_on_page;
}
$Shop_Controller_Show
->limit($limit)
->parseUrl();
// Обработка скачивания файла электронного товара
$guid = Core_Array::getGet('download_file');
if (strlen($guid))
{
$oShop_Order_Item_Digital = Core_Entity::factory('Shop_Order_Item_Digital')->getByGuid($guid);
if (!is_null($oShop_Order_Item_Digital) && $oShop_Order_Item_Digital->Shop_Order_Item->Shop_Order->shop_id == $oShop->id)
{
$iDay = 7;
// Проверяем, доступна ли ссылка (Ссылка доступна в течение недели после оплаты)
if (Core_Date::sql2timestamp($oShop_Order_Item_Digital->Shop_Order_Item->Shop_Order->payment_datetime) > time() - 24 * 60 * 60 * $iDay)
{
$oShop_Item_Digital = $oShop_Order_Item_Digital->Shop_Item_Digital;
if ($oShop_Item_Digital->filename != '')
{
Core_File::download($oShop_Item_Digital->getFullFilePath(), $oShop_Item_Digital->filename);
exit();
}
}
else
{
Core_Message::show(Core::_('Shop_Order_Item_Digital.time_is_up', $iDay));
}
}
Core_Page::instance()->response->status(404)->sendHeaders()->showBody();
exit();
}
// Сравнение товаров
if (Core_Array::getRequest('compare'))
{
$shop_item_id = intval(Core_Array::getRequest('compare'));
if (Core_Entity::factory('Shop_Item', $shop_item_id)->shop_id == $oShop->id)
{
Core_Session::start();
if (isset($_SESSION['hostcmsCompare'][$oShop->id][$shop_item_id]))
{
unset($_SESSION['hostcmsCompare'][$oShop->id][$shop_item_id]);
}
else
{
$_SESSION['hostcmsCompare'][$oShop->id][$shop_item_id] = 1;
}
}
Core_Page::instance()->response
->status(200)
->header('Pragma', "no-cache")
->header('Cache-Control', "private, no-cache")
->header('Vary', "Accept")
->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
->header('X-Powered-By', 'HostCMS')
->header('Content-Disposition', 'inline; filename="files.json"');
Core_Page::instance()->response
->body(json_encode('OK'))
->header('Content-type', 'application/json; charset=utf-8');
Core_Page::instance()->response
->sendHeaders()
->showBody();
exit();
}
// Избранное
/*if (Core_Array::getRequest('favorite'))
{
$shop_item_id = intval(Core_Array::getRequest('favorite'));
if (Core_Entity::factory('Shop_Item', $shop_item_id)->shop_id == $oShop->id)
{
Core_Session::start();
Core_Session::setMaxLifeTime(86400 * 30);
if (isset($_SESSION['hostcmsFavorite'][$oShop->id]) && in_array($shop_item_id, $_SESSION['hostcmsFavorite'][$oShop->id]))
{
unset($_SESSION['hostcmsFavorite'][$oShop->id][
array_search($shop_item_id, $_SESSION['hostcmsFavorite'][$oShop->id])
]);
}
else
{
$_SESSION['hostcmsFavorite'][$oShop->id][] = $shop_item_id;
}
}
Core_Page::instance()->response
->status(200)
->header('Pragma', "no-cache")
->header('Cache-Control', "private, no-cache")
->header('Vary', "Accept")
->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
->header('X-Powered-By', 'HostCMS')
->header('Content-Disposition', 'inline; filename="files.json"');
Core_Page::instance()->response
->body(json_encode('OK'))
->header('Content-type', 'application/json; charset=utf-8');
Core_Page::instance()->response
->sendHeaders()
->showBody();
exit();
}*/
// Viewed items
if ($Shop_Controller_Show->item && $Shop_Controller_Show->viewed)
{
$Shop_Controller_Show->addIntoViewed();
}
if (!is_null(Core_Array::getGet('vote')))
{
$oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
$entity_id = intval(Core_Array::getGet('id'));
if ($entity_id && !is_null($oSiteuser))
{
$entity_type = strval(Core_Array::getGet('entity_type'));
$vote = intval(Core_Array::getGet('vote'));
$oObject = Vote_Controller::instance()->getVotedObject($entity_type, $entity_id);
if (!is_null($oObject))
{
$oVote = $oObject->Votes->getBySiteuser_Id($oSiteuser->id);
$vote_value = $vote ? 1 : -1;
$deleteVote = 0;
// Пользователь не голосовал ранее
if (is_null($oVote))
{
$oVote = Core_Entity::factory('Vote');
$oVote->siteuser_id = $oSiteuser->id;
$oVote->value = $vote_value;
$oObject->add($oVote);
}
// Пользователь голосовал ранее, но поставил противоположную оценку
elseif ($oVote->value != $vote_value)
{
$oVote->value = $vote_value;
$oVote->save();
}
// Пользователь голосовал ранее и поставил такую же оценку как и ранее, обнуляем его голосование, как будто он вообще не голосовал
else
{
$deleteVote = 1;
$oVote->delete();
}
$aVotingStatistic = Vote_Controller::instance()->getRate($entity_type, $entity_id);
Core_Page::instance()->response
->body(
json_encode(array('value' => $oVote->value, 'item' => $oObject->id, 'entity_type' => $entity_type,
'likes' => $aVotingStatistic['likes'], 'dislikes' => $aVotingStatistic['dislikes'],
'rate' => $aVotingStatistic['rate'], 'delete_vote' => $deleteVote)
)
);
}
}
Core_Page::instance()->response
->status(200)
->header('Pragma', "no-cache")
->header('Cache-Control', "private, no-cache")
->header('Vary', "Accept")
->header('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT')
->header('X-Powered-By', 'HostCMS')
->header('Content-Disposition', 'inline; filename="files.json"');
if (strpos(Core_Array::get($_SERVER, 'HTTP_ACCEPT', ''), 'application/json') !== FALSE)
{
Core_Page::instance()->response->header('Content-type', 'application/json; charset=utf-8');
}
else
{
Core_Page::instance()->response
->header('X-Content-Type-Options', 'nosniff')
->header('Content-type', 'text/plain; charset=utf-8');
}
if(Core_Array::getRequest('_'))
{
Core_Page::instance()->response
->sendHeaders()
->showBody();
exit();
}
}
// Текстовая информация для указания номера страницы, например "страница"
$pageName = Core_Array::get(Core_Page::instance()->libParams, 'page')
? Core_Array::get(Core_Page::instance()->libParams, 'page')
: 'страница';
// Разделитель в заголовке страницы
$pageSeparator = Core_Array::get(Core_Page::instance()->libParams, 'separator')
? Core_Page::instance()->libParams['separator']
: ' / ';
$aTitle = array($oShop->name);
$aDescription = array($oShop->name);
$aKeywords = array($oShop->name);
if (!is_null($Shop_Controller_Show->tag) && Core::moduleIsActive('tag'))
{
$oTag = Core_Entity::factory('Tag')->getByPath($Shop_Controller_Show->tag);
if ($oTag)
{
$aTitle[] = $oTag->seo_title != ''
? $oTag->seo_title
: Core::_('Shop.tag', $oTag->name);
$aDescription[] = $oTag->seo_description != ''
? $oTag->seo_description
: $oTag->name;
$aKeywords[] = $oTag->seo_keywords != ''
? $oTag->seo_keywords
: $oTag->name;
}
}
if ($Shop_Controller_Show->group)
{
$oShop_Group = Core_Entity::factory('Shop_Group', $Shop_Controller_Show->group);
$bGroupTitle = $oShop_Group->seo_title != '';
$bGroupDescription = $oShop_Group->seo_description != '';
$bGroupKeywords = $oShop_Group->seo_keywords != '';
if (!$Shop_Controller_Show->item)
{
$bGroupTitle && Core_Page::instance()->title($oShop_Group->seo_title);
$bGroupDescription && Core_Page::instance()->description($oShop_Group->seo_description);
$bGroupKeywords && Core_Page::instance()->keywords($oShop_Group->seo_keywords);
}
do {
($Shop_Controller_Show->item || !$bGroupTitle) && $aTitle[] = $oShop_Group->name;
($Shop_Controller_Show->item || !$bGroupDescription) && $aDescription[] = $oShop_Group->name;
($Shop_Controller_Show->item || !$bGroupKeywords) && $aKeywords[] = $oShop_Group->name;
} while($oShop_Group = $oShop_Group->getParent());
}
if ($Shop_Controller_Show->item)
{
$oShop_Item = Core_Entity::factory('Shop_Item', $Shop_Controller_Show->item);
$oShop_Item->seo_title != ''
? Core_Page::instance()->title($oShop_Item->seo_title)
: $aTitle[] = $oShop_Item->name;
$oShop_Item->seo_description != ''
? Core_Page::instance()->description($oShop_Item->seo_description)
: $aDescription[] = $oShop_Item->name;
$oShop_Item->seo_keywords != ''
? Core_Page::instance()->keywords($oShop_Item->name)
: $aKeywords[] = $oShop_Item->name;
}
if ($Shop_Controller_Show->producer)
{
$oShop_Producer = Core_Entity::factory('Shop_Producer', $Shop_Controller_Show->producer);
$aKeywords[] = $aDescription[] = $aTitle[] = $oShop_Producer->name;
}
if ($Shop_Controller_Show->page)
{
array_unshift($aTitle, $pageName . ' ' . ($Shop_Controller_Show->page + 1));
}
if (count($aTitle) > 1)
{
$aTitle = array_reverse($aTitle);
$aDescription = array_reverse($aDescription);
$aKeywords = array_reverse($aKeywords);
Core_Page::instance()->title(implode($pageSeparator, $aTitle));
Core_Page::instance()->description(implode($pageSeparator, $aDescription));
Core_Page::instance()->keywords(implode($pageSeparator, $aKeywords));
}
Core_Page::instance()->object = $Shop_Controller_Show;
<?php
$Shop_Controller_Show = Core_Page::instance()->object;
$xslName = $Shop_Controller_Show->item
? Core_Array::get(Core_Page::instance()->libParams, 'shopItemXsl')
: Core_Array::get(Core_Page::instance()->libParams, 'shopXsl');
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('ТекущаяГруппа')->value($Shop_Controller_Show->group)
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('show_comments')->value(Core_Array::get(Core_Page::instance()->libParams, 'showComments', 1))
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('show_add_comments')->value(Core_Array::get(Core_Page::instance()->libParams, 'showAddComment', 2))
);
$Shop_Controller_Show
->tags(TRUE)
->comments(TRUE)
->associatedItems(TRUE)
->modifications(TRUE);
if ($Shop_Controller_Show->item == 0)
{
$Shop_Controller_Show->itemsForbiddenTags(array('text'));
// Producers
if (Core_Array::getGet('producer_id'))
{
$iProducerId = intval(Core_Array::getGet('producer_id'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('producer_id')->value($iProducerId)
);
$Shop_Controller_Show->shopItems()
->queryBuilder()
->select('shop_items.*')
->where('shop_items.shop_producer_id', '=', $iProducerId);
$Shop_Controller_Show->addCacheSignature('producer_id=' . $iProducerId);
}
if (Core_Array::getGet('filter') || Core_Array::getGet('sorting'))
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('filter')->value(1)
);
$oShop = $Shop_Controller_Show->getEntity();
$sorting = intval(Core_Array::getGet('sorting'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('sorting')->value($sorting)
);
$Shop_Controller_Show->addCacheSignature('sorting=' . $sorting);
// Prices
$price_from = intval(Core_Array::getGet('price_from'));
$price_to = intval(Core_Array::getGet('price_to'));
if ($price_from || $price_to || $sorting == 1 || $sorting == 2)
{
// Получаем список валют магазина
$aShop_Currencies = Core_Entity::factory('Shop_Currency')->findAll();
$query_tax = 'IF(`shop_taxes`.`tax_is_included` IS NULL OR `shop_taxes`.`tax_is_included` = 1, 0, `shop_items`.`price` * `shop_taxes`.`rate` / 100)';
$query_currency_switch = "`shop_items`.`price` + {$query_tax}";
foreach ($aShop_Currencies as $oShop_Currency)
{
// Получаем коэффициент пересчета для каждой валюты
$currency_coefficient = Shop_Controller::instance()->getCurrencyCoefficientInShopCurrency(
$oShop_Currency, $oShop->Shop_Currency
);
$query_currency_switch = "IF (`shop_items`.`shop_currency_id` = '{$oShop_Currency->id}', IF (COUNT(`shop_discounts`.`id`), ((`shop_items`.`price` + {$query_tax}) * (1 - SUM(IF(`shop_discounts`.`type` = 0, `shop_discounts`.`value`, 0)) / 100)) * {$currency_coefficient} - SUM(IF(`shop_discounts`.`type`, `shop_discounts`.`value`, 0)), (`shop_items`.`price`) * {$currency_coefficient}), {$query_currency_switch})";
}
$current_date = date('Y-m-d H:i:s');
$Shop_Controller_Show->shopItems()
->queryBuilder()
->select(array(Core_QueryBuilder::expression($query_currency_switch), 'absolute_price'))
->leftJoin('shop_item_discounts', 'shop_items.id', '=', 'shop_item_discounts.shop_item_id')
->leftJoin('shop_discounts', 'shop_item_discounts.shop_discount_id', '=', 'shop_discounts.id', array(
array('AND ' => array('shop_discounts.active', '=', 1)),
array('AND ' => array('shop_discounts.deleted', '=', 0)),
array('AND' => array('shop_discounts.start_datetime', '<=', $current_date)),
array('AND (' => array('shop_discounts.end_datetime', '>=', $current_date)),
array('OR' => array('shop_discounts.end_datetime', '=', '0000-00-00 00:00:00')),
array(')' => NULL)
))
->leftJoin('shop_taxes', 'shop_taxes.id', '=', 'shop_items.shop_tax_id')
->groupBy('shop_items.id');
if ($price_from)
{
$Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '>=', $price_from);
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_from')->value($price_from)
);
$Shop_Controller_Show->addCacheSignature('price_from=' . $price_from);
}
if ($price_to)
{
$Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '<=', $price_to);
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_to')->value($price_to)
);
$Shop_Controller_Show->addCacheSignature('price_to=' . $price_to);
}
$Shop_Controller_Show->shopItems()->queryBuilder()
->clearOrderBy()
->orderBy('absolute_price', $sorting == 1 ? 'ASC' : 'DESC');
}
$sorting == 3 && $Shop_Controller_Show->shopItems()->queryBuilder()
->clearOrderBy()
->orderBy('shop_items.name', 'ASC');
// Additional properties
$oShop_Item_Property_List = Core_Entity::factory('Shop_Item_Property_List', $oShop->id);
$aProperties = $Shop_Controller_Show->group !== FALSE && is_null($Shop_Controller_Show->tag)
? $oShop_Item_Property_List->getPropertiesForGroup($Shop_Controller_Show->group)
: $oShop_Item_Property_List->Properties->findAll();
$aTmpProperties = array();
$havingCount = 0;
foreach ($aProperties as $oProperty)
{
// Св-во может иметь несколько значений
$aPropertiesValue = Core_Array::getGet('property_' . $oProperty->id);
if ($aPropertiesValue)
{
!is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
$aPropertiesValue = array_map('strval', $aPropertiesValue);
$aTmpProperties[] = array($oProperty, $aPropertiesValue);
$havingCount++;
}
elseif (!is_null(Core_Array::getGet('property_' . $oProperty->id . '_from')))
{
$tmpFrom = Core_Array::getGet('property_' . $oProperty->id . '_from');
$tmpTo = Core_Array::getGet('property_' . $oProperty->id . '_to');
!is_array($tmpFrom) && $tmpFrom = array($tmpFrom);
!is_array($tmpTo) && $tmpTo = array($tmpTo);
// From ... to ...
foreach ($tmpFrom as $iKey => $sValue)
{
$to = Core_Array::get($tmpTo, $iKey);
$aTmpProperties[] = array($oProperty, array(
'from' => $sValue != ''
? ($oProperty->type == 11 ? floatval($sValue) : intval($sValue))
: '',
'to' => $to != ''
? ($oProperty->type == 11 ? floatval($to) : intval($to))
: ''
));
}
$havingCount++;
}
}
if (count($aTmpProperties))
{
$aTableNames = array();
$Shop_Controller_Show->shopItems()->queryBuilder()
->leftJoin('shop_item_properties', 'shop_items.shop_id', '=', 'shop_item_properties.shop_id')
->setAnd()
->open();
reset($aTmpProperties);
while(list(, list($oProperty, $aPropertyValues)) = each($aTmpProperties))
{
$tableName = $oProperty->createNewValue(0)->getTableName();
!in_array($tableName, $aTableNames) && $aTableNames[] = $tableName;
$Shop_Controller_Show->shopItems()->queryBuilder()
->where('shop_item_properties.property_id', '=', $oProperty->id);
if (!isset($aPropertyValues['from']))
{
// Для строк фильтр LIKE %...%
if ($oProperty->type == 1)
{
foreach ($aPropertyValues as $propertyValue)
{
$Shop_Controller_Show->shopItems()->queryBuilder()
->where($tableName . '.value', 'LIKE', "%{$propertyValue}%");
}
}
else
{
// Checkbox
$oProperty->type == 7 && $aPropertyValues[0] != '' && $aPropertyValues = array(1);
$bCheckUnset = $oProperty->type != 7 && $oProperty->type != 3;
$bCheckUnset && $Shop_Controller_Show->shopItems()->queryBuilder()->open();
$Shop_Controller_Show->shopItems()->queryBuilder()
->where(
$tableName . '.value',
count($aPropertyValues) == 1 ? '=' : 'IN',
count($aPropertyValues) == 1 ? $aPropertyValues[0] : $aPropertyValues
);
$bCheckUnset && $Shop_Controller_Show->shopItems()->queryBuilder()
->setOr()
->where($tableName . '.value', 'IS', NULL)
->close();
}
$Shop_Controller_Show->shopItems()->queryBuilder()
->setOr();
foreach ($aPropertyValues as $propertyValue)
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id)->value($propertyValue)
);
$Shop_Controller_Show->addCacheSignature("property{$oProperty->id}={$propertyValue}");
}
}
else
{
$from = trim(Core_Array::get($aPropertyValues, 'from'));
$from && $Shop_Controller_Show->shopItems()->queryBuilder()
->open()
->where($tableName . '.value', '>=', $from)
->setOr()
->where($tableName . '.value', 'IS', NULL)
->close()
->setAnd();
$to = trim(Core_Array::get($aPropertyValues, 'to'));
$to && $Shop_Controller_Show->shopItems()->queryBuilder()
->open()
->where($tableName . '.value', '<=', $to)
->setOr()
->where($tableName . '.value', 'IS', NULL)
->close();
$Shop_Controller_Show->shopItems()->queryBuilder()
->setOr();
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_from')->value($from)
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_to')->value($to)
);
$Shop_Controller_Show
->addCacheSignature("property{$oProperty->id}_from={$from}")
->addCacheSignature("property{$oProperty->id}_to={$to}");
}
}
$Shop_Controller_Show->shopItems()->queryBuilder()
->close()
->groupBy('shop_items.id');
$havingCount > 1
&& $Shop_Controller_Show->shopItems()->queryBuilder()
->having(Core_Querybuilder::expression('COUNT(DISTINCT `shop_item_properties`.`property_id`)'), '=', $havingCount);
foreach ($aTableNames as $tableName)
{
$Shop_Controller_Show->shopItems()->queryBuilder()
->leftJoin($tableName, 'shop_items.id', '=', $tableName . '.entity_id',
array(
array('AND' => array('shop_item_properties.property_id', '=', Core_QueryBuilder::expression($tableName . '.property_id')))
)
);
}
}
}
}
else
{
if (Core_Array::getPost('add_comment') && Core_Array::get(Core_Page::instance()->libParams, 'showComments', 1))
{
$oShop = $Shop_Controller_Show->getEntity();
$Shop_Controller_Show->cache(FALSE);
$oLastComment = Core_Entity::factory('Comment')->getLastCommentByIp(
Core_Array::get($_SERVER, 'REMOTE_ADDR')
);
$oXmlCommentTag = Core::factory('Core_Xml_Entity')
->name('document');
$siteuser_id = 0;
if (Core::moduleIsActive('siteuser'))
{
$oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
if ($oSiteuser)
{
$siteuser_id = $oSiteuser->id;
}
}
$oComment = Core_Entity::factory('Comment');
$allowable_tags = '<b><strong><i><em><br><p><u><strike><ul><ol><li>';
$oComment->parent_id = intval(Core_Array::getPost('parent_id', 0));
$oComment->active = $oShop->comment_active;
$oComment->author = Core_Str::stripTags(Core_Array::getPost('author'));
$oComment->email = Core_Str::stripTags(Core_Array::getPost('email'));
$oComment->phone = Core_Str::stripTags(Core_Array::getPost('phone'));
$oComment->grade = intval(Core_Array::getPost('grade', 0));
$oComment->subject = Core_Str::stripTags(Core_Array::getPost('subject'));
$oComment->text = nl2br(Core_Str::stripTags(Core_Array::getPost('text'), $allowable_tags));
$oComment->siteuser_id = $siteuser_id;
$oShop_Item = Core_Entity::factory('Shop_Item', $Shop_Controller_Show->item);
$oXmlCommentTag
->addEntity($oComment)
->addEntity($oShop_Item);
if (is_null($oLastComment) || time() > Core_Date::sql2timestamp($oLastComment->datetime) + ADD_COMMENT_DELAY)
{
if ($oShop->use_captcha == 0 || $siteuser_id > 0 || Core_Captcha::valid(Core_Array::getPost('captcha_id'), Core_Array::getPost('captcha')))
{
// Antispam
if (Core::moduleIsActive('antispam'))
{
$Antispam_Controller = new Antispam_Controller();
$bAntispamAnswer = $Antispam_Controller
->addText($oComment->author)
->addText($oComment->email)
->addText($oComment->phone)
->addText($oComment->subject)
->addText($oComment->text)
->execute();
}
else
{
$bAntispamAnswer = TRUE;
}
if ($bAntispamAnswer)
{
$oComment->save();
$oComment
->dateFormat($oShop->format_date)
->dateTimeFormat($oShop->format_datetime);
$oShop_Item->add($oComment)->clearCache();
$oXmlCommentTag->addEntity($oShop);
// Отправка письма администратору
$sText = Xsl_Processor::instance()
->xml($oXmlCommentTag->getXml())
->xsl(
Core_Entity::factory('Xsl')
->getByName(Core_Array::get(Core_Page::instance()->libParams, 'addCommentAdminMailXsl'))
)
->process();
$aFrom = array_map('trim', explode(',', EMAIL_TO));
Core_Mail::instance()
->to(EMAIL_TO)
->from($aFrom[0])
->header('Reply-To', Core_Valid::email($oComment->email)
? $oComment->email
: $aFrom[0]
)
->subject(Core::_('Shop.comment_mail_subject'))
->message(trim($sText))
->contentType(Core_Array::get(Core_Page::instance()->libParams, 'commentMailNoticeType', 0) == 0
? 'text/plain'
: 'text/html'
)
->send();
}
else
{
$oXmlCommentTag->addEntity(Core::factory('Core_Xml_Entity')
->name('error_antispam')->value(1)
);
$oComment->text = Core_Str::br2nl($oComment->text);
$Shop_Controller_Show->addEntity($oComment);
}
}
else
{
$oXmlCommentTag->addEntity(Core::factory('Core_Xml_Entity')
->name('error_captcha')->value(1)
);
$oComment->text = Core_Str::br2nl($oComment->text);
$Shop_Controller_Show->addEntity($oComment);
}
}
else
{
$oXmlCommentTag->addEntity(Core::factory('Core_Xml_Entity')
->name('error_time')->value(1)
);
$oComment->text = Core_Str::br2nl($oComment->text);
$Shop_Controller_Show->addEntity($oComment);
}
// Результат добавления комментария
$xsl_result = Xsl_Processor::instance()
->xml($oXmlCommentTag->getXml())
->xsl(Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'addCommentNoticeXsl'))
)
->process();
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('message')->value($xsl_result)
);
}
}
// В корне выводим из всех групп
/* if ($Shop_Controller_Show->group == 0)
{
$Shop_Controller_Show->group(FALSE)->forbidSelectModifications();
}*/
/* Производители */
$oShop = $Shop_Controller_Show->getEntity();
// XML-сущность, к которй будут добавляться производители
$oProducersXmlEntity = Core::factory('Core_Xml_Entity')->name('producers');
// Добавляем XML-сущность контроллеру показа
$Shop_Controller_Show->addEntity($oProducersXmlEntity);
// Список производителей
$oShop_Producers = $oShop->Shop_Producers;
$oShop_Producers->queryBuilder()
->select('shop_producers.*')
->distinct()
->join('shop_items', 'shop_items.shop_producer_id', '=', 'shop_producers.id')
->where('shop_items.shop_group_id', '=', $Shop_Controller_Show->group)
->where('shop_items.deleted', '=', 0);
$aShop_Producers = $oShop_Producers->findAll();
foreach ($aShop_Producers as $oShop_Producer)
{
// Добавляем производителя потомком XML-сущности
$oProducersXmlEntity->addEntity(
$oShop_Producer->clearEntities()
);
}
$Shop_Controller_Show
->xsl(
Core_Entity::factory('Xsl')->getByName($xslName)
)
// Выводить свойства товаров
->itemsProperties(TRUE)
// Выводить специальные цены
->specialprices(TRUE)
// Выводить модификации на уровне с товаром
//->modificationsList(TRUE)
// Режим вывода групп
//->groupsMode('none')
// Выводить доп. св-ва групп
//->groupsProperties(TRUE)
// Фильтровать по ярлыкам
//->filterShortcuts(TRUE)
->show();
$Shop_Controller_Show = Core_Page::instance()->object;
$xslName = $Shop_Controller_Show->item
? Core_Array::get(Core_Page::instance()->libParams, 'shopItemXsl')
: Core_Array::get(Core_Page::instance()->libParams, 'shopXsl');
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('ТекущаяГруппа')->value($Shop_Controller_Show->group)
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('show_comments')->value(Core_Array::get(Core_Page::instance()->libParams, 'showComments', 1))
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('show_add_comments')->value(Core_Array::get(Core_Page::instance()->libParams, 'showAddComment', 2))
);
$Shop_Controller_Show
->tags(TRUE)
->comments(TRUE)
->associatedItems(TRUE)
->modifications(TRUE);
if ($Shop_Controller_Show->item == 0)
{
$Shop_Controller_Show->itemsForbiddenTags(array('text'));
// Producers
if (Core_Array::getGet('producer_id'))
{
$iProducerId = intval(Core_Array::getGet('producer_id'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('producer_id')->value($iProducerId)
);
$Shop_Controller_Show->shopItems()
->queryBuilder()
->select('shop_items.*')
->where('shop_items.shop_producer_id', '=', $iProducerId);
$Shop_Controller_Show->addCacheSignature('producer_id=' . $iProducerId);
}
if (Core_Array::getGet('filter') || Core_Array::getGet('sorting'))
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('filter')->value(1)
);
$oShop = $Shop_Controller_Show->getEntity();
$sorting = intval(Core_Array::getGet('sorting'));
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('sorting')->value($sorting)
);
$Shop_Controller_Show->addCacheSignature('sorting=' . $sorting);
// Prices
$price_from = intval(Core_Array::getGet('price_from'));
$price_to = intval(Core_Array::getGet('price_to'));
if ($price_from || $price_to || $sorting == 1 || $sorting == 2)
{
// Получаем список валют магазина
$aShop_Currencies = Core_Entity::factory('Shop_Currency')->findAll();
$query_tax = 'IF(`shop_taxes`.`tax_is_included` IS NULL OR `shop_taxes`.`tax_is_included` = 1, 0, `shop_items`.`price` * `shop_taxes`.`rate` / 100)';
$query_currency_switch = "`shop_items`.`price` + {$query_tax}";
foreach ($aShop_Currencies as $oShop_Currency)
{
// Получаем коэффициент пересчета для каждой валюты
$currency_coefficient = Shop_Controller::instance()->getCurrencyCoefficientInShopCurrency(
$oShop_Currency, $oShop->Shop_Currency
);
$query_currency_switch = "IF (`shop_items`.`shop_currency_id` = '{$oShop_Currency->id}', IF (COUNT(`shop_discounts`.`id`), ((`shop_items`.`price` + {$query_tax}) * (1 - SUM(IF(`shop_discounts`.`type` = 0, `shop_discounts`.`value`, 0)) / 100)) * {$currency_coefficient} - SUM(IF(`shop_discounts`.`type`, `shop_discounts`.`value`, 0)), (`shop_items`.`price`) * {$currency_coefficient}), {$query_currency_switch})";
}
$current_date = date('Y-m-d H:i:s');
$Shop_Controller_Show->shopItems()
->queryBuilder()
->select(array(Core_QueryBuilder::expression($query_currency_switch), 'absolute_price'))
->leftJoin('shop_item_discounts', 'shop_items.id', '=', 'shop_item_discounts.shop_item_id')
->leftJoin('shop_discounts', 'shop_item_discounts.shop_discount_id', '=', 'shop_discounts.id', array(
array('AND ' => array('shop_discounts.active', '=', 1)),
array('AND ' => array('shop_discounts.deleted', '=', 0)),
array('AND' => array('shop_discounts.start_datetime', '<=', $current_date)),
array('AND (' => array('shop_discounts.end_datetime', '>=', $current_date)),
array('OR' => array('shop_discounts.end_datetime', '=', '0000-00-00 00:00:00')),
array(')' => NULL)
))
->leftJoin('shop_taxes', 'shop_taxes.id', '=', 'shop_items.shop_tax_id')
->groupBy('shop_items.id');
if ($price_from)
{
$Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '>=', $price_from);
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_from')->value($price_from)
);
$Shop_Controller_Show->addCacheSignature('price_from=' . $price_from);
}
if ($price_to)
{
$Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '<=', $price_to);
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('price_to')->value($price_to)
);
$Shop_Controller_Show->addCacheSignature('price_to=' . $price_to);
}
$Shop_Controller_Show->shopItems()->queryBuilder()
->clearOrderBy()
->orderBy('absolute_price', $sorting == 1 ? 'ASC' : 'DESC');
}
$sorting == 3 && $Shop_Controller_Show->shopItems()->queryBuilder()
->clearOrderBy()
->orderBy('shop_items.name', 'ASC');
// Additional properties
$oShop_Item_Property_List = Core_Entity::factory('Shop_Item_Property_List', $oShop->id);
$aProperties = $Shop_Controller_Show->group !== FALSE && is_null($Shop_Controller_Show->tag)
? $oShop_Item_Property_List->getPropertiesForGroup($Shop_Controller_Show->group)
: $oShop_Item_Property_List->Properties->findAll();
$aTmpProperties = array();
$havingCount = 0;
foreach ($aProperties as $oProperty)
{
// Св-во может иметь несколько значений
$aPropertiesValue = Core_Array::getGet('property_' . $oProperty->id);
if ($aPropertiesValue)
{
!is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
$aPropertiesValue = array_map('strval', $aPropertiesValue);
$aTmpProperties[] = array($oProperty, $aPropertiesValue);
$havingCount++;
}
elseif (!is_null(Core_Array::getGet('property_' . $oProperty->id . '_from')))
{
$tmpFrom = Core_Array::getGet('property_' . $oProperty->id . '_from');
$tmpTo = Core_Array::getGet('property_' . $oProperty->id . '_to');
!is_array($tmpFrom) && $tmpFrom = array($tmpFrom);
!is_array($tmpTo) && $tmpTo = array($tmpTo);
// From ... to ...
foreach ($tmpFrom as $iKey => $sValue)
{
$to = Core_Array::get($tmpTo, $iKey);
$aTmpProperties[] = array($oProperty, array(
'from' => $sValue != ''
? ($oProperty->type == 11 ? floatval($sValue) : intval($sValue))
: '',
'to' => $to != ''
? ($oProperty->type == 11 ? floatval($to) : intval($to))
: ''
));
}
$havingCount++;
}
}
if (count($aTmpProperties))
{
$aTableNames = array();
$Shop_Controller_Show->shopItems()->queryBuilder()
->leftJoin('shop_item_properties', 'shop_items.shop_id', '=', 'shop_item_properties.shop_id')
->setAnd()
->open();
reset($aTmpProperties);
while(list(, list($oProperty, $aPropertyValues)) = each($aTmpProperties))
{
$tableName = $oProperty->createNewValue(0)->getTableName();
!in_array($tableName, $aTableNames) && $aTableNames[] = $tableName;
$Shop_Controller_Show->shopItems()->queryBuilder()
->where('shop_item_properties.property_id', '=', $oProperty->id);
if (!isset($aPropertyValues['from']))
{
// Для строк фильтр LIKE %...%
if ($oProperty->type == 1)
{
foreach ($aPropertyValues as $propertyValue)
{
$Shop_Controller_Show->shopItems()->queryBuilder()
->where($tableName . '.value', 'LIKE', "%{$propertyValue}%");
}
}
else
{
// Checkbox
$oProperty->type == 7 && $aPropertyValues[0] != '' && $aPropertyValues = array(1);
$bCheckUnset = $oProperty->type != 7 && $oProperty->type != 3;
$bCheckUnset && $Shop_Controller_Show->shopItems()->queryBuilder()->open();
$Shop_Controller_Show->shopItems()->queryBuilder()
->where(
$tableName . '.value',
count($aPropertyValues) == 1 ? '=' : 'IN',
count($aPropertyValues) == 1 ? $aPropertyValues[0] : $aPropertyValues
);
$bCheckUnset && $Shop_Controller_Show->shopItems()->queryBuilder()
->setOr()
->where($tableName . '.value', 'IS', NULL)
->close();
}
$Shop_Controller_Show->shopItems()->queryBuilder()
->setOr();
foreach ($aPropertyValues as $propertyValue)
{
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id)->value($propertyValue)
);
$Shop_Controller_Show->addCacheSignature("property{$oProperty->id}={$propertyValue}");
}
}
else
{
$from = trim(Core_Array::get($aPropertyValues, 'from'));
$from && $Shop_Controller_Show->shopItems()->queryBuilder()
->open()
->where($tableName . '.value', '>=', $from)
->setOr()
->where($tableName . '.value', 'IS', NULL)
->close()
->setAnd();
$to = trim(Core_Array::get($aPropertyValues, 'to'));
$to && $Shop_Controller_Show->shopItems()->queryBuilder()
->open()
->where($tableName . '.value', '<=', $to)
->setOr()
->where($tableName . '.value', 'IS', NULL)
->close();
$Shop_Controller_Show->shopItems()->queryBuilder()
->setOr();
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_from')->value($from)
)->addEntity(
Core::factory('Core_Xml_Entity')
->name('property_' . $oProperty->id . '_to')->value($to)
);
$Shop_Controller_Show
->addCacheSignature("property{$oProperty->id}_from={$from}")
->addCacheSignature("property{$oProperty->id}_to={$to}");
}
}
$Shop_Controller_Show->shopItems()->queryBuilder()
->close()
->groupBy('shop_items.id');
$havingCount > 1
&& $Shop_Controller_Show->shopItems()->queryBuilder()
->having(Core_Querybuilder::expression('COUNT(DISTINCT `shop_item_properties`.`property_id`)'), '=', $havingCount);
foreach ($aTableNames as $tableName)
{
$Shop_Controller_Show->shopItems()->queryBuilder()
->leftJoin($tableName, 'shop_items.id', '=', $tableName . '.entity_id',
array(
array('AND' => array('shop_item_properties.property_id', '=', Core_QueryBuilder::expression($tableName . '.property_id')))
)
);
}
}
}
}
else
{
if (Core_Array::getPost('add_comment') && Core_Array::get(Core_Page::instance()->libParams, 'showComments', 1))
{
$oShop = $Shop_Controller_Show->getEntity();
$Shop_Controller_Show->cache(FALSE);
$oLastComment = Core_Entity::factory('Comment')->getLastCommentByIp(
Core_Array::get($_SERVER, 'REMOTE_ADDR')
);
$oXmlCommentTag = Core::factory('Core_Xml_Entity')
->name('document');
$siteuser_id = 0;
if (Core::moduleIsActive('siteuser'))
{
$oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
if ($oSiteuser)
{
$siteuser_id = $oSiteuser->id;
}
}
$oComment = Core_Entity::factory('Comment');
$allowable_tags = '<b><strong><i><em><br><p><u><strike><ul><ol><li>';
$oComment->parent_id = intval(Core_Array::getPost('parent_id', 0));
$oComment->active = $oShop->comment_active;
$oComment->author = Core_Str::stripTags(Core_Array::getPost('author'));
$oComment->email = Core_Str::stripTags(Core_Array::getPost('email'));
$oComment->phone = Core_Str::stripTags(Core_Array::getPost('phone'));
$oComment->grade = intval(Core_Array::getPost('grade', 0));
$oComment->subject = Core_Str::stripTags(Core_Array::getPost('subject'));
$oComment->text = nl2br(Core_Str::stripTags(Core_Array::getPost('text'), $allowable_tags));
$oComment->siteuser_id = $siteuser_id;
$oShop_Item = Core_Entity::factory('Shop_Item', $Shop_Controller_Show->item);
$oXmlCommentTag
->addEntity($oComment)
->addEntity($oShop_Item);
if (is_null($oLastComment) || time() > Core_Date::sql2timestamp($oLastComment->datetime) + ADD_COMMENT_DELAY)
{
if ($oShop->use_captcha == 0 || $siteuser_id > 0 || Core_Captcha::valid(Core_Array::getPost('captcha_id'), Core_Array::getPost('captcha')))
{
// Antispam
if (Core::moduleIsActive('antispam'))
{
$Antispam_Controller = new Antispam_Controller();
$bAntispamAnswer = $Antispam_Controller
->addText($oComment->author)
->addText($oComment->email)
->addText($oComment->phone)
->addText($oComment->subject)
->addText($oComment->text)
->execute();
}
else
{
$bAntispamAnswer = TRUE;
}
if ($bAntispamAnswer)
{
$oComment->save();
$oComment
->dateFormat($oShop->format_date)
->dateTimeFormat($oShop->format_datetime);
$oShop_Item->add($oComment)->clearCache();
$oXmlCommentTag->addEntity($oShop);
// Отправка письма администратору
$sText = Xsl_Processor::instance()
->xml($oXmlCommentTag->getXml())
->xsl(
Core_Entity::factory('Xsl')
->getByName(Core_Array::get(Core_Page::instance()->libParams, 'addCommentAdminMailXsl'))
)
->process();
$aFrom = array_map('trim', explode(',', EMAIL_TO));
Core_Mail::instance()
->to(EMAIL_TO)
->from($aFrom[0])
->header('Reply-To', Core_Valid::email($oComment->email)
? $oComment->email
: $aFrom[0]
)
->subject(Core::_('Shop.comment_mail_subject'))
->message(trim($sText))
->contentType(Core_Array::get(Core_Page::instance()->libParams, 'commentMailNoticeType', 0) == 0
? 'text/plain'
: 'text/html'
)
->send();
}
else
{
$oXmlCommentTag->addEntity(Core::factory('Core_Xml_Entity')
->name('error_antispam')->value(1)
);
$oComment->text = Core_Str::br2nl($oComment->text);
$Shop_Controller_Show->addEntity($oComment);
}
}
else
{
$oXmlCommentTag->addEntity(Core::factory('Core_Xml_Entity')
->name('error_captcha')->value(1)
);
$oComment->text = Core_Str::br2nl($oComment->text);
$Shop_Controller_Show->addEntity($oComment);
}
}
else
{
$oXmlCommentTag->addEntity(Core::factory('Core_Xml_Entity')
->name('error_time')->value(1)
);
$oComment->text = Core_Str::br2nl($oComment->text);
$Shop_Controller_Show->addEntity($oComment);
}
// Результат добавления комментария
$xsl_result = Xsl_Processor::instance()
->xml($oXmlCommentTag->getXml())
->xsl(Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'addCommentNoticeXsl'))
)
->process();
$Shop_Controller_Show->addEntity(
Core::factory('Core_Xml_Entity')
->name('message')->value($xsl_result)
);
}
}
// В корне выводим из всех групп
/* if ($Shop_Controller_Show->group == 0)
{
$Shop_Controller_Show->group(FALSE)->forbidSelectModifications();
}*/
/* Производители */
$oShop = $Shop_Controller_Show->getEntity();
// XML-сущность, к которй будут добавляться производители
$oProducersXmlEntity = Core::factory('Core_Xml_Entity')->name('producers');
// Добавляем XML-сущность контроллеру показа
$Shop_Controller_Show->addEntity($oProducersXmlEntity);
// Список производителей
$oShop_Producers = $oShop->Shop_Producers;
$oShop_Producers->queryBuilder()
->select('shop_producers.*')
->distinct()
->join('shop_items', 'shop_items.shop_producer_id', '=', 'shop_producers.id')
->where('shop_items.shop_group_id', '=', $Shop_Controller_Show->group)
->where('shop_items.deleted', '=', 0);
$aShop_Producers = $oShop_Producers->findAll();
foreach ($aShop_Producers as $oShop_Producer)
{
// Добавляем производителя потомком XML-сущности
$oProducersXmlEntity->addEntity(
$oShop_Producer->clearEntities()
);
}
$Shop_Controller_Show
->xsl(
Core_Entity::factory('Xsl')->getByName($xslName)
)
// Выводить свойства товаров
->itemsProperties(TRUE)
// Выводить специальные цены
->specialprices(TRUE)
// Выводить модификации на уровне с товаром
//->modificationsList(TRUE)
// Режим вывода групп
//->groupsMode('none')
// Выводить доп. св-ва групп
//->groupsProperties(TRUE)
// Фильтровать по ярлыкам
//->filterShortcuts(TRUE)
->show();
e-mail: webmaster@maiboroda.pro / maiboroda.pro / Создание и поддержка сайтов / г. Ставрополь
Seri
23 ноября 2018 г.
Стандартно фильтр показывает диапазон цены по нулям если в текущей категории нет товаров. Либо вы смотрите не тот ТДС.
E-mail: info@syrbek.ru / телега: @syrbek /skype: activexm / syrbek.ru / Поддержка сайтов / г. Москва [HTML, CSS (Bootstrap), JS(JQuery, ExtJS), PHP, MySQL, MSSql, Posgres, Git, SVN, Redmine]
maiborodava
23 ноября 2018 г.
Да нет, смотрю ТДС интернет магазина, если в категорию любую я провалюсь то все фильтруется, а вот в корне где подкатегории есть и выводтся товары из подкатегорий в корневую категорию фильтр не работает, даже если отбросить то что он по нулям показывает, если отсортировать по цене то ничего не произойдет.
e-mail: webmaster@maiboroda.pro / maiboroda.pro / Создание и поддержка сайтов / г. Ставрополь
Seri
23 ноября 2018 г.
Можете посмотреть код в контролере и ознакомиться с методом ->addMinMaxPrice() как он работает. И найти нужное применение. См. http://demo.hostcms.ru/ Как работает стандартный код.
E-mail: info@syrbek.ru / телега: @syrbek /skype: activexm / syrbek.ru / Поддержка сайтов / г. Москва [HTML, CSS (Bootstrap), JS(JQuery, ExtJS), PHP, MySQL, MSSql, Posgres, Git, SVN, Redmine]
maiborodava
28 ноября 2018 г.
C ->addMinMaxPrice() все понятно он у меня используется. Но он не работает если есть в корневой категории выведены товары из подкатегорий (
e-mail: webmaster@maiboroda.pro / maiboroda.pro / Создание и поддержка сайтов / г. Ставрополь
Rewired
3 ноября 2020 г.
php ругается на The each() function is deprecated. в Строке while(list(, list($oProperty, $propertyValue)) = each($aTmpProperties)).
В говно может вступить любой желающий. (с)
llirik
3 ноября 2020 г.
Ответ дан в онлайн чате.
«Не выходи из комнаты, не совершай ошибку…»
Авторизация