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

tomasnorre / crawler / 17588511395

09 Sep 2025 04:01PM UTC coverage: 68.78% (+0.03%) from 68.752%
17588511395

Pull #1178

github

web-flow
Merge 8743a201f into 51ae33053
Pull Request #1178: [TASK] Cleanup CrawlerController

2 of 3 new or added lines in 1 file covered. (66.67%)

1 existing line in 1 file now uncovered.

1877 of 2729 relevant lines covered (68.78%)

3.26 hits per line

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

80.05
/Classes/Controller/CrawlerController.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace AOE\Crawler\Controller;
6

7
/*
8
 * (c) 2021 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\Configuration\ExtensionConfigurationProvider;
23
use AOE\Crawler\Converter\JsonCompatibilityConverter;
24
use AOE\Crawler\Crawler;
25
use AOE\Crawler\CrawlStrategy\CrawlStrategyFactory;
26
use AOE\Crawler\Domain\Repository\ConfigurationRepository;
27
use AOE\Crawler\Domain\Repository\ProcessRepository;
28
use AOE\Crawler\Domain\Repository\QueueRepository;
29
use AOE\Crawler\Event\AfterQueueItemAddedEvent;
30
use AOE\Crawler\Event\AfterUrlAddedToQueueEvent;
31
use AOE\Crawler\Event\BeforeQueueItemAddedEvent;
32
use AOE\Crawler\QueueExecutor;
33
use AOE\Crawler\Service\ConfigurationService;
34
use AOE\Crawler\Service\PageService;
35
use AOE\Crawler\Service\ProcessInstructionService;
36
use AOE\Crawler\Service\UrlService;
37
use AOE\Crawler\Value\QueueRow;
38
use Psr\Http\Message\UriInterface;
39
use Psr\Log\LoggerAwareInterface;
40
use Psr\Log\LoggerAwareTrait;
41
use TYPO3\CMS\Backend\Tree\View\PageTreeView;
42
use TYPO3\CMS\Backend\Utility\BackendUtility;
43
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
44
use TYPO3\CMS\Core\Core\Bootstrap;
45
use TYPO3\CMS\Core\Database\ConnectionPool;
46
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
47
use TYPO3\CMS\Core\EventDispatcher\EventDispatcher;
48
use TYPO3\CMS\Core\Imaging\Icon;
49
use TYPO3\CMS\Core\Imaging\IconFactory;
50
use TYPO3\CMS\Core\Type\Bitmask\Permission;
51
use TYPO3\CMS\Core\Utility\DebugUtility;
52
use TYPO3\CMS\Core\Utility\GeneralUtility;
53
use TYPO3\CMS\Core\Utility\MathUtility;
54

55
/**
56
 * @package AOE\Crawler\Controller
57
 * @internal since v12.0.0
58
 */
59
class CrawlerController implements LoggerAwareInterface
60
{
61
    use LoggerAwareTrait;
62

63
    public const CLI_STATUS_POLLABLE_PROCESSED = 8;
64

65
    public int $setID = 0;
66
    public string $processID = '';
67
    public array $duplicateTrack = [];
68
    public array $downloadUrls = [];
69
    public array $incomingProcInstructions = [];
70
    public array $incomingConfigurationSelection = [];
71
    public bool $registerQueueEntriesInternallyOnly = false;
72
    public array $queueEntries = [];
73
    public array $urlList = [];
74
    public array $extensionSettings = [];
75

76
    /**
77
     * Mount Point
78
     */
79
    public ?string $MP = null;
80
    protected QueueRepository $queueRepository;
81
    protected ProcessRepository $processRepository;
82
    protected ConfigurationRepository $configurationRepository;
83
    protected QueueExecutor $queueExecutor;
84
    protected int $maximumUrlsToCompile = 10000;
85
    protected IconFactory $iconFactory;
86

87
    /**
88
     * @var BackendUserAuthentication|null
89
     */
90
    private $backendUser;
91
    private int $scheduledTime = 0;
92
    private int $reqMinute = 0;
93
    private bool $submitCrawlUrls = false;
94
    private bool $downloadCrawlUrls = false;
95
    private PageRepository $pageRepository;
96
    private ConfigurationService $configurationService;
97
    private UrlService $urlService;
98
    private EventDispatcher $eventDispatcher;
99

100
    /************************************
101
     *
102
     * Getting URLs based on Page TSconfig
103
     *
104
     ************************************/
105

106
    public function __construct()
107
    {
108
        $crawlStrategyFactory = GeneralUtility::makeInstance(CrawlStrategyFactory::class);
16✔
109
        $this->queueRepository = GeneralUtility::makeInstance(QueueRepository::class);
16✔
110
        $this->processRepository = GeneralUtility::makeInstance(ProcessRepository::class);
16✔
111
        $this->configurationRepository = GeneralUtility::makeInstance(ConfigurationRepository::class);
16✔
112
        $this->pageRepository = GeneralUtility::makeInstance(PageRepository::class);
16✔
113
        $this->eventDispatcher = GeneralUtility::makeInstance(EventDispatcher::class);
16✔
114
        $this->queueExecutor = GeneralUtility::makeInstance(
16✔
115
            QueueExecutor::class,
16✔
116
            $crawlStrategyFactory,
16✔
117
            $this->eventDispatcher
16✔
118
        );
16✔
119
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
16✔
120
        GeneralUtility::makeInstance(Crawler::class);
16✔
121
        $this->configurationService = GeneralUtility::makeInstance(
16✔
122
            ConfigurationService::class,
16✔
123
            GeneralUtility::makeInstance(UrlService::class),
16✔
124
            $this->configurationRepository
16✔
125
        );
16✔
126
        $this->urlService = GeneralUtility::makeInstance(UrlService::class);
16✔
127

128
        /** @var ExtensionConfigurationProvider $configurationProvider */
129
        $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class);
16✔
130
        $this->extensionSettings = $configurationProvider->getExtensionConfiguration();
16✔
131

132
        if (MathUtility::convertToPositiveInteger($this->extensionSettings['countInARun']) === 0) {
16✔
133
            $this->extensionSettings['countInARun'] = 100;
×
134
        }
135

136
        $this->extensionSettings['processLimit'] = MathUtility::forceIntegerInRange(
16✔
137
            $this->extensionSettings['processLimit'],
16✔
138
            1,
16✔
139
            99,
16✔
140
            1
16✔
141
        );
16✔
142
        $this->setMaximumUrlsToCompile(
16✔
143
            MathUtility::forceIntegerInRange($this->extensionSettings['maxCompileUrls'], 1, 1000000000, 10000)
16✔
144
        );
16✔
145
    }
146

147
    public function setMaximumUrlsToCompile(int $maximumUrlsToCompile): void
148
    {
149
        $this->maximumUrlsToCompile = $maximumUrlsToCompile;
16✔
150
    }
151

152
    /**
153
     * Sets the extensions settings (unserialized pendant of $TYPO3_CONF_VARS['EXT']['extConf']['crawler']).
154
     */
155
    public function setExtensionSettings(array $extensionSettings): void
156
    {
157
        $this->extensionSettings = $extensionSettings;
1✔
158
    }
159

160
    /**
161
     * Wrapper method for getUrlsForPageId()
162
     * It returns an array of configurations and no urls!
163
     *
164
     * @param array $pageRow Page record with at least dok-type and uid columns.
165
     * @see getUrlsForPageId()
166
     */
167
    public function getUrlsForPageRow(array $pageRow, string &$skipMessage = ''): array
168
    {
169
        if (!isset($pageRow['uid'])) {
14✔
170
            $skipMessage = "pageRow['uid'] is missing";
1✔
171
            return [];
1✔
172
        }
173

174
        $pageRowUid = intval($pageRow['uid']);
13✔
175
        if (!$pageRowUid) {
13✔
176
            $skipMessage = 'PageUid "' . $pageRow['uid'] . '" was not an integer';
2✔
177
            return [];
2✔
178
        }
179

180
        $message = $this->getPageService()->checkIfPageShouldBeSkipped($pageRow);
11✔
181
        if ($message === false) {
11✔
182
            $res = $this->getUrlsForPageId($pageRowUid);
10✔
183
            $skipMessage = '';
10✔
184
        } else {
185
            $skipMessage = $message;
2✔
186
            $res = [];
2✔
187
        }
188

189
        return $res;
11✔
190
    }
191

192
    /**
193
     * Creates a list of URLs from input array (and submits them to queue if asked for)
194
     * See Web > Info module script + "indexed_search"'s crawler hook-client using this!
195
     *
196
     * @param array $vv Information about URLs from pageRow to crawl.
197
     * @param array $pageRow Page row
198
     * @param int $scheduledTime Unix time to schedule indexing to, typically time()
199
     * @param int $reqMinute Number of requests per minute (creates the interleave between requests)
200
     * @param bool $submitCrawlUrls If set, submits the URLs to queue
201
     * @param bool $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
202
     * @param array $duplicateTrack Array which is passed by reference and contains the an id per url to secure we will not crawl duplicates
203
     * @param array $downloadUrls Array which will be filled with URLS for download if flag is set.
204
     * @param array $incomingProcInstructions Array of processing instructions
205
     * @return string List of URLs (meant for display in backend module)
206
     */
