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

tomasnorre / crawler / 11237471329

08 Oct 2024 02:20PM UTC coverage: 68.586% (-1.3%) from 69.862%
11237471329

push

github

web-flow
ci: Update coveralls workflow (#1109)

1834 of 2674 relevant lines covered (68.59%)

3.37 hits per line

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

79.79
/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
                $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
    public function addQueueEntry_callBack($setId, $params, $callBack, $page_id = 0, $schedule = 0): void
407
    {
408
        if (!is_array($params)) {
×
409
            $params = [];
×
410
        }
411
        $params['_CALLBACKOBJ'] = $callBack;
×
412

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

427
    /************************************
428
     *
429
     * URL setting
430
     *
431
     ************************************/
432

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

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

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

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

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

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

509
                $this->eventDispatcher->dispatch(new AfterUrlAddedToQueueEvent($uid, $fieldArray));
8✔
510
            }
511
        }
512

513
        return $urlAdded;
11✔
514
    }
515

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

526
    /************************************
527
     *
528
     * URL reading
529
     *
530
     ************************************/
531

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

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

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

551
        /** @var BeforeQueueItemAddedEvent $event */
552
        $event = $this->eventDispatcher->dispatch(new BeforeQueueItemAddedEvent((int) $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
        if (!empty($processId)) {
2✔
561
            //if mulitprocessing is used we need to store the id of the process which has handled this entry
562
            $field_array['process_id_completed'] = $processId;
2✔
563
        }
564

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

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

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

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

605
        return $ret;
2✔
606
    }
607

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

626
        // Set result in log which also denotes the end of the processing of this entry.
627
        $field_array = [
1✔
628
            'result_data' => json_encode($result),
1✔
629
        ];
1✔
630

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

633
        return $result;
1✔
634
    }
635

636
    /*****************************
637
     *
638
     * Compiling URLs to crawl - tools
639
     *
640
     *****************************/
641

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

672
        $this->duplicateTrack = [];
5✔
673
        $this->downloadUrls = [];
5✔
674

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

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

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

695
        $queueRows = [];
5✔
696

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

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

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

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

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

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

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

736
        return $queueRows;
5✔
737
    }
738

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

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

754
        // Traverse parameter combinations:
755
        $c = 0;
5✔
756

757
        $queueRowCollection = [];
5✔
758

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

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

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

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

818
                    // Remove empty array entries;
819
                    $queueRowOptionCollection = array_filter($queueRowOptionCollection);
5✔
820

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

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

852
        return $queueRowCollection;
5✔
853
    }
854

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

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

872
    /**
873
     * @return BackendUserAuthentication
874
     */
875
    private function getBackendUser()
876
    {
877
        // Make sure the _cli_ user is loaded
878
        Bootstrap::initializeBackendAuthentication();
6✔
879
        if ($this->backendUser === null) {
6✔
880
            $this->backendUser = $GLOBALS['BE_USER'];
6✔
881
        }
882
        return $this->backendUser;
6✔
883
    }
884
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc