Passed
Push — cleanup/drawLogAddRows ( 3ca412...41d4c6 )
by Tomas Norre
05:26
created

CrawlerController::addUrl()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 84
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 44
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 51
c 1
b 0
f 0
nc 20
nop 6
dl 0
loc 84
ccs 44
cts 44
cp 1
crap 6
rs 8.4468

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace AOE\Crawler\Controller;
6
7
/***************************************************************
8
 *  Copyright notice
9
 *
10
 *  (c) 2020 AOE GmbH <[email protected]>
11
 *
12
 *  All rights reserved
13
 *
14
 *  This script is part of the TYPO3 project. The TYPO3 project is
15
 *  free software; you can redistribute it and/or modify
16
 *  it under the terms of the GNU General Public License as published by
17
 *  the Free Software Foundation; either version 3 of the License, or
18
 *  (at your option) any later version.
19
 *
20
 *  The GNU General Public License can be found at
21
 *  http://www.gnu.org/copyleft/gpl.html.
22
 *
23
 *  This script is distributed in the hope that it will be useful,
24
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26
 *  GNU General Public License for more details.
27
 *
28
 *  This copyright notice MUST APPEAR in all copies of the script!
29
 ***************************************************************/
30
31
use AOE\Crawler\Configuration\ExtensionConfigurationProvider;
32
use AOE\Crawler\Converter\JsonCompatibilityConverter;
33
use AOE\Crawler\Crawler;
34
use AOE\Crawler\CrawlStrategy\CrawlStrategyFactory;
35
use AOE\Crawler\Domain\Model\Process;
36
use AOE\Crawler\Domain\Repository\ConfigurationRepository;
37
use AOE\Crawler\Domain\Repository\ProcessRepository;
38
use AOE\Crawler\Domain\Repository\QueueRepository;
39
use AOE\Crawler\QueueExecutor;
40
use AOE\Crawler\Service\ConfigurationService;
41
use AOE\Crawler\Service\UrlService;
42
use AOE\Crawler\Utility\SignalSlotUtility;
43
use AOE\Crawler\Value\QueueFilter;
44
use PDO;
45
use Psr\Http\Message\UriInterface;
46
use Psr\Log\LoggerAwareInterface;
47
use Psr\Log\LoggerAwareTrait;
48
use TYPO3\CMS\Backend\Tree\View\PageTreeView;
49
use TYPO3\CMS\Backend\Utility\BackendUtility;
50
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
51
use TYPO3\CMS\Core\Compatibility\PublicMethodDeprecationTrait;
52
use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
53
use TYPO3\CMS\Core\Core\Bootstrap;
54
use TYPO3\CMS\Core\Core\Environment;
55
use TYPO3\CMS\Core\Database\Connection;
56
use TYPO3\CMS\Core\Database\ConnectionPool;
57
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
58
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
59
use TYPO3\CMS\Core\Database\QueryGenerator;
60
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
61
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
62
use TYPO3\CMS\Core\Imaging\Icon;
63
use TYPO3\CMS\Core\Imaging\IconFactory;
64
use TYPO3\CMS\Core\Routing\InvalidRouteArgumentsException;
65
use TYPO3\CMS\Core\Site\Entity\Site;
66
use TYPO3\CMS\Core\Type\Bitmask\Permission;
67
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
68
use TYPO3\CMS\Core\Utility\DebugUtility;
69
use TYPO3\CMS\Core\Utility\GeneralUtility;
70
use TYPO3\CMS\Core\Utility\MathUtility;
71
use TYPO3\CMS\Extbase\Object\ObjectManager;
72
73
/**
74
 * Class CrawlerController
75
 *
76
 * @package AOE\Crawler\Controller
77
 */
78
class CrawlerController implements LoggerAwareInterface
79
{
80
    use LoggerAwareTrait;
81
    use PublicMethodDeprecationTrait;
82
    use PublicPropertyDeprecationTrait;
83
84
    public const CLI_STATUS_NOTHING_PROCCESSED = 0;
85
86
    //queue not empty
87
    public const CLI_STATUS_REMAIN = 1;
88
89
    //(some) queue items where processed
90
    public const CLI_STATUS_PROCESSED = 2;
91
92
    //instance didn't finish
93
    public const CLI_STATUS_ABORTED = 4;
94
95
    public const CLI_STATUS_POLLABLE_PROCESSED = 8;
96
97
    /**
98
     * @var integer
99
     */
100
    public $setID = 0;
101
102
    /**
103
     * @var string
104
     */
105
    public $processID = '';
106
107
    /**
108
     * @var array
109
     */
110
    public $duplicateTrack = [];
111
112
    /**
113
     * @var array
114
     */
115
    public $downloadUrls = [];
116
117
    /**
118
     * @var array
119
     */
120
    public $incomingProcInstructions = [];
121
122
    /**
123
     * @var array
124
     */
125
    public $incomingConfigurationSelection = [];
126
127
    /**
128
     * @var bool
129
     */
130
    public $registerQueueEntriesInternallyOnly = false;
131
132
    /**
133
     * @var array
134
     */
135
    public $queueEntries = [];
136
137
    /**
138
     * @var array
139
     */
140
    public $urlList = [];
141
142
    /**
143
     * @var array
144
     */
145
    public $extensionSettings = [];
146
147
    /**
148
     * Mount Point
149
     *
150
     * @var bool
151
     * Todo: Check what this is used for and adjust the type hint or code, as bool doesn't match the current code.
152
     */
153
    public $MP = false;
154
155
    /**
156
     * @var string
157
     * @deprecated
158
     */
159
    protected $processFilename;
160
161
    /**
162
     * Holds the internal access mode can be 'gui','cli' or 'cli_im'
163
     *
164
     * @var string
165
     * @deprecated
166
     */
167
    protected $accessMode;
168
169
    /**
170
     * @var QueueRepository
171
     */
172
    protected $queueRepository;
173
174
    /**
175
     * @var ProcessRepository
176
     */
177
    protected $processRepository;
178
179
    /**
180
     * @var ConfigurationRepository
181
     */
182
    protected $configurationRepository;
183
184
    /**
185
     * @var string
186
     */
187
    protected $tableName = 'tx_crawler_queue';
188
189
    /**
190
     * @var QueueExecutor
191
     */
192
    protected $queueExecutor;
193
194
    /**
195
     * @var int
196
     */
197
    protected $maximumUrlsToCompile = 10000;
198
199
    /**
200
     * @var IconFactory
201
     */
202
    protected $iconFactory;
203
204
    /**
205
     * @var string[]
206
     */
207
    private $deprecatedPublicMethods = [
0 ignored issues
show
introduced by
The private property $deprecatedPublicMethods is not used, and could be removed.
Loading history...
208
        'cleanUpOldQueueEntries' => 'Using CrawlerController::cleanUpOldQueueEntries() is deprecated since 9.0.1 and will be removed in v11.x, please use QueueRepository->cleanUpOldQueueEntries() instead.',
209
        'CLI_debug' => 'Using CrawlerController->CLI_debug() is deprecated since 9.1.3 and will be removed in v11.x',
210
        'CLI_runHooks' => 'Using CrawlerController->CLI_runHooks() is deprecated since 9.1.5 and will be removed in v11.x',
211
        'getAccessMode' => 'Using CrawlerController->getAccessMode() is deprecated since 9.1.3 and will be removed in v11.x',
212
        'getLogEntriesForPageId' => 'Using CrawlerController->getLogEntriesForPageId() is deprecated since 9.1.5 and will be remove in v11.x',
213
        'getLogEntriesForSetId' => 'Using crawlerController::getLogEntriesForSetId() is deprecated since 9.0.1 and will be removed in v11.x',
214
        'flushQueue' => 'Using CrawlerController::flushQueue() is deprecated since 9.0.1 and will be removed in v11.x, please use QueueRepository->flushQueue() instead.',
215
        'setAccessMode' => 'Using CrawlerController->setAccessMode() is deprecated since 9.1.3 and will be removed in v11.x',
216
        'getDisabled' => 'Using CrawlerController->getDisabled() is deprecated since 9.1.3 and will be removed in v11.x, please use Crawler->isDisabled() instead',
217
        'setDisabled' => 'Using CrawlerController->setDisabled() is deprecated since 9.1.3 and will be removed in v11.x, please use Crawler->setDisabled() instead',
218
        'getProcessFilename' => 'Using CrawlerController->getProcessFilename() is deprecated since 9.1.3 and will be removed in v11.x',
219
        'setProcessFilename' => 'Using CrawlerController->setProcessFilename() is deprecated since 9.1.3 and will be removed in v11.x',
220
        'getDuplicateRowsIfExist' => 'Using CrawlerController->getDuplicateRowsIfExist() is deprecated since 9.1.4 and will be remove in v11.x, please use QueueRepository->getDuplicateQueueItemsIfExists() instead',
221
    ];
222
223
    /**
224
     * @var string[]
225
     */
226
    private $deprecatedPublicProperties = [
1 ignored issue
show
introduced by
The private property $deprecatedPublicProperties is not used, and could be removed.
Loading history...
227
        'accessMode' => 'Using CrawlerController->accessMode is deprecated since 9.1.3 and will be removed in v11.x',
228
        'processFilename' => 'Using CrawlerController->accessMode is deprecated since 9.1.3 and will be removed in v11.x',
229
    ];
230
231
    /**
232
     * @var BackendUserAuthentication|null
233
     */
234
    private $backendUser;
235
236
    /**
237
     * @var integer
238
     */
239
    private $scheduledTime = 0;
240
241
    /**
242
     * @var integer
243
     */
244
    private $reqMinute = 0;
245
246
    /**
247
     * @var bool
248
     */
249
    private $submitCrawlUrls = false;
250
251
    /**
252
     * @var bool
253
     */
254
    private $downloadCrawlUrls = false;
255
256
    /**
257
     * @var PageRepository
258
     */
259
    private $pageRepository;
260
261
    /**
262
     * @var Crawler
263
     */
264
    private $crawler;
265
266
    /************************************
267
     *
268
     * Getting URLs based on Page TSconfig
269
     *
270
     ************************************/
271
272 36
    public function __construct()
273
    {
274 36
        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
275 36
        $crawlStrategyFactory = GeneralUtility::makeInstance(CrawlStrategyFactory::class);
276 36
        $this->queueRepository = $objectManager->get(QueueRepository::class);
277 36
        $this->processRepository = $objectManager->get(ProcessRepository::class);
278 36
        $this->configurationRepository = $objectManager->get(ConfigurationRepository::class);
279 36
        $this->pageRepository = GeneralUtility::makeInstance(PageRepository::class);
280 36
        $this->queueExecutor = GeneralUtility::makeInstance(QueueExecutor::class, $crawlStrategyFactory);
281 36
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
282 36
        $this->crawler = GeneralUtility::makeInstance(Crawler::class);
283
284 36
        $this->processFilename = Environment::getVarPath() . '/lock/tx_crawler.proc';
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

284
        /** @scrutinizer ignore-deprecated */ $this->processFilename = Environment::getVarPath() . '/lock/tx_crawler.proc';
Loading history...
285
286
        /** @var ExtensionConfigurationProvider $configurationProvider */
287 36
        $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class);
288 36
        $settings = $configurationProvider->getExtensionConfiguration();
289 36
        $this->extensionSettings = is_array($settings) ? $settings : [];
0 ignored issues
show
introduced by
The condition is_array($settings) is always true.
Loading history...
290
291
        // set defaults:
292 36
        if (MathUtility::convertToPositiveInteger($this->extensionSettings['countInARun']) === 0) {
293
            $this->extensionSettings['countInARun'] = 100;
294
        }
295
296 36
        $this->extensionSettings['processLimit'] = MathUtility::forceIntegerInRange($this->extensionSettings['processLimit'], 1, 99, 1);
297 36
        $this->maximumUrlsToCompile = MathUtility::forceIntegerInRange($this->extensionSettings['maxCompileUrls'], 1, 1000000000, 10000);
298 36
    }