207
    public function urlListFromUrlArray(
208
        array $vv,
209
        array $pageRow,
210
        int $scheduledTime,
211
        int $reqMinute,
212
        bool $submitCrawlUrls,
213
        bool $downloadCrawlUrls,
214
        array &$duplicateTrack,
215
        array &$downloadUrls,
216
        array $incomingProcInstructions
217
    ): string {
218
        if (!is_array($vv['URLs'])) {
8✔
219
            return 'ERROR - no URL generated';
×
220
        }
221
        $urlLog = [];
8✔
222
        $pageId = (int) $pageRow['uid'];
8✔
223
        $configurationHash = $this->getConfigurationHash($vv);
8✔
224
        $skipInnerCheck = $this->queueRepository->noUnprocessedQueueEntriesForPageWithConfigurationHashExist(
8✔
225
            $pageId,
8✔
226
            $configurationHash
8✔
227
        );
8✔
228

229
        $processInstructionService = new ProcessInstructionService();
8✔
230

231
        foreach ($vv['URLs'] as $urlQuery) {
8✔
232
            if (!$processInstructionService->isAllowed(
8✔
233
                $vv['subCfg']['procInstrFilter'] ?? '',
8✔
234
                $incomingProcInstructions
8✔
235
            )) {
8✔
236
                continue;
×
237
            }
238
            $url = $this->urlService->getUrlFromPageAndQueryParameters(
8✔
239
                $pageId,
8✔
240
                $urlQuery,
8✔
241
                $vv['subCfg']['baseUrl'] ?? null,
8✔
242
                (int) ($vv['subCfg']['force_ssl'] ?? 0)
8✔
243
            );
8✔
244

245
            if (!$url instanceof UriInterface) {
8✔
246
                continue;
×
247
            }
248

249
            $url = (string) $url;
8✔
250

251
            // Create key by which to determine unique-ness:
252
            $uKey = $url . '|' . ($vv['subCfg']['userGroups'] ?? '') . '|' . ($vv['subCfg']['procInstrFilter'] ?? '');
8✔
253

254
            if (isset($duplicateTrack[$uKey])) {
8✔
255
                //if the url key is registered just display it and do not resubmit is
256
                $urlLog[] = '<em><span class="text-muted">' . htmlspecialchars($url) . '</span></em>';
×
257
            } else {
258
                // Scheduled time:
259
                $schTime = $scheduledTime + round(count($duplicateTrack) * (60 / $reqMinute));
8✔
260
                $schTime = intval($schTime / 60) * 60;
8✔
261
                $formattedDate = BackendUtility::datetime($schTime);
8✔
262
                $this->urlList[] = '[' . $formattedDate . '] ' . $url;
8✔
263
                $urlList = '[' . $formattedDate . '] ' . htmlspecialchars($url);
8✔
264

265
                // Submit for crawling!
266
                if ($submitCrawlUrls) {
8✔
267
                    $added = $this->addUrl(
7✔
268
                        $pageId,
7✔
269
                        $url,
7✔
270
                        $vv['subCfg'],
7✔
271
                        $scheduledTime,
7✔
272
                        $configurationHash,
7✔
273
                        $skipInnerCheck
7✔
274
                    );
7✔
275
                    if ($added === false) {
7✔
276
                        $urlList .= ' (URL already existed)';
7✔
277
                    }
278
                } elseif ($downloadCrawlUrls) {
1✔
279
                    $downloadUrls[$url] = $url;
1✔
280
                }
281
                $urlLog[] = $urlList;
8✔
282
            }
283
            $duplicateTrack[$uKey] = true;
8✔
284
        }
285

286
        // Todo: Find a better option to have this correct in both backend (<br>) and cli (<new line>)
287
        return implode('<br>', $urlLog);
8✔
288
    }
289

290
    /**
291
     * Returns true if input processing instruction is among registered ones.
292
     *
293
     * @param string $piString PI to test
294
     * @param array $incomingProcInstructions Processing instructions
295
     * @return boolean
296
     * @deprecated since 11.0.3 will be removed in v13.x
297
     */
298
    public function drawURLs_PIfilter(string $piString, array $incomingProcInstructions)
299
    {
300
        $processInstructionService = new ProcessInstructionService();
5✔
301
        return $processInstructionService->isAllowed($piString, $incomingProcInstructions);
5✔
302
    }
303

304
    public function getPageTSconfigForId(int $id): array
305
    {
306
        if (!$this->MP) {
9✔
307
            $pageTSconfig = BackendUtility::getPagesTSconfig($id);
9✔
308
        } else {
309
            [, $mountPointId] = explode('-', $this->MP);
×
NEW
310
            $pageTSconfig = BackendUtility::getPagesTSconfig((int) $mountPointId);
×
311
        }
312

313
        // Call a hook to alter configuration
314
        if (
315
            isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'])
9✔
316
            && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'])
9✔
317
        ) {
318
            $params = [
×
319
                'pageId' => $id,
×
320
                'pageTSConfig' => &$pageTSconfig,
×
321
            ];
×
322
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'] as $userFunc) {
×
323
                GeneralUtility::callUserFunction($userFunc, $params, $this);
×
324
            }
325
        }
