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
if (empty($request)) {
$request = $this->request->getArguments(); $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);
if ($withFacets) {
} else {
$solr->setHighlight("<span class=\"searchResults__searchTerm\">|</span>"); $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
// Fetch data // Fetch data
$jsonData = $solr->fetch(true); $jsonData = $solr->fetch(true);
$result = $dataHelper->APIDecode($jsonData); $result = $dataHelper->APIDecode($jsonData);
...@@ -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)
{ {
// 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 = [];
...@@ -511,7 +539,8 @@ class SearchController extends ActionController ...@@ -511,7 +539,8 @@ 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),
...@@ -573,4 +602,117 @@ class SearchController extends ActionController ...@@ -573,4 +602,117 @@ class SearchController extends ActionController
{ {
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)) {
$newParam = '';
// Remove page switcher
if (strpos($param, 'currentPage') > 0) {
// Remove hash
if (strpos($param, 'cHash') === 0) {
$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;
} }
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
$queryBuilder->expr()->eq('uid', $uid)
case 'tag':
// Fetch category name
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_news_domain_model_tag')->createQueryBuilder();
$row = $queryBuilder
$queryBuilder->expr()->eq('uid', $uid)
// Return
return $row['title'] ?? $uid;
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
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.
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
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.