Passed
Push — master ( 4ea91f...651b75 )
by Timo
56:50 queued 47:41
created

AbstractModuleController::injectStringHelper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
namespace ApacheSolrForTypo3\Solr\Controller\Backend\Search;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2010-2017 dkd Internet Service GmbH <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 2 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\Domain\Site\SiteRepository;
28
use ApacheSolrForTypo3\Solr\Site;
29
use ApacheSolrForTypo3\Solr\SolrService as SolrCoreConnection;
30
use ApacheSolrForTypo3\Solr\System\Mvc\Backend\Component\Exception\InvalidViewObjectNameException;
31
use ApacheSolrForTypo3\Solr\Utility\StringUtility;
32
use TYPO3\CMS\Backend\Template\Components\Menu\Menu;
33
use TYPO3\CMS\Backend\Utility\BackendUtility;
34
use TYPO3\CMS\Backend\View\BackendTemplateView;
35
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
36
use TYPO3\CMS\Core\Messaging\AbstractMessage;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
39
use TYPO3\CMS\Extbase\Mvc\View\NotFoundView;
40
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
41
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
42
43
/**
44
 * Abstract Module
45
 *
46
 * @property BackendTemplateView $view
47
 */
48
abstract class AbstractModuleController extends ActionController
49
{
50
    /**
51
     * Backend Template Container
52
     *
53
     * @var string
54
     */
55
    protected $defaultViewObjectName = BackendTemplateView::class;
56
57
    /**
58
     * In the pagetree selected page UID
59
     *
60
     * @var int
61
     */
62
    protected $selectedPageUID;
63
64
    /**
65
     * @var SiteRepository
66
     */
67
    protected $siteRepository;
68
    /**
69
     * @var Site
70
     */
71
    protected $selectedSite;
72
73
    /**
74
     * @var SolrCoreConnection
75
     */
76
    protected $selectedSolrCoreConnection;
77
78
    /**
79
     * @var Menu
80
     */
81
    protected $coreSelectorMenu = null;
82
83
    /**
84
     * @var \ApacheSolrForTypo3\Solr\ConnectionManager
85
     * @inject
86
     */
87
    protected $solrConnectionManager = null;
88
89
    /**
90
     * @var \ApacheSolrForTypo3\Solr\System\Mvc\Backend\Service\ModuleDataStorageService
91
     * @inject
92
     */
93
    protected $moduleDataStorageService = null;
94
95
    /**
96
     * Initializes the controller and sets needed vars.
97
     */
98
    protected function initializeAction()
99
    {
100
        parent::initializeAction();
101
        $this->selectedPageUID = (int)GeneralUtility::_GP('id');
102
        if ($this->request->hasArgument('id')) {
103
            $this->selectedPageUID = (int)$this->request->getArgument('id');
104
        }
105
106
        if ($this->selectedPageUID < 1) {
107
            return;
108
        }
109
110
        $this->siteRepository = $this->objectManager->get(SiteRepository::class);
111
112
        try {
113
            $this->selectedSite = $this->siteRepository->getSiteByPageId($this->selectedPageUID);
114
        } catch (\InvalidArgumentException $exception) {
115
            return;
116
        }
117
    }
118
119
    /**
120
     * Set up the doc header properly here
121
     *
122
     * @param ViewInterface $view
123
     * @return void
124
     */
125
    protected function initializeView(ViewInterface $view)
126
    {
127
        parent::initializeView($view);
128
        $this->view->assign('pageUID', $this->selectedPageUID);
129
        if ($view instanceof NotFoundView || $this->selectedPageUID < 1) {
130
            return;
131
        }
132
        $this->view->getModuleTemplate()->addJavaScriptCode('mainJsFunctions', '
133
                top.fsMod.recentIds["searchbackend"] = ' . (int)$this->selectedPageUID . ';'
134
        );
135
        if (null === $this->selectedSite) {
136
            return;
137
        }
138
139
        /* @var BackendUserAuthentication $beUser */
140
        $beUser = $GLOBALS['BE_USER'];
141
        $permissionClause = $beUser->getPagePermsClause(1);
142
        $pageRecord = BackendUtility::readPageAccess($this->selectedSite->getRootPageId(), $permissionClause);
143
144
        if (false === $pageRecord) {
145
            throw new \InvalidArgumentException(vsprintf('There is something wrong with permissions for page "%s" for backend user "%s".', [$this->selectedSite->getRootPageId(), $beUser->user['username']]), 1496146317);
146
        }
147
        $this->view->getModuleTemplate()->getDocHeaderComponent()->setMetaInformation($pageRecord);
148
    }
149
150
    /**
151
     * Generates selector menu in backends doc header using selected page from page tree.
152
     *
153
     * @param string|null $uriToRedirectTo
154
     */
155
    public function generateCoreSelectorMenuUsingPageTree(string $uriToRedirectTo = null)
156
    {
157
        if ($this->selectedPageUID < 1 || null === $this->selectedSite) {
158
            return;
159
        }
160
161
        if ($this->view instanceof NotFoundView) {
162
            $this->initializeSelectedSolrCoreConnection();
163
            return;
164
        }
165
166
        $this->generateCoreSelectorMenu($this->selectedSite, $uriToRedirectTo);
167
    }
168
169
    /**
170
     * Generates Core selector Menu for given Site.
171
     *
172
     * @param Site $site
173
     * @param string|null $uriToRedirectTo
174
     * @throws InvalidViewObjectNameException
175
     */
176
    protected function generateCoreSelectorMenu(Site $site, string $uriToRedirectTo = null)
177
    {
178
        if (!$this->view instanceof BackendTemplateView) {
179
            throw new InvalidViewObjectNameException(vsprintf(
180
                'The controller "%s" must use BackendTemplateView to be able to generate menu for backends docheader. \
181
                Please set `protected $defaultViewObjectName = BackendTemplateView::class;` field in your controller.',
182
                [static::class]), 1493804179);
183
        }
184
        $this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
185
186
        $this->coreSelectorMenu = $this->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
187
        $this->coreSelectorMenu->setIdentifier('component_core_selector_menu');
188
189
        if (!isset($uriToRedirectTo)) {
190
            $uriToRedirectTo = $this->uriBuilder->reset()->uriFor();
191
        }
192
193
        $this->initializeSelectedSolrCoreConnection();
194
        $cores = $this->solrConnectionManager->getConnectionsBySite($site);
195
        foreach ($cores as $core) {
196
            $menuItem = $this->coreSelectorMenu->makeMenuItem();
197
            $menuItem->setTitle($core->getPath());
198
            $uri = $this->uriBuilder->reset()->uriFor('switchCore',
199
                [
200
                    'corePath' => $core->getPath(),
201
                    'uriToRedirectTo' => $uriToRedirectTo
202
                ]
203
            );
204
            $menuItem->setHref($uri);
205
206
            if ($core->getPath() == $this->selectedSolrCoreConnection->getPath()) {
207
                $menuItem->setActive(true);
208
            }
209
            $this->coreSelectorMenu->addMenuItem($menuItem);
210
        }
211
212
        $this->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->addMenu($this->coreSelectorMenu);
213
    }
214
215
    /**
216
     * Switches used core.
217
     *
218
     * Note: Does not check availability of core in site. All this stuff is done in the generation step.
219
     *
220
     * @param string $corePath
221
     * @param string $uriToRedirectTo
222
     */
223
    public function switchCoreAction(string $corePath, string $uriToRedirectTo)
224
    {
225
        $moduleData = $this->moduleDataStorageService->loadModuleData();
226
        $moduleData->setCore($corePath);
227
228
        $this->moduleDataStorageService->persistModuleData($moduleData);
229
        $message = LocalizationUtility::translate('coreselector_switched_successfully', 'solr', [$corePath]);
230
        $this->addFlashMessage($message);
231
        $this->redirectToUri($uriToRedirectTo);
232
    }
233
234
    /**
235
     * Initializes the solr core connection considerately to the components state.
236
     * Uses and persists default core connection if persisted core in Site does not exist.
237
     *
238
     */
239
    private function initializeSelectedSolrCoreConnection()
240
    {
241
        $moduleData = $this->moduleDataStorageService->loadModuleData();
242
243
        $solrCoreConnections = $this->solrConnectionManager->getConnectionsBySite($this->selectedSite);
244
        $currentSolrCorePath = $moduleData->getCore();
245
        if (empty($currentSolrCorePath)) {
246
            $this->initializeFirstAvailableSolrCoreConnection($solrCoreConnections, $moduleData);
247
            return;
248
        }
249
        foreach ($solrCoreConnections as $solrCoreConnection) {
250
            if ($solrCoreConnection->getPath() == $currentSolrCorePath) {
251
                $this->selectedSolrCoreConnection = $solrCoreConnection;
252
            }
253
        }
254
        if (!$this->selectedSolrCoreConnection instanceof SolrCoreConnection && count($solrCoreConnections) > 0) {
255
            $this->initializeFirstAvailableSolrCoreConnection($solrCoreConnections, $moduleData);
256
            $message = LocalizationUtility::translate('coreselector_switched_to_default_core', 'solr', [$currentSolrCorePath, $this->selectedSite->getLabel(), $this->selectedSolrCoreConnection->getPath()]);
257
            $this->addFlashMessage($message, '', AbstractMessage::NOTICE);
258
        }
259
    }
260
261
    /**
262
     * @param SolrCoreConnection[] $solrCoreConnections
263
     */
264
    private function initializeFirstAvailableSolrCoreConnection(array $solrCoreConnections, $moduleData)
265
    {
266
        if (empty($solrCoreConnections)) {
267
            return;
268
        }
269
        $this->selectedSolrCoreConnection = $solrCoreConnections[0];
270
        $moduleData->setCore($this->selectedSolrCoreConnection->getPath());
271
        $this->moduleDataStorageService->persistModuleData($moduleData);
272
    }
273
}
274