326
        return $pageTSconfig;
9✔
327
    }
328

329
    /**
330
     * This method returns an array of configurations.
331
     * Adds no urls!
332
     */
333
    public function getUrlsForPageId(int $pageId): array
334
    {
335
        // Get page TSconfig for page ID
336
        $pageTSconfig = $this->getPageTSconfigForId($pageId);
8✔
337

338
        $mountPoint = $this->MP ?? '';
8✔
339

340
        $res = [];
8✔
341

342
        // Fetch Crawler Configuration from pageTSConfig
343
        $res = $this->configurationService->getConfigurationFromPageTS($pageTSconfig, $pageId, $res, $mountPoint);
8✔
344

345
        // Get configuration from tx_crawler_configuration records up the rootline
346
        $res = $this->configurationService->getConfigurationFromDatabase($pageId, $res);
8✔
347

348
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['processUrls'] ?? [] as $func) {
8✔
349
            $params = [
×
350
                'res' => &$res,
×
351
            ];
×
352
            GeneralUtility::callUserFunction($func, $params, $this);
×
353
        }
354
        return $res;
8✔
355
    }
356

357
    /**
358
     * Find all configurations of subpages of a page
359
     * TODO: Write Functional Tests
360
     */
361
    public function getConfigurationsForBranch(int $rootid, int $depth): array
362
    {
363
        $configurationsForBranch = [];
1✔
364
        $pageTSconfig = $this->getPageTSconfigForId($rootid);
1✔
365
        $sets = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? [];
1✔
366
        foreach ($sets as $key => $value) {
1✔
367
            if (!is_array($value)) {
×
368
                continue;
×
369
            }
370
            $configurationsForBranch[] = str_ends_with($key, '.') ? substr($key, 0, -1) : $key;
×
371
        }
372
        $pids = [];
1✔
373
        $rootLine = BackendUtility::BEgetRootLine($rootid);
1✔
374
        foreach ($rootLine as $node) {
1✔
375
            $pids[] = $node['uid'];
1✔
376
        }
377
        /** @var PageTreeView $tree */
378
        $tree = GeneralUtility::makeInstance(PageTreeView::class);
1✔
379
        $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
1✔
380
        $tree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
1✔
381
        $tree->getTree($rootid, $depth, '');
1✔
382
        foreach ($tree->tree as $node) {
1✔
383
            $pids[] = $node['row']['uid'];
×
384
        }
385

386
        $configurations = $this->configurationRepository->getCrawlerConfigurationRecordsFromRootLine($rootid, $pids);
1✔
387

388
        foreach ($configurations as $configuration) {
1✔
389
            $configurationsForBranch[] = $configuration['name'];
1✔
390
        }
391
        return $configurationsForBranch;
1✔
392
    }
393

394
    /************************************
395
     *
396
     * Crawler log
397
     *
398
     ************************************/
399

400
    /**
401
     * Adding call back entries to log (called from hooks typically, see indexed search class "class.crawler.php"
402
     *
403
     * @param integer $setId Set ID
404
     * @param array $params Parameters to pass to call back function
405
     * @param string $callBack Call back object reference, eg. 'EXT:indexed_search/class.crawler.php:&tx_indexedsearch_crawler'
406
     * @param integer $page_id Page ID to attach it to
407
     * @param integer $schedule Time at which to activate
408
     *
409
     * @deprecated since 12.0.5 will be removed in 14.x
410
     */
411
    public function addQueueEntry_callBack(
412
        int $setId,
413
        array $params,
414
        string $callBack,
415
        int $page_id = 0,
416
        int $schedule = 0
417
    ): void {
UNCOV
418
        $params['_CALLBACKOBJ'] = $callBack;
×
419

420
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(QueueRepository::TABLE_NAME)
×
421
            ->insert(
×
422
                QueueRepository::TABLE_NAME,
×
423
                [
×
424
                    'page_id' => (int) $page_id,
×
425
                    'parameters' => json_encode($params),
×
426
                    'scheduled' => (int) $schedule ?: $this->getCurrentTime(),
×
427
                    'exec_time' => 0,
×
428
                    'set_id' => (int) $setId,
×
429
                    'result_data' => '',
×
430
                ]
×
431
            );
×
432
    }
433

434
    /************************************
435
     *
436
     * URL setting
437
     *
438
     ************************************/
439