299
300
    /**
301
     * Method to set the accessMode can be gui, cli or cli_im
302
     *
303
     * @return string
304
     * @deprecated
305
     */
306 1
    public function getAccessMode()
307
    {
308 1
        return $this->accessMode;
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...Controller::$accessMode has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

308
        return /** @scrutinizer ignore-deprecated */ $this->accessMode;
Loading history...
309
    }
310
311
    /**
312
     * @param string $accessMode
313
     * @deprecated
314
     */
315 1
    public function setAccessMode($accessMode): void
316
    {
317 1
        $this->accessMode = $accessMode;
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...Controller::$accessMode has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

317
        /** @scrutinizer ignore-deprecated */ $this->accessMode = $accessMode;
Loading history...
318 1
    }
319
320
    /**
321
     * Set disabled status to prevent processes from being processed
322
     *
323
     * @param bool $disabled (optional, defaults to true)
324
     * @deprecated
325
     */
326 2
    public function setDisabled($disabled = true): void
327
    {
328 2
        if ($disabled) {
329 1
            GeneralUtility::writeFile($this->processFilename, '');
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

329
            GeneralUtility::writeFile(/** @scrutinizer ignore-deprecated */ $this->processFilename, '');
Loading history...
330
        } else {
331 1
            if (is_file($this->processFilename)) {
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

331
            if (is_file(/** @scrutinizer ignore-deprecated */ $this->processFilename)) {
Loading history...
332 1
                unlink($this->processFilename);
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

332
                unlink(/** @scrutinizer ignore-deprecated */ $this->processFilename);
Loading history...
333
            }
334
        }
335 2
    }
336
337
    /**
338
     * Get disable status
339
     *
340
     * @return bool true if disabled
341
     * @deprecated
342
     */
343 2
    public function getDisabled()
344
    {
345 2
        return is_file($this->processFilename);
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

345
        return is_file(/** @scrutinizer ignore-deprecated */ $this->processFilename);
Loading history...
346
    }
347
348
    /**
349
     * @param string $filenameWithPath
350
     * @deprecated
351
     */
352 3
    public function setProcessFilename($filenameWithPath): void
353
    {
354 3
        $this->processFilename = $filenameWithPath;
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

354
        /** @scrutinizer ignore-deprecated */ $this->processFilename = $filenameWithPath;
Loading history...
355 3
    }
356
357
    /**
358
     * @return string
359
     * @deprecated
360
     */
361 1
    public function getProcessFilename()
362
    {
363 1
        return $this->processFilename;
0 ignored issues
show
Deprecated Code introduced by
The property AOE\Crawler\Controller\C...oller::$processFilename has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

363
        return /** @scrutinizer ignore-deprecated */ $this->processFilename;
Loading history...
364
    }
365
366
    /**
367
     * Sets the extensions settings (unserialized pendant of $TYPO3_CONF_VARS['EXT']['extConf']['crawler']).
368
     */
369 14
    public function setExtensionSettings(array $extensionSettings): void
370
    {
371 14
        $this->extensionSettings = $extensionSettings;
372 14
    }
373
374
    /**
375
     * Check if the given page should be crawled
376
     *
377
     * @return false|string false if the page should be crawled (not excluded), true / skipMessage if it should be skipped
378
     */
379 12
    public function checkIfPageShouldBeSkipped(array $pageRow)
380
    {
381
        // if page is hidden
382 12
        if (! $this->extensionSettings['crawlHiddenPages'] && $pageRow['hidden']) {
383 1
            return 'Because page is hidden';
384
        }
385
386 11
        if (GeneralUtility::inList('3,4,199,254,255', $pageRow['doktype'])) {
387 3
            return 'Because doktype is not allowed';
388
        }
389
390 8
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['excludeDoktype'] ?? [] as $key => $doktypeList) {
391 1
            if (GeneralUtility::inList($doktypeList, $pageRow['doktype'])) {
392 1
                return 'Doktype was excluded by "' . $key . '"';
393
            }
394
        }
395
396
        // veto hook
397 7
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pageVeto'] ?? [] as $key => $func) {
398
            $params = [
399 2
                'pageRow' => $pageRow,
400
            ];
401
            // expects "false" if page is ok and "true" or a skipMessage if this page should _not_ be crawled
402 2
            $veto = GeneralUtility::callUserFunction($func, $params, $this);
403 2
            if ($veto !== false) {
404 2
                if (is_string($veto)) {
405 1
                    return $veto;
406
                }
407 1
                return 'Veto from hook "' . htmlspecialchars($key) . '"';
408
            }
409
        }
410
411 5
        return false;
412
    }
413
414
    /**
415
     * Wrapper method for getUrlsForPageId()
416
     * It returns an array of configurations and no urls!
417
     *
418
     * @param array $pageRow Page record with at least dok-type and uid columns.
419
     * @param string $skipMessage
420
     * @return array
421
     * @see getUrlsForPageId()
422
     */
423 6
    public function getUrlsForPageRow(array $pageRow, &$skipMessage = '')
424
    {
425 6
        if (! is_int($pageRow['uid'])) {
426
            $skipMessage = 'PageUid ' . $pageRow['uid'] . ' was not an integer';
427
            return [];
428
        }
429
430 6
        $message = $this->checkIfPageShouldBeSkipped($pageRow);
431 6
        if ($message === false) {
432 5
            $res = $this->getUrlsForPageId($pageRow['uid']);
433 5
            $skipMessage = '';
434
        } else {
435 1
            $skipMessage = $message;
436 1
            $res = [];
437
        }
438
439 6
        return $res;
440
    }
441
442
    /**
443
     * Creates a list of URLs from input array (and submits them to queue if asked for)
444
     * See Web > Info module script + "indexed_search"'s crawler hook-client using this!
445
     *
446
     * @param array $vv Information about URLs from pageRow to crawl.
447
     * @param array $pageRow Page row
448
     * @param int $scheduledTime Unix time to schedule indexing to, typically time()
449
     * @param int $reqMinute Number of requests per minute (creates the interleave between requests)
450
     * @param bool $submitCrawlUrls If set, submits the URLs to queue
451
     * @param bool $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
452
     * @param array $duplicateTrack Array which is passed by reference and contains the an id per url to secure we will not crawl duplicates
453
     * @param array $downloadUrls Array which will be filled with URLS for download if flag is set.
454
     * @param array $incomingProcInstructions Array of processing instructions
455
     * @return string List of URLs (meant for display in backend module)
456
     */
457 4
    public function urlListFromUrlArray(
458
        array $vv,
459
        array $pageRow,
460
        $scheduledTime,
461
        $reqMinute,
462
        $submitCrawlUrls,
463
        $downloadCrawlUrls,
464
        array &$duplicateTrack,
465
        array &$downloadUrls,
466
        array $incomingProcInstructions
467
    ) {
468 4
        if (! is_array($vv['URLs'])) {
469
            return 'ERROR - no URL generated';
470
        }
471 4
        $urlLog = [];
472 4
        $pageId = (int) $pageRow['uid'];
473 4
        $configurationHash = $this->getConfigurationHash($vv);
474 4
        $skipInnerCheck = $this->queueRepository->noUnprocessedQueueEntriesForPageWithConfigurationHashExist($pageId, $configurationHash);
475
476 4
        $urlService = new UrlService();
477
478 4
        foreach ($vv['URLs'] as $urlQuery) {
479 4
            if (! $this->drawURLs_PIfilter($vv['subCfg']['procInstrFilter'], $incomingProcInstructions)) {
480
                continue;
481
            }
482 4
            $url = (string) $urlService->getUrlFromPageAndQueryParameters(
483 4
                $pageId,
484
                $urlQuery,
485 4
                $vv['subCfg']['baseUrl'] ?? null,
486 4
                $vv['subCfg']['force_ssl'] ?? 0
487
            );
488
489
            // Create key by which to determine unique-ness:
490 4
            $uKey = $url . '|' . $vv['subCfg']['userGroups'] . '|' . $vv['subCfg']['procInstrFilter'];
491
492 4
            if (isset($duplicateTrack[$uKey])) {
493
                //if the url key is registered just display it and do not resubmit is
494
                $urlLog[] = '<em><span class="text-muted">' . htmlspecialchars($url) . '</span></em>';
495
            } else {
496
                // Scheduled time:
497 4
                $schTime = $scheduledTime + round(count($duplicateTrack) * (60 / $reqMinute));
498 4
                $schTime = intval($schTime / 60) * 60;
499 4
                $formattedDate = BackendUtility::datetime($schTime);
500 4
                $this->urlList[] = '[' . $formattedDate . '] ' . $url;
501 4
                $urlList = '[' . $formattedDate . '] ' . htmlspecialchars($url);
502
503
                // Submit for crawling!
504 4
                if ($submitCrawlUrls) {
505 4
                    $added = $this->addUrl(
506 4
                        $pageId,
507
                        $url,
508 4
                        $vv['subCfg'],
509
                        $scheduledTime,
510
                        $configurationHash,
511
                        $skipInnerCheck
512
                    );
513 4
                    if ($added === false) {
514 4
                        $urlList .= ' (URL already existed)';
515
                    }
516
                } elseif ($downloadCrawlUrls) {
517
                    $downloadUrls[$url] = $url;
518
                }
519 4
                $urlLog[] = $urlList;
520
            }
521 4
            $duplicateTrack[$uKey] = true;
522
        }
523
524 4
        return implode('<br>', $urlLog);
525
    }
