SearchController.php 24.6 KB
Newer Older
Dainis Abols's avatar
Dainis Abols committed
1
2
3
4
5
<?php

namespace Lu\LuSearch\Controller;

use Lu\LuApi\DataSources\SolrSearch;
6
7
8
9
use Lu\LuSearch\Domain\Model\Course;
use Lu\LuSearch\Domain\Model\CourseContinue;
use Lu\LuSearch\Domain\Model\Programme;
use Lu\LuSearch\Domain\Model\ProgrammeContinue;
10
use Lu\LuSearch\Domain\Model\Results;
Dainis Abols's avatar
Dainis Abols committed
11
use Lu\LuSearch\Helpers\DataHelper;
12
13
use TYPO3\CMS\Beuser\Domain\Model\BackendUser;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
Dainis Abols's avatar
Dainis Abols committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;

/**
 * Class SearchController
 *
 * @author  Dainis Abols <dainis.abols@lu.lv>
 * @owner   University of Latvia
 * @version 1.0.0
 * @since   02.09.2020
 *
 * @package Lu\LuSearch\Controller
 */
class SearchController extends ActionController
{
    /**
     * Frontend-Session
     *
     * @var \Lu\LuSearch\Domain\Session\FrontendSessionHandler
     */
    protected $frontendSession;

    /**
     * Frontend- or Backend-Session
     * The type of session is set automatically in initializeAction().
     *
     * @var \Lu\LuSearch\Domain\Session\SessionHandler
     */
    protected $session;

    /**
     * Main language array
     *
     * @var array
     */
    private $language;

    /**
     * Uri Builder object
     *
     * @var \TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder
     */
    private $uri_builder;

    /**
     * Selected page number
     *
     * @var int
     */
    private $currentPage;

    /**
     * Define pagination limit
     *
     * @var int
     */
77
    private $limit = 10;
Dainis Abols's avatar
Dainis Abols committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

    /**
     * Parent IDs
     *
     * @var array
     */
    private $parentIDs = [];

    /**
     * MusicController constructor.
     *
     * Assign page ID
     */
    public function __construct()
    {
93
94
        global $GLOBALS;

Dainis Abols's avatar
Dainis Abols committed
95
        // Set language data
96
97
98
99
100
101
102
103
        $context           = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Context\Context::class);
        $currentLanguageId = $context->getPropertyFromAspect('language', 'id');
        if (!empty($GLOBALS['TSFE']->site)) {
            $currentLanguage = $GLOBALS['TSFE']->site->getLanguages()[$currentLanguageId];
        } else {
            $currentLanguage = $GLOBALS['TYPO3_REQUEST']->getAttribute('language');
        }

Dainis Abols's avatar
Dainis Abols committed
104
        $this->language = [
105
106
107
108
            'id'   => $currentLanguageId,
            'name' => $currentLanguage->getTitle(),
            'iso'  => strtolower($currentLanguage->getTwoLetterIsoCode()) ?? 'en',
            'code' => strtolower($currentLanguage->getTwoLetterIsoCode()) ?? 'en',
Dainis Abols's avatar
Dainis Abols committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        ];

        // Set uri builder
        $this->uri_builder = GeneralUtility::makeInstance(UriBuilder::class)->setCreateAbsoluteUri(true)->reset();
    }

    /**
     * List Action
     * Build search field and displays results.
     *
     * /search?query=<query-string>
     *
     * @return void
     */
    public function listAction()
    {
        // Pre-define variables
126
127
        $data        = [];
        $request     = $_REQUEST;
128
        $currentPage = $request["tx_lusearch_pi1"]['@widget_0']['currentPage'];
Dainis Abols's avatar
Dainis Abols committed
129

130
131
132
133
134
135
136
137
138
139
140
141
142
143
        // Check queries
        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);
            }
Dainis Abols's avatar
Dainis Abols committed
144
        }
Dainis Abols's avatar
Dainis Abols committed
145

146
        // Find page tree if limit set
Dainis Abols's avatar
Dainis Abols committed
147
148
        if ($this->settings['limitToDomain']) {
            // Get page record for tree starting point
149
            $this->parentIDs = @$this->buildTree($this->getParentSite($GLOBALS['TSFE']->id)->getRootPageId());
Dainis Abols's avatar
Dainis Abols committed
150
151
152
        }

        // Get current page @FIXME There has to be a better way!