440
    /**
441
     * Setting a URL for crawling:
442
     *
443
     * @param integer $id Page ID
444
     * @param string $url Complete URL
445
     * @param array $subCfg Sub configuration array (from TS config)
446
     * @param integer $tstamp Scheduled-time
447
     * @param string $configurationHash (optional) configuration hash
448
     * @param bool $skipInnerDuplicationCheck (optional) skip inner duplication check
449
     * @return bool
450
     */
451
    public function addUrl(
452
        $id,
453
        $url,
454
        array $subCfg,
455
        $tstamp,
456
        $configurationHash = '',
457
        $skipInnerDuplicationCheck = false
458
    ) {
459
        $urlAdded = false;
11✔
460
        $rows = [];
11✔
461

462
        // Creating parameters:
463
        $parameters = [
11✔
464
            'url' => $url,
11✔
465
        ];
11✔
466

467
        // fe user group simulation:
468
        $uGs = implode(',', array_unique(GeneralUtility::intExplode(',', $subCfg['userGroups'] ?? '', true)));
11✔
469
        if ($uGs) {
11✔
470
            $parameters['feUserGroupList'] = $uGs;
1✔
471
        }
472

473
        // Setting processing instructions
474
        $parameters['procInstructions'] = GeneralUtility::trimExplode(',', $subCfg['procInstrFilter'] ?? '');
11✔
475
        if (is_array($subCfg['procInstrParams.'] ?? false)) {
11✔
476
            $parameters['procInstrParams'] = $subCfg['procInstrParams.'];
8✔
477
        }
478

479
        // Compile value array:
480
        $parameters_serialized = json_encode($parameters) ?: '';
11✔
481
        $fieldArray = [
11✔
482
            'page_id' => (int) $id,
11✔
483
            'parameters' => $parameters_serialized,
11✔
484
            'parameters_hash' => md5($parameters_serialized),
11✔
485
            'configuration_hash' => $configurationHash,
11✔
486
            'scheduled' => $tstamp,
11✔
487
            'exec_time' => 0,
11✔
488
            'set_id' => (int) $this->setID,
11✔
489
            'result_data' => '',
11✔
490
            'configuration' => $subCfg['key'],
11✔
491
        ];
11✔
492

493
        if ($this->registerQueueEntriesInternallyOnly) {
11✔
494
            //the entries will only be registered and not stored to the database
495
            $this->queueEntries[] = $fieldArray;
2✔
496
        } else {
497
            if (!$skipInnerDuplicationCheck) {
9✔
498
                // check if there is already an equal entry
499
                $rows = $this->queueRepository->getDuplicateQueueItemsIfExists(
5✔
500
                    (bool) $this->extensionSettings['enableTimeslot'],
5✔
501
                    $tstamp,
5✔
502
                    $this->getCurrentTime(),
5✔
503
                    $fieldArray['page_id'],
5✔
504
                    $fieldArray['parameters_hash']
5✔
505
                );
5✔
506
            }
507
            if ($rows === []) {
9✔
508
                $connectionForCrawlerQueue = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(
8✔
509
                    QueueRepository::TABLE_NAME
8✔
510
                );
8✔
511
                $connectionForCrawlerQueue->insert(QueueRepository::TABLE_NAME, $fieldArray);
8✔
512
                $uid = $connectionForCrawlerQueue->lastInsertId(QueueRepository::TABLE_NAME, 'qid');
8✔
513
                $rows[] = $uid;
8✔
514
                $urlAdded = true;
8✔
515

516
                $this->eventDispatcher->dispatch(new AfterUrlAddedToQueueEvent($uid, $fieldArray));
8✔
517
            }
518
        }
519

520
        return $urlAdded;
11✔
521
    }
522

523
    /**
524
     * Returns the current system time
525
     *
526
     * @return int
527
     */
528
    public function getCurrentTime()
529
    {
530
        return time();
9✔
531
    }
532

533
    /************************************
534
     *
535
     * URL reading
536
     *
537
     ************************************/
538

539
    /**
540
     * Read URL for single queue entry
541
     *
542
     * @param integer $queueId
543
     * @param boolean $force If set, will process even if exec_time has been set!
544
     *
545
     * @return int|null
546
     */
547
    public function readUrl($queueId, $force = false, string $processId = '')
548
    {
549
        $ret = 0;
2✔
550
        $this->logger?->debug('crawler-readurl start ' . microtime(true));
2✔
551

552
        $queueRec = $this->queueRepository->getQueueEntriesByQid($queueId, $force);
2✔
553

554
        if (!is_array($queueRec)) {
2✔
555
            return null;
×
556
        }
557

558
        /** @var BeforeQueueItemAddedEvent $event */
559
        $event = $this->eventDispatcher->dispatch(new BeforeQueueItemAddedEvent((int) $queueId, $queueRec));
2✔
560
        $queueRec = $event->getQueueRecord();
2✔
561

562
        // Set exec_time to lock record:
563
        $field_array = [
2✔
564
            'exec_time' => $this->getCurrentTime(),
2✔
565
        ];
2✔
566

567
        if (!empty($processId)) {
2✔
568
            //if mulitprocessing is used we need to store the id of the process which has handled this entry
569
            $field_array['process_id_completed'] = $processId;
2✔
570
        }
571

572
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(QueueRepository::TABLE_NAME)
2✔
573
            ->update(QueueRepository::TABLE_NAME, $field_array, [
2✔
574
                'qid' => (int) $queueId,
2✔
575
            ]);
2✔
576

577
        $result = $this->queueExecutor->executeQueueItem($queueRec, $this);
2✔
578
        if ($result === 'ERROR' || ($result['content'] ?? null) === null) {
2✔
579
            $resultData = 'An errors happened';
2✔
580
        } else {
581
            /** @var JsonCompatibilityConverter $jsonCompatibilityConverter */
582
            $jsonCompatibilityConverter = GeneralUtility::makeInstance(JsonCompatibilityConverter::class);
×
583
            $resultData = $jsonCompatibilityConverter->convert($result['content']);
×
584

585
            //atm there's no need to point to specific pollable extensions
586
            if (
587
                is_array($resultData)
×
588
                && isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'])
×
589
                && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'])
×
590
            ) {
591
                foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'] as $pollable) {
×
592
                    // only check the success value if the instruction is runnig
593
                    // it is important to name the pollSuccess key same as the procInstructions key
594
                    if (is_array($resultData['parameters']['procInstructions'])
×
595
                        && in_array($pollable, $resultData['parameters']['procInstructions'], true)
×
596
                    ) {
597
                        if (!empty($resultData['success'][$pollable])) {
×
598
                            $ret |= self::CLI_STATUS_POLLABLE_PROCESSED;
×
599
                        }
600
                    }
601
                }
602
            }
603
        }
604
        // Set result in log which also denotes the end of the processing of this entry.
605
        $field_array = [
2✔
606
            'result_data' => json_encode($result),
2✔
607
        ];
2✔
608

609
        $this->eventDispatcher->dispatch(new AfterQueueItemAddedEvent($queueId, $field_array));
2✔
610
        $this->logger?->debug('crawler-readurl stop ' . microtime(true));
2✔
611

612
        return $ret;
2✔
613
    }
614

615
    /**
616
     * Read URL for not-yet-inserted log-entry
617
     *
618
     * @param array $field_array Queue field array,
619
     *
620
     * @return array|bool|mixed|string
621
     */
622
    public function readUrlFromArray($field_array)
623
    {
624
        // Set exec_time to lock record:
625
        $field_array['exec_time'] = $this->getCurrentTime();
1✔
626
        $connectionForCrawlerQueue = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(
1✔
627
            QueueRepository::TABLE_NAME
1✔
628
        );
1✔
629
        $connectionForCrawlerQueue->insert(QueueRepository::TABLE_NAME, $field_array);
1✔
630
        $queueId = $field_array['qid'] = $connectionForCrawlerQueue->lastInsertId(QueueRepository::TABLE_NAME, 'qid');
1✔
631
        $result = $this->queueExecutor->executeQueueItem($field_array, $this);
1✔
632

633
        // Set result in log which also denotes the end of the processing of this entry.
634
        $field_array = [
1✔
635
            'result_data' => json_encode($result),
1✔
636
        ];
1✔
637

638
        $this->eventDispatcher->dispatch(new AfterQueueItemAddedEvent($queueId, $field_array));
1✔
639

640
        return $result;
1✔
641
    }
642

643
    /*****************************
644
     *
645
     * Compiling URLs to crawl - tools
646
     *
647
     *****************************/
648

649
    /**
650
     * This draws the pageTree with URLs for e.g the Backend Log Module
651
     *
652
     * @param integer $id Root page id to start from.
653
     * @param integer $depth Depth of tree, 0=only id-page, 1= on sublevel, 99 = infinite
654
     * @param integer $scheduledTime Unix Time when the URL is timed to be visited when put in queue
655
     * @param integer $reqMinute Number of requests per minute (creates the interleave between requests)
656
     * @param boolean $submitCrawlUrls If set, submits the URLs to queue in database (real crawling)
657
     * @param boolean $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
658
     * @param array $incomingProcInstructions Array of processing instructions
659
     * @param array $configurationSelection Array of configuration keys
660
     * @return array
661
     */
