0 Пользователей и 1 Гость просматривают эту тему.
  • 35 Ответов
  • 3429 Просмотров
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Всем добрый день!
Проблема в следующем: я использую на своем сайте плагин голосования - extravote, и с помощью изменений в файле - папка_сайта/components/com_content/helpers/query.php, заменив в 85 строке, $orderby = 'a.hits DESC';  на - $orderby = 'rating_sum DESC'; , а затем выставив в админке - в Параметры макета Блога – Порядок материалов и выбираем значение – По хитам, добивался того, что все материалы в категории, при выводе, сортировались по рейтингу.

Начиная с версии Joomla 3.5, я столкнулся с проблемой, данный вариант больше не работает. Теперь, при замене 'a.hits DESC';  на - $orderby = 'rating_sum DESC'; , на экран вместо контента, выводится ошибка: 500 Unknown column 'rating_sum' in 'order clause'

Подскажите пожалуйста, как решить эту проблему, поскольку, я увы, в кодинге не силен.
« Последнее редактирование: 21.03.2018, 18:27:05 от Дмитрий_ »
*

Aleks.Denezh

  • Живу я здесь
  • 3406
  • 428 / 4
« Последнее редактирование: 04.05.2018, 22:27:43 от Aleks.Denezh »
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
У вас же всё написано:что значит что в таблице нет поля rating_sum для сортировки.. откройте таблицу в phpMyAdmin и посмотрите какие там поля...
Спасибо за совет! Как я понимаю смотреть это поле надо в таблице - content ?!, потому как в таблице - content_extravote , есть поле - rating_sum
« Последнее редактирование: 22.03.2018, 11:13:54 от Дмитрий_ »
*

Aleks.Denezh

  • Живу я здесь
  • 3406
  • 428 / 4
« Последнее редактирование: 04.05.2018, 22:27:37 от Aleks.Denezh »
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
тогда попробуйте написать не  $orderby = 'rating_sum DESC';
а  $orderby = 'a.rating_sum DESC';
попробовал, теперь ругается, что нет поля - a.rating_sum
Походу дела, ругается на любое поле, которого нет в таблице - content. При всем при этом, в старых версиях Joomla 2.5 - 3.0, в таблице - content, этого поля тоже не было, но данный способ работал.
*

beliyadm

  • Легенда
  • 9758
  • 1664 / 66
  • Севастополь, Россия
Возможно в предыдущих версиях таблица рейтинга подтягивалась в общий запрос, теперь нет.
Значит чтобы использовать поле rating_sum вам надо джойнить таблицу рейтинга в \components\com_content\models\articles.php
и обновлять код при каждом обновлении движка
Все истины, которые я хочу вам изложить, — бесстыдная ложь. Сделать всё хорошо
TLG: @Beliyadm
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Возможно в предыдущих версиях таблица рейтинга подтягивалась в общий запрос, теперь нет.
Значит чтобы использовать поле rating_sum вам надо джойнить таблицу рейтинга в \components\com_content\models\articles.php
и обновлять код при каждом обновлении движка
Спасибо, я попробую, надеюсь, что справлюсь с этой задачей. Если получится отпишусь.
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
попробовал, теперь ругается, что нет поля - a.rating_sum
Возможно, content_extravote идет в join под другим алиасом. Сделайте
Код
echo $query; exit;
, чтобы посмотреть весь запрос.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Возможно, content_extravote идет в join под другим алиасом. Сделайте
Код
echo $query; exit;
, чтобы посмотреть весь запрос.
Роберт, спасибо Вам за совет. Но как я и писал выше, я не силен в кодинге, если можете - подскажите куда необходимо вставить Ваш код?
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
куда необходимо вставить Ваш код?
Файл /components/com_content/models/articles.php, в конце функции getListQuery() перед
Код
return $query;
Только не очень понял, как вы плагином можете менять стандартный запрос в модели.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Цитата: Дмитрий_ от Сегодня в 11:27:51 куда необходимо вставить Ваш код? Файл /components/com_content/models/articles.php, в конце функции getListQuery() перед Код return $query;
Выводит следующее:
Код
SELECT a.id, a.title, a.alias, a.introtext, a.fulltext, a.checked_out, a.checked_out_time, a.catid, a.created, a.created_by, a.created_by_alias, CASE WHEN c.published = 2 AND a.state > 0 THEN 2 WHEN c.published != 1 THEN 0 ELSE a.state END as state,CASE WHEN a.modified = '0000-00-00 00:00:00' THEN a.created ELSE a.modified END as modified, a.modified_by, uam.name as modified_by_name,CASE WHEN a.publish_up = '0000-00-00 00:00:00' THEN a.created ELSE a.publish_up END as publish_up,a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access, a.hits, a.xreference, a.featured, a.language,  LENGTH(a.fulltext) AS readmore, a.ordering,c.title AS category_title, c.path AS category_route, c.access AS category_access, c.alias AS category_alias,c.published, c.published AS parents_published, c.lft,CASE WHEN a.created_by_alias > ' ' THEN a.created_by_alias ELSE ua.name END AS author,ua.email AS author_email,parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias FROM #__content AS a LEFT JOIN #__categories AS c ON c.id = a.catid LEFT JOIN #__users AS ua ON ua.id = a.created_by LEFT JOIN #__users AS uam ON uam.id = a.modified_by LEFT JOIN #__categories as parent ON parent.id = c.parent_id WHERE a.access IN (1,1,5) AND c.access IN (1,1,5) AND c.published = 1 AND a.state = 1 AND a.catid = 124 AND (a.publish_up = '0000-00-00 00:00:00' OR a.publish_up <= '2018-03-22 10:50:59') AND (a.publish_down = '0000-00-00 00:00:00' OR a.publish_down >= '2018-03-22 10:50:59') ORDER BY  c.lft,  rating_sum DESC,  a.created  
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Только не очень понял, как вы плагином можете менять стандартный запрос в модели.
В файле /components/com_content/helpers/query.php, менял
Код
$orderby = 'a.hits DESC';  на $orderby = 'rating_sum DESC';
В Админке Joomla - Параметры макета Блога – Порядок материалов и выбирал значение – По хитам. В Менеджере плагинов - отключал встроенный - "Контент-Рейтинг" и включал - "Контент - ExtraVote" и все работало, все материалы сортировались по количеству голосов плагина - Extravote.
« Последнее редактирование: 22.03.2018, 14:14:06 от Дмитрий_ »
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Возможно в предыдущих версиях таблица рейтинга подтягивалась в общий запрос, теперь нет.
Значит чтобы использовать поле rating_sum вам надо джойнить таблицу рейтинга в \components\com_content\models\articles.php
и обновлять код при каждом обновлении движка
Вы правы! Вся загвоздка находится в файле - \components\com_content\models\articles.php.
Скопировав данный файл из старой версии Joomla, у меня все заработало. Но увы, думаю это не совсем корректно и может вызывать ошибки. Просьба, если можете, помогите разобраться в данной проблеме.

На всякий случай, прикладываю код этих 2х файлов:
Первый (старый рабочий):
Код
<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_content
 *
 * [member=126442]copyright[/member]   Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

/**
 * This models supports retrieving lists of articles.
 *
 * @since  1.6
 */