153
        $this->currentPage = !empty($currentPage) ? (int)$currentPage : 1;
Dainis Abols's avatar
Dainis Abols committed
154
155
156
157
158

        // Fetch data from SOLR
        $cleanQuery = strip_tags($request['query']);
        $cleanQuery = strlen($cleanQuery) >= 3 ? $cleanQuery : '';
        if ($cleanQuery) {
159
160
            $data       = $this->listResults($request);
            $dataFacets = $this->listResults($request, true);
Dainis Abols's avatar
Dainis Abols committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        }

        // Add highlighting
        $singleTranslate = false;
        if ($data['numFound'] > 0 || $data['response']['numFound'] > 0) {
            $numRows = $data['numFound'] > 0 ? $data['numFound'] : $data['response']['numFound'];

            $results = $this->buildResult($data, $cleanQuery);
            $this->view->assign('results', $results);

            // Set what type of text to use (Latvian number formats only)
            if (substr($numRows, -1) == 1 && substr($numRows, -2) != 11) {
                $singleTranslate = true;
            }

            // Add paginate object
            $data['paginate'] = [];
            for ($k = 0; $k < $numRows; $k++) {
                $data['paginate'][] = $k;
            }
        }

        // Add custom JS
        $this->renderJs();

        // Assign variables
        $this->view->assign('query', $cleanQuery);
188
        $this->view->assign('orderBy', $request['orderBy']);
Dainis Abols's avatar
Dainis Abols committed
189
190
191
192
193
        $this->view->assign('currentPage', $this->currentPage);
        $this->view->assign('singleTranslate', $singleTranslate);
        $this->view->assign('pageId', $GLOBALS['TSFE']->id);
        $this->view->assign('language', $this->language);
        $this->view->assign('newsPageId', $this->language);
194
        $this->view->assign('pageLimit', $this->limit);
Dainis Abols's avatar
Dainis Abols committed
195
196

        // Assign final data element to view
197
198
199
200
        $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);
201
202
        $facets_names = $this->getFacetSlugs($facets);
        $this->view->assign('facets_names', $facets_names);
203

Dainis Abols's avatar
Dainis Abols committed
204
205
206
207
208
209
210
211
212
213
214
215
        $this->view->assign('data', $data);
    }

    /**
     * Searches in
     * (title:<query> OR author:<query>OR body:<query>)
     *
     * Adds type, based on settings
     * (type:news OR ...)
     *
     * @param $query
     */
216
    private function listResults($request, $withFacets = false)
Dainis Abols's avatar
Dainis Abols committed
217
218
219
    {
        // Pre-set models and values
        $dataHelper = new DataHelper();
220
        $query      = mb_strtolower($request['query']);
221
        $orderBy    = $request['orderBy'];
Dainis Abols's avatar
Dainis Abols committed
222
223
224
225
226

        // Search in SOLR
        $solr = new SolrSearch();
        $solr->setLimit($this->limit);
        $solr->setOffset(($this->currentPage - 1) * $this->limit);
227
        $solr->setLanguage($this->language['iso']);
228
229
230
231
232
233
234
235
236
237
238
239
        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);
            }
        }
Dainis Abols's avatar
Dainis Abols committed
240
241

        // Set filters
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
        if ($query) {
            // Save OR requests!
            $query = str_replace(" or ", "||", $query);
            $query = str_replace(" ", " AND ", $query);
            $query = str_replace("||", " or ", $query);

            // Title field CAN NOT be empty
            $filters = [
                'id:('.$query.')',
                'uid:('.$query.')',
                'parent_id:('.$query.')',
                'title:('.$query.')',
                'title_clean:('.$query.')',
                'author:('.$query.')',
                'author_clean:('.$query.')',
                'body:('.$query.')',
                'body_clean:('.$query.')',
            ];
        }
Dainis Abols's avatar
Dainis Abols committed
261
262
263
264
265
266
267
268
269
270
271
272
273
        $solr->setFilters($filters);

        // Set parent IDs
        $solr->setParentIDs($this->parentIDs);

        // Set types
        $types = [];
        if ($this->settings['searchNews']) {
            $types[] = 'type:news';
        }
        if ($this->settings['searchContent']) {
            $types[] = 'type:content';
        }
