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

tomasnorre / crawler / 13166490870

05 Feb 2025 09:01PM UTC coverage: 67.753% (-1.4%) from 69.194%
13166490870

push

github

web-flow
[TASK] Refactor commands (#1127)

42 of 75 new or added lines in 2 files covered. (56.0%)

19 existing lines in 2 files now uncovered.

1830 of 2701 relevant lines covered (67.75%)

3.27 hits per line

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

76.6
/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 Crawler $crawler;
97
    private ConfigurationService $configurationService;
98
    private UrlService $urlService;
99
    private EventDispatcher $eventDispatcher;
100

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

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

129
        /** @var ExtensionConfigurationProvider $configurationProvider */
130
        $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class);
16✔
131
        $settings = $configurationProvider->getExtensionConfiguration();
16✔
132
        $this->extensionSettings = is_array($settings) ? $settings : [];
16✔
133

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

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

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

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

162
    /**
163
     * Wrapper method for getUrlsForPageId()
164
     * It returns an array of configurations and no urls!
165
     *
166
     * @param array $pageRow Page record with at least dok-type and uid columns.
167
     * @see getUrlsForPageId()
168
     */
169
    public function getUrlsForPageRow(array $pageRow, string &$skipMessage = ''): array
170
    {
171
        $pageRowUid = intval($pageRow['uid']);
13✔
172
        if (!$pageRowUid) {
13✔
173
            $skipMessage = 'PageUid "' . $pageRow['uid'] . '" was not an integer';
2✔
174
            return [];
2✔
175
        }
176

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

186
        return $res;
11✔
187
    }
188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

337
        $res = [];
8✔
338

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

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

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

354
    /**
355
     * Find all configurations of subpages of a page
356
     * TODO: Write Functional Tests
357
     */
358
    public function getConfigurationsForBranch(int $rootid, int $depth): array
359
    {
360
        $configurationsForBranch = [];
1✔
361
        $pageTSconfig = $this->getPageTSconfigForId($rootid);
1✔
362
        $sets = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? [];
1✔
363
        foreach ($sets as $key => $value) {
1✔
364
            if (!is_array($value)) {
×
365
                continue;
×
366
            }
367
            $configurationsForBranch[] = str_ends_with($key, '.') ? substr($key, 0, -1) : $key;
×
368
        }
369
        $pids = [];
1✔
370
        $rootLine = BackendUtility::BEgetRootLine($rootid);
1✔
371
        foreach ($rootLine as $node) {
1✔
372
            $pids[] = $node['uid'];
1✔
373
        }
374
        /** @var PageTreeView $tree */
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($setId, $params, $callBack, $page_id = 0, $schedule = 0): void
409
    {
410
        if (!is_array($params)) {
×
411
            $params = [];
×
412
        }
413
        $params['_CALLBACKOBJ'] = $callBack;
×
414

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

429
    /************************************
430
     *
431
     * URL setting
432
     *
433
     ************************************/
434

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

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

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

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

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

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

511
                $this->eventDispatcher->dispatch(new AfterUrlAddedToQueueEvent($uid, $fieldArray));
9✔
512
            }
513
        }
514

515
        return $urlAdded;
11✔
516
    }
517

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

528
    /************************************
529
     *
530
     * URL reading
531
     *
532
     ************************************/
533

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

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

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

553
        /** @var BeforeQueueItemAddedEvent $event */
554
        $event = $this->eventDispatcher->dispatch(new BeforeQueueItemAddedEvent((int) $queueId, $queueRec));
2✔
555
        $queueRec = $event->getQueueRecord();
2✔
556

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

562
        if (!empty($processId)) {
2✔
563
            //if mulitprocessing is used we need to store the id of the process which has handled this entry
564
            $field_array['process_id_completed'] = $processId;
2✔
565
        }
566

567
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable(QueueRepository::TABLE_NAME)
2✔
568
            ->update(QueueRepository::TABLE_NAME, $field_array, [
2✔
569
                'qid' => (int) $queueId,
2✔
570
            ]);
2✔
571

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

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

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

607
        return $ret;
2✔
608
    }
609

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

628
        // Set result in log which also denotes the end of the processing of this entry.
UNCOV
629
        $field_array = [
×
UNCOV
630
            'result_data' => json_encode($result),
×
UNCOV
631
        ];
×
632

UNCOV
633
        $this->eventDispatcher->dispatch(new AfterQueueItemAddedEvent($queueId, $field_array));
×
634

UNCOV
635
        return $result;
×
636
    }
637

638
    /*****************************
639
     *
640
     * Compiling URLs to crawl - tools
641
     *
642
     *****************************/