526
527
    /**
528
     * Returns true if input processing instruction is among registered ones.
529
     *
530
     * @param string $piString PI to test
531
     * @param array $incomingProcInstructions Processing instructions
532
     * @return boolean
533
     */
534 5
    public function drawURLs_PIfilter($piString, array $incomingProcInstructions)
535
    {
536 5
        if (empty($incomingProcInstructions)) {
537 1
            return true;
538
        }
539
540 4
        foreach ($incomingProcInstructions as $pi) {
541 4
            if (GeneralUtility::inList($piString, $pi)) {
542 2
                return true;
543
            }
544
        }
545 2
        return false;
546
    }
547
548 5
    public function getPageTSconfigForId($id): array
549
    {
550 5
        if (! $this->MP) {
551 5
            $pageTSconfig = BackendUtility::getPagesTSconfig($id);
552
        } else {
553
            // TODO: Please check, this makes no sense to split a boolean value.
554
            [, $mountPointId] = explode('-', $this->MP);
0 ignored issues
show
Bug introduced by
$this->MP of type true is incompatible with the type string expected by parameter $string of explode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

554
            [, $mountPointId] = explode('-', /** @scrutinizer ignore-type */ $this->MP);
Loading history...
555
            $pageTSconfig = BackendUtility::getPagesTSconfig($mountPointId);
0 ignored issues
show
Bug introduced by
$mountPointId of type string is incompatible with the type integer expected by parameter $id of TYPO3\CMS\Backend\Utilit...ity::getPagesTSconfig(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

555
            $pageTSconfig = BackendUtility::getPagesTSconfig(/** @scrutinizer ignore-type */ $mountPointId);
Loading history...
556
        }
557
558
        // Call a hook to alter configuration
559 5
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'])) {
560
            $params = [
561
                'pageId' => $id,
562
                'pageTSConfig' => &$pageTSconfig,
563
            ];
564
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'] as $userFunc) {
565
                GeneralUtility::callUserFunction($userFunc, $params, $this);
566
            }
567
        }
568 5
        return $pageTSconfig;
569
    }
570
571
    /**
572
     * This methods returns an array of configurations.
573
     * Adds no urls!
574
     */
575 4
    public function getUrlsForPageId(int $pageId): array
576
    {
577
        // Get page TSconfig for page ID
578 4
        $pageTSconfig = $this->getPageTSconfigForId($pageId);
579
580 4
        $res = [];
581
582
        // Fetch Crawler Configuration from pageTSconfig
583 4
        $crawlerCfg = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? [];
584 4
        foreach ($crawlerCfg as $key => $values) {
585 3
            if (! is_array($values)) {
586 3
                continue;
587
            }
588 3
            $key = str_replace('.', '', $key);
589
            // Sub configuration for a single configuration string:
590 3
            $subCfg = (array) $crawlerCfg[$key . '.'];
591 3
            $subCfg['key'] = $key;
592
593 3
            if (strcmp($subCfg['procInstrFilter'] ?? '', '')) {
594 3
                $subCfg['procInstrFilter'] = implode(',', GeneralUtility::trimExplode(',', $subCfg['procInstrFilter']));
595
            }
596 3
            $pidOnlyList = implode(',', GeneralUtility::trimExplode(',', $subCfg['pidsOnly'], true));
597
598
            // process configuration if it is not page-specific or if the specific page is the current page:
599
            // TODO: Check if $pidOnlyList can be kept as Array instead of imploded
600 3
            if (! strcmp((string) $subCfg['pidsOnly'], '') || GeneralUtility::inList($pidOnlyList, strval($pageId))) {
601
602
                // Explode, process etc.:
603 3
                $res[$key] = [];
604 3
                $res[$key]['subCfg'] = $subCfg;
605 3
                $res[$key]['paramParsed'] = GeneralUtility::explodeUrl2Array($crawlerCfg[$key]);
606 3
                $res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'], $pageId);
607 3
                $res[$key]['origin'] = 'pagets';
608
609
                // recognize MP value
610 3
                if (! $this->MP) {
611 3
                    $res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], ['?id=' . $pageId]);
612
                } else {
613
                    $res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], ['?id=' . $pageId . '&MP=' . $this->MP]);
0 ignored issues
show
Bug introduced by
Are you sure $this->MP of type true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

613
                    $res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], ['?id=' . $pageId . '&MP=' . /** @scrutinizer ignore-type */ $this->MP]);
Loading history...
614
                }
615
            }
616
        }
617
618
        // Get configuration from tx_crawler_configuration records up the rootline
619 4
        $crawlerConfigurations = $this->configurationRepository->getCrawlerConfigurationRecordsFromRootLine($pageId);
620 4
        foreach ($crawlerConfigurations as $configurationRecord) {
621
622
            // check access to the configuration record
623 1
            if (empty($configurationRecord['begroups']) || $this->getBackendUser()->isAdmin() || $this->hasGroupAccess($this->getBackendUser()->user['usergroup_cached_list'], $configurationRecord['begroups'])) {
624 1
                $pidOnlyList = implode(',', GeneralUtility::trimExplode(',', $configurationRecord['pidsonly'], true));
625
626
                // process configuration if it is not page-specific or if the specific page is the current page:
627
                // TODO: Check if $pidOnlyList can be kept as Array instead of imploded
628 1
                if (! strcmp($configurationRecord['pidsonly'], '') || GeneralUtility::inList($pidOnlyList, strval($pageId))) {
629 1
                    $key = $configurationRecord['name'];
630
631
                    // don't overwrite previously defined paramSets
632 1
                    if (! isset($res[$key])) {
633
634
                        /* @var $TSparserObject TypoScriptParser */
635 1
                        $TSparserObject = GeneralUtility::makeInstance(TypoScriptParser::class);
636 1
                        $TSparserObject->parse($configurationRecord['processing_instruction_parameters_ts']);
637
638
                        $subCfg = [
639 1
                            'procInstrFilter' => $configurationRecord['processing_instruction_filter'],
640 1
                            'procInstrParams.' => $TSparserObject->setup,
641 1
                            'baseUrl' => $configurationRecord['base_url'],
642 1
                            'force_ssl' => (int) $configurationRecord['force_ssl'],
643 1
                            'userGroups' => $configurationRecord['fegroups'],
644 1
                            'exclude' => $configurationRecord['exclude'],
645 1
                            'key' => $key,
646
                        ];
647
648 1
                        if (! in_array($pageId, $this->expandExcludeString($subCfg['exclude']), true)) {
649 1
                            $res[$key] = [];
650 1
                            $res[$key]['subCfg'] = $subCfg;
651 1
                            $res[$key]['paramParsed'] = GeneralUtility::explodeUrl2Array($configurationRecord['configuration']);
652 1
                            $res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'], $pageId);
653 1
                            $res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], ['?id=' . $pageId]);
654 1
                            $res[$key]['origin'] = 'tx_crawler_configuration_' . $configurationRecord['uid'];
655
                        }
656
                    }
657
                }
658
            }
659
        }
660
661 4
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['processUrls'] ?? [] as $func) {
662
            $params = [
663
                'res' => &$res,
664
            ];
665
            GeneralUtility::callUserFunction($func, $params, $this);
666
        }
667 4
        return $res;
668
    }
669
670
    /**
671
     * Find all configurations of subpages of a page
672
     * TODO: Write Functional Tests
673
     */
674 1
    public function getConfigurationsForBranch(int $rootid, int $depth): array
675
    {
676 1
        $configurationsForBranch = [];
677 1
        $pageTSconfig = $this->getPageTSconfigForId($rootid);
678 1
        $sets = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? [];
679 1
        foreach ($sets as $key => $value) {
680
            if (! is_array($value)) {
681
                continue;
682
            }
683
            $configurationsForBranch[] = substr($key, -1) === '.' ? substr($key, 0, -1) : $key;
684
        }
685 1
        $pids = [];
686 1
        $rootLine = BackendUtility::BEgetRootLine($rootid);
687 1
        foreach ($rootLine as $node) {
688 1
            $pids[] = $node['uid'];
689
        }
690
        /* @var PageTreeView $tree */
691 1
        $tree = GeneralUtility::makeInstance(PageTreeView::class);
692 1
        $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
693 1
        $tree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause));
694 1
        $tree->getTree($rootid, $depth, '');
695 1
        foreach ($tree->tree as $node) {
696
            $pids[] = $node['row']['uid'];
697
        }
698
699 1
        $queryBuilder = $this->getQueryBuilder('tx_crawler_configuration');
700
        $statement = $queryBuilder
701 1
            ->select('name')
702 1
            ->from('tx_crawler_configuration')
703 1
            ->where(
704 1
                $queryBuilder->expr()->in('pid', $queryBuilder->createNamedParameter($pids, Connection::PARAM_INT_ARRAY))
705
            )
706 1
            ->execute();
707
708 1
        while ($row = $statement->fetch()) {
709 1
            $configurationsForBranch[] = $row['name'];
710
        }
711 1
        return $configurationsForBranch;
712
    }
713
714
    /**
715
     * Check if a user has access to an item
716
     * (e.g. get the group list of the current logged in user from $GLOBALS['TSFE']->gr_list)
717
     *
718
     * @param string $groupList Comma-separated list of (fe_)group UIDs from a user
719
     * @param string $accessList Comma-separated list of (fe_)group UIDs of the item to access
720
     * @return bool TRUE if at least one of the users group UIDs is in the access list or the access list is empty
721
     * @see \TYPO3\CMS\Frontend\Page\PageRepository::getMultipleGroupsWhereClause()
722
     */
723 3
    public function hasGroupAccess($groupList, $accessList)
724
    {
725 3
        if (empty($accessList)) {
726 1
            return true;
727
        }
728 2
        foreach (GeneralUtility::intExplode(',', $groupList) as $groupUid) {
729 2
            if (GeneralUtility::inList($accessList, $groupUid)) {
730 1
                return true;
731
            }
732
        }
733 1
        return false;
734
    }
735
736
    /**
737
     * Will expand the parameters configuration to individual values. This follows a certain syntax of the value of each parameter.
738
     * Syntax of values:
739
     * - Basically: If the value is wrapped in [...] it will be expanded according to the following syntax, otherwise the value is taken literally
740
     * - Configuration is splitted by "|" and the parts are processed individually and finally added together
741
     * - For each configuration part:
742
     *         - "[int]-[int]" = Integer range, will be expanded to all values in between, values included, starting from low to high (max. 1000). Example "1-34" or "-40--30"
743
     *         - "_TABLE:[TCA table name];[_PID:[optional page id, default is current page]];[_ENABLELANG:1]" = Look up of table records from PID, filtering out deleted records. Example "_TABLE:tt_content; _PID:123"
744
     *        _ENABLELANG:1 picks only original records without their language overlays
745
     *         - Default: Literal value
746
     *
747
     * @param array $paramArray Array with key (GET var name) and values (value of GET var which is configuration for expansion)
748
     * @param integer $pid Current page ID
749
     * @return array
750
     *
751
     * TODO: Write Functional Tests
752
     */
753 11
    public function expandParameters($paramArray, $pid)
754
    {
755
        // Traverse parameter names:
756 11
        foreach ($paramArray as $p => $v) {
757 11
            $v = trim($v);
758
759
            // If value is encapsulated in square brackets it means there are some ranges of values to find, otherwise the value is literal
760 11
            if (strpos($v, '[') === 0 && substr($v, -1) === ']') {
761
                // So, find the value inside brackets and reset the paramArray value as an array.
762 11
                $v = substr($v, 1, -1);
763 11
                $paramArray[$p] = [];
764
765
                // Explode parts and traverse them:
766 11
                $parts = explode('|', $v);
767 11
                foreach ($parts as $pV) {
768
769
                    // Look for integer range: (fx. 1-34 or -40--30 // reads minus 40 to minus 30)
770 11
                    if (preg_match('/^(-?[0-9]+)\s*-\s*(-?[0-9]+)$/', trim($pV), $reg)) {
771 1
                        $reg = $this->swapIfFirstIsLargerThanSecond($reg);
772
773
                        // Traverse range, add values:
774
                        // Limit to size of range!
775 1
                        $runAwayBrake = 1000;
776 1
                        for ($a = $reg[1]; $a <= $reg[2]; $a++) {
777 1
                            $paramArray[$p][] = $a;
778 1
                            $runAwayBrake--;
779 1
                            if ($runAwayBrake <= 0) {
780
                                break;
781
                            }
782
                        }
783 10
                    } elseif (strpos(trim($pV), '_TABLE:') === 0) {
784
785
                        // Parse parameters:
786 6
                        $subparts = GeneralUtility::trimExplode(';', $pV);
787 6
                        $subpartParams = [];
788 6
                        foreach ($subparts as $spV) {
789 6
                            [$pKey, $pVal] = GeneralUtility::trimExplode(':', $spV);
790 6
                            $subpartParams[$pKey] = $pVal;
791
                        }
792
793
                        // Table exists:
794 6
                        if (isset($GLOBALS['TCA'][$subpartParams['_TABLE']])) {
795 6
                            $lookUpPid = isset($subpartParams['_PID']) ? intval($subpartParams['_PID']) : intval($pid);
796 6
                            $recursiveDepth = isset($subpartParams['_RECURSIVE']) ? intval($subpartParams['_RECURSIVE']) : 0;
797 6
                            $pidField = isset($subpartParams['_PIDFIELD']) ? trim($subpartParams['_PIDFIELD']) : 'pid';
798 6
                            $where = $subpartParams['_WHERE'] ?? '';
799 6
                            $addTable = $subpartParams['_ADDTABLE'] ?? '';
800
801 6
                            $fieldName = $subpartParams['_FIELD'] ? $subpartParams['_FIELD'] : 'uid';
802 6
                            if ($fieldName === 'uid' || $GLOBALS['TCA'][$subpartParams['_TABLE']]['columns'][$fieldName]) {
803 6
                                $queryBuilder = $this->getQueryBuilder($subpartParams['_TABLE']);
804
805 6
                                if ($recursiveDepth > 0) {
806
                                    /** @var QueryGenerator $queryGenerator */
807 2
                                    $queryGenerator = GeneralUtility::makeInstance(QueryGenerator::class);
808 2
                                    $pidList = $queryGenerator->getTreeList($lookUpPid, $recursiveDepth, 0, 1);
809 2
                                    $pidArray = GeneralUtility::intExplode(',', $pidList);
810
                                } else {
811 4
                                    $pidArray = [(string) $lookUpPid];
812
                                }
813
814 6
                                $queryBuilder->getRestrictions()
815 6
                                    ->removeAll()
816 6
                                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
817
818
                                $queryBuilder
819 6
                                    ->select($fieldName)
820 6
                                    ->from($subpartParams['_TABLE'])
821 6
                                    ->where(
822 6
                                        $queryBuilder->expr()->in($pidField, $queryBuilder->createNamedParameter($pidArray, Connection::PARAM_INT_ARRAY)),
823
                                        $where
824
                                    );
825
826 6
                                if (! empty($addTable)) {
827
                                    // TODO: Check if this works as intended!
828
                                    $queryBuilder->add('from', $addTable);
829
                                }
830 6
                                $transOrigPointerField = $GLOBALS['TCA'][$subpartParams['_TABLE']]['ctrl']['transOrigPointerField'];
831
832 6
                                if ($subpartParams['_ENABLELANG'] && $transOrigPointerField) {
833
                                    $queryBuilder->andWhere(
834
                                        $queryBuilder->expr()->lte(
835
                                            $transOrigPointerField,
836
                                            0
837
                                        )
838
                                    );
839
                                }
840
841 6
                                $statement = $queryBuilder->execute();
842
843 6
                                $rows = [];
844 6
                                while ($row = $statement->fetch()) {
845 6
                                    $rows[$row[$fieldName]] = $row;
846
                                }
847
848 6
                                if (is_array($rows)) {
849 6
                                    $paramArray[$p] = array_merge($paramArray[$p], array_keys($rows));
850
                                }
851
                            }
852
                        }
853
                    } else {
854
                        // Just add value:
855 4
                        $paramArray[$p][] = $pV;
856
                    }
857
                    // Hook for processing own expandParameters place holder
858 11
                    if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['crawler/class.tx_crawler_lib.php']['expandParameters'])) {
859
                        $_params = [
860
                            'pObj' => &$this,
861
                            'paramArray' => &$paramArray,
862
                            'currentKey' => $p,
863
                            'currentValue' => $pV,
864
                            'pid' => $pid,
865
                        ];
866
                        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['crawler/class.tx_crawler_lib.php']['expandParameters'] as $_funcRef) {
867
                            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
868
                        }
869
                    }
870
                }
871
872
                // Make unique set of values and sort array by key:
873 11
                $paramArray[$p] = array_unique($paramArray[$p]);
874 11
                ksort($paramArray);
875
            } else {
876
                // Set the literal value as only value in array:
877 4
                $paramArray[$p] = [$v];
878
            }
879
        }
880
881 11
        return $paramArray;
882
    }
883
884
    /**
885
     * Compiling URLs from parameter array (output of expandParameters())
886
     * The number of URLs will be the multiplication of the number of parameter values for each key
887
     *
888
     * @param array $paramArray Output of expandParameters(): Array with keys (GET var names) and for each an array of values
889
     * @param array $urls URLs accumulated in this array (for recursion)
890
     * @return array
891
     */
892 7
    public function compileUrls($paramArray, array $urls)
893
    {
894 7
        if (empty($paramArray)) {
895 7
            return $urls;
896
        }
897
        // shift first off stack:
898 6
        reset($paramArray);
899 6
        $varName = key($paramArray);
900 6
        $valueSet = array_shift($paramArray);
901
902
        // Traverse value set:
903 6
        $newUrls = [];
904 6
        foreach ($urls as $url) {
905 5
            foreach ($valueSet as $val) {
906 5
                $newUrls[] = $url . (strcmp((string) $val, '') ? '&' . rawurlencode($varName) . '=' . rawurlencode((string) $val) : '');
907
908 5
                if (count($newUrls) > $this->maximumUrlsToCompile) {
909
                    break;
910
                }
911
            }
912
        }
913 6
        return $this->compileUrls($paramArray, $newUrls);
914
    }
915
916
    /************************************
917
     *
918
     * Crawler log
919
     *
920
     ************************************/
921
922
    /**
923
     * Return array of records from crawler queue for input page ID
924
     *
925
     * @param integer $id Page ID for which to look up log entries.
926
     * @param boolean $doFlush If TRUE, then entries selected at DELETED(!) instead of selected!
927
     * @param boolean $doFullFlush
928
     * @param integer $itemsPerPage Limit the amount of entries per page default is 10
929
     * @return array
930
     *
931
     * @deprecated
932
     */
933 4
    public function getLogEntriesForPageId($id, QueueFilter $queueFilter, $doFlush = false, $doFullFlush = false, $itemsPerPage = 10)
0 ignored issues
show
Unused Code introduced by
The parameter $doFullFlush is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

933
    public function getLogEntriesForPageId($id, QueueFilter $queueFilter, $doFlush = false, /** @scrutinizer ignore-unused */ $doFullFlush = false, $itemsPerPage = 10)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
934
    {
935 4
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
936
        $queryBuilder
937 4
            ->select('*')
938 4
            ->from($this->tableName)
939 4
            ->where(
940 4
                $queryBuilder->expr()->eq('page_id', $queryBuilder->createNamedParameter($id, PDO::PARAM_INT))
941
            )
942 4
            ->orderBy('scheduled', 'DESC');
943
944 4
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
945 4
            ->getConnectionForTable($this->tableName)
946 4
            ->getExpressionBuilder();
947 4
        $query = $expressionBuilder->andX();
0 ignored issues
show
Unused Code introduced by
The assignment to $query is dead and can be removed.
Loading history...
948
        // PHPStorm adds the highlight that the $addWhere is immediately overwritten,
949
        // but the $query = $expressionBuilder->andX() ensures that the $addWhere is written correctly with AND
950
        // between the statements, it's not a mistake in the code.
951 4
        switch ($queueFilter) {
952 4
            case 'pending':
953
                $queryBuilder->andWhere($queryBuilder->expr()->eq('exec_time', 0));
954
                break;
955 4
            case 'finished':
956
                $queryBuilder->andWhere($queryBuilder->expr()->gt('exec_time', 0));
957
                break;
958
        }
959
960 4
        if ($doFlush) {
961 2
            $this->queueRepository->flushQueue($queueFilter);
962
        }
963 4
        if ($itemsPerPage > 0) {
964
            $queryBuilder
965 4
                ->setMaxResults((int) $itemsPerPage);
966
        }
967
968 4
        return $queryBuilder->execute()->fetchAll();
969
    }
970
971
    /**
972
     * Return array of records from crawler queue for input set ID
973
     *
974
     * @param int $set_id Set ID for which to look up log entries.
975
     * @param string $filter Filter: "all" => all entries, "pending" => all that is not yet run, "finished" => all complete ones
976
     * @param bool $doFlush If TRUE, then entries selected at DELETED(!) instead of selected!
977
     * @param int $itemsPerPage Limit the amount of entries per page default is 10
978
     * @return array
979
     *
980
     * @deprecated
981
     */
982 6
    public function getLogEntriesForSetId(int $set_id, string $filter = '', bool $doFlush = false, bool $doFullFlush = false, int $itemsPerPage = 10)
983
    {
984 6
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
985
        $queryBuilder
986 6
            ->select('*')
987 6
            ->from($this->tableName)
988 6
            ->where(
989 6
                $queryBuilder->expr()->eq('set_id', $queryBuilder->createNamedParameter($set_id, PDO::PARAM_INT))
990
            )
991 6
            ->orderBy('scheduled', 'DESC');
992
993 6
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
994 6
            ->getConnectionForTable($this->tableName)
995 6
            ->getExpressionBuilder();
996 6
        $query = $expressionBuilder->andX();
997
        // PHPStorm adds the highlight that the $addWhere is immediately overwritten,
998
        // but the $query = $expressionBuilder->andX() ensures that the $addWhere is written correctly with AND
999
        // between the statements, it's not a mistake in the code.
1000 6
        $addWhere = '';
1001 6
        switch ($filter) {
1002 6
            case 'pending':
1003 1
                $queryBuilder->andWhere($queryBuilder->expr()->eq('exec_time', 0));
1004 1
                $addWhere = $query->add($expressionBuilder->eq('exec_time', 0));
0 ignored issues
show
Unused Code introduced by
The assignment to $addWhere is dead and can be removed.
Loading history...
1005 1
                break;
1006 5
            case 'finished':
1007 1
                $queryBuilder->andWhere($queryBuilder->expr()->gt('exec_time', 0));
1008 1
                $addWhere = $query->add($expressionBuilder->gt('exec_time', 0));
1009 1
                break;
1010
        }
1011 6
        if ($doFlush) {
1012 4
            $addWhere = $query->add($expressionBuilder->eq('set_id', (int) $set_id));
1013 4
            $this->flushQueue($doFullFlush ? '' : $addWhere);
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...ontroller::flushQueue() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1013
            /** @scrutinizer ignore-deprecated */ $this->flushQueue($doFullFlush ? '' : $addWhere);
Loading history...
1014 4
            return [];
1015
        }
1016 2
        if ($itemsPerPage > 0) {
1017
            $queryBuilder
1018 2
                ->setMaxResults((int) $itemsPerPage);
1019
        }
1020
1021 2
        return $queryBuilder->execute()->fetchAll();
1022
    }
1023
1024
    /**
1025
     * Adding call back entries to log (called from hooks typically, see indexed search class "class.crawler.php"
1026
     *
1027
     * @param integer $setId Set ID
1028
     * @param array $params Parameters to pass to call back function
1029
     * @param string $callBack Call back object reference, eg. 'EXT:indexed_search/class.crawler.php:&tx_indexedsearch_crawler'
1030
     * @param integer $page_id Page ID to attach it to
1031
     * @param integer $schedule Time at which to activate
1032
     */
1033
    public function addQueueEntry_callBack($setId, $params, $callBack, $page_id = 0, $schedule = 0): void
1034
    {
1035
        if (! is_array($params)) {
0 ignored issues
show
introduced by
The condition is_array($params) is always true.
Loading history...
1036
            $params = [];
1037
        }
1038
        $params['_CALLBACKOBJ'] = $callBack;
1039
1040
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_queue')
1041
            ->insert(
1042
                'tx_crawler_queue',
1043
                [
1044
                    'page_id' => (int) $page_id,
1045
                    'parameters' => json_encode($params),
1046
                    'scheduled' => (int) $schedule ?: $this->getCurrentTime(),
1047
                    'exec_time' => 0,
1048
                    'set_id' => (int) $setId,
1049
                    'result_data' => '',
1050
                ]
1051
            );
1052
    }
1053
1054
    /************************************
1055
     *
1056
     * URL setting
1057
     *
1058
     ************************************/
1059
1060
    /**
1061
     * Setting a URL for crawling:
1062
     *
1063
     * @param integer $id Page ID
1064
     * @param string $url Complete URL
1065
     * @param array $subCfg Sub configuration array (from TS config)
1066
     * @param integer $tstamp Scheduled-time
1067
     * @param string $configurationHash (optional) configuration hash
1068
     * @param bool $skipInnerDuplicationCheck (optional) skip inner duplication check
1069
     * @return bool
1070
     */
1071 8
    public function addUrl(
1072
        $id,
1073
        $url,
1074
        array $subCfg,
1075
        $tstamp,
1076
        $configurationHash = '',
1077
        $skipInnerDuplicationCheck = false
1078
    ) {
1079 8
        $urlAdded = false;
1080 8
        $rows = [];
1081
1082
        // Creating parameters:
1083
        $parameters = [
1084 8
            'url' => $url,
1085
        ];
1086
1087
        // fe user group simulation:
1088 8
        $uGs = implode(',', array_unique(GeneralUtility::intExplode(',', $subCfg['userGroups'], true)));
1089 8
        if ($uGs) {
1090 1
            $parameters['feUserGroupList'] = $uGs;
1091
        }
1092
1093
        // Setting processing instructions
1094 8
        $parameters['procInstructions'] = GeneralUtility::trimExplode(',', $subCfg['procInstrFilter']);
1095 8
        if (is_array($subCfg['procInstrParams.'])) {
1096 5
            $parameters['procInstrParams'] = $subCfg['procInstrParams.'];
1097
        }
1098
1099
        // Compile value array:
1100 8
        $parameters_serialized = json_encode($parameters);
1101
        $fieldArray = [
1102 8
            'page_id' => (int) $id,
1103 8
            'parameters' => $parameters_serialized,
1104 8
            'parameters_hash' => GeneralUtility::shortMD5($parameters_serialized),
1105 8
            'configuration_hash' => $configurationHash,
1106 8
            'scheduled' => $tstamp,
1107 8
            'exec_time' => 0,
1108 8
            'set_id' => (int) $this->setID,
1109 8
            'result_data' => '',
1110 8
            'configuration' => $subCfg['key'],
1111
        ];
1112
1113 8
        if ($this->registerQueueEntriesInternallyOnly) {
1114
            //the entries will only be registered and not stored to the database
1115 1
            $this->queueEntries[] = $fieldArray;
1116
        } else {
1117 7
            if (! $skipInnerDuplicationCheck) {
1118
                // check if there is already an equal entry
1119 6
                $rows = $this->queueRepository->getDuplicateQueueItemsIfExists(
1120 6
                    (bool) $this->extensionSettings['enableTimeslot'],
1121
                    $tstamp,
1122 6
                    $this->getCurrentTime(),
1123 6
                    $fieldArray['page_id'],
1124 6
                    $fieldArray['parameters_hash']
1125
                );
1126
            }
1127
1128 7
            if (empty($rows)) {
1129 6
                $connectionForCrawlerQueue = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_queue');
1130 6
                $connectionForCrawlerQueue->insert(
1131 6
                    'tx_crawler_queue',
1132
                    $fieldArray
1133
                );
1134 6
                $uid = $connectionForCrawlerQueue->lastInsertId('tx_crawler_queue', 'qid');
1135 6
                $rows[] = $uid;
1136 6
                $urlAdded = true;
1137
1138 6
                $signalPayload = ['uid' => $uid, 'fieldArray' => $fieldArray];
1139 6
                SignalSlotUtility::emitSignal(
1140 6
                    self::class,
1141 6
                    SignalSlotUtility::SIGNAL_URL_ADDED_TO_QUEUE,
1142
                    $signalPayload
1143
                );
1144
            } else {
1145 3
                $signalPayload = ['rows' => $rows, 'fieldArray' => $fieldArray];
1146 3
                SignalSlotUtility::emitSignal(
1147 3
                    self::class,
1148 3
                    SignalSlotUtility::SIGNAL_DUPLICATE_URL_IN_QUEUE,
1149
                    $signalPayload
1150
                );
1151
            }
1152
        }
1153
1154 8
        return $urlAdded;
1155
    }
1156
1157
    /**
1158
     * Returns the current system time
1159
     *
1160
     * @return int
1161
     */
1162 2
    public function getCurrentTime()
1163
    {
1164 2
        return time();
1165
    }
1166
1167
    /************************************
1168
     *
1169
     * URL reading
1170
     *
1171
     ************************************/
1172
1173
    /**
1174
     * Read URL for single queue entry
1175
     *
1176
     * @param integer $queueId
1177
     * @param boolean $force If set, will process even if exec_time has been set!
1178
     * @return integer
1179
     */
1180
    public function readUrl($queueId, $force = false)
1181
    {
1182
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
1183
        $ret = 0;
1184
        $this->logger->debug('crawler-readurl start ' . microtime(true));
1185
        // Get entry:
1186
        $queryBuilder
1187
            ->select('*')
1188
            ->from('tx_crawler_queue')
1189
            ->where(
1190
                $queryBuilder->expr()->eq('qid', $queryBuilder->createNamedParameter($queueId, PDO::PARAM_INT))
1191
            );
1192
        if (! $force) {
1193
            $queryBuilder
1194
                ->andWhere('exec_time = 0')
1195
                ->andWhere('process_scheduled > 0');
1196
        }
1197
        $queueRec = $queryBuilder->execute()->fetch();
1198
1199
        if (! is_array($queueRec)) {
1200
            return;
1201
        }
1202
1203
        SignalSlotUtility::emitSignal(
1204
            self::class,
1205
            SignalSlotUtility::SIGNAL_QUEUEITEM_PREPROCESS,
1206
            [$queueId, &$queueRec]
1207
        );
1208
1209
        // Set exec_time to lock record:
1210
        $field_array = ['exec_time' => $this->getCurrentTime()];
1211
1212
        if (isset($this->processID)) {
1213
            //if mulitprocessing is used we need to store the id of the process which has handled this entry
1214
            $field_array['process_id_completed'] = $this->processID;
1215
        }
1216
1217
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_queue')
1218
            ->update(
1219
                'tx_crawler_queue',
1220
                $field_array,
1221
                ['qid' => (int) $queueId]
1222
            );
1223
1224
        $result = $this->queueExecutor->executeQueueItem($queueRec, $this);
1225
        if ($result['content'] === null) {
1226
            $resultData = 'An errors happened';
1227
        } else {
1228
            /** @var JsonCompatibilityConverter $jsonCompatibilityConverter */
1229
            $jsonCompatibilityConverter = GeneralUtility::makeInstance(JsonCompatibilityConverter::class);
1230
            $resultData = $jsonCompatibilityConverter->convert($result['content']);
1231
        }
1232
1233
        //atm there's no need to point to specific pollable extensions
1234
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'])) {
1235
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pollSuccess'] as $pollable) {
1236
                // only check the success value if the instruction is runnig
1237
                // it is important to name the pollSuccess key same as the procInstructions key
1238
                if (is_array($resultData['parameters']['procInstructions'])
1239
                    && in_array(
1240
                        $pollable,
1241
                        $resultData['parameters']['procInstructions'], true
1242
                    )
1243
                ) {
1244
                    if (! empty($resultData['success'][$pollable]) && $resultData['success'][$pollable]) {
1245
                        $ret |= self::CLI_STATUS_POLLABLE_PROCESSED;
1246
                    }
1247
                }
1248
            }