class ContentModelArticles extends JModelList
{
/**
* Constructor.
*
* @param   array  $config  An optional associative array of configuration settings.
*
* @see     JController
* @since   1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'title', 'a.title',
'alias', 'a.alias',
'checked_out', 'a.checked_out',
'checked_out_time', 'a.checked_out_time',
'catid', 'a.catid', 'category_title',
'state', 'a.state',
'access', 'a.access', 'access_level',
'created', 'a.created',
'created_by', 'a.created_by',
'ordering', 'a.ordering',
'featured', 'a.featured',
'language', 'a.language',
'hits', 'a.hits',
'publish_up', 'a.publish_up',
'publish_down', 'a.publish_down',
'images', 'a.images',
'urls', 'a.urls',
'filter_tag'
);
}

parent::__construct($config);
}

/**
* Method to auto-populate the model state.
*
* This method should only be called once per instantiation and is designed
* to be called on the first call to the getState() method unless the model
* configuration flag to ignore the request is set.
*
* Note. Calling getState in this method will result in recursion.
*
* @param   string  $ordering   An optional ordering field.
* @param   string  $direction  An optional direction (asc|desc).
*
* @return  void
*
* @since   12.2
*/
protected function populateState($ordering = 'ordering', $direction = 'ASC')
{
$app = JFactory::getApplication();

// List state information
$value = $app->input->get('limit', $app->get('list_limit', 0), 'uint');
$this->setState('list.limit', $value);

$value = $app->input->get('limitstart', 0, 'uint');
$this->setState('list.start', $value);

$value = $app->input->get('filter_tag', 0, 'uint');
$this->setState('filter.tag', $value);

$orderCol = $app->input->get('filter_order', 'a.ordering');

if (!in_array($orderCol, $this->filter_fields))
{
$orderCol = 'a.ordering';
}

$this->setState('list.ordering', $orderCol);

$listOrder = $app->input->get('filter_order_Dir', 'ASC');

if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', '')))
{
$listOrder = 'ASC';
}

$this->setState('list.direction', $listOrder);

$params = $app->getParams();
$this->setState('params', $params);
$user = JFactory::getUser();

if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content')))
{
// Filter on published for those who do not have edit or edit.state rights.
$this->setState('filter.published', 1);
}

$this->setState('filter.language', JLanguageMultilang::isEnabled());

// Process show_noauth parameter
if (!$params->get('show_noauth'))
{
$this->setState('filter.access', true);
}
else
{
$this->setState('filter.access', false);
}

$this->setState('layout', $app->input->getString('layout'));
}

/**
* Method to get a store id based on model configuration state.
*
* This is necessary because the model is used by the component and
* different modules that might need different sets of data or different
* ordering requirements.
*
* @param   string  $id  A prefix for the store id.
*
* @return  string  A store id.
*
* @since   1.6
*/
protected function getStoreId($id = '')
{
// Compile the store id.
$id .= ':' . serialize($this->getState('filter.published'));
$id .= ':' . $this->getState('filter.access');
$id .= ':' . $this->getState('filter.featured');
$id .= ':' . serialize($this->getState('filter.article_id'));
$id .= ':' . $this->getState('filter.article_id.include');
$id .= ':' . serialize($this->getState('filter.category_id'));
$id .= ':' . $this->getState('filter.category_id.include');
$id .= ':' . serialize($this->getState('filter.author_id'));
$id .= ':' . $this->getState('filter.author_id.include');
$id .= ':' . serialize($this->getState('filter.author_alias'));
$id .= ':' . $this->getState('filter.author_alias.include');
$id .= ':' . $this->getState('filter.date_filtering');
$id .= ':' . $this->getState('filter.date_field');
$id .= ':' . $this->getState('filter.start_date_range');
$id .= ':' . $this->getState('filter.end_date_range');
$id .= ':' . $this->getState('filter.relative_date');

return parent::getStoreId($id);
}

/**
* Get the master query for retrieving a list of articles subject to the model state.
*
* @return  JDatabaseQuery
*
* @since   1.6
*/
protected function getListQuery()
{
// Get the current user for authorisation checks
$user = JFactory::getUser();

// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);

// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.id, a.title, a.alias, a.introtext, a.fulltext, ' .
'a.checked_out, a.checked_out_time, ' .
'a.catid, a.created, a.created_by, a.created_by_alias, ' .
// Use created if modified is 0
'CASE WHEN a.modified = ' . $db->quote($db->getNullDate()) . ' THEN a.created ELSE a.modified END as modified, ' .
'a.modified_by, uam.name as modified_by_name,' .
// Use created if publish_up is 0
'CASE WHEN a.publish_up = ' . $db->quote($db->getNullDate()) . ' THEN a.created ELSE a.publish_up END as publish_up,' .
'a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access, ' .
'a.hits, a.xreference, a.featured, a.language, ' . ' ' . $query->length('a.fulltext') . ' AS readmore'
)
);

// Process an Archived Article layout
if ($this->getState('filter.published') == 2)
{
// If badcats is not null, this means that the article is inside an archived category
// In this case, the state is set to 2 to indicate Archived (even if the article state is Published)
$query->select($this->getState('list.select', 'CASE WHEN badcats.id is null THEN a.state ELSE 2 END AS state'));
}
else
{
/*
Process non-archived layout
If badcats is not null, this means that the article is inside an unpublished category
In this case, the state is set to 0 to indicate Unpublished (even if the article state is Published)
*/
$query->select($this->getState('list.select', 'CASE WHEN badcats.id is not null THEN 0 ELSE a.state END AS state'));
}

$query->from('#__content AS a');

$params = $this->getState('params');
$orderby_sec = $params->get('orderby_sec');

// Join over the frontpage articles if required.
if ($this->getState('filter.frontpage'))
{
if ($orderby_sec == 'front')
{
$query->join('INNER', '#__content_frontpage AS fp ON fp.content_id = a.id');
}
else
{
$query->where('a.featured = 1');
}
}
elseif ($orderby_sec == 'front' || $this->getState('list.ordering') == 'fp.ordering')
{
$query->join('LEFT', '#__content_frontpage AS fp ON fp.content_id = a.id');
}

// Join over the categories.
$query->select('c.title AS category_title, c.path AS category_route, c.access AS category_access, c.alias AS category_alias')
->join('LEFT', '#__categories AS c ON c.id = a.catid');

// Join over the users for the author and modified_by names.
$query->select("CASE WHEN a.created_by_alias > ' ' THEN a.created_by_alias ELSE ua.name END AS author")
->select("ua.email AS author_email")

->join('LEFT', '#__users AS ua ON ua.id = a.created_by')
->join('LEFT', '#__users AS uam ON uam.id = a.modified_by');

// Join over the categories to get parent category titles
$query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias')
->join('LEFT', '#__categories as parent ON parent.id = c.parent_id');

// Join on voting table
$query->select('ROUND(v.rating_sum / v.rating_count, 0) AS rating, v.rating_count as rating_count')
->join('LEFT', '#__content_extravote AS v ON a.id = v.content_id');

// Join to check for category published state in parent categories up the tree
$query->select('c.published, CASE WHEN badcats.id is null THEN c.published ELSE 0 END AS parents_published');
$subquery = 'SELECT cat.id as id FROM #__categories AS cat JOIN #__categories AS parent ';
$subquery .= 'ON cat.lft BETWEEN parent.lft AND parent.rgt ';
$subquery .= 'WHERE parent.extension = ' . $db->quote('com_content');

if ($this->getState('filter.published') == 2)
{
// Find any up-path categories that are archived
// If any up-path categories are archived, include all children in archived layout
$subquery .= ' AND parent.published = 2 GROUP BY cat.id ';

// Set effective state to archived if up-path category is archived
$publishedWhere = 'CASE WHEN badcats.id is null THEN a.state ELSE 2 END';
}
else
{
// Find any up-path categories that are not published
// If all categories are published, badcats.id will be null, and we just use the article state
$subquery .= ' AND parent.published != 1 GROUP BY cat.id ';

// Select state to unpublished if up-path category is unpublished
$publishedWhere = 'CASE WHEN badcats.id is null THEN a.state ELSE 0 END';
}

$query->join('LEFT OUTER', '(' . $subquery . ') AS badcats ON badcats.id = c.id');

// Filter by access level.
if ($access = $this->getState('filter.access'))
{
$groups = implode(',', $user->getAuthorisedViewLevels());
$query->where('a.access IN (' . $groups . ')')
->where('c.access IN (' . $groups . ')');
}

// Filter by published state
$published = $this->getState('filter.published');

if (is_numeric($published))
{
// Use article state if badcats.id is null, otherwise, force 0 for unpublished
$query->where($publishedWhere . ' = ' . (int) $published);
}
elseif (is_array($published))
{
$published = ArrayHelper::toInteger($published);
$published = implode(',', $published);

// Use article state if badcats.id is null, otherwise, force 0 for unpublished
$query->where($publishedWhere . ' IN (' . $published . ')');
}

