• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tomasnorre / crawler / 4092880773

pending completion
4092880773

push

github

GitHub
[TASK] Cleanup BackendModule Controllers (#1005)

246 of 246 new or added lines in 9 files covered. (100.0%)

1778 of 2545 relevant lines covered (69.86%)

3.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/Classes/Controller/Backend/BackendModuleStartCrawlingController.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace AOE\Crawler\Controller\Backend;
6

7
/*
8
 * (c) 2022-     Tomas Norre Mikkelsen <tomasnorre@gmail.com>
9
 *
10
 * This file is part of the TYPO3 Crawler Extension.
11
 *
12
 * It is free software; you can redistribute it and/or modify it under
13
 * the terms of the GNU General Public License, either version 2
14
 * of the License, or any later version.
15
 *
16
 * For the full copyright and license information, please read the
17
 * LICENSE.txt file that was distributed with this source code.
18
 *
19
 * The TYPO3 project - inspiring people to share!
20
 */
21

22
use AOE\Crawler\Controller\Backend\Helper\UrlBuilder;
23
use AOE\Crawler\Controller\CrawlerController;
24
use AOE\Crawler\Domain\Model\Reason;
25
use AOE\Crawler\Event\InvokeQueueChangeEvent;
26
use AOE\Crawler\Utility\MessageUtility;
27
use Psr\Http\Message\ResponseInterface;
28
use Psr\Http\Message\ServerRequestInterface;
29
use Symfony\Contracts\Service\Attribute\Required;
30
use TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException;
31
use TYPO3\CMS\Backend\Routing\UriBuilder;
32
use TYPO3\CMS\Backend\Template\ModuleTemplate;
33
use TYPO3\CMS\Core\EventDispatcher\EventDispatcher;
34
use TYPO3\CMS\Core\Http\Uri;
35
use TYPO3\CMS\Core\Utility\GeneralUtility;
36

37
/**
38
 * @internal since v12.0.0
39
 */
40
class BackendModuleStartCrawlingController extends AbstractBackendModuleController implements BackendModuleControllerInterface
41
{
42
    private const BACKEND_MODULE = 'web_site_crawler_start';
43
    private const LINE_FEED = 10;
44
    private const CARRIAGE_RETURN = 13;
45
    private int $reqMinute = 1000;
46
    private EventDispatcher $eventDispatcher;
47

48
    /**
49
     * @var array holds the selection of configuration from the configuration selector box
50
     */
51
    private $incomingConfigurationSelection = [];
52

53
    public function __construct(
54
        private readonly CrawlerController $crawlerController,
55
        private readonly UriBuilder $backendUriBuilder,
56
    ) {
57
    }
×
58

59
    #[Required]
60
    public function setEventDispatcher(): void
61
    {
62
        $this->eventDispatcher = GeneralUtility::makeInstance(EventDispatcher::class);
×
63
    }
64

65
    public function handleRequest(ServerRequestInterface $request): ResponseInterface
66
    {
67
        $this->makeCrawlerProcessableChecks($this->extensionSettings);
×
68
        $this->pageUid = (int) ($request->getQueryParams()['id'] ?? -1);
×
69
        $this->moduleTemplate = $this->setupView($request, $this->pageUid);
×
70
        $this->moduleTemplate->makeDocHeaderModuleMenu(['id' => $request->getQueryParams()['id'] ?? -1]);
×
71

72
        $this->assignValues();
×
73
        return $this->moduleTemplate->renderResponse('Backend/ShowCrawlerInformation');
×
74
    }
75

76
    private function assignValues(): ModuleTemplate
77
    {
78
        $logUrl = $this->backendUriBuilder->buildUriFromRoute('web_site_crawler_log', ['id' => $this->pageUid]);
×
79

80
        $crawlingDepth = GeneralUtility::_GP('crawlingDepth') ?? '0';
×
81
        $crawlParameter = GeneralUtility::_GP('_crawl');
×
82
        $downloadParameter = GeneralUtility::_GP('_download');
×
83
        $scheduledTime = $this->getScheduledTime((string) GeneralUtility::_GP('tstamp'));
×
84
        $submitCrawlUrls = isset($crawlParameter);
×
85
        $downloadCrawlUrls = isset($downloadParameter);
×
86

87
        $this->incomingConfigurationSelection = GeneralUtility::_GP('configurationSelection');
×
88
        $this->incomingConfigurationSelection = is_array(
×
89
            $this->incomingConfigurationSelection
×
90
        ) ? $this->incomingConfigurationSelection : [];
×
91

92
        //$this->crawlerController = $this->getCrawlerController();
93
        $this->crawlerController->setID = GeneralUtility::md5int(microtime());
×
94

95
        $queueRows = '';
×
96
        $noConfigurationSelected = empty($this->incomingConfigurationSelection)
×
97
            || (count($this->incomingConfigurationSelection) === 1 && empty($this->incomingConfigurationSelection[0]));
×
98
        if ($noConfigurationSelected) {
×
99
            MessageUtility::addWarningMessage(
×
100
                $this->getLanguageService()->sL(
×
101
                    'LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.noConfigSelected'
×
102
                )
×
103
            );
×
104
        } else {
105
            if ($submitCrawlUrls) {
×
106
                $reason = new Reason();
×
107
                $reason->setReason(Reason::REASON_GUI_SUBMIT);
×
108
                $reason->setDetailText(
×
109
                    'The user ' . $GLOBALS['BE_USER']->user['username'] . ' added pages to the crawler queue manually'
×
110
                );
×
111
                $this->eventDispatcher->dispatch(new InvokeQueueChangeEvent($reason));
×
112
            }
113

114
            $queueRows = $this->crawlerController->getPageTreeAndUrls(
×
115
                $this->pageUid,
×
116
                $crawlingDepth,
×
117
                $scheduledTime,
×
118
                $this->reqMinute,
×
119
                $submitCrawlUrls,
×
120
                $downloadCrawlUrls,
×
121
                // Do not filter any processing instructions
122
                [],
×
123
                $this->incomingConfigurationSelection
×
124
            );
×
125
        }
126

127
        // Download Urls to crawl:
128
        $downloadUrls = $this->crawlerController->downloadUrls;
×
129
        if ($downloadCrawlUrls) {
×
130
            // Creating output header:
131
            header('Content-Type: application/octet-stream');
×
132
            header('Content-Disposition: attachment; filename=CrawlerUrls.txt');
×
133

134
            // Printing the content of the CSV lines:
135
            echo implode(chr(self::CARRIAGE_RETURN) . chr(self::LINE_FEED), $downloadUrls);
×
136
            exit;
×
137
        }
138

139
        return $this->moduleTemplate->assignMultiple([
×
140
            'currentPageId' => $this->pageUid,
×
141
            'noConfigurationSelected' => $noConfigurationSelected,
×
142
            'submitCrawlUrls' => $submitCrawlUrls,
×
143
            'amountOfUrls' => count($this->crawlerController->duplicateTrack ?? []),
×
144
            'selectors' => $this->generateConfigurationSelectors($this->pageUid, $crawlingDepth),
×
145
            'queueRows' => $queueRows,
×
146
            'displayActions' => 0,
×
147
            'actionUrl' => $this->getActionUrl(),
×
148
            'logUrl' => $logUrl,
×
149
        ]);
×
150
    }
151
    
152
    /**
153
     * Generates the configuration selectors for compiling URLs:
154
     */
155
    private function generateConfigurationSelectors(int $pageId, string $crawlingDepth): array
156
    {
157
        $selectors = [];
×
158
        $selectors['depth'] = $this->selectorBox(
×
159
            [
×
160
                0 => $this->getLanguageService()->sL(
×
161
                    'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.depth_0'
×
162
                ),
×
163
                1 => $this->getLanguageService()->sL(
×
164
                    'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.depth_1'
×
165
                ),
×
166
                2 => $this->getLanguageService()->sL(
×
167
                    'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.depth_2'
×
168
                ),
×
169
                3 => $this->getLanguageService()->sL(
×
170
                    'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.depth_3'
×
171
                ),
×
172
                4 => $this->getLanguageService()->sL(
×
173
                    'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.depth_4'
×
174
                ),
×
175
                99 => $this->getLanguageService()->sL(
×
176
                    'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.depth_infi'
×
177
                ),
×
178
            ],
×
179
            'crawlingDepth',
×
180
            $crawlingDepth,
×
181
            false
×
182
        );
×
183

184
        // Configurations
185
        $availableConfigurations = $this->crawlerController->getConfigurationsForBranch(
×
186
            $pageId,
×
187
            (int) $crawlingDepth,
×
188
        );
×
189
        $selectors['configurations'] = $this->selectorBox(
×
190
            empty($availableConfigurations) ? [] : array_combine($availableConfigurations, $availableConfigurations),
×
191
            'configurationSelection',
×
192
            $this->incomingConfigurationSelection,
×
193
            true
×
194
        );
×
195

196
        // Scheduled time:
197
        $selectors['scheduled'] = $this->selectorBox(
×
198
            [
×
199
                'now' => $this->getLanguageService()->sL(
×
200
                    'LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.time.now'
×
201
                ),
×
202
                'midnight' => $this->getLanguageService()->sL(
×
203
                    'LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.time.midnight'
×
204
                ),
×
205
                '04:00' => $this->getLanguageService()->sL(
×
206
                    'LLL:EXT:crawler/Resources/Private/Language/locallang.xlf:labels.time.4am'
×
207
                ),
×
208
            ],
×
209
            'tstamp',
×
210
            GeneralUtility::_POST('tstamp'),
×
211
            false
×
212
        );
×
213

214
        return $selectors;
×
215
    }
216

217
    /**
218
     * Create selector box
219
     *
220
     * @param array $optArray Options key(value) => label pairs
221
     * @param string $name Selector box name
222
     * @param string|array|null $value Selector box value (array for multiple...)
223
     * @param boolean $multiple If set, will draw multiple box.
224
     *
225
     * @return string HTML select element
226
     */
227
    private function selectorBox($optArray, $name, string|array|null $value, bool $multiple): string
228
    {
229
        if (!is_string($value) || !is_array($value)) {
×
230
            $value = '';
×
231
        }
232

233
        $options = [];
×
234
        foreach ($optArray as $key => $val) {
×
235
            $selected = (!$multiple && !strcmp($value, (string) $key)) || ($multiple && in_array(
×
236
                $key,
×
237
                (array) $value,
×
238
                true
×
239
            ));
×
240
            $options[] = '
×
241
                <option value="' . $key . '" ' . ($selected ? ' selected="selected"' : '') . '>' . htmlspecialchars(
×
242
                (string) $val,
×
243
                ENT_QUOTES | ENT_HTML5
×
244
            ) . '</option>';
×
245
        }
246

247
        return '<select class="form-control" name="' . htmlspecialchars(
×
248
            $name . ($multiple ? '[]' : ''),
×
249
            ENT_QUOTES | ENT_HTML5
×
250
        ) . '"' . ($multiple ? ' multiple' : '') . '>' . implode('', $options) . '</select>';
×
251
    }
252

253
    private function getScheduledTime(string $time): float|int
254
    {
255
        $scheduledTime = match ($time) {
×
256
            'midnight' => mktime(0, 0, 0),
×
257
            '04:00' => mktime(0, 0, 0) + 4 * 3600,
×
258
            default => time(),
×
259
        };
×
260

261
        if (!$scheduledTime) {
×
262
            return time();
×
263
        }
264

265
        return $scheduledTime;
×
266
    }
267

268
    /**
269
     * @throws RouteNotFoundException
270
     */
271
    private function getActionUrl(): Uri
272
    {
273
        return GeneralUtility::makeInstance(UrlBuilder::class)->getBackendModuleUrl([], self::BACKEND_MODULE);
×
274
    }
275
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc