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

tomasnorre / crawler / 19905003791

03 Dec 2025 06:44PM UTC coverage: 69.485% (-0.03%) from 69.514%
19905003791

Pull #1241

github

web-flow
Merge 5228f347f into 15874a84e
Pull Request #1241: !!! [TASK] Remove class JsonCompatibilityConverter

10 of 14 new or added lines in 7 files covered. (71.43%)

1915 of 2756 relevant lines covered (69.48%)

3.17 hits per line

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

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

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

62
    public const CLI_STATUS_POLLABLE_PROCESSED = 8;
63

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

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

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

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

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

127
        $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class);
16✔
128
        $this->extensionSettings = $configurationProvider->getExtensionConfiguration();
16✔
129

130
        if (abs((int) $this->extensionSettings['countInARun']) === 0) {
16✔
131
            $this->extensionSettings['countInARun'] = 100;
×
132
        }
133

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

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

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

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

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

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

187
        return $res;
11✔
188
    }
189

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

227
        $processInstructionService = new ProcessInstructionService();
8✔
228

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

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

247
            $url = (string) $url;
8✔
248

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

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

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

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

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

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

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

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

336
        $mountPoint = $this->MP ?? '';
8✔
337

338
        $res = [];
8✔
339

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

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

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

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

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

385
        foreach ($configurations as $configuration) {
1✔
386
            $configurationsForBranch[] = $configuration['name'];
1✔
387
        }
388
        return $configurationsForBranch;
1✔
389
    }
390

391
    /************************************
392
     *
393
     * Crawler log
394
     *
395
     ************************************/
396

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

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

431
    /************************************
432
     *
433
     * URL setting
434
     *
435
     ************************************/
436

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

459
        // Creating parameters:
460
        $parameters = [
11✔
461
            'url' => $url,
11✔
462
        ];
11✔
463

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

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

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

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

513
                $this->eventDispatcher->dispatch(new AfterUrlAddedToQueueEvent($uid, $fieldArray));
8✔
514
            }
515
        }
516

517
        return $urlAdded;
11✔
518
    }
519

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

530
    /************************************
531
     *
532
     * URL reading
533
     *
534
     ************************************/
535
    /**
536
     * Read URL for single queue entry
537
     *
538
     * @param boolean $force If set, will process even if exec_time has been set!
539
     * @return int|null
540
     */
541
    public function readUrl(int $queueId, bool $force = false, string $processId = '')
542
    {
543
        $ret = 0;
2✔
544
        $this->logger?->debug('crawler-readurl start ' . microtime(true));
2✔
545

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

548
        if (!is_array($queueRec)) {
2✔
549
            return null;
×
550
        }
551

552
        $event = $this->eventDispatcher->dispatch(new BeforeQueueItemAddedEvent($queueId, $queueRec));
2✔
553
        $queueRec = $event->getQueueRecord();
2✔
554

555
        // Set exec_time to lock record:
556
        $field_array = [
2✔
557
            'exec_time' => $this->getCurrentTime(),
2✔
558
        ];
2✔
559

560
        $field_array['process_id_completed'] = $processId;
2✔
561

562
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(QueueRepository::TABLE_NAME)
2✔
563
            ->update(QueueRepository::TABLE_NAME, $field_array, [
2✔
564
                'qid' => $queueId,
2✔
565
            ]);
2✔
566

567
        $result = $this->queueExecutor->executeQueueItem($queueRec, $this);
2✔
568
        if (!($result === 'ERROR' || ($result['content'] ?? null) === null)) {
2✔
NEW
569
            $resultData = json_decode($result['content'], true);
×
570
            //atm there's no need to point to specific pollable extensions
571
            if (
572
                is_array($resultData)
×
573
                && isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'])
×
574
                && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'])
×
575
            ) {
576
                foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'] as $pollable) {
×
577
                    // only check the success value if the instruction is runnig
578
                    // it is important to name the pollSuccess key same as the procInstructions key
579
                    if (is_array($resultData['parameters']['procInstructions'])
×
580
                        && in_array($pollable, $resultData['parameters']['procInstructions'], true)
×
581
                    ) {
582
                        if (!empty($resultData['success'][$pollable])) {
×
583
                            $ret |= self::CLI_STATUS_POLLABLE_PROCESSED;
×
584
                        }
585
                    }
586
                }
587
            }
588
        }