// Filter by featured state
$featured = $this->getState('filter.featured');

switch ($featured)
{
case 'hide':
$query->where('a.featured = 0');
break;

case 'only':
$query->where('a.featured = 1');
break;

case 'show':
default:
// Normally we do not discriminate
// between featured/unfeatured items.
break;
}

// Filter by a single or group of articles.
$articleId = $this->getState('filter.article_id');

if (is_numeric($articleId))
{
$type = $this->getState('filter.article_id.include', true) ? '= ' : '<> ';
$query->where('a.id ' . $type . (int) $articleId);
}
elseif (is_array($articleId))
{
$articleId = ArrayHelper::toInteger($articleId);
$articleId = implode(',', $articleId);
$type = $this->getState('filter.article_id.include', true) ? 'IN' : 'NOT IN';
$query->where('a.id ' . $type . ' (' . $articleId . ')');
}

// Filter by a single or group of categories
$categoryId = $this->getState('filter.category_id');

if (is_numeric($categoryId))
{
$type = $this->getState('filter.category_id.include', true) ? '= ' : '<> ';

// Add subcategory check
$includeSubcategories = $this->getState('filter.subcategories', false);
$categoryEquals = 'a.catid ' . $type . (int) $categoryId;

if ($includeSubcategories)
{
$levels = (int) $this->getState('filter.max_category_levels', '1');

// Create a subquery for the subcategory list
$subQuery = $db->getQuery(true)
->select('sub.id')
->from('#__categories as sub')
->join('INNER', '#__categories as this ON sub.lft > this.lft AND sub.rgt < this.rgt')
->where('this.id = ' . (int) $categoryId);

if ($levels >= 0)
{
$subQuery->where('sub.level <= this.level + ' . $levels);
}

// Add the subquery to the main query
$query->where('(' . $categoryEquals . ' OR a.catid IN (' . (string) $subQuery . '))');
}
else
{
$query->where($categoryEquals);
}
}
elseif (is_array($categoryId) && (count($categoryId) > 0))
{
$categoryId = ArrayHelper::toInteger($categoryId);
$categoryId = implode(',', $categoryId);

if (!empty($categoryId))
{
$type = $this->getState('filter.category_id.include', true) ? 'IN' : 'NOT IN';
$query->where('a.catid ' . $type . ' (' . $categoryId . ')');
}
}

// Filter by author
$authorId = $this->getState('filter.author_id');
$authorWhere = '';

if (is_numeric($authorId))
{
$type = $this->getState('filter.author_id.include', true) ? '= ' : '<> ';
$authorWhere = 'a.created_by ' . $type . (int) $authorId;
}
elseif (is_array($authorId))
{
$authorId = ArrayHelper::toInteger($authorId);
$authorId = implode(',', $authorId);

if ($authorId)
{
$type = $this->getState('filter.author_id.include', true) ? 'IN' : 'NOT IN';
$authorWhere = 'a.created_by ' . $type . ' (' . $authorId . ')';
}
}

// Filter by author alias
$authorAlias = $this->getState('filter.author_alias');
$authorAliasWhere = '';

if (is_string($authorAlias))
{
$type = $this->getState('filter.author_alias.include', true) ? '= ' : '<> ';
$authorAliasWhere = 'a.created_by_alias ' . $type . $db->quote($authorAlias);
}
elseif (is_array($authorAlias))
{
$first = current($authorAlias);

if (!empty($first))
{
foreach ($authorAlias as $key => $alias)
{
$authorAlias[$key] = $db->quote($alias);
}

$authorAlias = implode(',', $authorAlias);

if ($authorAlias)
{
$type = $this->getState('filter.author_alias.include', true) ? 'IN' : 'NOT IN';
$authorAliasWhere = 'a.created_by_alias ' . $type . ' (' . $authorAlias .
')';
}
}
}

if (!empty($authorWhere) && !empty($authorAliasWhere))
{
$query->where('(' . $authorWhere . ' OR ' . $authorAliasWhere . ')');
}
elseif (empty($authorWhere) && empty($authorAliasWhere))
{
// If both are empty we don't want to add to the query
}
else
{
// One of these is empty, the other is not so we just add both
$query->where($authorWhere . $authorAliasWhere);
}

// Define null and now dates
$nullDate = $db->quote($db->getNullDate());
$nowDate  = $db->quote(JFactory::getDate()->toSql());

// Filter by start and end dates.
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content')))
{
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')')
->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
}

// Filter by Date Range or Relative Date
$dateFiltering = $this->getState('filter.date_filtering', 'off');
$dateField = $this->getState('filter.date_field', 'a.created');

switch ($dateFiltering)
{
case 'range':
$startDateRange = $db->quote($this->getState('filter.start_date_range', $nullDate));
$endDateRange = $db->quote($this->getState('filter.end_date_range', $nullDate));
$query->where(
'(' . $dateField . ' >= ' . $startDateRange . ' AND ' . $dateField .
' <= ' . $endDateRange . ')'
);
break;

case 'relative':
$relativeDate = (int) $this->getState('filter.relative_date', 0);
$query->where(
$dateField . ' >= DATE_SUB(' . $nowDate . ', INTERVAL ' .
$relativeDate . ' DAY)'
);
break;

case 'off':
default:
break;
}

// Process the filter for list views with user-entered filters
if ((is_object($params)) && ($params->get('filter_field') != 'hide') && ($filter = $this->getState('list.filter')))
{
// Clean filter variable
$filter = JString::strtolower($filter);
$hitsFilter = (int) $filter;
$filter = $db->quote('%' . $db->escape($filter, true) . '%', false);

switch ($params->get('filter_field'))
{
case 'author':
$query->where(
'LOWER( CASE WHEN a.created_by_alias > ' . $db->quote(' ') .
' THEN a.created_by_alias ELSE ua.name END ) LIKE ' . $filter . ' '
);
break;

case 'hits':
$query->where('a.hits >= ' . $hitsFilter . ' ');
break;

case 'title':
default:
// Default to 'title' if parameter is not valid
$query->where('LOWER( a.title ) LIKE ' . $filter);
break;
}
}

// Filter by language
if ($this->getState('filter.language'))
{
$query->where('a.language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
}

// Filter by a single tag.
$tagId = $this->getState('filter.tag');

if (!empty($tagId) && is_numeric($tagId))
{
$query->where($db->quoteName('tagmap.tag_id') . ' = ' . (int) $tagId)
->join(
'LEFT', $db->quoteName('#__contentitem_tag_map', 'tagmap')
. ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id')
. ' AND ' . $db->quoteName('tagmap.type_alias') . ' = ' . $db->quote('com_content.article')
);
}

// Add the list ordering clause.
$query->order($this->getState('list.ordering', 'a.ordering') . ' ' . $this->getState('list.direction', 'ASC'));

return $query;
}