643

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

674
        $this->duplicateTrack = [];
5✔
675
        $this->downloadUrls = [];
5✔
676

677
        // Drawing tree:
678
        /** @var PageTreeView $tree */
679
        $tree = GeneralUtility::makeInstance(PageTreeView::class);
5✔
680
        $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
5✔
681
        $tree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
5✔
682

683
        $pageInfo = BackendUtility::readPageAccess($id, $perms_clause);
5✔
684
        if (is_array($pageInfo)) {
5✔
685
            // Set root row:
686
            $tree->tree[] = [
5✔
687
                'row' => $pageInfo,
5✔
688
                'HTML' => $this->iconFactory->getIconForRecord('pages', $pageInfo, Icon::SIZE_SMALL),
5✔
689
            ];
5✔
690
        }
691

692
        // Get branch beneath:
693
        if ($depth) {
5✔
694
            $tree->getTree($id, $depth, '');
1✔
695
        }
696

697
        $queueRows = [];
5✔
698

699
        // Traverse page tree:
700
        foreach ($tree->tree as $data) {
5✔
701
            $this->MP = null;
5✔
702

703
            // recognize mount points
704
            if ($data['row']['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
5✔
705
                $mountpage = $this->pageRepository->getPage($data['row']['uid']);
×
706

707
                // fetch mounted pages
708
                $this->MP = $mountpage[0]['mount_pid'] . '-' . $data['row']['uid'];
×
709

710
                $mountTree = GeneralUtility::makeInstance(PageTreeView::class);
×
711
                $mountTree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
×
712
                $mountTree->getTree($mountpage[0]['mount_pid'], $depth);
×
713

714
                foreach ($mountTree->tree as $mountData) {
×
715
                    $queueRows = array_merge($queueRows, $this->drawURLs_addRowsForPage(
×
716
                        $mountData['row'],
×
717
                        BackendUtility::getRecordTitle('pages', $mountData['row'], true),
×
718
                        (string) $data['HTML']
×
719
                    ));
×
720
                }
721

722
                // replace page when mount_pid_ol is enabled
723
                if ($mountpage[0]['mount_pid_ol']) {
×
724
                    $data['row']['uid'] = $mountpage[0]['mount_pid'];
×
725
                } else {
726
                    // if the mount_pid_ol is not set the MP must not be used for the mountpoint page
727
                    $this->MP = null;
×
728
                }
729
            }
730

731
            $queueRows = array_merge($queueRows, $this->drawURLs_addRowsForPage(
5✔
732
                $data['row'],
5✔
733
                BackendUtility::getRecordTitle('pages', $data['row'], true),
5✔
734
                (string) $data['HTML']
5✔
735
            ));
5✔
736
        }
737

738
        return $queueRows;
5✔
739
    }
740

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

749
        // Get list of configurations
750
        $configurations = $this->getUrlsForPageRow($pageRow, $skipMessage);
5✔
751
        $configurations = ConfigurationService::removeDisallowedConfigurations(
5✔
752
            $this->incomingConfigurationSelection,
5✔
753
            $configurations
5✔
754
        );
5✔
755

756
        // Traverse parameter combinations:
757
        $c = 0;
5✔
758

759
        $queueRowCollection = [];
5✔
760

761
        if (!empty($configurations)) {
5✔
762
            foreach ($configurations as $confKey => $confArray) {
5✔
763
                // Title column:
764
                if (!$c) {
5✔
765
                    $queueRow = new QueueRow($pageTitle);
5✔
766
                } else {
767
                    $queueRow = new QueueRow();
×
768
                }
769
                $queueRow->setPageTitleHTML($pageTitleHTML);
5✔
770

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

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

811
                    // Options
812
                    $queueRowOptionCollection = [];
5✔
813
                    if ($confArray['subCfg']['userGroups'] ?? false) {
5✔
814
                        $queueRowOptionCollection[] = 'User Groups: ' . $confArray['subCfg']['userGroups'];
×
815
                    }
816
                    if ($confArray['subCfg']['procInstrFilter'] ?? false) {
5✔
817
                        $queueRowOptionCollection[] = 'ProcInstr: ' . $confArray['subCfg']['procInstrFilter'];
×
818
                    }
819

820
                    // Remove empty array entries;
821
                    $queueRowOptionCollection = array_filter($queueRowOptionCollection);
5✔
822

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

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

854
        return $queueRowCollection;
5✔
855
    }
856

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

869
    protected function getPageService(): PageService
870
    {
871
        return new PageService();
8✔
872
    }
873

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