589
        // Set result in log which also denotes the end of the processing of this entry.
590
        $field_array = [
2✔
591
            'result_data' => json_encode($result),
2✔
592
        ];
2✔
593

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

597
        return $ret;
2✔
598
    }
599

600
    /**
601
     * Read URL for not-yet-inserted log-entry
602
     *
603
     * @param array $field_array Queue field array,
604
     *
605
     * @return array|bool|mixed|string
606
     */
607
    public function readUrlFromArray($field_array)
608
    {
609
        // Set exec_time to lock record:
610
        $field_array['exec_time'] = $this->getCurrentTime();
1✔
611
        $connectionForCrawlerQueue = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(
1✔
612
            QueueRepository::TABLE_NAME
1✔
613
        );
1✔
614
        $connectionForCrawlerQueue->insert(QueueRepository::TABLE_NAME, $field_array);
1✔
615
        $queueId = $field_array['qid'] = $connectionForCrawlerQueue->lastInsertId();
1✔
616
        $result = $this->queueExecutor->executeQueueItem($field_array, $this);
1✔
617

618
        // Set result in log which also denotes the end of the processing of this entry.
619
        $field_array = [
1✔
620
            'result_data' => json_encode($result),
1✔
621
        ];
1✔
622

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

625
        return $result;
1✔
626
    }
627

628
    /*****************************
629
     *
630
     * Compiling URLs to crawl - tools
631
     *
632
     *****************************/
633

634
    /**
635
     * This draws the pageTree with URLs for e.g the Backend Log Module
636
     *
637
     * @param integer $id Root page id to start from.
638
     * @param integer $depth Depth of tree, 0=only id-page, 1= on sublevel, 99 = infinite
639
     * @param integer $scheduledTime Unix Time when the URL is timed to be visited when put in queue
640
     * @param integer $reqMinute Number of requests per minute (creates the interleave between requests)
641
     * @param boolean $submitCrawlUrls If set, submits the URLs to queue in database (real crawling)
642
     * @param boolean $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
643
     * @param array $incomingProcInstructions Array of processing instructions
644
     * @param array $configurationSelection Array of configuration keys
645
     * @return array
646
     */