/**
* Method to get a list of articles.
*
* Overriden to inject convert the attribs field into a JParameter object.
*
* @return  mixed  An array of objects on success, false on failure.
*
* @since   1.6
*/
public function getItems()
{
$items = parent::getItems();
$user = JFactory::getUser();
$userId = $user->get('id');
$guest = $user->get('guest');
$groups = $user->getAuthorisedViewLevels();
$input = JFactory::getApplication()->input;

// Get the global params
$globalParams = JComponentHelper::getParams('com_content', true);

// Convert the parameter fields into objects.
foreach ($items as &$item)
{
$articleParams = new Registry;
$articleParams->loadString($item->attribs);

// Unpack readmore and layout params
$item->alternative_readmore = $articleParams->get('alternative_readmore');
$item->layout = $articleParams->get('layout');

$item->params = clone $this->getState('params');

/*For blogs, article params override menu item params only if menu param = 'use_article'
Otherwise, menu item params control the layout
If menu item is 'use_article' and there is no article param, use global*/
if (($input->getString('layout') == 'blog') || ($input->getString('view') == 'featured')
|| ($this->getState('params')->get('layout_type') == 'blog'))
{
// Create an array of just the params set to 'use_article'
$menuParamsArray = $this->getState('params')->toArray();
$articleArray = array();

foreach ($menuParamsArray as $key => $value)
{
if ($value === 'use_article')
{
// If the article has a value, use it
if ($articleParams->get($key) != '')
{
// Get the value from the article
$articleArray[$key] = $articleParams->get($key);
}
else
{
// Otherwise, use the global value
$articleArray[$key] = $globalParams->get($key);
}
}
}

// Merge the selected article params
if (count($articleArray) > 0)
{
$articleParams = new Registry;
$articleParams->loadArray($articleArray);
$item->params->merge($articleParams);
}
}
else
{
// For non-blog layouts, merge all of the article params
$item->params->merge($articleParams);
}

// Get display date
switch ($item->params->get('list_show_date'))
{
case 'modified':
$item->displayDate = $item->modified;
break;

case 'published':
$item->displayDate = ($item->publish_up == 0) ? $item->created : $item->publish_up;
break;

default:
case 'created':
$item->displayDate = $item->created;
break;
}

// Compute the asset access permissions.
// Technically guest could edit an article, but lets not check that to improve performance a little.
if (!$guest)
{
$asset = 'com_content.article.' . $item->id;

// Check general edit permission first.
if ($user->authorise('core.edit', $asset))
{
$item->params->set('access-edit', true);
}

// Now check if edit.own is available.
elseif (!empty($userId) && $user->authorise('core.edit.own', $asset))
{
// Check for a valid user and that they are the owner.
if ($userId == $item->created_by)
{
$item->params->set('access-edit', true);
}
}
}

$access = $this->getState('filter.access');

if ($access)
{
// If the access filter has been set, we already have only the articles this user can view.
$item->params->set('access-view', true);
}
else
{
// If no access filter is set, the layout takes some responsibility for display of limited information.
if ($item->catid == 0 || $item->category_access === null)
{
$item->params->set('access-view', in_array($item->access, $groups));
}
else
{
$item->params->set('access-view', in_array($item->access, $groups) && in_array($item->category_access, $groups));
}
}

// Get the tags
if ($item->params->get('show_tags'))
{
$item->tags = new JHelperTags;
$item->tags->getItemTags('com_content.article', $item->id);
}
}

return $items;
}

/**
* Method to get the starting number of items for the data set.
*
* @return  integer  The starting number of items available in the data set.
*
* @since   12.2
*/
public function getStart()
{
return $this->getState('list.start');
}
}
Второй (новый):
Код
<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_content
 *
 * [member=126442]copyright[/member]   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;

/**
 * This models supports retrieving lists of articles.
 *
 * @since  1.6
 */
class ContentModelArticles extends JModelList
{
/**
* Constructor.
*
* @param   array  $config  An optional associative array of configuration settings.
*
* @see     JController
* @since   1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'title', 'a.title',
'alias', 'a.alias',
'checked_out', 'a.checked_out',
'checked_out_time', 'a.checked_out_time',
'catid', 'a.catid', 'category_title',
'state', 'a.state',
'access', 'a.access', 'access_level',
'created', 'a.created',
'created_by', 'a.created_by',
'ordering', 'a.ordering',
'featured', 'a.featured',
'language', 'a.language',
'hits', 'a.hits',
'publish_up', 'a.publish_up',
'publish_down', 'a.publish_down',
'images', 'a.images',
'urls', 'a.urls',
'filter_tag',
);
}

parent::__construct($config);
}

/**
* Method to auto-populate the model state.
*
* This method should only be called once per instantiation and is designed
* to be called on the first call to the getState() method unless the model
* configuration flag to ignore the request is set.
*
* Note. Calling getState in this method will result in recursion.
*
* @param   string  $ordering   An optional ordering field.
* @param   string  $direction  An optional direction (asc|desc).
*
* @return  void
*
* @since   12.2
*/
protected function populateState($ordering = 'ordering', $direction = 'ASC')
{
$app = JFactory::getApplication();

// List state information
$value = $app->input->get('limit', $app->get('list_limit', 0), 'uint');
$this->setState('list.limit', $value);

$value = $app->input->get('limitstart', 0, 'uint');
$this->setState('list.start', $value);

$value = $app->input->get('filter_tag', 0, 'uint');
$this->setState('filter.tag', $value);

$orderCol = $app->input->get('filter_order', 'a.ordering');

if (!in_array($orderCol, $this->filter_fields))
{
$orderCol = 'a.ordering';
}

$this->setState('list.ordering', $orderCol);

$listOrder = $app->input->get('filter_order_Dir', 'ASC');

if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', '')))
{
$listOrder = 'ASC';
}

$this->setState('list.direction', $listOrder);

$params = $app->getParams();
$this->setState('params', $params);
$user = JFactory::getUser();

if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content')))
{
// Filter on published for those who do not have edit or edit.state rights.
$this->setState('filter.published', 1);
}

$this->setState('filter.language', JLanguageMultilang::isEnabled());

// Process show_noauth parameter
if ((!$params->get('show_noauth')) || (!JComponentHelper::getParams('com_content')->get('show_noauth')))
{
$this->setState('filter.access', true);
}
else
{
$this->setState('filter.access', false);
}

$this->setState('layout', $app->input->getString('layout'));
}

/**
* Method to get a store id based on model configuration state.
*
* This is necessary because the model is used by the component and
* different modules that might need different sets of data or different
* ordering requirements.
*
* @param   string  $id  A prefix for the store id.
*
* @return  string  A store id.
*
* @since   1.6
*/
protected function getStoreId($id = '')
{
// Compile the store id.
$id .= ':' . serialize($this->getState('filter.published'));
$id .= ':' . $this->getState('filter.access');
$id .= ':' . $this->getState('filter.featured');
$id .= ':' . serialize($this->getState('filter.article_id'));
$id .= ':' . $this->getState('filter.article_id.include');
$id .= ':' . serialize($this->getState('filter.category_id'));
$id .= ':' . $this->getState('filter.category_id.include');
$id .= ':' . serialize($this->getState('filter.author_id'));
$id .= ':' . $this->getState('filter.author_id.include');
$id .= ':' . serialize($this->getState('filter.author_alias'));
$id .= ':' . $this->getState('filter.author_alias.include');
$id .= ':' . $this->getState('filter.date_filtering');
$id .= ':' . $this->getState('filter.date_field');
$id .= ':' . $this->getState('filter.start_date_range');
$id .= ':' . $this->getState('filter.end_date_range');
$id .= ':' . $this->getState('filter.relative_date');
$id .= ':' . serialize($this->getState('filter.tag'));

return parent::getStoreId($id);
}

/**
* Get the master query for retrieving a list of articles subject to the model state.
*
* @return  JDatabaseQuery
*
* @since   1.6
*/
protected function getListQuery()
{
// Get the current user for authorisation checks
$user = JFactory::getUser();

// Create a new query object.
$db    = $this->getDbo();
$query = $db->getQuery(true);

// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.id, a.title, a.alias, a.introtext, a.fulltext, ' .
'a.checked_out, a.checked_out_time, ' .
'a.catid, a.created, a.created_by, a.created_by_alias, ' .
// Published/archived article in archive category is treats as archive article
// If category is not published then force 0
'CASE WHEN c.published = 2 AND a.state > 0 THEN 2 WHEN c.published != 1 THEN 0 ELSE a.state END as state,' .
// Use created if modified is 0
'CASE WHEN a.modified = ' . $db->quote($db->getNullDate()) . ' THEN a.created ELSE a.modified END as modified, ' .
'a.modified_by, uam.name as modified_by_name,' .
// Use created if publish_up is 0
'CASE WHEN a.publish_up = ' . $db->quote($db->getNullDate()) . ' THEN a.created ELSE a.publish_up END as publish_up,' .
'a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access, ' .
'a.hits, a.xreference, a.featured, a.language, ' . ' ' . $query->length('a.fulltext') . ' AS readmore, a.ordering'
)
);

$query->from('#__content AS a');

$params      = $this->getState('params');
$orderby_sec = $params->get('orderby_sec');

