Commit 23d130ce authored by Dainis Abols's avatar Dainis Abols
Browse files

Major search changes. Filters + ordering + solr + TYPO3 v10 compatability

parent e8c1d641
...@@ -2,22 +2,20 @@ ...@@ -2,22 +2,20 @@
namespace Lu\LuSearch\Controller; namespace Lu\LuSearch\Controller;
use HDNET\Calendarize\ViewHelpers\Link\AbstractLinkViewHelper;
use Lu\LuApi\DataSources\SolrSearch; use Lu\LuApi\DataSources\SolrSearch;
use Lu\LuSearch\Domain\Model\Results;
use Lu\LuSearch\Helpers\DataHelper; use Lu\LuSearch\Helpers\DataHelper;
use TYPO3\CMS\Beuser\Domain\Model\BackendUser;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Context\Context; use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Database\ConnectionPool; use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Exception\SiteNotFoundException; use TYPO3\CMS\Core\Exception\SiteNotFoundException;
use TYPO3\CMS\Core\Page\PageRenderer; use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\FileRepository; use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Resource\ResourceStorage;
use TYPO3\CMS\Core\Site\SiteFinder; use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController; use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder; use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
/** /**
* Class SearchController * Class SearchController
...@@ -67,19 +65,12 @@ class SearchController extends ActionController ...@@ -67,19 +65,12 @@ class SearchController extends ActionController
*/ */
private $currentPage; private $currentPage;
/**
* Filter array
*
* @var array
*/
private $filter;
/** /**
* Define pagination limit * Define pagination limit
* *
* @var int * @var int
*/ */
private $limit = 25; private $limit = 10;
/** /**
* Parent IDs * Parent IDs
...@@ -122,25 +113,39 @@ class SearchController extends ActionController ...@@ -122,25 +113,39 @@ class SearchController extends ActionController
// Pre-define variables // Pre-define variables
$data = []; $data = [];
$request = $_REQUEST; $request = $_REQUEST;
$currentPage = $request["tx_lusearch_pi1"]['@widget_0']['currentPage'];
if (empty($request['query'])) { // Check queries
$request = $this->request->getArguments(); if (empty($request)) {
$request = $this->request->getArguments();
$currentPage = $this->request->getArguments()['@widget_0']['currentPage'];
}
// Set order
$request['orderBy'] = !empty($request['orderBy']) ? $request['orderBy'] : 'default';
// Clear filter
if (!empty($request['filter'])) {
foreach ($request['filter'] as &$filter) {
$filter = array_unique($filter);
}
} }
// Find pagetree if limit set // Find page tree if limit set
if ($this->settings['limitToDomain']) { if ($this->settings['limitToDomain']) {
// Get page record for tree starting point // Get page record for tree starting point
$this->parentIDs = $this->buildTree($this->getParentSite($GLOBALS['TSFE']->id)->getRootPageId()); $this->parentIDs = @$this->buildTree($this->getParentSite($GLOBALS['TSFE']->id)->getRootPageId());
} }
// Get current page @FIXME There has to be a better way! // Get current page @FIXME There has to be a better way!
$this->currentPage = !empty($request['@widget_0']['currentPage']) ? (int)$request['@widget_0']['currentPage'] : 1; $this->currentPage = !empty($currentPage) ? (int)$currentPage : 1;
// Fetch data from SOLR // Fetch data from SOLR
$cleanQuery = strip_tags($request['query']); $cleanQuery = strip_tags($request['query']);
$cleanQuery = strlen($cleanQuery) >= 3 ? $cleanQuery : ''; $cleanQuery = strlen($cleanQuery) >= 3 ? $cleanQuery : '';
if ($cleanQuery) { if ($cleanQuery) {
$data = $this->listResults($cleanQuery); $data = $this->listResults($request);
$dataFacets = $this->listResults($request, true);
} }
// Add highlighting // Add highlighting
...@@ -156,7 +161,6 @@ class SearchController extends ActionController ...@@ -156,7 +161,6 @@ class SearchController extends ActionController
$singleTranslate = true; $singleTranslate = true;
} }
// Add paginate object // Add paginate object
$data['paginate'] = []; $data['paginate'] = [];
for ($k = 0; $k < $numRows; $k++) { for ($k = 0; $k < $numRows; $k++) {
...@@ -169,13 +173,20 @@ class SearchController extends ActionController ...@@ -169,13 +173,20 @@ class SearchController extends ActionController
// Assign variables // Assign variables
$this->view->assign('query', $cleanQuery); $this->view->assign('query', $cleanQuery);
$this->view->assign('orderBy', $request['orderBy']);
$this->view->assign('currentPage', $this->currentPage); $this->view->assign('currentPage', $this->currentPage);
$this->view->assign('singleTranslate', $singleTranslate); $this->view->assign('singleTranslate', $singleTranslate);
$this->view->assign('pageId', $GLOBALS['TSFE']->id); $this->view->assign('pageId', $GLOBALS['TSFE']->id);
$this->view->assign('language', $this->language); $this->view->assign('language', $this->language);
$this->view->assign('newsPageId', $this->language); $this->view->assign('newsPageId', $this->language);
$this->view->assign('pageLimit', $this->limit);
// Assign final data element to view // Assign final data element to view
$this->view->assign('visual', $this->getVisualsFilter($request['filter']));
$this->view->assign('filters', $request['filter']);
$facets = $this->convertFacets($dataFacets['facet_fields'] ?? []);
$this->view->assign('facets', $facets);
$this->view->assign('data', $data); $this->view->assign('data', $data);
} }
...@@ -188,16 +199,29 @@ class SearchController extends ActionController ...@@ -188,16 +199,29 @@ class SearchController extends ActionController
* *
* @param $query * @param $query
*/ */
private function listResults($query) private function listResults($request, $withFacets = false)
{ {
// Pre-set models and values // Pre-set models and values
$dataHelper = new DataHelper(); $dataHelper = new DataHelper();
$query = $request['query'];
$orderBy = $request['orderBy'];
// Search in SOLR // Search in SOLR
$solr = new SolrSearch(); $solr = new SolrSearch();
$solr->setLimit($this->limit); $solr->setLimit($this->limit);
$solr->setOffset(($this->currentPage - 1) * $this->limit); $solr->setOffset(($this->currentPage - 1) * $this->limit);
$solr->setHighlight("<span class=\"searchResults__searchTerm\">|</span>"); if ($withFacets) {
$solr->useFacets(true);
} else {
$solr->setHighlight("<span class=\"searchResults__searchTerm\">|</span>");
}
// Check facet call
if (!empty($request['filter'])) {
foreach ($request['filter'] as $name => $value) {
$solr->setFacetFilter($name, $value);
}
}
// Set filters // Set filters
$filters = ['title:"'.$query.'"', 'author:"'.$query.'"', 'body:"'.$query.'"']; $filters = ['title:"'.$query.'"', 'author:"'.$query.'"', 'body:"'.$query.'"'];
...@@ -217,14 +241,17 @@ class SearchController extends ActionController ...@@ -217,14 +241,17 @@ class SearchController extends ActionController
// if ($this->settings['searchContacts']) { // if ($this->settings['searchContacts']) {
// $types[] = 'type:contact'; // $types[] = 'type:contact';
// } // }
if ($this->settings['searchEvents']) { // if ($this->settings['searchEvents']) {
$types[] = 'type:event'; // $types[] = 'type:event';
} // }
if ($this->settings['searchPages']) { if ($this->settings['searchPages']) {
$types[] = 'type:page'; $types[] = 'type:page';
} }
$solr->setTypes($types); $solr->setTypes($types);
// Set order
$solr->setOrder($orderBy);
// Fetch data // Fetch data
$jsonData = $solr->fetch(true); $jsonData = $solr->fetch(true);
$result = $dataHelper->APIDecode($jsonData); $result = $dataHelper->APIDecode($jsonData);
...@@ -262,8 +289,8 @@ class SearchController extends ActionController ...@@ -262,8 +289,8 @@ class SearchController extends ActionController
$siteData = $this->getParentSite($item['parent_id']); $siteData = $this->getParentSite($item['parent_id']);
// Fetch data // Fetch data
$uid = str_replace($item['type'].'-', '', $item['id']); $uid = str_replace($item['type'].'-', '', $item['id']);
$title = $highlight[$item['id']]['title'][0] ?? $this->clearAndHighlight($item['title'], $cleanQuery, false); $title = $highlight[$item['id']]['title'][0] ?? $this->clearAndHighlight($item['title'], $cleanQuery, false);
$siteUrl = !empty($siteData) ? 'https://'.$siteData->getBase()->getHost() : ''; $siteUrl = !empty($siteData) ? 'https://'.$siteData->getBase()->getHost() : '';
if (empty($title)) { if (empty($title)) {
// If title is not still set, try to get parent page title // If title is not still set, try to get parent page title
...@@ -345,6 +372,8 @@ class SearchController extends ActionController ...@@ -345,6 +372,8 @@ class SearchController extends ActionController
*/ */
public function buildTree($startingPoint, $depth = 100) public function buildTree($startingPoint, $depth = 100)
{ {
GLOBAL $GLOBALS;
// Get page record for tree starting point // Get page record for tree starting point
$pageRecord = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord( $pageRecord = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord(
'pages', 'pages',
...@@ -361,12 +390,11 @@ class SearchController extends ActionController ...@@ -361,12 +390,11 @@ class SearchController extends ActionController
'HTML' => '', 'HTML' => '',
]; ];
// Create the page tree, from the starting point, 2 levels deep // Create the page tree, from the starting point, 2 levels deep with admin rights
$tree->getTree( $GLOBALS['BE_USER'] = new BackendUserAuthentication();
$startingPoint, $GLOBALS['BE_USER']->user['admin'] = 1;
$depth, $tree->getTree($startingPoint, $depth, '');
'' $GLOBALS['BE_USER'] = null;
);
// Fetch only uids and retrn data // Fetch only uids and retrn data
$treeIds = []; $treeIds = [];
...@@ -488,7 +516,7 @@ class SearchController extends ActionController ...@@ -488,7 +516,7 @@ class SearchController extends ActionController
{ {
// Fetch image from storage // Fetch image from storage
$fileRepository = GeneralUtility::makeInstance(FileRepository::class); $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
$fileObjects = $fileRepository->findByRelation('tx_news_domain_model_news', 'fal_media', $uid); $fileObjects = $fileRepository->findByRelation('tx_news_domain_model_news', 'fal_media', $uid);
// Build image // Build image
if (!empty($fileObjects)) { if (!empty($fileObjects)) {
...@@ -511,9 +539,10 @@ class SearchController extends ActionController ...@@ -511,9 +539,10 @@ class SearchController extends ActionController
* *
* @return string * @return string
*/ */
private function getPageTitle($page_id) { private function getPageTitle($page_id)
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('page')->createQueryBuilder(); $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('page')->createQueryBuilder();
$statement = $queryBuilder->select('title', 'slug')->from('pages')->where( $statement = $queryBuilder->select('title', 'slug')->from('pages')->where(
$queryBuilder->expr()->eq('uid', $page_id), $queryBuilder->expr()->eq('uid', $page_id),
)->execute(); )->execute();
...@@ -546,12 +575,12 @@ class SearchController extends ActionController ...@@ -546,12 +575,12 @@ class SearchController extends ActionController
{ {
// Fetch image from storage // Fetch image from storage
$fileRepository = GeneralUtility::makeInstance(FileRepository::class); $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
$fileObjects = $fileRepository->findByRelation('pages', 'media', $uid); $fileObjects = $fileRepository->findByRelation('pages', 'media', $uid);
// Fetch level up // Fetch level up
if (empty($fileObjects)) { if (empty($fileObjects)) {
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('page')->createQueryBuilder(); $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('page')->createQueryBuilder();
$statement = $queryBuilder->select('pid')->from('pages')->where( $statement = $queryBuilder->select('pid')->from('pages')->where(
$queryBuilder->expr()->eq('uid', $uid), $queryBuilder->expr()->eq('uid', $uid),
)->execute(); )->execute();
...@@ -567,10 +596,123 @@ class SearchController extends ActionController ...@@ -567,10 +596,123 @@ class SearchController extends ActionController
// Build first element image // Build first element image
return $this->getPublicPath($fileObjects[0]); return $this->getPublicPath($fileObjects[0]);
} }
private function addCalendarId($uid) private function addCalendarId($uid)
{ {
return 55699; return 55699;
} }
/**
* Convert facets to readable array
*
* @param $facets
*
* @return array
*/
private function convertFacets(array $facets): array
{
// Preset models
$myResults = new Results();
// Loop fasets
$result = [];
if (!empty($facets)) {
foreach ($facets as $field => $items) {
// Reformat items
$item = [];
for ($k = 0; $k < count($items); $k = $k + 2) {
if ($items[$k + 1] > 0) {
$item[] = [
'name' => $items[$k],
'visual' => $myResults->getTitleByFacet($field, $items[$k]),
'count' => $items[$k + 1],
'url' => $this->generateUrl($field, $items[$k]),
];
}
}
if (!empty($item)) {
$result[] = [
'name' => $field,
'items' => $item,
];
}
}
}
// Return result
return $result;
}
/**
* Genereate url for facet usage
*
* @param $field
* @param $item
*
* @return string
*/
private function generateUrl($field, $item)
{
// Fetch uri
$uri = parse_url($_SERVER['REQUEST_URI']);
// Build new param
$newParam = 'filter['.$field.'][]='.$item;
// Check if params already present
if (!empty($uri['query'])) {
$params = explode('&', $uri['query']);
$params = array_unique($params);
foreach ($params as $k => $param) {
// Remove own entry
if ($newParam == urldecode($param)) {
unset($params[$k]);
$newParam = '';
}
// Remove page switcher
if (strpos($param, 'currentPage') > 0) {
unset($params[$k]);
}
// Remove hash
if (strpos($param, 'cHash') === 0) {
unset($params[$k]);
}
}
$params[] = $newParam;
$params = array_filter($params);
$uri['query'] = implode('&', $params);
$uri['query'] = !empty($uri['query']) ? '?'.$uri['query'] : '';
}
// Return finalized url
return $uri['path'].$uri['query'];
}
/**
* Build visual filter display
*
* @param $filters
*
* @return array
*/
private function getVisualsFilter($filters)
{
// Preset
$visual = [];
// Fetch title and move value to key
foreach ($filters as $field => $items) {
foreach ($items as $item) {
$myResults = new Results();
$visual[$field][$item] = $myResults->getTitleByFacet($field, $item);
}
}
return $visual;
}
} }
<?php
namespace Lu\LuSearch\Domain\Model;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
/**
* Class Results
*
* @package Lu\LuSearch\Domain\Model
*/
class Results
{
/**
* Fetch title by uid and field
*
* @param $field
* @param $uid
*
* @return mixed|string
*/
public function getTitleByFacet($field, $uid)
{
// Fetch titles
switch ($field) {
case 'category':
// Fetch category name
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_category')->createQueryBuilder();
$row = $queryBuilder
->select('title')
->from('sys_category')->where(
$queryBuilder->expr()->eq('uid', $uid)
)
->execute()->fetch();
break;
case 'tag':
// Fetch category name
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_news_domain_model_tag')->createQueryBuilder();
$row = $queryBuilder
->select('title')
->from('tx_news_domain_model_tag')->where(
$queryBuilder->expr()->eq('uid', $uid)
)
->execute()->fetch();
break;
}
// Return
return $row['title'] ?? $uid;
}
}
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this