662
    public function getPageTreeAndUrls(
663
        $id,
664
        $depth,
665
        $scheduledTime,
666
        $reqMinute,
667
        $submitCrawlUrls,
668
        $downloadCrawlUrls,
669
        array $incomingProcInstructions,
670
        array $configurationSelection
671
    ) {
672
        $this->scheduledTime = $scheduledTime;
5✔
673
        $this->reqMinute = $reqMinute;
5✔
674
        $this->submitCrawlUrls = $submitCrawlUrls;
5✔
675
        $this->downloadCrawlUrls = $downloadCrawlUrls;
5✔
676
        $this->incomingProcInstructions = $incomingProcInstructions;
5✔
677
        $this->incomingConfigurationSelection = $configurationSelection;
5✔
678

679
        $this->duplicateTrack = [];
5✔
680
        $this->downloadUrls = [];
5✔
681

682
        // Drawing tree:
683
        /** @var PageTreeView $tree */
684
        $tree = GeneralUtility::makeInstance(PageTreeView::class);
5✔
685
        $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
5✔
686
        $tree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
5✔
687

688
        $pageInfo = BackendUtility::readPageAccess($id, $perms_clause);
5✔
689
        if (is_array($pageInfo)) {
5✔
690
            // Set root row:
691
            $tree->tree[] = [
5✔
692
                'row' => $pageInfo,
5✔
693
                'HTML' => $this->iconFactory->getIconForRecord('pages', $pageInfo, Icon::SIZE_SMALL),
5✔
694
            ];
5✔
695
        }
696

697
        // Get branch beneath:
698
        if ($depth) {
5✔
699
            $tree->getTree($id, $depth, '');
1✔
700
        }
701

702
        $queueRows = [];
5✔
703

704
        // Traverse page tree:
705
        foreach ($tree->tree as $data) {
5✔
706
            $this->MP = null;
5✔
707

708
            // recognize mount points
709
            if ($data['row']['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
5✔
710
                $mountpage = $this->pageRepository->getPage($data['row']['uid']);
×
711

712
                // fetch mounted pages
713
                $this->MP = $mountpage['mount_pid'] . '-' . $data['row']['uid'];
×
714

715
                $mountTree = GeneralUtility::makeInstance(PageTreeView::class);
×
716
                $mountTree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
×
717
                $mountTree->getTree($mountpage['mount_pid'], $depth);
×
718

719
                foreach ($mountTree->tree as $mountData) {
×
720
                    $queueRows = array_merge($queueRows, $this->drawURLs_addRowsForPage(
×
721
                        $mountData['row'],
×
722
                        BackendUtility::getRecordTitle('pages', $mountData['row'], true),
×
723
                        (string) $data['HTML']
×
724
                    ));
×
725
                }
726

727
                // replace page when mount_pid_ol is enabled
728
                if ($mountpage['mount_pid_ol']) {
×
729
                    $data['row']['uid'] = $mountpage['mount_pid'];
×
730
                } else {
731
                    // if the mount_pid_ol is not set the MP must not be used for the mountpoint page
732
                    $this->MP = null;
×
733
                }
734
            }
735

736
            $queueRows = array_merge($queueRows, $this->drawURLs_addRowsForPage(
5✔
737
                $data['row'],
5✔
738
                BackendUtility::getRecordTitle('pages', $data['row'], true),
5✔
739
                (string) $data['HTML']
5✔
740
            ));
5✔
741
        }
742

743
        return $queueRows;
5✔
744
    }
745

746
    /**
747
     * Create the rows for display of the page tree
748
     * For each page a number of rows are shown displaying GET variable configuration
749
     */
750
    public function drawURLs_addRowsForPage(array $pageRow, string $pageTitle, string $pageTitleHTML = ''): array
751
    {
752
        $skipMessage = '';
5✔
753

754
        // Get list of configurations
755
        $configurations = $this->getUrlsForPageRow($pageRow, $skipMessage);
5✔
756
        $configurations = ConfigurationService::removeDisallowedConfigurations(
5✔
757
            $this->incomingConfigurationSelection,
5✔
758
            $configurations
5✔
759
        );
5✔
760

761
        // Traverse parameter combinations:
762
        $c = 0;
5✔
763

764
        $queueRowCollection = [];
5✔
765

766
        if (!empty($configurations)) {
5✔
767
            foreach ($configurations as $confKey => $confArray) {
5✔
768
                // Title column:
769
                if (!$c) {
5✔
770
                    $queueRow = new QueueRow($pageTitle);
5✔
771
                } else {
772
                    $queueRow = new QueueRow();
×
773
                }
774
                $queueRow->setPageTitleHTML($pageTitleHTML);
5✔
775

776
                if (!in_array(
5✔
777
                    $pageRow['uid'],
5✔
778
                    $this->configurationService->expandExcludeString($confArray['subCfg']['exclude'] ?? ''),
5✔
779
                    true
5✔
780
                )) {
5✔
781
                    // URL list:
782
                    $urlList = $this->urlListFromUrlArray(
5✔
783
                        $confArray,
5✔
784
                        $pageRow,
5✔
785
                        $this->scheduledTime,
5✔
786
                        $this->reqMinute,
5✔
787
                        $this->submitCrawlUrls,
5✔
788
                        $this->downloadCrawlUrls,
5✔
789
                        $this->duplicateTrack,
5✔
790
                        $this->downloadUrls,
5✔
791
                        // if empty the urls won't be filtered by processing instructions
792
                        $this->incomingProcInstructions
5✔
793
                    );
5✔
794

795
                    // Expanded parameters:
796
                    $paramExpanded = '';
5✔
797
                    $calcAccu = [];
5✔
798
                    $calcRes = 1;
5✔
799
                    foreach ($confArray['paramExpanded'] as $gVar => $gVal) {
5✔
800
                        $paramExpanded .= '
×
801
                            <tr>
802
                                <td>' . htmlspecialchars('&' . $gVar . '=') . '<br/>' .
×
803
                            '(' . count($gVal) . ')' .
×
804
                            '</td>
×
805
                                <td nowrap="nowrap">' . nl2br(
×
806
                                htmlspecialchars(implode(chr(10), $gVal))
×
807
                            ) . '</td>
×
808
                            </tr>
809
                        ';
×
810
                        $calcRes *= count($gVal);
×
811
                        $calcAccu[] = count($gVal);
×
812
                    }
813
                    if (!empty($paramExpanded)) {
5✔
814
                        $paramExpanded = "<table>{$paramExpanded}</table>";
×
815
                    }
816
                    $paramExpanded .= 'Comb: ' . implode('*', $calcAccu) . '=' . $calcRes;
5✔
817

818
                    // Options
819
                    $queueRowOptionCollection = [];
5✔
820
                    if ($confArray['subCfg']['userGroups'] ?? false) {
5✔
821
                        $queueRowOptionCollection[] = 'User Groups: ' . $confArray['subCfg']['userGroups'];
×
822
                    }
823
                    if ($confArray['subCfg']['procInstrFilter'] ?? false) {
5✔
824
                        $queueRowOptionCollection[] = 'ProcInstr: ' . $confArray['subCfg']['procInstrFilter'];
×
825
                    }
826

827
                    $parameterConfig = nl2br(
5✔
828
                        htmlspecialchars(rawurldecode(
5✔
829
                            trim(str_replace(
5✔
830
                                '&',
5✔
831
                                chr(10) . '&',
5✔
832
                                GeneralUtility::implodeArrayForUrl('', $confArray['paramParsed'] ?? [])
5✔
833
                            ))
5✔
834
                        ))
5✔
835
                    );
5✔
836
                    $queueRow->setValuesExpanded($paramExpanded);
5✔
837
                    $queueRow->setConfigurationKey($confKey);
5✔
838
                    $queueRow->setUrls($urlList);
5✔
839
                    $queueRow->setOptions($queueRowOptionCollection);
5✔
840
                    $queueRow->setParameters(DebugUtility::viewArray($confArray['subCfg']['procInstrParams.'] ?? []));
5✔
841
                    $queueRow->setParameterConfig($parameterConfig);
5✔
842
                } else {
843
                    $queueRow->setConfigurationKey($confKey);
×
844
                    $queueRow->setMessage('(Page is excluded in this configuration)');
×
845
                }
846
                $queueRowCollection[] = $queueRow;
5✔
847

848
                $c++;
5✔
849
            }
850
        } else {
851
            $message = !empty($skipMessage) ? ' (' . $skipMessage . ')' : '';
1✔
852
            $queueRow = new QueueRow($pageTitle);
1✔
853
            $queueRow->setPageTitleHTML($pageTitleHTML);
1✔
854
            $queueRow->setMessage($message);
1✔
855
            $queueRowCollection[] = $queueRow;
1✔
856
        }
857

858
        return $queueRowCollection;
5✔
859
    }
860

861
    /**
862
     * Returns a md5 hash generated from a serialized configuration array.
863
     *
864
     * @return string
865
     */
866
    protected function getConfigurationHash(array $configuration)
867
    {
868
        unset($configuration['paramExpanded']);
14✔
869
        unset($configuration['URLs']);
14✔
870
        return md5(serialize($configuration));
14✔
871
    }
872

873
    protected function getPageService(): PageService
874
    {
875
        return new PageService();
8✔
876
    }
877

878
    /**
879
     * @return BackendUserAuthentication
880
     */
881
    private function getBackendUser()
882
    {
883
        // Make sure the _cli_ user is loaded
884
        Bootstrap::initializeBackendAuthentication();
6✔
885
        if ($this->backendUser === null) {
6✔
886
            $this->backendUser = $GLOBALS['BE_USER'];
6✔
887
        }
888
        return $this->backendUser;
6✔
889
    }
890
}
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

© 2026 Coveralls, Inc