// Join over the frontpage articles if required.
if ($this->getState('filter.frontpage'))
{
if ($orderby_sec === 'front')
{
$query->select('fp.ordering');
$query->join('INNER', '#__content_frontpage AS fp ON fp.content_id = a.id');
}
else
{
$query->where('a.featured = 1');
}
}
elseif ($orderby_sec === 'front' || $this->getState('list.ordering') === 'fp.ordering')
{
$query->select('fp.ordering');
$query->join('LEFT', '#__content_frontpage AS fp ON fp.content_id = a.id');
}

// Join over the categories.
$query->select('c.title AS category_title, c.path AS category_route, c.access AS category_access, c.alias AS category_alias')
->select('c.published, c.published AS parents_published, c.lft')
->join('LEFT', '#__categories AS c ON c.id = a.catid');

// Join over the users for the author and modified_by names.
$query->select("CASE WHEN a.created_by_alias > ' ' THEN a.created_by_alias ELSE ua.name END AS author")
->select('ua.email AS author_email')
->join('LEFT', '#__users AS ua ON ua.id = a.created_by')
->join('LEFT', '#__users AS uam ON uam.id = a.modified_by');

// Join over the categories to get parent category titles
$query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias')
->join('LEFT', '#__categories as parent ON parent.id = c.parent_id');

if (JPluginHelper::isEnabled('content', 'vote'))
{
// Join on voting table
$query->select('COALESCE(NULLIF(ROUND(v.rating_sum  / v.rating_count, 0), 0), 0) AS rating,
COALESCE(NULLIF(v.rating_count, 0), 0) as rating_count')
->join('LEFT', '#__content_rating AS v ON a.id = v.content_id');
}

// Filter by access level.
if ($this->getState('filter.access', true))
{
$groups = implode(',', $user->getAuthorisedViewLevels());
$query->where('a.access IN (' . $groups . ')')
->where('c.access IN (' . $groups . ')');
}

// Filter by published state
$published = $this->getState('filter.published');

if (is_numeric($published) && $published == 2)
{
/**
* If category is archived then article has to be published or archived.
* Or categogy is published then article has to be archived.
*/
$query->where('((c.published = 2 AND a.state > 0) OR (c.published = 1 AND a.state = 2))');
}
elseif (is_numeric($published))
{
// Category has to be published
$query->where('c.published = 1 AND a.state = ' . (int) $published);
}
elseif (is_array($published))
{
$published = ArrayHelper::toInteger($published);
$published = implode(',', $published);

// Category has to be published
$query->where('c.published = 1 AND a.state IN (' . $published . ')');
}

// Filter by featured state
$featured = $this->getState('filter.featured');

switch ($featured)
{
case 'hide':
$query->where('a.featured = 0');
break;

case 'only':
$query->where('a.featured = 1');
break;

case 'show':
default:
// Normally we do not discriminate between featured/unfeatured items.
break;
}

// Filter by a single or group of articles.
$articleId = $this->getState('filter.article_id');

if (is_numeric($articleId))
{
$type = $this->getState('filter.article_id.include', true) ? '= ' : '<> ';
$query->where('a.id ' . $type . (int) $articleId);
}
elseif (is_array($articleId))
{
$articleId = ArrayHelper::toInteger($articleId);
$articleId = implode(',', $articleId);
$type      = $this->getState('filter.article_id.include', true) ? 'IN' : 'NOT IN';
$query->where('a.id ' . $type . ' (' . $articleId . ')');
}

// Filter by a single or group of categories
$categoryId = $this->getState('filter.category_id');

if (is_numeric($categoryId))
{
$type = $this->getState('filter.category_id.include', true) ? '= ' : '<> ';

// Add subcategory check
$includeSubcategories = $this->getState('filter.subcategories', false);
$categoryEquals       = 'a.catid ' . $type . (int) $categoryId;

if ($includeSubcategories)
{
$levels = (int) $this->getState('filter.max_category_levels', '1');

// Create a subquery for the subcategory list
$subQuery = $db->getQuery(true)
->select('sub.id')
->from('#__categories as sub')
->join('INNER', '#__categories as this ON sub.lft > this.lft AND sub.rgt < this.rgt')
->where('this.id = ' . (int) $categoryId);

if ($levels >= 0)
{
$subQuery->where('sub.level <= this.level + ' . $levels);
}

// Add the subquery to the main query
$query->where('(' . $categoryEquals . ' OR a.catid IN (' . (string) $subQuery . '))');
}
else
{
$query->where($categoryEquals);
}
}
elseif (is_array($categoryId) && (count($categoryId) > 0))
{
$categoryId = ArrayHelper::toInteger($categoryId);
$categoryId = implode(',', $categoryId);

if (!empty($categoryId))
{
$type = $this->getState('filter.category_id.include', true) ? 'IN' : 'NOT IN';
$query->where('a.catid ' . $type . ' (' . $categoryId . ')');
}
}

// Filter by author
$authorId    = $this->getState('filter.author_id');
$authorWhere = '';

if (is_numeric($authorId))
{
$type        = $this->getState('filter.author_id.include', true) ? '= ' : '<> ';
$authorWhere = 'a.created_by ' . $type . (int) $authorId;
}
elseif (is_array($authorId))
{
$authorId = ArrayHelper::toInteger($authorId);
$authorId = implode(',', $authorId);

if ($authorId)
{
$type        = $this->getState('filter.author_id.include', true) ? 'IN' : 'NOT IN';
$authorWhere = 'a.created_by ' . $type . ' (' . $authorId . ')';
}
}

// Filter by author alias
$authorAlias      = $this->getState('filter.author_alias');
$authorAliasWhere = '';

if (is_string($authorAlias))
{
$type             = $this->getState('filter.author_alias.include', true) ? '= ' : '<> ';
$authorAliasWhere = 'a.created_by_alias ' . $type . $db->quote($authorAlias);
}
elseif (is_array($authorAlias))
{
$first = current($authorAlias);

if (!empty($first))
{
foreach ($authorAlias as $key => $alias)
{
$authorAlias[$key] = $db->quote($alias);
}

$authorAlias = implode(',', $authorAlias);

if ($authorAlias)
{
$type             = $this->getState('filter.author_alias.include', true) ? 'IN' : 'NOT IN';
$authorAliasWhere = 'a.created_by_alias ' . $type . ' (' . $authorAlias .
')';
}
}
}

if (!empty($authorWhere) && !empty($authorAliasWhere))
{
$query->where('(' . $authorWhere . ' OR ' . $authorAliasWhere . ')');
}
elseif (empty($authorWhere) && empty($authorAliasWhere))
{
// If both are empty we don't want to add to the query
}
else
{
// One of these is empty, the other is not so we just add both
$query->where($authorWhere . $authorAliasWhere);
}

// Define null and now dates
$nullDate = $db->quote($db->getNullDate());
$nowDate  = $db->quote(JFactory::getDate()->toSql());

// Filter by start and end dates.
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content')))
{
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')')
->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
}

// Filter by Date Range or Relative Date
$dateFiltering = $this->getState('filter.date_filtering', 'off');
$dateField     = $this->getState('filter.date_field', 'a.created');

switch ($dateFiltering)
{
case 'range':
$startDateRange = $db->quote($this->getState('filter.start_date_range', $nullDate));
$endDateRange   = $db->quote($this->getState('filter.end_date_range', $nullDate));
$query->where(
'(' . $dateField . ' >= ' . $startDateRange . ' AND ' . $dateField .
' <= ' . $endDateRange . ')'
);
break;

case 'relative':
$relativeDate = (int) $this->getState('filter.relative_date', 0);
$query->where(
$dateField . ' >= DATE_SUB(' . $nowDate . ', INTERVAL ' .
$relativeDate . ' DAY)'
);
break;

case 'off':
default:
break;
}