647
    public function getPageTreeAndUrls(
648
        $id,
649
        $depth,
650
        $scheduledTime,
651
        $reqMinute,
652
        $submitCrawlUrls,
653
        $downloadCrawlUrls,
654
        array $incomingProcInstructions,
655
        array $configurationSelection
656
    ) {
657
        $this->scheduledTime = $scheduledTime;
5✔
658
        $this->reqMinute = $reqMinute;
5✔
659
        $this->submitCrawlUrls = $submitCrawlUrls;
5✔
660
        $this->downloadCrawlUrls = $downloadCrawlUrls;
5✔
661
        $this->incomingProcInstructions = $incomingProcInstructions;
5✔
662
        $this->incomingConfigurationSelection = $configurationSelection;
5✔
663

664
        $this->duplicateTrack = [];
5✔
665
        $this->downloadUrls = [];
5✔
666

667
        // Drawing tree:
668
        $tree = GeneralUtility::makeInstance(PageTreeView::class);
5✔
669
        $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
5✔
670
        $tree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
5✔
671

672
        $pageInfo = BackendUtility::readPageAccess($id, $perms_clause);
5✔
673
        if (is_array($pageInfo)) {
5✔
674
            // Set root row:
675
            $tree->tree[] = [
5✔
676
                'row' => $pageInfo,
5✔
677
                'HTML' => $this->iconFactory->getIconForRecord('pages', $pageInfo, IconSize::SMALL),
5✔
678
            ];
5✔
679
        }
680

681
        // Get branch beneath:
682
        if ($depth) {
5✔
683
            $tree->getTree($id, $depth, '');
1✔
684
        }
685

686
        $queueRows = [];
5✔
687

688
        // Traverse page tree:
689
        foreach ($tree->tree as $data) {
5✔
690
            $this->MP = null;
5✔
691

692
            // recognize mount points
693
            if ($data['row']['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
5✔
694
                $mountpage = $this->pageRepository->getPage($data['row']['uid']);
×
695

696
                // fetch mounted pages
697
                $this->MP = $mountpage['mount_pid'] . '-' . $data['row']['uid'];
×
698

699
                $mountTree = GeneralUtility::makeInstance(PageTreeView::class);
×
700
                $mountTree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
×
701
                $mountTree->getTree($mountpage['mount_pid'], $depth);
×
702

703
                foreach ($mountTree->tree as $mountData) {
×
704
                    $queueRows = array_merge($queueRows, $this->drawURLs_addRowsForPage(
×
705
                        $mountData['row'],
×
706
                        BackendUtility::getRecordTitle('pages', $mountData['row'], true),
×
707
                        (string) $data['HTML']
×
708
                    ));
×
709
                }
710

711
                // replace page when mount_pid_ol is enabled
712
                if ($mountpage['mount_pid_ol']) {
×
713
                    $data['row']['uid'] = $mountpage['mount_pid'];
×
714
                } else {
715
                    // if the mount_pid_ol is not set the MP must not be used for the mountpoint page
716
                    $this->MP = null;
×
717
                }
718
            }
719

720
            $queueRows = array_merge($queueRows, $this->drawURLs_addRowsForPage(
5✔
721
                $data['row'],
5✔
722
                BackendUtility::getRecordTitle('pages', $data['row'], true),
5✔
723
                (string) $data['HTML']
5✔
724
            ));
5✔
725
        }
726

727
        return $queueRows;
5✔
728
    }
729

730
    /**
731
     * Create the rows for display of the page tree
732
     * For each page a number of rows are shown displaying GET variable configuration
733
     */
734
    public function drawURLs_addRowsForPage(array $pageRow, string $pageTitle, string $pageTitleHTML = ''): array
735
    {
736
        $skipMessage = '';
5✔
737

738
        // Get list of configurations
739
        $configurations = $this->getUrlsForPageRow($pageRow, $skipMessage);
5✔
740
        $configurations = ConfigurationService::removeDisallowedConfigurations(
5✔
741
            $this->incomingConfigurationSelection,
5✔
742
            $configurations
5✔
743
        );
5✔
744

745
        // Traverse parameter combinations:
746
        $c = 0;
5✔
747

748
        $queueRowCollection = [];
5✔
749

750
        if (!empty($configurations)) {
5✔
751
            foreach ($configurations as $confKey => $confArray) {
5✔
752
                // Title column:
753
                if (!$c) {
5✔
754
                    $queueRow = new QueueRow($pageTitle);
5✔
755
                } else {
756
                    $queueRow = new QueueRow();
×
757
                }
758
                $queueRow->setPageTitleHTML($pageTitleHTML);
5✔
759

760
                if (!in_array(
5✔
761
                    $pageRow['uid'],
5✔
762
                    $this->configurationService->expandExcludeString($confArray['subCfg']['exclude'] ?? ''),
5✔
763
                    true
5✔
764
                )) {
5✔
765
                    // URL list:
766
                    $urlList = $this->urlListFromUrlArray(
5✔
767
                        $confArray,
5✔
768
                        $pageRow,
5✔
769
                        $this->scheduledTime,
5✔
770
                        $this->reqMinute,
5✔
771
                        $this->submitCrawlUrls,
5✔
772
                        $this->downloadCrawlUrls,
5✔
773
                        $this->duplicateTrack,
5✔
774
                        $this->downloadUrls,
5✔
775
                        // if empty the urls won't be filtered by processing instructions
776
                        $this->incomingProcInstructions
5✔
777
                    );
5✔
778

779
                    // Expanded parameters:
780
                    $paramExpanded = '';
5✔
781
                    $calcAccu = [];
5✔
782
                    $calcRes = 1;
5✔
783
                    foreach ($confArray['paramExpanded'] as $gVar => $gVal) {
5✔
784
                        $paramExpanded .= '
×
785
                            <tr>
786
                                <td>' . htmlspecialchars('&' . $gVar . '=') . '<br/>' .
×
787
                            '(' . count($gVal) . ')' .
×
788
                            '</td>
×
789
                                <td nowrap="nowrap">' . nl2br(
×
790
                                htmlspecialchars(implode(chr(10), $gVal))
×
791
                            ) . '</td>
×
792
                            </tr>
793
                        ';
×
794
                        $calcRes *= count($gVal);
×
795
                        $calcAccu[] = count($gVal);
×
796
                    }
797
                    if (!empty($paramExpanded)) {
5✔
798
                        $paramExpanded = "<table>{$paramExpanded}</table>";
×
799
                    }
800
                    $paramExpanded .= 'Comb: ' . implode('*', $calcAccu) . '=' . $calcRes;
5✔
801

802
                    // Options
803
                    $queueRowOptionCollection = [];
5✔
804
                    if ($confArray['subCfg']['userGroups'] ?? false) {
5✔
805
                        $queueRowOptionCollection[] = 'User Groups: ' . $confArray['subCfg']['userGroups'];
×
806
                    }
807
                    if ($confArray['subCfg']['procInstrFilter'] ?? false) {
5✔
808
                        $queueRowOptionCollection[] = 'ProcInstr: ' . $confArray['subCfg']['procInstrFilter'];
×
809
                    }
810

811
                    $parameterConfig = nl2br(
5✔
812
                        htmlspecialchars(rawurldecode(
5✔
813
                            trim(str_replace(
5✔
814
                                '&',
5✔
815
                                chr(10) . '&',
5✔
816
                                GeneralUtility::implodeArrayForUrl('', $confArray['paramParsed'] ?? [])
5✔
817
                            ))
5✔
818
                        ))
5✔
819
                    );
5✔
820
                    $queueRow->setValuesExpanded($paramExpanded);
5✔
821
                    $queueRow->setConfigurationKey($confKey);
5✔
822
                    $queueRow->setUrls($urlList);
5✔
823
                    $queueRow->setOptions($queueRowOptionCollection);
5✔
824
                    $queueRow->setParameters(DebugUtility::viewArray($confArray['subCfg']['procInstrParams.'] ?? []));
5✔
825
                    $queueRow->setParameterConfig($parameterConfig);
5✔
826
                } else {
827
                    $queueRow->setConfigurationKey($confKey);
×
828
                    $queueRow->setMessage('(Page is excluded in this configuration)');
×
829
                }
830
                $queueRowCollection[] = $queueRow;
5✔
831

832
                $c++;
5✔
833
            }
834
        } else {
835
            $message = !empty($skipMessage) ? ' (' . $skipMessage . ')' : '';
1✔
836
            $queueRow = new QueueRow($pageTitle);
1✔
837
            $queueRow->setPageTitleHTML($pageTitleHTML);
1✔
838
            $queueRow->setMessage($message);
1✔
839
            $queueRowCollection[] = $queueRow;
1✔
840
        }
841

842
        return $queueRowCollection;
5✔
843
    }
844

845
    /**
846
     * Returns a md5 hash generated from a serialized configuration array.
847
     *
848
     * @return string
849
     */
850
    protected function getConfigurationHash(array $configuration)
851
    {
852
        unset($configuration['paramExpanded']);
14✔
853
        unset($configuration['URLs']);
14✔
854
        return md5(serialize($configuration));
14✔
855
    }
856

857
    protected function getPageService(): PageService
858
    {
859
        return new PageService();
8✔
860
    }
861

862
    /**
863
     * @return BackendUserAuthentication
864
     */
865
    private function getBackendUser()
866
    {
867
        // Make sure the _cli_ user is loaded
868
        Bootstrap::initializeBackendAuthentication();
6✔
869
        if ($this->backendUser === null) {
6✔
870
            $this->backendUser = $GLOBALS['BE_USER'];
6✔
871
        }
872
        return $this->backendUser;
6✔
873
    }
874
}
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