274
275
276
277
278
        if ($this->settings['searchContacts']) {
            $types[] = 'type:contact';
        }
        if ($this->settings['searchEvents']) {
            $types[] = 'type:event';
Dainis Abols's avatar
Dainis Abols committed
279
        }
280
281
282
283
284
285
286
287
288
289
290
291
292
        if ($this->settings['searchCourse']) {
            $types[] = 'type:course';
        }
        if ($this->settings['searchCourseContinue']) {
            $types[] = 'type:course_continue';
        }
        if ($this->settings['searchProgram']) {
            $types[] = 'type:program';
        }
        if ($this->settings['searchProgramContinue']) {
            $types[] = 'type:program_continue';
        }

Dainis Abols's avatar
Dainis Abols committed
293
294
        $solr->setTypes($types);

295
296
297
        // Set order
        $solr->setOrder($orderBy);

Dainis Abols's avatar
Dainis Abols committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
        // Fetch data
        $jsonData = $solr->fetch(true);
        $result   = $dataHelper->APIDecode($jsonData);

        return $result;
    }

    /**
     * Build results array for use in multiple paginations
     *
     * @param $data
     * @param $cleanQuery
     *
     * @return array
     */
    private function buildResult($data, $cleanQuery)
    {
        // Fetch variables for easier overview
        $response  = $data['response'] ?? $data;
        $highlight = $data['highlighting'] ?? [];

        // Build response array
        $result = [
            'recordsTotal'       => "<span class=\"searchResults__queryCountNum\">".$response['numFound']."</span>",
            'recordsTotal_clean' => $response['numFound'],
            'recordsFiltered'    => count($response['docs']),
            'pageTotal'          => ceil($response['numFound'] / $this->limit),
            'pageCurrent'        => $this->currentPage,
            'data'               => [],
        ];

        // Add data info
        foreach ($response['docs'] as $item) {
            // Set site data
            $siteData = $this->getParentSite($item['parent_id']);

            // Fetch data
335
            $id      = $item['uid'];
336
337
            $uid     = str_replace($item['type'].'-', '', $item['id']);
            $title   = $highlight[$item['id']]['title'][0] ?? $this->clearAndHighlight($item['title'], $cleanQuery, false);
Dainis Abols's avatar
Dainis Abols committed
338
339
340
341
342
343
344
            $siteUrl = !empty($siteData) ? 'https://'.$siteData->getBase()->getHost() : '';
            if (empty($title)) {
                // If title is not still set, try to get parent page title
                $title = $this->getPageTitle($item['parent_id']);
            }
            $image = !empty($siteData) ? $this->addNewsImage((int)$uid) : '';
            if (empty($image)) {
345
                // If still empty, check page images recursively
Dainis Abols's avatar
Dainis Abols committed
346
347
348
349
350
                $image = $this->getParentImage($item['parent_id']);
            }

            // Add values to array
            $result['data'][] = [
351
                'id'             => $id,
Dainis Abols's avatar
Dainis Abols committed
352
353
354
355
356
357
358
                'uid'            => $uid,
                'parent_id'      => $item['parent_id'],
                'type'           => $item['type'],
                'date_published' => $item['date_published'],
                'author'         => $highlight[$item['id']]['author'][0] ?? $this->clearAndHighlight($item['author'], $cleanQuery),
                'title'          => $title,
                'body'           => $highlight[$item['id']]['body'][0] ?? $this->clearAndHighlight($item['body'], $cleanQuery),
359
                'body_original'  => $item['body'],
Dainis Abols's avatar
Dainis Abols committed
360
361
362
363
364
365
366
367
                'siteName'       => !empty($siteData) ? $this->getSiteName($siteData->getRootPageId()) : '',
                'siteUrl'        => $siteUrl,
                'newsId'         => !empty($siteData) ? $this->addNewsIds($siteData->getRootPageId()) : '',
                'calendarId'     => !empty($siteData) ? $this->addCalendarId($uid) : '',
                'imgUrl'         => $image,
            ];
        }

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
        // Make type modifications
        foreach ($result['data'] as &$res) {
            switch ($res['type']) {
                case "course":
                    $res = Course::buildSearchResult($res);
                    $res['imgUrl'] = $this->getParentImage($res['parent_id']);
                    break;
                case "course_continue":
                    $res = CourseContinue::buildSearchResult($res);
                    $res['imgUrl'] = $this->getParentImage($res['parent_id']);
                    break;
                case "program":
                    $res = Programme::buildSearchResult($res);
                    $res['imgUrl'] = $this->getParentImage($res['parent_id']);
                    break;
                case "program_continue":
                    $res = ProgrammeContinue::buildSearchResult($res);
                    $res['imgUrl'] = $this->getParentImage($res['parent_id']);
                    break;
            }
        }

Dainis Abols's avatar
Dainis Abols committed
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
        // Return result
        return $result;
    }

    /**
     * Removed all tags and newlines and adds highlight to search words
     *
     * @param      $string
     * @param      $cleanQuery
     * @param bool $crop
     *
     * @return string
     */
    private function clearAndHighlight($string, $cleanQuery, $crop = true)
    {
        // Clear
        $string = trim(preg_replace('/\s\s+/', ' ', strip_tags($string)));
        if ($crop) {
            $string = substr($string, 0, strrpos(substr($string, 0, 1000), ' '));
        }

        // Highlight
        $string = preg_replace("/(".$cleanQuery.")/i", "<span class=\"searchResults__searchTerm\">$1</span>", $string);

        // Return
        return $string;
    }


    /**
     * Adds our own custom js
     */
    private function renderJs()
    {
        $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);

        // Add jQuery UI
        $pageRenderer->addCssFile("//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css");
        $pageRenderer->addJsFooterFile("//code.jquery.com/jquery-1.12.4.js");
        $pageRenderer->addJsFooterFile("//code.jquery.com/ui/1.12.1/jquery-ui.js");

        // Add own JS
        $pageRenderer->addJsFooterFile("/typo3conf/ext/lu_search/Resources/Public/JavaScript/scripts.js");
    }

    /**
     * Builds tree
     *
     * @param     $startingPoint
     * @param int $depth
     */
    public function buildTree($startingPoint, $depth = 100)
    {
443
        global $GLOBALS;
444

Dainis Abols's avatar
Dainis Abols committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        // Get page record for tree starting point
        $pageRecord = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord(
            'pages',
            $startingPoint
        );

        // Create and initialize the tree object
        /** @var $tree \TYPO3\CMS\Backend\Tree\View\PageTreeView */
        $tree = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Tree\View\PageTreeView::class);

        // Creating the icon for the current page and add it to the tree
        $tree->tree[] = [
            'row'  => $pageRecord,
            'HTML' => '',
        ];