// Process the filter for list views with user-entered filters
if (is_object($params) && ($params->get('filter_field') !== 'hide') && ($filter = $this->getState('list.filter')))
{
// Clean filter variable
$filter     = StringHelper::strtolower($filter);
$hitsFilter = (int) $filter;
$filter     = $db->quote('%' . $db->escape($filter, true) . '%', false);

switch ($params->get('filter_field'))
{
case 'author':
$query->where(
'LOWER( CASE WHEN a.created_by_alias > ' . $db->quote(' ') .
' THEN a.created_by_alias ELSE ua.name END ) LIKE ' . $filter . ' '
);
break;

case 'hits':
$query->where('a.hits >= ' . $hitsFilter . ' ');
break;

case 'title':
default:
// Default to 'title' if parameter is not valid
$query->where('LOWER( a.title ) LIKE ' . $filter);
break;
}
}

// Filter by language
if ($this->getState('filter.language'))
{
$query->where('a.language IN (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
}

// Filter by a single or group of tags.
$tagId = $this->getState('filter.tag');

if (is_array($tagId) && count($tagId) === 1)
{
$tagId = current($tagId);
}

if (is_array($tagId))
{
$tagId = implode(',', ArrayHelper::toInteger($tagId));

if ($tagId)
{
$subQuery = $db->getQuery(true)
->select('DISTINCT content_item_id')
->from($db->quoteName('#__contentitem_tag_map'))
->where('tag_id IN (' . $tagId . ')')
->where('type_alias = ' . $db->quote('com_content.article'));

$query->innerJoin('(' . (string) $subQuery . ') AS tagmap ON tagmap.content_item_id = a.id');
}
}
elseif ($tagId)
{
$query->innerJoin(
$db->quoteName('#__contentitem_tag_map', 'tagmap')
. ' ON tagmap.tag_id = ' . (int) $tagId
. ' AND tagmap.content_item_id = a.id'
. ' AND tagmap.type_alias = ' . $db->quote('com_content.article')
);
}

// Add the list ordering clause.
$query->order($this->getState('list.ordering', 'a.ordering') . ' ' . $this->getState('list.direction', 'ASC'));

return $query;
}

/**
* Method to get a list of articles.
*
* Overriden to inject convert the attribs field into a JParameter object.
*
* @return  mixed  An array of objects on success, false on failure.
*
* @since   1.6
*/
public function getItems()
{
$items  = parent::getItems();
$user   = JFactory::getUser();
$userId = $user->get('id');
$guest  = $user->get('guest');
$groups = $user->getAuthorisedViewLevels();
$input  = JFactory::getApplication()->input;

// Get the global params
$globalParams = JComponentHelper::getParams('com_content', true);

// Convert the parameter fields into objects.
foreach ($items as &$item)
{
$articleParams = new Registry($item->attribs);

// Unpack readmore and layout params
$item->alternative_readmore = $articleParams->get('alternative_readmore');
$item->layout               = $articleParams->get('layout');

$item->params = clone $this->getState('params');

/**
* For blogs, article params override menu item params only if menu param = 'use_article'
* Otherwise, menu item params control the layout
* If menu item is 'use_article' and there is no article param, use global
*/
if (($input->getString('layout') === 'blog') || ($input->getString('view') === 'featured')
|| ($this->getState('params')->get('layout_type') === 'blog'))
{
// Create an array of just the params set to 'use_article'
$menuParamsArray = $this->getState('params')->toArray();
$articleArray    = array();

foreach ($menuParamsArray as $key => $value)
{
if ($value === 'use_article')
{
// If the article has a value, use it
if ($articleParams->get($key) != '')
{
// Get the value from the article
$articleArray[$key] = $articleParams->get($key);
}
else
{
// Otherwise, use the global value
$articleArray[$key] = $globalParams->get($key);
}
}
}

// Merge the selected article params
if (count($articleArray) > 0)
{
$articleParams = new Registry($articleArray);
$item->params->merge($articleParams);
}
}
else
{
// For non-blog layouts, merge all of the article params
$item->params->merge($articleParams);
}

// Get display date
switch ($item->params->get('list_show_date'))
{
case 'modified':
$item->displayDate = $item->modified;
break;

case 'published':
$item->displayDate = ($item->publish_up == 0) ? $item->created : $item->publish_up;
break;

default:
case 'created':
$item->displayDate = $item->created;
break;
}

/**
* Compute the asset access permissions.
* Technically guest could edit an article, but lets not check that to improve performance a little.
*/
if (!$guest)
{
$asset = 'com_content.article.' . $item->id;

// Check general edit permission first.
if ($user->authorise('core.edit', $asset))
{
$item->params->set('access-edit', true);
}

// Now check if edit.own is available.
elseif (!empty($userId) && $user->authorise('core.edit.own', $asset))
{
// Check for a valid user and that they are the owner.
if ($userId == $item->created_by)
{
$item->params->set('access-edit', true);
}
}
}

$access = $this->getState('filter.access');

if ($access)
{
// If the access filter has been set, we already have only the articles this user can view.
$item->params->set('access-view', true);
}
else
{
// If no access filter is set, the layout takes some responsibility for display of limited information.
if ($item->catid == 0 || $item->category_access === null)
{
$item->params->set('access-view', in_array($item->access, $groups));
}
else
{
$item->params->set('access-view', in_array($item->access, $groups) && in_array($item->category_access, $groups));
}
}

// Some contexts may not use tags data at all, so we allow callers to disable loading tag data
if ($this->getState('load_tags', $item->params->get('show_tags', '1')))
{
$item->tags = new JHelperTags;
$item->tags->getItemTags('com_content.article', $item->id);
}

if ($item->params->get('show_associations'))
{
$item->associations = ContentHelperAssociation::displayAssociations($item->id);
}
}

return $items;
}

/**
* Method to get the starting number of items for the data set.
*
* @return  integer  The starting number of items available in the data set.
*
* @since   12.2
*/
public function getStart()
{
return $this->getState('list.start');
}
}
« Последнее редактирование: 22.03.2018, 15:11:17 от Дмитрий_ »
*

beliyadm

  • Легенда
  • 9758
  • 1664 / 66
  • Севастополь, Россия
К примеру после этих строк
Код
		elseif ($orderby_sec === 'front' || $this->getState('list.ordering') === 'fp.ordering')
{
$query->select('fp.ordering');
$query->join('LEFT', '#__content_frontpage AS fp ON fp.content_id = a.id');
}

Добавьте джойн

Код
$query->select('ar.rating_sum as rating_sum);
$query->join('LEFT', '#__content_rating AS ar ON ar.content_id = a.id');

Тогда в массиве появится это элемент rating_sum и дальше по идее ваши манипуляции с добавлением условия сортировки должны работать
Все истины, которые я хочу вам изложить, — бесстыдная ложь. Сделать всё хорошо
TLG: @Beliyadm
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Добавьте джойн Код $query->select('ar.rating_sum as rating_sum); $query->join('LEFT', '#__content_rating AS ar ON ar.content_id = a.id'); Тогда в массиве появится это элемент rating_sum и дальше по идее ваши манипуляции с добавлением условия сортировки должны работать
Добавил, теперь выдает ошибку: 0 syntax error, unexpected 'LEFT' (T_STRING), expecting ',' or ')'
*

beliyadm

  • Легенда
  • 9758
  • 1664 / 66
  • Севастополь, Россия
Виноват, кавычку стер :)
Код
		$query->select('ar.rating_sum as rating_sum');
$query->join('LEFT', '#__content_rating AS ar ON ar.content_id = a.id');
Все истины, которые я хочу вам изложить, — бесстыдная ложь. Сделать всё хорошо
TLG: @Beliyadm
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
В файле /components/com_content/helpers/query.php, менял
Это я видел, я имел в виду другое.
Вы правы! Вся загвоздка находится в файле - \components\com_content\models\articles.php.
Скопировав данный файл из старой версии Joomla, у меня все заработало.
Не нужно хакать модель. Включите плагин "Content-Vote", тогда таблица content_rating добавится в join и у вас появятся поля rating и rating_count для сортировки.

« Последнее редактирование: 22.03.2018, 15:43:32 от robert »
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Виноват, кавычку стер :)
Код
		$query->select('ar.rating_sum as rating_sum');