1249
        }
1250
1251
        // Set result in log which also denotes the end of the processing of this entry.
1252
        $field_array = ['result_data' => json_encode($result)];
1253
1254
        SignalSlotUtility::emitSignal(
1255
            self::class,
1256
            SignalSlotUtility::SIGNAL_QUEUEITEM_POSTPROCESS,
1257
            [$queueId, &$field_array]
1258
        );
1259
1260
        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_queue')
1261
            ->update(
1262
                'tx_crawler_queue',
1263
                $field_array,
1264
                ['qid' => (int) $queueId]
1265
            );
1266
1267
        $this->logger->debug('crawler-readurl stop ' . microtime(true));
1268
        return $ret;
1269
    }
1270
1271
    /**
1272
     * Read URL for not-yet-inserted log-entry
1273
     *
1274
     * @param array $field_array Queue field array,
1275
     *
1276
     * @return array|bool|mixed|string
1277
     */
1278
    public function readUrlFromArray($field_array)
1279
    {
1280
        // Set exec_time to lock record:
1281
        $field_array['exec_time'] = $this->getCurrentTime();
1282
        $connectionForCrawlerQueue = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->tableName);
1283
        $connectionForCrawlerQueue->insert(
1284
            $this->tableName,
1285
            $field_array
1286
        );
1287
        $queueId = $connectionForCrawlerQueue->lastInsertId($this->tableName, 'qid');
1288
        $result = $this->queueExecutor->executeQueueItem($field_array, $this);
1289
1290
        // Set result in log which also denotes the end of the processing of this entry.
1291
        $field_array = ['result_data' => json_encode($result)];
1292
1293
        SignalSlotUtility::emitSignal(
1294
            self::class,
1295
            SignalSlotUtility::SIGNAL_QUEUEITEM_POSTPROCESS,
1296
            [$queueId, &$field_array]
1297
        );
1298
1299
        $connectionForCrawlerQueue->update(
1300
            $this->tableName,
1301
            $field_array,
1302
            ['qid' => $queueId]
1303
        );
1304
1305
        return $result;
1306
    }
1307
1308
    /*****************************
1309
     *
1310
     * Compiling URLs to crawl - tools
1311
     *
1312
     *****************************/
1313
1314
    /**
1315
     * @param integer $id Root page id to start from.
1316
     * @param integer $depth Depth of tree, 0=only id-page, 1= on sublevel, 99 = infinite
1317
     * @param integer $scheduledTime Unix Time when the URL is timed to be visited when put in queue
1318
     * @param integer $reqMinute Number of requests per minute (creates the interleave between requests)
1319
     * @param boolean $submitCrawlUrls If set, submits the URLs to queue in database (real crawling)
1320
     * @param boolean $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
1321
     * @param array $incomingProcInstructions Array of processing instructions
1322
     * @param array $configurationSelection Array of configuration keys
1323
     * @return string
1324
     */
1325
    public function getPageTreeAndUrls(
1326
        $id,
1327
        $depth,
1328
        $scheduledTime,
1329
        $reqMinute,
1330
        $submitCrawlUrls,
1331
        $downloadCrawlUrls,
1332
        array $incomingProcInstructions,
1333
        array $configurationSelection
1334
    ) {
1335
        $this->scheduledTime = $scheduledTime;
1336
        $this->reqMinute = $reqMinute;
1337
        $this->submitCrawlUrls = $submitCrawlUrls;
1338
        $this->downloadCrawlUrls = $downloadCrawlUrls;
1339
        $this->incomingProcInstructions = $incomingProcInstructions;
1340
        $this->incomingConfigurationSelection = $configurationSelection;
1341
1342
        $this->duplicateTrack = [];
1343
        $this->downloadUrls = [];
1344
1345
        // Drawing tree:
1346
        /* @var PageTreeView $tree */
1347
        $tree = GeneralUtility::makeInstance(PageTreeView::class);
1348
        $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
1349
        $tree->init('AND ' . $perms_clause);
1350
1351
        $pageInfo = BackendUtility::readPageAccess($id, $perms_clause);
1352
        if (is_array($pageInfo)) {
1353
            // Set root row:
1354
            $tree->tree[] = [
1355
                'row' => $pageInfo,
1356
                'HTML' => $this->iconFactory->getIconForRecord('pages', $pageInfo, Icon::SIZE_SMALL),
1357
            ];
1358
        }
1359
1360
        // Get branch beneath:
1361
        if ($depth) {
1362
            $tree->getTree($id, $depth, '');
1363
        }
1364
1365
        // Traverse page tree:
1366
        $code = '';
1367
1368
        foreach ($tree->tree as $data) {
1369
            $this->MP = false;
1370
1371
            // recognize mount points
1372
            if ($data['row']['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
1373
                $mountpage = $this->pageRepository->getPage($data['row']['uid']);
1374
1375
                // fetch mounted pages
1376
                $this->MP = $mountpage[0]['mount_pid'] . '-' . $data['row']['uid'];
0 ignored issues
show
Documentation Bug introduced by
The property $MP was declared of type boolean, but $mountpage[0]['mount_pid...' . $data['row']['uid'] is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1377
1378
                $mountTree = GeneralUtility::makeInstance(PageTreeView::class);
1379
                $mountTree->init('AND ' . $perms_clause);
1380
                $mountTree->getTree($mountpage[0]['mount_pid'], $depth);
1381
1382
                foreach ($mountTree->tree as $mountData) {
1383
                    $code .= $this->drawURLs_addRowsForPage(
1384
                        $mountData['row'],
1385
                        $mountData['HTML'] . BackendUtility::getRecordTitle('pages', $mountData['row'], true)
1386
                    );
1387
                }
1388
1389
                // replace page when mount_pid_ol is enabled
1390
                if ($mountpage[0]['mount_pid_ol']) {
1391
                    $data['row']['uid'] = $mountpage[0]['mount_pid'];
1392
                } else {
1393
                    // if the mount_pid_ol is not set the MP must not be used for the mountpoint page
1394
                    $this->MP = false;
1395
                }
1396
            }
1397
1398
            $code .= $this->drawURLs_addRowsForPage(
1399
                $data['row'],
1400
                $data['HTML'] . BackendUtility::getRecordTitle('pages', $data['row'], true)
1401
            );
1402
        }
1403
1404
        return $code;
1405
    }
1406
1407
    /**
1408
     * Expands exclude string
1409
     *
1410
     * @param string $excludeString Exclude string
1411
     * @return array
1412
     */
1413 2
    public function expandExcludeString($excludeString)
1414
    {
1415
        // internal static caches;
1416 2
        static $expandedExcludeStringCache;
1417 2
        static $treeCache;
1418
1419 2
        if (empty($expandedExcludeStringCache[$excludeString])) {
1420 2
            $pidList = [];
1421
1422 2
            if (! empty($excludeString)) {
1423
                /** @var PageTreeView $tree */
1424 1
                $tree = GeneralUtility::makeInstance(PageTreeView::class);
1425 1
                $tree->init('AND ' . $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW));
1426
1427 1
                $excludeParts = GeneralUtility::trimExplode(',', $excludeString);
1428
1429 1
                foreach ($excludeParts as $excludePart) {
1430 1
                    [$pid, $depth] = GeneralUtility::trimExplode('+', $excludePart);
1431
1432
                    // default is "page only" = "depth=0"
1433 1
                    if (empty($depth)) {
1434 1
                        $depth = (stristr($excludePart, '+')) ? 99 : 0;
1435
                    }
1436
1437 1
                    $pidList[] = (int) $pid;
1438
1439 1
                    if ($depth > 0) {
1440
                        if (empty($treeCache[$pid][$depth])) {
1441
                            $tree->reset();
1442
                            $tree->getTree($pid, $depth);
0 ignored issues
show
Bug introduced by
$pid of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Tree\V...ractTreeView::getTree(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1442
                            $tree->getTree(/** @scrutinizer ignore-type */ $pid, $depth);
Loading history...
1443
                            $treeCache[$pid][$depth] = $tree->tree;
1444
                        }
1445
1446
                        foreach ($treeCache[$pid][$depth] as $data) {
1447
                            $pidList[] = (int) $data['row']['uid'];
1448
                        }
1449
                    }
1450
                }
1451
            }
1452
1453 2
            $expandedExcludeStringCache[$excludeString] = array_unique($pidList);
1454
        }
1455
1456 2
        return $expandedExcludeStringCache[$excludeString];
1457
    }
1458
1459
    /**
1460
     * Create the rows for display of the page tree
1461
     * For each page a number of rows are shown displaying GET variable configuration
1462
     */
1463
    public function drawURLs_addRowsForPage(array $pageRow, string $pageTitle): string
1464
    {
1465
        $skipMessage = '';
1466
1467
        // Get list of configurations
1468
        $configurations = $this->getUrlsForPageRow($pageRow, $skipMessage);
1469
        $configurations = ConfigurationService::removeDisallowedConfigurations($this->incomingConfigurationSelection, $configurations);
1470
1471
        // Traverse parameter combinations:
1472
        $c = 0;
1473
        $content = '';
1474
        if (! empty($configurations)) {
1475
            foreach ($configurations as $confKey => $confArray) {
1476
1477
                // Title column:
1478
                if (! $c) {
1479
                    $titleClm = '<td rowspan="' . count($configurations) . '">' . $pageTitle . '</td>';
1480
                } else {
1481
                    $titleClm = '';
1482
                }
1483
1484
                if (! in_array($pageRow['uid'], $this->expandExcludeString($confArray['subCfg']['exclude']), true)) {
1485
1486
                    // URL list:
1487
                    $urlList = $this->urlListFromUrlArray(
1488
                        $confArray,
1489
                        $pageRow,
1490
                        $this->scheduledTime,
1491
                        $this->reqMinute,
1492
                        $this->submitCrawlUrls,
1493
                        $this->downloadCrawlUrls,
1494
                        $this->duplicateTrack,
1495
                        $this->downloadUrls,
1496
                        // if empty the urls won't be filtered by processing instructions
1497
                        $this->incomingProcInstructions
1498
                    );
1499
1500
                    // Expanded parameters:
1501
                    $paramExpanded = '';
1502
                    $calcAccu = [];
1503
                    $calcRes = 1;
1504
                    foreach ($confArray['paramExpanded'] as $gVar => $gVal) {
1505
                        $paramExpanded .= '
1506
                            <tr>
1507
                                <td>' . htmlspecialchars('&' . $gVar . '=') . '<br/>' .
1508
                            '(' . count($gVal) . ')' .
1509
                            '</td>
1510
                                <td nowrap="nowrap">' . nl2br(htmlspecialchars(implode(chr(10), $gVal))) . '</td>
1511
                            </tr>
1512
                        ';
1513
                        $calcRes *= count($gVal);
1514
                        $calcAccu[] = count($gVal);
1515
                    }
1516
                    $paramExpanded = '<table>' . $paramExpanded . '</table>';
1517
                    $paramExpanded .= 'Comb: ' . implode('*', $calcAccu) . '=' . $calcRes;
1518
1519
                    // Options
1520
                    $optionValues = '';
1521
                    if ($confArray['subCfg']['userGroups']) {
1522
                        $optionValues .= 'User Groups: ' . $confArray['subCfg']['userGroups'] . '<br/>';
1523
                    }
1524
                    if ($confArray['subCfg']['procInstrFilter']) {
1525
                        $optionValues .= 'ProcInstr: ' . $confArray['subCfg']['procInstrFilter'] . '<br/>';
1526
                    }
1527
1528
                    // Compile row:
1529
                    $content .= '
1530
                        <tr>
1531
                            ' . $titleClm . '
1532
                            <td>' . htmlspecialchars($confKey) . '</td>
1533
                            <td>' . nl2br(htmlspecialchars(rawurldecode(trim(str_replace('&', chr(10) . '&', GeneralUtility::implodeArrayForUrl('', $confArray['paramParsed'])))))) . '</td>
1534
                            <td>' . $paramExpanded . '</td>
1535
                            <td nowrap="nowrap">' . $urlList . '</td>
1536
                            <td nowrap="nowrap">' . $optionValues . '</td>
1537
                            <td nowrap="nowrap">' . DebugUtility::viewArray($confArray['subCfg']['procInstrParams.']) . '</td>
1538
                        </tr>';
1539
                } else {
1540
                    $content .= '<tr>
1541
                            ' . $titleClm . '
1542
                            <td>' . htmlspecialchars($confKey) . '</td>
1543
                            <td colspan="5"><em>No entries</em> (Page is excluded in this configuration)</td>
1544
                        </tr>';
1545
                }
1546
1547
                $c++;
1548
            }
1549
        } else {
1550
            $message = ! empty($skipMessage) ? ' (' . $skipMessage . ')' : '';
1551
1552
            // Compile row:
1553
            $content .= '
1554
                <tr>
1555
                    <td>' . $pageTitle . '</td>
1556
                    <td colspan="6"><em>No entries</em>' . $message . '</td>
1557
                </tr>';
1558
        }
1559
1560
        return $content;
1561
    }
1562
1563
    /*****************************
1564
     *
1565
     * CLI functions
1566
     *
1567
     *****************************/
1568
1569
    /**
1570
     * Running the functionality of the CLI (crawling URLs from queue)
1571
     */
1572
    public function CLI_run(int $countInARun, int $sleepTime, int $sleepAfterFinish): int
1573
    {
1574
        $result = 0;
1575
        $counter = 0;
1576
1577
        // First, run hooks:
1578
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['cli_hooks'] ?? [] as $objRef) {
1579
            trigger_error(
1580
                'This hook (crawler/cli_hooks) is deprecated since 9.1.5 and will be removed when dropping support for TYPO3 9LTS and 10LTS',
1581
                E_USER_DEPRECATED
1582
            );
1583
            $hookObj = GeneralUtility::makeInstance($objRef);
1584
            if (is_object($hookObj)) {
1585
                $hookObj->crawler_init($this);
1586
            }
1587
        }
1588
1589
        // Clean up the queue
1590
        $this->queueRepository->cleanupQueue();
1591
1592
        // Select entries:
1593
        $rows = $this->queueRepository->fetchRecordsToBeCrawled($countInARun);
1594
1595
        if (! empty($rows)) {
1596
            $quidList = [];
1597
1598
            foreach ($rows as $r) {
1599
                $quidList[] = $r['qid'];
1600
            }
1601
1602
            $processId = $this->CLI_buildProcessId();
1603
1604
            //save the number of assigned queue entries to determine how many have been processed later
1605
            $numberOfAffectedRows = $this->queueRepository->updateProcessIdAndSchedulerForQueueIds($quidList, $processId);
1606
            $this->processRepository->updateProcessAssignItemsCount($numberOfAffectedRows, $processId);
1607
1608
            if ($numberOfAffectedRows !== count($quidList)) {
1609
                $this->CLI_debug('Nothing processed due to multi-process collision (' . $this->CLI_buildProcessId() . ')');
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...Controller::CLI_debug() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1609
                /** @scrutinizer ignore-deprecated */ $this->CLI_debug('Nothing processed due to multi-process collision (' . $this->CLI_buildProcessId() . ')');
Loading history...
1610
                return ($result | self::CLI_STATUS_ABORTED);
1611
            }
1612
1613
            foreach ($rows as $r) {
1614
                $result |= $this->readUrl($r['qid']);
1615
1616
                $counter++;
1617
                // Just to relax the system
1618
                usleep((int) $sleepTime);
1619
1620
                // if during the start and the current read url the cli has been disable we need to return from the function
1621
                // mark the process NOT as ended.
1622
                if ($this->crawler->isDisabled()) {
1623
                    return ($result | self::CLI_STATUS_ABORTED);
1624
                }
1625
1626
                if (! $this->processRepository->isProcessActive($this->CLI_buildProcessId())) {
1627
                    $this->CLI_debug('conflict / timeout (' . $this->CLI_buildProcessId() . ')');
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...Controller::CLI_debug() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1627
                    /** @scrutinizer ignore-deprecated */ $this->CLI_debug('conflict / timeout (' . $this->CLI_buildProcessId() . ')');
Loading history...
1628
                    $result |= self::CLI_STATUS_ABORTED;
1629
                    //possible timeout
1630
                    break;
1631
                }
1632
            }
1633
1634
            sleep((int) $sleepAfterFinish);
1635
1636
            $msg = 'Rows: ' . $counter;
1637
            $this->CLI_debug($msg . ' (' . $this->CLI_buildProcessId() . ')');
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...Controller::CLI_debug() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1637
            /** @scrutinizer ignore-deprecated */ $this->CLI_debug($msg . ' (' . $this->CLI_buildProcessId() . ')');
Loading history...
1638
        } else {
1639
            $this->CLI_debug('Nothing within queue which needs to be processed (' . $this->CLI_buildProcessId() . ')');
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...Controller::CLI_debug() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1639
            /** @scrutinizer ignore-deprecated */ $this->CLI_debug('Nothing within queue which needs to be processed (' . $this->CLI_buildProcessId() . ')');
Loading history...
1640
        }
1641
1642
        if ($counter > 0) {
1643
            $result |= self::CLI_STATUS_PROCESSED;
1644
        }
1645
1646
        return $result;
1647
    }
1648
1649
    /**
1650
     * Activate hooks
1651
     * @deprecated
1652
     */
1653
    public function CLI_runHooks(): void
1654
    {
1655
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['cli_hooks'] ?? [] as $objRef) {
1656
            $hookObj = GeneralUtility::makeInstance($objRef);
1657
            if (is_object($hookObj)) {
1658
                $hookObj->crawler_init($this);
1659
            }
1660
        }
1661
    }
1662
1663
    /**
1664
     * Try to acquire a new process with the given id
1665
     * also performs some auto-cleanup for orphan processes
1666
     * @param string $id identification string for the process
1667
     * @return boolean
1668
     * @todo preemption might not be the most elegant way to clean up
1669
     */
1670
    public function CLI_checkAndAcquireNewProcess($id)
1671
    {
1672
        $ret = true;
1673
1674
        $systemProcessId = getmypid();
1675
        if (! $systemProcessId) {
1676
            return false;
1677
        }
1678
1679
        $processCount = 0;
1680
        $orphanProcesses = [];
1681
1682
        $activeProcesses = $this->processRepository->findAllActive();
1683
        $currentTime = $this->getCurrentTime();
1684
1685
        /** @var Process $process */
1686
        foreach ($activeProcesses as $process) {
1687
            if ($process->getTtl() < $currentTime) {
1688
                $orphanProcesses[] = $process->getProcessId();
1689
            } else {
1690
                $processCount++;
1691
            }
1692
        }
1693
1694
        // if there are less than allowed active processes then add a new one
1695
        if ($processCount < (int) $this->extensionSettings['processLimit']) {
1696
            $this->CLI_debug('add process ' . $this->CLI_buildProcessId() . ' (' . ($processCount + 1) . '/' . (int) $this->extensionSettings['processLimit'] . ')');
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...Controller::CLI_debug() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1696
            /** @scrutinizer ignore-deprecated */ $this->CLI_debug('add process ' . $this->CLI_buildProcessId() . ' (' . ($processCount + 1) . '/' . (int) $this->extensionSettings['processLimit'] . ')');
Loading history...
1697
1698
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_process')->insert(
1699
                'tx_crawler_process',
1700
                [
1701
                    'process_id' => $id,
1702
                    'active' => 1,
1703
                    'ttl' => $currentTime + (int) $this->extensionSettings['processMaxRunTime'],
1704
                    'system_process_id' => $systemProcessId,
1705
                ]
1706
            );
1707
        } else {
1708
            $this->CLI_debug('Processlimit reached (' . ($processCount) . '/' . (int) $this->extensionSettings['processLimit'] . ')');
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...Controller::CLI_debug() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1708
            /** @scrutinizer ignore-deprecated */ $this->CLI_debug('Processlimit reached (' . ($processCount) . '/' . (int) $this->extensionSettings['processLimit'] . ')');
Loading history...
1709
            $ret = false;
1710
        }
1711
1712
        $this->processRepository->deleteProcessesMarkedAsDeleted();
1713
        $this->CLI_releaseProcesses($orphanProcesses);
1714
1715
        return $ret;
1716
    }
1717
1718
    /**
1719
     * Release a process and the required resources
1720
     *
1721
     * @param mixed $releaseIds string with a single process-id or array with multiple process-ids
1722
     * @return boolean
1723
     */
1724
    public function CLI_releaseProcesses($releaseIds)
1725
    {
1726
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
1727
1728
        if (! is_array($releaseIds)) {
1729
            $releaseIds = [$releaseIds];
1730
        }
1731
1732
        if (empty($releaseIds)) {
1733
            //nothing to release
1734
            return false;
1735
        }
1736
1737
        // some kind of 2nd chance algo - this way you need at least 2 processes to have a real cleanup
1738
        // this ensures that a single process can't mess up the entire process table
1739
1740
        // mark all processes as deleted which have no "waiting" queue-entires and which are not active
1741
1742
        $queryBuilder
1743
            ->update($this->tableName, 'q')
1744
            ->where(
1745
                'q.process_id IN(SELECT p.process_id FROM tx_crawler_process as p WHERE p.active = 0)'
1746
            )
1747
            ->set('q.process_scheduled', 0)
1748
            ->set('q.process_id', '')
1749
            ->execute();
1750
1751
        // FIXME: Not entirely sure that this is equivalent to the previous version
1752
        $queryBuilder->resetQueryPart('set');
1753
1754
        $queryBuilder
1755
            ->update('tx_crawler_process')
1756
            ->where(
1757
                $queryBuilder->expr()->eq('active', 0),
1758
                'process_id IN(SELECT q.process_id FROM tx_crawler_queue as q WHERE q.exec_time = 0)'
1759
            )
1760
            ->set('system_process_id', 0)
1761
            ->execute();
1762
1763
        $this->processRepository->markRequestedProcessesAsNotActive($releaseIds);
1764
        $this->queueRepository->unsetProcessScheduledAndProcessIdForQueueEntries($releaseIds);
1765
1766
        return true;
1767
    }
1768
1769
    /**
1770
     * Create a unique Id for the current process
1771
     *
1772
     * @return string the ID
1773
     */
1774 1
    public function CLI_buildProcessId()
1775
    {
1776 1
        if (! $this->processID) {
1777
            $this->processID = GeneralUtility::shortMD5(microtime(true));
1778
        }
1779 1
        return $this->processID;
1780
    }
1781
1782
    /**
1783
     * Prints a message to the stdout (only if debug-mode is enabled)
1784
     *
1785
     * @param string $msg the message
1786
     * @deprecated
1787
     * @codeCoverageIgnore
1788
     */
1789
    public function CLI_debug($msg): void
1790
    {
1791
        if ((int) $this->extensionSettings['processDebug']) {
1792
            echo $msg . "\n";
1793
            flush();
1794
        }
1795
    }
1796
1797
    /**
1798
     * Cleans up entries that stayed for too long in the queue. These are:
1799
     * - processed entries that are over 1.5 days in age
1800
     * - scheduled entries that are over 7 days old
1801
     *
1802
     * @deprecated
1803
     */
1804 1
    public function cleanUpOldQueueEntries(): void
1805
    {
1806
        // 24*60*60 Seconds in 24 hours
1807 1
        $processedAgeInSeconds = $this->extensionSettings['cleanUpProcessedAge'] * 86400;
1808 1
        $scheduledAgeInSeconds = $this->extensionSettings['cleanUpScheduledAge'] * 86400;
1809
1810 1
        $now = time();
1811 1
        $condition = '(exec_time<>0 AND exec_time<' . ($now - $processedAgeInSeconds) . ') OR scheduled<=' . ($now - $scheduledAgeInSeconds);
1812 1
        $this->flushQueue($condition);
0 ignored issues
show
Deprecated Code introduced by
The function AOE\Crawler\Controller\C...ontroller::flushQueue() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1812
        /** @scrutinizer ignore-deprecated */ $this->flushQueue($condition);
Loading history...
1813 1
    }
1814
1815
    /**
1816
     * Removes queue entries
1817
     *
1818
     * @param string $where SQL related filter for the entries which should be removed
1819
     *
1820
     * @deprecated
1821
     */
1822 5
    protected function flushQueue($where = ''): void
1823
    {
1824 5
        $realWhere = strlen((string) $where) > 0 ? $where : '1=1';
1825
1826 5
        $queryBuilder = $this->getQueryBuilder($this->tableName);
1827
1828
        $groups = $queryBuilder
1829 5
            ->selectLiteral('DISTINCT set_id')
1830 5
            ->from($this->tableName)
1831 5
            ->where($realWhere)
1832 5
            ->execute()
1833 5
            ->fetchAll();
1834 5
        if (is_array($groups)) {
0 ignored issues
show
introduced by
The condition is_array($groups) is always true.
Loading history...
1835 5
            foreach ($groups as $group) {
1836
                $subSet = $queryBuilder
1837 4
                    ->select('qid', 'set_id')
1838 4
                    ->from($this->tableName)
1839 4
                    ->where(
1840 4
                        $realWhere,
1841 4
                        $queryBuilder->expr()->eq('set_id', $group['set_id'])
1842
                    )
1843 4
                    ->execute()
1844 4
                    ->fetchAll();
1845
1846 4
                $payLoad = ['subSet' => $subSet];
1847 4
                SignalSlotUtility::emitSignal(
1848 4
                    self::class,
1849 4
                    SignalSlotUtility::SIGNAL_QUEUE_ENTRY_FLUSH,
1850
                    $payLoad
1851
                );
1852
            }
1853
        }
1854
1855
        $queryBuilder
1856 5
            ->delete($this->tableName)
1857 5
            ->where($realWhere)
1858 5
            ->execute();
1859 5
    }
1860
1861
    /**
1862
     * This method determines duplicates for a queue entry with the same parameters and this timestamp.
1863
     * If the timestamp is in the past, it will check if there is any unprocessed queue entry in the past.
1864
     * If the timestamp is in the future it will check, if the queued entry has exactly the same timestamp
1865
     *
1866
     * @param int $tstamp
1867
     * @param array $fieldArray
1868
     *
1869
     * @return array
1870
     * @deprecated
1871
     */
1872 5
    protected function getDuplicateRowsIfExist($tstamp, $fieldArray)
1873
    {
1874 5
        $rows = [];
1875
1876 5
        $currentTime = $this->getCurrentTime();
1877
1878 5
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
1879
        $queryBuilder
1880 5
            ->select('qid')
1881 5
            ->from('tx_crawler_queue');
1882
        //if this entry is scheduled with "now"
1883 5
        if ($tstamp <= $currentTime) {
1884 2
            if ($this->extensionSettings['enableTimeslot']) {
1885 1
                $timeBegin = $currentTime - 100;
1886 1
                $timeEnd = $currentTime + 100;
1887
                $queryBuilder
1888 1
                    ->where(
1889 1
                        'scheduled BETWEEN ' . $timeBegin . ' AND ' . $timeEnd . ''
1890
                    )
1891 1
                    ->orWhere(
1892 1
                        $queryBuilder->expr()->lte('scheduled', $currentTime)
1893
                    );
1894
            } else {
1895
                $queryBuilder
1896 1
                    ->where(
1897 2
                        $queryBuilder->expr()->lte('scheduled', $currentTime)
1898
                    );
1899
            }
1900 3
        } elseif ($tstamp > $currentTime) {
1901
            //entry with a timestamp in the future need to have the same schedule time
1902
            $queryBuilder
1903 3
                ->where(
1904 3
                    $queryBuilder->expr()->eq('scheduled', $tstamp)
1905
                );
1906
        }
1907
1908
        $queryBuilder
1909 5
            ->andWhere('NOT exec_time')
1910 5
            ->andWhere('NOT process_id')
1911 5
            ->andWhere($queryBuilder->expr()->eq('page_id', $queryBuilder->createNamedParameter($fieldArray['page_id'], PDO::PARAM_INT)))
1912 5
            ->andWhere($queryBuilder->expr()->eq('parameters_hash', $queryBuilder->createNamedParameter($fieldArray['parameters_hash'], PDO::PARAM_STR)));
1913
1914 5
        $statement = $queryBuilder->execute();
1915
1916 5
        while ($row = $statement->fetch()) {
1917 5
            $rows[] = $row['qid'];
1918
        }
1919
1920 5
        return $rows;
1921
    }
1922
1923
    /**
1924
     * Returns a md5 hash generated from a serialized configuration array.
1925
     *
1926
     * @return string
1927
     */
1928 10
    protected function getConfigurationHash(array $configuration)
1929
    {
1930 10
        unset($configuration['paramExpanded']);
1931 10
        unset($configuration['URLs']);
1932 10
        return md5(serialize($configuration));
1933
    }
1934
1935
    /**
1936
     * Build a URL from a Page and the Query String. If the page has a Site configuration, it can be built by using
1937
     * the Site instance.
1938
     *
1939
     * @param int $httpsOrHttp see tx_crawler_configuration.force_ssl
1940
     * @throws SiteNotFoundException
1941
     * @throws InvalidRouteArgumentsException
1942
     *
1943
     * @deprecated Using CrawlerController::getUrlFromPageAndQueryParameters() is deprecated since 9.1.1 and will be removed in v11.x, please use UrlService->getUrlFromPageAndQueryParameters() instead.
1944
     * @codeCoverageIgnore
1945
     */
1946
    protected function getUrlFromPageAndQueryParameters(int $pageId, string $queryString, ?string $alternativeBaseUrl, int $httpsOrHttp): UriInterface
1947
    {
1948
        $urlService = new UrlService();
1949
        return $urlService->getUrlFromPageAndQueryParameters($pageId, $queryString, $alternativeBaseUrl, $httpsOrHttp);
1950
    }
1951
1952 1
    protected function swapIfFirstIsLargerThanSecond(array $reg): array
1953
    {
1954
        // Swap if first is larger than last:
1955 1
        if ($reg[1] > $reg[2]) {
1956
            $temp = $reg[2];
1957
            $reg[2] = $reg[1];
1958
            $reg[1] = $temp;
1959
        }
1960
1961 1
        return $reg;
1962
    }
1963
1964
    /**
1965
     * @return BackendUserAuthentication
1966
     */
1967 2
    private function getBackendUser()
1968
    {
1969
        // Make sure the _cli_ user is loaded
1970 2
        Bootstrap::initializeBackendAuthentication();
1971 2
        if ($this->backendUser === null) {
1972 2
            $this->backendUser = $GLOBALS['BE_USER'];
1973
        }
1974 2
        return $this->backendUser;
1975
    }
1976
1977
    /**
1978
     * Get querybuilder for given table
1979
     *
1980
     * @return QueryBuilder
1981
     */
1982 12
    private function getQueryBuilder(string $table)
1983
    {
1984 12
        return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1985
    }
1986
}
1987