461
        // Create the page tree, from the starting point, 2 levels deep with admin rights
462
        $GLOBALS['BE_USER']                = new BackendUserAuthentication();
463
464
465
        $GLOBALS['BE_USER']->user['admin'] = 1;
        $tree->getTree($startingPoint, $depth, '');
        $GLOBALS['BE_USER'] = null;
Dainis Abols's avatar
Dainis Abols committed
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586

        // Fetch only uids and retrn data
        $treeIds = [];
        foreach ($tree->tree as $item) {
            $treeIds[] = $item['row']['uid'];
        }

        // Return
        return $treeIds;
    }


    /**
     * Recursive method for finding site objects
     *
     * @return \array|\TYPO3\CMS\Core\Site\Entity\Site
     */
    private function getParentSite($current_id = 0)
    {
        // Get current ID if parent ID = 0
        if (!$current_id) {
            $current_id = $GLOBALS['TSFE']->id;
        }

        $parent_id = $this->getParentId($current_id);

        // Check if parent exists
        if ($parent_id < 1) {
            return [];
        }

        // Try to find site info
        try {
            $sites = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId($parent_id);
        } catch (SiteNotFoundException $e) {
            return [];
        }

        // Go up, if no site founf
        if (empty($sites)) {
            return $this->getParentSite($parent_id);
        }

        // Return site data
        return $sites;
    }

    /**
     * Fetch current page parent id
     *
     * @param $current_id
     *
     * @return int
     */
    private function getParentId($current_id): int
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages')->createQueryBuilder();

        return (int)$queryBuilder->select('pid')->from('pages')->where(
            $queryBuilder->expr()->eq('uid', $current_id)
        )->execute()->fetchColumn(0);
    }

    /**
     * Fetch page title
     *
     * @param $uid
     *
     * @return string
     */
    private function getSiteName(int $uid): string
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages')->createQueryBuilder();

        return (string)$queryBuilder->select('title')->from('pages')->where(
            $queryBuilder->expr()->eq('uid', $uid)
        )->execute()->fetchColumn(0);
    }

    /**
     * Get constants entry by root page id
     *
     * @param $rootPageId
     */
    private function addNewsIds($rootPageId)
    {
        // SELECT constants FROM `sys_template` WHERE pid = 468 AND deleted = 0
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('sys_template')->createQueryBuilder();

        $statement = $queryBuilder->select('constants')->from('sys_template')->where(
            $queryBuilder->expr()->eq('pid', $rootPageId),
            $queryBuilder->expr()->eq('deleted', 0)
        )->execute();

        // Try finding news ID entries
        while ($row = $statement->fetch()) {
            foreach (preg_split("/((\r?\n)|(\r\n?))/", $row['constants']) as $line) {
                if (!empty($line)) {
                    $contsOptions = explode("=", $line);
                    if (trim($contsOptions[0]) == 'news.defaultDetailPid') {
                        return (int)$contsOptions[1];
                    }
                }
            }
        }

        // Return results
        return 0;
    }

    /**
     * Fetch news image, if available
     *
     * @param $uid
     *
     * @return string
     */
    private function addNewsImage($uid)
    {
        // Fetch image from storage
        $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
587
        $fileObjects    = $fileRepository->findByRelation('tx_news_domain_model_news', 'fal_media', $uid);
Dainis Abols's avatar
Dainis Abols committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609

        // Build image
        if (!empty($fileObjects)) {
            foreach ($fileObjects as $fileRef) {
                // Check if allowed list view
                if ($fileRef->getProperties()['showinpreview']) {
                    return $this->getPublicPath($fileRef);
                }
            }
        }

        // Return empty
        return '';
    }

    /**
     * Fetch page title by id
     *
     * @param $page_id
     *
     * @return string
     */