$query->join('LEFT', '#__content_rating AS ar ON ar.content_id = a.id');
Вы где-то в правильном направлении ^-^, но пока не получается :P Теперь вывод материала идет - ошибок нет, но и сортировки нет ;D
*

beliyadm

  • Легенда
  • 9758
  • 1664 / 66
  • Севастополь, Россия
Вы где-то в правильном направлении ^-^, но пока не получается :P Теперь вывод материала идет - ошибок нет, но и сортировки нет ;D
я и не добавлял сортировку, лишь добавил в выдаваемый массив нужную таблицу и алиас поля, хаки с сортировкой вы приводили в самом начале.

Либо попробуйте сделать как сказал robert, возможно оно и будет правильней
Все истины, которые я хочу вам изложить, — бесстыдная ложь. Сделать всё хорошо
TLG: @Beliyadm
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Не нужно хакать модель. Включите плагин "Content-Vote", тогда таблица content_rating добавится в join и у вас появятся поля rating и rating_count для сортировки.
Не совсем понял, что Вы имели ввиду - под включением - "Content-Vote" ?, - если плагин - "Контент-Рейтинг", то включение его ничего не дает, только добавляет дополнительный рейтинг рядом с выводом рейтинга плагина - Extravote. Да и проблема то - стоит конкретная, как сортировать материал по рейтингу, при условии, что голосование идет именно с помощью плагина - "Extravote" ?
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
при условии, что голосование идет именно с помощью плагина - "Extravote"
Тогда - только хаком, что вы уже делали до обновления и забыли, что и как. Я посмотрел код плагина Extravote - он выводит рейтинг, а не сортирует по нему. Короче, до следующего обновления, на этом же месте :).
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Тогда - только хаком, что вы уже делали до обновления и забыли, что и как. Я посмотрел код плагина Extravote - он выводит рейтинг, а не сортирует по нему. Короче, до следующего обновления, на этом же месте :).
Я в курсе, что он не сортирует ^-^ И я ничего не забыл, я записывал свои действия и повторял их уже не единожды - после очередного обновления, но тут - увы не помогло, код сильно изменился) Но все-равно, спасибо, что попытались помочь. Буду пробовать тогда сам дохакать - если конечно совсем в дебрях кода не потеряюсь ;D
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Всем, кто попытался помочь - спасибо огромное! ^-^
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Кстати, поскольку Extravote может использовать Jooml'овскую таблицу content_rating, я на вашем месте бы переделал его под стандартный Content-Vote и подсунул системе. При очередном обновлении вам нужно всего лишь заменить новый файл старым.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Кстати, поскольку Extravote может использовать Jooml'овскую таблицу content_rating, я на вашем месте бы переделал его под стандартный Content-Vote и подсунул системе. При очередном обновлении вам нужно всего лишь заменить новый файл старым.
Урааа, решил!!! :D *POPCORN* Я попробовал включить плагин "Content-Vote", скопировал данные голосования всех материалов из таблицы Extravote - в Jooml'овскую таблицу content_rating, и в файлике \components\com_content\helpers\query.php, заменил:
Код
case 'hits' : $orderby = 'a.hits DESC'; на case 'hits' : $orderby = 'rating_sum DESC';
Осталось дело за малым, убрать со страниц вывод голосования "Content-Vote", и подключить Jooml'овскую таблицу content_rating к Extravote.

Но увы, подключить корректно таблицу content_rating к Extravote не получается, она подключается, все сортируется, но когда пробуешь голосовать - голос уходит походу в таблицу content_extravote.

Вот файлик, где должно вроде все это правиться, подскажите, как мне корректно подключить здесь табличку - content_rating :
Код
<?php
/*------------------------------------------------------------------------
# plg_extravote - ExtraVote Plugin
# ------------------------------------------------------------------------
# author    Jesús Vargas Garita
# Copyright (C) 2010 www.munditico.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.munditico.com
# Technical Support:  Forum - http://www.munditico.com/forum
-------------------------------------------------------------------------*/

// No direct access
defined('_JEXEC') or die;

jimport('joomla.plugin.plugin');


class plgContentExtraVote extends JPlugin
{
protected $article_id;

public function __construct(& $subject, $config)
{
parent::__construct($subject, $config);
$this->loadLanguage();

$this->view = JRequest::getCmd('view');
}

public function onContentBeforeDisplay($context, &$article, &$params, $limitstart = 1)
{
if (strpos($context, 'com_content') !== false) {

$this->article_id = $article->id;

$this->ExtraVotePrepare($article, $params);

if ( $this->params->get('display') == 0  )
{
$hide  = $this->params->get('hide', 1);

if ( $hide != 1 || $this->view == 'article' ) {
$article->xid = 0;
return $this->ContentExtraVote($article, $params);
}
}
}

  }

protected function ContentExtraVote(&$article, &$params)
{
$table =($this->params->get('table',1)==1?'#__content_extravote':'#__content_rating');
$rating_count=$rating_sum=0;
$html=$ip='';

if ($params->get('show_vote'))
{
$db = JFactory::getDBO();
$query='SELECT * FROM ' . $table . ' WHERE content_id='.$this->article_id . ($table == '#__content_extravote' ? ' AND extra_id = 0' : '');
$db->setQuery($query);
$vote=$db->loadObject();

if($vote) {
$rating_sum = $vote->rating_sum;
$rating_count = intval($vote->rating_count);
$ip = $vote->lastip;
}

$html .= $this->plgContentExtraVoteStars( $this->article_id, $rating_sum, $rating_count, $article->xid, $ip );
}
return $html;
  }

 
  protected function plgContentExtraVoteStars( $id, $rating_sum, $rating_count, $xid, $ip )
{
$document = JFactory::getDocument();

if ( $this->params->get('css', 1) ) :
$document->addStyleSheet(JURI::root(true).'/plugins/content/extravote/assets/extravote.css');
endif;

$document->addScript(JURI::root(true).'/plugins/content/extravote/assets/extravote.js');

      global $plgContentExtraVoteAddScript;

$show_counter = $this->params->get('show_counter',1);
$show_rating  = $this->params->get('show_rating',1);
$rating_mode  = $this->params->get('rating_mode', 1);
$show_unrated = $this->params->get('show_unrated',1);
$initial_hide = $this->params->get('initial_hide',0);
$currip = $_SERVER['REMOTE_ADDR'];
$add_snippets = 0;
$rating  = 0;

if(!$plgContentExtraVoteAddScript){
          $document->addScriptDeclaration("
var ev_basefolder = '".JURI::base(true)."';
var extravote_text=Array('".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_MESSAGE_NO_AJAX')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_MESSAGE_LOADING')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_MESSAGE_THANKS')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_MESSAGE_LOGIN')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_MESSAGE_RATED')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_LABEL_VOTES')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_LABEL_VOTE')."','".
JTEXT::_('PLG_CONTENT_EXTRAVOTE_LABEL_RATING').
"');
");
      $plgContentExtraVoteAddScript = 1;
}

if( $rating_count!=0 ) {
$rating  = ($rating_sum / intval( $rating_count ));
$add_snippets = $this->params->get('snippets',0);
} elseif( $show_unrated == 0 ) {
$show_counter = -1;
$show_rating  = -1;
}

$container = 'div';
$class     = 'size-'.$this->params->get('size', 1);

if( (int)$xid ) {
if ( $show_counter == 2 ) $show_counter = 0;
if ( $show_rating == 2 ) $show_rating = 0;
$container = 'span';
$class    .= ' extravote-small'; 
$add_snippets = 0;
} else {
if ( $show_counter == 3 ) $show_counter = 0;
if ( $show_rating == 3 ) $show_rating = 0;
$class    .= ' extravote'; 
}

$stars = (($this->params->get('table',1)!=1 && !(int)$xid)?5:$this->params->get('stars',10));
$spans = '';

for ($i=0,$j=5/$stars; $i<$stars; $i++,$j+=5/$stars) :
$spans .= "
      <span class=\"extravote-star\"><a href=\"javascript:void(null)\" onclick=\"javascript:JVXVote(".$id.",".$j.",".$rating_sum.",".$rating_count.",'".$xid."',".$show_counter.",".$show_rating.",".$rating_mode.");\" title=\"".JTEXT::_('PLG_CONTENT_EXTRAVOTE_RATING_'.($j*10).'_OUT_OF_5')."\" class=\"ev-".($j*10)."-stars\">1</a></span>";
endfor;

$html = "
<".$container." class=\"".$class."\">
  <span class=\"extravote-stars\"".($add_snippets?" itemprop=\"aggregateRating\" itemscope itemtype=\"http://schema.org/AggregateRating\"":"").">".($add_snippets?"
  <meta itemprop=\"ratingCount\" content=\"".$rating_count."\" />
":"
")."<span id=\"rating_".$id."_".$xid."\" class=\"current-rating\"".((!$initial_hide||$currip==$ip)?" style=\"width:".round($rating*20)."%;\"":"")."".($add_snippets?" itemprop=\"ratingValue\"":"").">".($add_snippets?$rating:"")."</span>"
.$spans."
  </span>
  <span class=\"extravote-info".(($initial_hide&&$currip!=$ip)?" ihide\"":"")."\" id=\"extravote_".$id."_".$xid."\">";
 
  if ( $show_rating > 0 ) {
if ( $rating_mode == 0 ) {
$rating = round($rating*20) . '%';
} else {
$rating = number_format($rating,2);
}
$html .= JTEXT::sprintf('PLG_CONTENT_EXTRAVOTE_LABEL_RATING', $rating);
}

  if ( $show_counter > 0 ) {
if($rating_count!=1) {
$html .= JTEXT::sprintf('PLG_CONTENT_EXTRAVOTE_LABEL_VOTES', $rating_count);
} else {
$html .= JTEXT::sprintf('PLG_CONTENT_EXTRAVOTE_LABEL_VOTE', $rating_count);
}
}

  $html .="</span>";
  $html .="
</".$container.">";

return $html;
  }

  protected function ExtraVotePrepare( $article, &$params )
{
    if (isset($this->article_id)) {

        $extra = $this->params->get('extra', 1);
$main  = $this->params->get('main', 1);

      if ( $extra != 0 ) {

        $regex = "/{extravote\s*([0-9]+)}/i";

if ( $this->view != 'article' && stripos($article->text, 'extravote') ) {
if ( $extra == 2 ) {
$article->introtext = preg_replace( $regex, '', $article->introtext );
} else {
$article->introtext = preg_replace_callback( $regex, array($this,'plgContentExtraVoteReplacer'), $article->introtext );
}
} elseif (stripos($article->text, 'extravote')) {
//     $this->article_id = $article->id;
        $article->text = preg_replace_callback( $regex, array($this,'plgContentExtraVoteReplacer'), $article->text );
    }
    }

      if ( $main != 0 ) {

$strposIntro = isset($article->introtext)?stripos($article->introtext, 'mainvote'):false;
$strposText  = stripos($article->text, 'mainvote');

$regex = "/{mainvote\s*([0-9]*)}/i";

if ( $main == 2 && $this->view != 'article' && $strposIntro)
    {
        $article->introtext = preg_replace( $regex, '', $article->introtext );
    } else {
    $this->article_id = $article->id;
if ( $this->view == 'article' && $strposText ) {
        $article->text = preg_replace_callback( $regex, array($this,'plgContentExtraVoteReplacer'), $article->text );
} elseif( $strposIntro ) {
        $article->introtext = preg_replace_callback( $regex, array($this,'plgContentExtraVoteReplacer'), $article->introtext );
}
    }
    }

    if ( $this->params->get('display') == 1 )  {

        $article->xid = 0;
if ( $this->view == 'article' ) {
        $article->text .= $this->ContentExtraVote($article, $params);
} elseif ( $this->params->get('hide') == 0 ) {
        $article->introtext .= $this->ContentExtraVote($article, $params);
}
    }
      }
  }
 
protected function plgContentExtraVoteReplacer(&$matches )
{
  $db = JFactory::getDBO();
  $cid = 0;
$xid = 0;
if (isset($matches[1])) {
if(stripos($matches[0], 'extravote')) {
$xid = (int)$matches[1];
} else {
$cid = (int)$matches[1];
}
}
if ( $cid == 0 && ($this->params->get('article_id') || $xid == 0) ) {
$cid = $this->article_id;
}
  $rating_sum = 0;
  $rating_count = 0;

if ( $xid == 0 ) :
global $extravote_mainvote;
$extravote_mainvote .= 'x';
$xid = $extravote_mainvote;
$table =($this->params->get('table',1)==1?'#__content_extravote':'#__content_rating');
$db->setQuery('SELECT * FROM ' . $table . ' WHERE content_id='.(int)$cid);
else : 
$db->setQuery('SELECT * FROM #__content_extravote WHERE content_id='.(int)$cid.' AND extra_id='.(int)$xid);
endif; 
  $vote = $db->loadObject();
  if($vote) {
if($vote->rating_count!=0)
$rating_sum = $vote->rating_sum;
$rating_count = intval($vote->rating_count);
}
return $this->plgContentExtraVoteStars( $cid, $rating_sum, $rating_count, $xid, ($vote?$vote->lastip:'') );
}

}
« Последнее редактирование: 22.03.2018, 18:58:30 от Дмитрий_ »
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Но увы, подключить корректно таблицу content_rating к Extravote не получается
Как вы подключаете ее?
А вообще, делайте, как я советовал: измените плагин Extravote так, чтобы Joomla приняла его за родной Content-Vote. Extravote больше не будет, есть Content-Vote, который на самом деле Extravote - вот такая вот загогулина :).
« Последнее редактирование: 22.03.2018, 19:32:03 от robert »
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Дмитрий_

  • Осваиваюсь на форуме
  • 19
  • 0 / 0
Как вы подключаете ее?
А вообще, делайте, как я советовал: измените плагин Extravote так, чтобы Joomla приняла его за родной Content-Vote. Extravote больше не будет, есть Content-Vote, который на самом деле Extravote - вот такая вот загогулина :).
Да я бы с радостью сделал, то, о чем Вы говорите, но Вы забываете, что я в коде не бум-бум ;D
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Ну, это на самом деле не так трудно: будете скрупулезно названия менять, а не код писать.
Не будь паразитом, сделай что-нибудь самостоятельно!
*

Diman2050

  • Новичок
  • 3
  • 0 / 0
Ну, это на самом деле не так трудно: будете скрупулезно названия менять, а не код писать.
Да вообще не трудно - ни разу, когда знаешь - где и что менять) Такая идея мне приходила в голову, но опять, нужно знать код: что, в каком месте и на что менять?! если бы я знал, что и как делать, я бы наверное не обращался за помощью.
*

robert

  • Живу я здесь
  • 4974
  • 457 / 20
Вот, попробуйте. root - это коренная папка вашего сайта, меняйте файлы по аналогии, предварительно сохранив старые. Не уверен, что все учел (не пользуюсь этими плагинами), но по идеи должно работать.
P.S. Почему заходите на форум под разными логинами?
Не будь паразитом, сделай что-нибудь самостоятельно!
Чтобы оставить сообщение,
Вам необходимо Войти или Зарегистрироваться
 

Версии РНР и Joomla 3

Автор Ebelous

Ответов: 6
Просмотров: 413
Последний ответ 29.02.2024, 17:50:02
от web1
SP polls в Joomla 3.8.2

Автор wawont

Ответов: 2
Просмотров: 1447
Последний ответ 22.02.2024, 21:03:15
от Zegeberg
Исправление уязвимости в Joomla 3.10.12

Автор Sulpher

Ответов: 8
Просмотров: 781
Последний ответ 12.01.2024, 22:15:52
от stepan39
Заявки с сайта на Joomla

Автор ivs1

Ответов: 8
Просмотров: 624
Последний ответ 18.12.2023, 12:37:45
от SeBun
Прошу помощи. Ошибка при обновлении на Joomla 4

Автор wmsonic

Ответов: 1
Просмотров: 918
Последний ответ 29.10.2023, 22:07:23
от Kukush