610
611
    private function getPageTitle($page_id)
    {
Dainis Abols's avatar
Dainis Abols committed
612
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('page')->createQueryBuilder();
613
        $statement    = $queryBuilder->select('title', 'slug')->from('pages')->where(
Dainis Abols's avatar
Dainis Abols committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
            $queryBuilder->expr()->eq('uid', $page_id),
        )->execute();

        // Get info
        $result = $statement->fetch();

        return $result['title'];
    }

    /**
     * Return public path
     *
     * @param $fileRef
     *
     * @return string
     */
    private function getPublicPath($fileRef)
    {
        return $fileRef->getStorage()->getConfiguration()['basePath'].$fileRef->getIdentifier();
    }

    /**
     * Recursivly retrieve title image
     *
     * @param $uid
     *
     * @return string
     */
    private function getParentImage($uid)
    {
        // Fetch image from storage
        $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
646
        $fileObjects    = $fileRepository->findByRelation('pages', 'media', $uid);
Dainis Abols's avatar
Dainis Abols committed
647
648
649
650

        // Fetch level up
        if (empty($fileObjects)) {
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('page')->createQueryBuilder();
651
            $statement    = $queryBuilder->select('pid')->from('pages')->where(
Dainis Abols's avatar
Dainis Abols committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
                $queryBuilder->expr()->eq('uid', $uid),
            )->execute();

            $result = $statement->fetch();
            if (empty($result)) {
                return '';
            }

            // Call level up
            return $this->getParentImage($result['pid']);
        }

        // Build first element image
        return $this->getPublicPath($fileObjects[0]);

667
    }
Dainis Abols's avatar
Dainis Abols committed
668

669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
    private function addCalendarId($uid)
    {
        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],
696
                            'visual' => ($items[$k] > 0) ? $myResults->getTitleByFacet($field, $items[$k]) : $items[$k],
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
                            '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;
    }
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806

    /**
     * Convert string to basic slug
     *
     * @param $facets
     *
     * @return array
     */
    private function getFacetSlugs($facets)
    {
        $slugs = [];
        foreach($facets as $facet) {
            foreach($facet['items'] as $item) {
                $delimiter = '_';
                $str = $item['name'];
                $slugs[$item['name']] = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
            }
        }

        return $slugs;
    }
Dainis Abols's avatar
Dainis Abols committed
807
}