Passed
Push — ci/infection ( a25359...ab479d )
by Tomas Norre
07:29
created

CrawlerController::CLI_checkAndAcquireNewProcess()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 53
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 33
nc 7
nop 1
dl 0
loc 53
ccs 0
cts 31
cp 0
crap 30
rs 9.0808
c 0
b 0
f 0

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\Domain\Repository\ConfigurationRepository;
34
use AOE\Crawler\Domain\Repository\ProcessRepository;
35
use AOE\Crawler\Domain\Repository\QueueRepository;
36
use AOE\Crawler\QueueExecutor;
37
use AOE\Crawler\Utility\SignalSlotUtility;
38
use Psr\Http\Message\UriInterface;
39
use Psr\Log\LoggerAwareInterface;
40
use Psr\Log\LoggerAwareTrait;
41
use TYPO3\CMS\Backend\Tree\View\PageTreeView;
42
use TYPO3\CMS\Backend\Utility\BackendUtility;
43
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
44
use TYPO3\CMS\Core\Compatibility\PublicMethodDeprecationTrait;
45
use TYPO3\CMS\Core\Core\Bootstrap;
46
use TYPO3\CMS\Core\Core\Environment;
47
use TYPO3\CMS\Core\Database\Connection;
48
use TYPO3\CMS\Core\Database\ConnectionPool;
49
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
50
use TYPO3\CMS\Core\Http\Uri;
51
use TYPO3\CMS\Core\Imaging\Icon;
52
use TYPO3\CMS\Core\Imaging\IconFactory;
53
use TYPO3\CMS\Core\Routing\SiteMatcher;
54
use TYPO3\CMS\Core\Site\Entity\Site;
55
use TYPO3\CMS\Core\Type\Bitmask\Permission;
56
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
57
use TYPO3\CMS\Core\Utility\DebugUtility;
58
use TYPO3\CMS\Core\Utility\GeneralUtility;
59
use TYPO3\CMS\Core\Utility\MathUtility;
60
use TYPO3\CMS\Extbase\Object\ObjectManager;
61
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
62
use TYPO3\CMS\Frontend\Page\PageRepository;
63
64
/**
65
 * Class CrawlerController
66
 *
67
 * @package AOE\Crawler\Controller
68
 */
69
class CrawlerController implements LoggerAwareInterface
70
{
71
    use LoggerAwareTrait;
72
    use PublicMethodDeprecationTrait;
73
74
    public const CLI_STATUS_NOTHING_PROCCESSED = 0;
75
76
    public const CLI_STATUS_REMAIN = 1; //queue not empty
77
78
    public const CLI_STATUS_PROCESSED = 2; //(some) queue items where processed
79
80
    public const CLI_STATUS_ABORTED = 4; //instance didn't finish
81
82
    public const CLI_STATUS_POLLABLE_PROCESSED = 8;
83
84
    /**
85
     * @var integer
86
     */
87
    public $setID = 0;
88
89
    /**
90
     * @var string
91
     */
92
    public $processID = '';
93
94
    /**
95
     * @var array
96
     */
97
    public $duplicateTrack = [];
98
99
    /**
100
     * @var array
101
     */
102
    public $downloadUrls = [];
103
104
    /**
105
     * @var array
106
     */
107
    public $incomingProcInstructions = [];
108
109
    /**
110
     * @var array
111
     */
112
    public $incomingConfigurationSelection = [];
113
114
    /**
115
     * @var bool
116
     */
117
    public $registerQueueEntriesInternallyOnly = false;
118
119
    /**
120
     * @var array
121
     */
122
    public $queueEntries = [];
123
124
    /**
125
     * @var array
126
     */
127
    public $urlList = [];
128
129
    /**
130
     * @var array
131
     */
132
    public $extensionSettings = [];
133
134
    /**
135
     * Mount Point
136
     *
137
     * @var bool
138
     * Todo: Check what this is used for and adjust the type hint or code, as bool doesn't match the current code.
139
     */
140
    public $MP = false;
141
142
    /**
143
     * @var string
144
     */
145
    protected $processFilename;
146
147
    /**
148
     * Holds the internal access mode can be 'gui','cli' or 'cli_im'
149
     *
150
     * @var string
151
     */
152
    protected $accessMode;
153
154
    /**
155
     * @var QueueRepository
156
     */
157
    protected $queueRepository;
158
159
    /**
160
     * @var ProcessRepository
161
     */
162
    protected $processRepository;
163
164
    /**
165
     * @var ConfigurationRepository
166
     */
167
    protected $configurationRepository;
168
169
    /**
170
     * @var string
171
     */
172
    protected $tableName = 'tx_crawler_queue';
173
174
    /**
175
     * @var QueueExecutor
176
     */
177
    protected $queueExecutor;
178
179
    /**
180
     * @var int
181
     */
182
    protected $maximumUrlsToCompile = 10000;
183
184
    /**
185
     * @var IconFactory
186
     */
187
    protected $iconFactory;
188
189
    /**
190
     * @var string[]
191
     */
192
    private $deprecatedPublicMethods = [
0 ignored issues
show
introduced by
The private property $deprecatedPublicMethods is not used, and could be removed.
Loading history...
193
        'getLogEntriesForSetId' => 'Using crawlerController::getLogEntriesForSetId() is deprecated since 9.0.1 and will be removed in v11.x',
194
        'flushQueue' => 'Using CrawlerController::flushQueue() is deprecated since 9.0.1 and will be removed in v11.x, please use QueueRepository->flushQueue() instead.',
195
        'cleanUpOldQueueEntries' => 'Using CrawlerController::cleanUpOldQueueEntries() is deprecated since 9.0.1 and will be removed in v11.x, please use QueueRepository->cleanUpOldQueueEntries() instead.',
196
    ];
197
198
    /**
199
     * @var BackendUserAuthentication|null
200
     */
201
    private $backendUser;
202
203
    /**
204
     * @var integer
205
     */
206
    private $scheduledTime = 0;
207
208
    /**
209
     * @var integer
210
     */
211
    private $reqMinute = 0;
212
213
    /**
214
     * @var bool
215
     */
216
    private $submitCrawlUrls = false;
217
218
    /**
219
     * @var bool
220
     */
221
    private $downloadCrawlUrls = false;
222
223
    /************************************
224
     *
225
     * Getting URLs based on Page TSconfig
226
     *
227
     ************************************/
228
229 37
    public function __construct()
230
    {
231 37
        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
232 37
        $this->queueRepository = $objectManager->get(QueueRepository::class);
233 37
        $this->processRepository = $objectManager->get(ProcessRepository::class);
234 37
        $this->configurationRepository = $objectManager->get(ConfigurationRepository::class);
235 37
        $this->queueExecutor = $objectManager->get(QueueExecutor::class);
236 37
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
237
238 37
        $this->processFilename = Environment::getVarPath() . '/lock/tx_crawler.proc';
239
240
        /** @var ExtensionConfigurationProvider $configurationProvider */
241 37
        $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class);
242 37
        $settings = $configurationProvider->getExtensionConfiguration();
243 37
        $this->extensionSettings = is_array($settings) ? $settings : [];
0 ignored issues
show
introduced by
The condition is_array($settings) is always true.
Loading history...
244
245
        // set defaults:
246 37
        if (MathUtility::convertToPositiveInteger($this->extensionSettings['countInARun']) === 0) {
247
            $this->extensionSettings['countInARun'] = 100;
248
        }
249
250 37
        $this->extensionSettings['processLimit'] = MathUtility::forceIntegerInRange($this->extensionSettings['processLimit'], 1, 99, 1);
251 37
        $this->maximumUrlsToCompile = MathUtility::forceIntegerInRange($this->extensionSettings['maxCompileUrls'], 1, 1000000000, 10000);
252 37
    }
253
254
    public function getMaximumUrlsToCompile(): int
255
    {
256
        return $this->maximumUrlsToCompile;
257
    }
258
259 4
    public function setMaximumUrlsToCompile(int $maximumUrlsToCompile): void
260
    {
261 4
        $this->maximumUrlsToCompile = $maximumUrlsToCompile;
262 4
    }
263
264
    /**
265
     * Method to set the accessMode can be gui, cli or cli_im
266
     *
267
     * @return string
268
     */
269 1
    public function getAccessMode()
270
    {
271 1
        return $this->accessMode;
272
    }
273
274
    /**
275
     * @param string $accessMode
276
     */
277 1
    public function setAccessMode($accessMode): void
278
    {
279 1
        $this->accessMode = $accessMode;
280 1
    }
281
282
    /**
283
     * Set disabled status to prevent processes from being processed
284
     */
285 3
    public function setDisabled(?bool $disabled = true): void
286
    {
287 3
        if ($disabled) {
288 2
            GeneralUtility::writeFile($this->processFilename, 'disabled');
289 1
        } elseif (is_file($this->processFilename)) {
290 1
            unlink($this->processFilename);
291
        }
292 3
    }
293
294
    /**
295
     * Get disable status
296
     */
297 3
    public function getDisabled(): bool
298
    {
299 3
        return is_file($this->processFilename);
300
    }
301
302
    /**
303
     * @param string $filenameWithPath
304
     */
305 4
    public function setProcessFilename($filenameWithPath): void
306
    {
307 4
        $this->processFilename = $filenameWithPath;
308 4
    }
309
310
    /**
311
     * @return string
312
     */
313 1
    public function getProcessFilename()
314
    {
315 1
        return $this->processFilename;
316
    }
317
318
    /**
319
     * Sets the extensions settings (unserialized pendant of $TYPO3_CONF_VARS['EXT']['extConf']['crawler']).
320
     */
321 6
    public function setExtensionSettings(array $extensionSettings): void
322
    {
323 6
        $this->extensionSettings = $extensionSettings;
324 6
    }
325
326
    /**
327
     * Check if the given page should be crawled
328
     *
329
     * @return false|string false if the page should be crawled (not excluded), true / skipMessage if it should be skipped
330
     */
331
    public function checkIfPageShouldBeSkipped(array $pageRow)
332
    {
333
        $skipPage = false;
334
        $skipMessage = 'Skipped'; // message will be overwritten later
335
336
        // if page is hidden
337
        if (! $this->extensionSettings['crawlHiddenPages']) {
338
            if ($pageRow['hidden']) {
339
                $skipPage = true;
340
                $skipMessage = 'Because page is hidden';
341
            }
342
        }
343
344
        if (! $skipPage) {
345
            if (GeneralUtility::inList('3,4,199,254,255', $pageRow['doktype'])) {
346
                $skipPage = true;
347
                $skipMessage = 'Because doktype is not allowed';
348
            }
349
        }
350
351
        if (! $skipPage) {
352
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['excludeDoktype'] ?? [] as $key => $doktypeList) {
353
                if (GeneralUtility::inList($doktypeList, $pageRow['doktype'])) {
354
                    $skipPage = true;
355
                    $skipMessage = 'Doktype was excluded by "' . $key . '"';
356
                    break;
357
                }
358
            }
359
        }
360
361
        if (! $skipPage) {
362
            // veto hook
363
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pageVeto'] ?? [] as $key => $func) {
364
                $params = [
365
                    'pageRow' => $pageRow,
366
                ];
367
                // expects "false" if page is ok and "true" or a skipMessage if this page should _not_ be crawled
368
                $veto = GeneralUtility::callUserFunction($func, $params, $this);
369
                if ($veto !== false) {
370
                    $skipPage = true;
371
                    if (is_string($veto)) {
372
                        $skipMessage = $veto;
373
                    } else {
374
                        $skipMessage = 'Veto from hook "' . htmlspecialchars($key) . '"';
375
                    }
376
                    // no need to execute other hooks if a previous one return a veto
377
                    break;
378
                }
379
            }
380
        }
381
382
        return $skipPage ? $skipMessage : false;
383
    }
384
385
    /**
386
     * Wrapper method for getUrlsForPageId()
387
     * It returns an array of configurations and no urls!
388
     *
389
     * @param array $pageRow Page record with at least dok-type and uid columns.
390
     * @param string $skipMessage
391
     * @return array
392
     * @see getUrlsForPageId()
393
     */
394 2
    public function getUrlsForPageRow(array $pageRow, &$skipMessage = '')
395
    {
396 2
        $message = $this->checkIfPageShouldBeSkipped($pageRow);
397 2
        if ($message === false) {
398 1
            $res = $this->getUrlsForPageId($pageRow['uid']);
399 1
            $skipMessage = '';
400
        } else {
401 1
            $skipMessage = $message;
402 1
            $res = [];
403
        }
404
405 2
        return $res;
406
    }
407
408
    /**
409
     * Creates a list of URLs from input array (and submits them to queue if asked for)
410
     * See Web > Info module script + "indexed_search"'s crawler hook-client using this!
411
     *
412
     * @param array $vv Information about URLs from pageRow to crawl.
413
     * @param array $pageRow Page row
414
     * @param int $scheduledTime Unix time to schedule indexing to, typically time()
415
     * @param int $reqMinute Number of requests per minute (creates the interleave between requests)
416
     * @param bool $submitCrawlUrls If set, submits the URLs to queue
417
     * @param bool $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
418
     * @param array $duplicateTrack Array which is passed by reference and contains the an id per url to secure we will not crawl duplicates
419
     * @param array $downloadUrls Array which will be filled with URLS for download if flag is set.
420
     * @param array $incomingProcInstructions Array of processing instructions
421
     * @return string List of URLs (meant for display in backend module)
422
     */
423
    public function urlListFromUrlArray(
424
        array $vv,
425
        array $pageRow,
426
        $scheduledTime,
427
        $reqMinute,
428
        $submitCrawlUrls,
429
        $downloadCrawlUrls,
430
        array &$duplicateTrack,
431
        array &$downloadUrls,
432
        array $incomingProcInstructions
433
    ) {
434
        if (! is_array($vv['URLs'])) {
435
            return 'ERROR - no URL generated';
436
        }
437
        $urlLog = [];
438
        $pageId = (int) $pageRow['uid'];
439
        $configurationHash = $this->getConfigurationHash($vv);
440
        $skipInnerCheck = $this->queueRepository->noUnprocessedQueueEntriesForPageWithConfigurationHashExist($pageId, $configurationHash);
441
442
        foreach ($vv['URLs'] as $urlQuery) {
443
            if (! $this->drawURLs_PIfilter($vv['subCfg']['procInstrFilter'], $incomingProcInstructions)) {
444
                continue;
445
            }
446
            $url = (string) $this->getUrlFromPageAndQueryParameters(
447
                $pageId,
448
                $urlQuery,
449
                $vv['subCfg']['baseUrl'] ?? null,
450
                $vv['subCfg']['force_ssl'] ?? 0
451
            );
452
453
            // Create key by which to determine unique-ness:
454
            $uKey = $url . '|' . $vv['subCfg']['userGroups'] . '|' . $vv['subCfg']['procInstrFilter'];
455
456
            if (isset($duplicateTrack[$uKey])) {
457
                //if the url key is registered just display it and do not resubmit is
458
                $urlLog[] = '<em><span class="text-muted">' . htmlspecialchars($url) . '</span></em>';
459
            } else {
460
                // Scheduled time:
461
                $schTime = $scheduledTime + round(count($duplicateTrack) * (60 / $reqMinute));
462
                $schTime = intval($schTime / 60) * 60;
463
                $formattedDate = BackendUtility::datetime($schTime);
464
                $this->urlList[] = '[' . $formattedDate . '] ' . $url;
465
                $urlList = '[' . $formattedDate . '] ' . htmlspecialchars($url);
466
467
                // Submit for crawling!
468
                if ($submitCrawlUrls) {
469
                    $added = $this->addUrl(
470
                        $pageId,
471
                        $url,
472
                        $vv['subCfg'],
473
                        $scheduledTime,
474
                        $configurationHash,
475
                        $skipInnerCheck
476
                    );
477
                    if ($added === false) {
478
                        $urlList .= ' (URL already existed)';
479
                    }
480
                } elseif ($downloadCrawlUrls) {
481
                    $downloadUrls[$url] = $url;
482
                }
483
                $urlLog[] = $urlList;
484
            }
485
            $duplicateTrack[$uKey] = true;
486
        }
487
488
        return implode('<br>', $urlLog);
489
    }
490
491
    /**
492
     * Returns true if input processing instruction is among registered ones.
493
     *
494
     * @param string $piString PI to test
495
     * @param array $incomingProcInstructions Processing instructions
496
     * @return boolean
497
     */
498 5
    public function drawURLs_PIfilter($piString, array $incomingProcInstructions)
499
    {
500 5
        if (empty($incomingProcInstructions)) {
501 1
            return true;
502
        }
503
504 4
        foreach ($incomingProcInstructions as $pi) {
505 4
            if (GeneralUtility::inList($piString, $pi)) {
506 2
                return true;
507
            }
508
        }
509 2
        return false;
510
    }
511
512 1
    public function getPageTSconfigForId($id): array
513
    {
514 1
        if (! $this->MP) {
515 1
            $pageTSconfig = BackendUtility::getPagesTSconfig($id);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Backend\Utilit...ity::getPagesTSconfig() 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

515
            $pageTSconfig = /** @scrutinizer ignore-deprecated */ BackendUtility::getPagesTSconfig($id);
Loading history...
516
        } else {
517
            // TODO: Please check, this makes no sense to split a boolean value.
518
            [, $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

518
            [, $mountPointId] = explode('-', /** @scrutinizer ignore-type */ $this->MP);
Loading history...
519
            $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

519
            $pageTSconfig = BackendUtility::getPagesTSconfig(/** @scrutinizer ignore-type */ $mountPointId);
Loading history...
Deprecated Code introduced by
The function TYPO3\CMS\Backend\Utilit...ity::getPagesTSconfig() 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

519
            $pageTSconfig = /** @scrutinizer ignore-deprecated */ BackendUtility::getPagesTSconfig($mountPointId);
Loading history...
520
        }
521
522
        // Call a hook to alter configuration
523 1
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'])) {
524
            $params = [
525
                'pageId' => $id,
526
                'pageTSConfig' => &$pageTSconfig,
527
            ];
528
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'] as $userFunc) {
529
                GeneralUtility::callUserFunction($userFunc, $params, $this);
530
            }
531
        }
532 1
        return $pageTSconfig;
533
    }
534
535
    /**
536
     * This methods returns an array of configurations.
537
     * Adds no urls!
538
     */
539
    public function getUrlsForPageId(int $pageId): array
540
    {
541
        // Get page TSconfig for page ID
542
        $pageTSconfig = $this->getPageTSconfigForId($pageId);
543
544
        $res = [];
545
546
        // Fetch Crawler Configuration from pageTSconfig
547
        $crawlerCfg = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? [];
548
        foreach ($crawlerCfg as $key => $values) {
549
            if (! is_array($values)) {
550
                continue;
551
            }
552
            $key = str_replace('.', '', $key);
553
            // Sub configuration for a single configuration string:
554
            $subCfg = (array) $crawlerCfg[$key . '.'];
555
            $subCfg['key'] = $key;
556
557
            if (strcmp($subCfg['procInstrFilter'] ?? '', '')) {
558
                $subCfg['procInstrFilter'] = implode(',', GeneralUtility::trimExplode(',', $subCfg['procInstrFilter']));
559
            }
560
            $pidOnlyList = implode(',', GeneralUtility::trimExplode(',', $subCfg['pidsOnly'], true));
561
562
            // process configuration if it is not page-specific or if the specific page is the current page:
563
            // TODO: Check if $pidOnlyList can be kept as Array instead of imploded
564
            if (! strcmp((string) $subCfg['pidsOnly'], '') || GeneralUtility::inList($pidOnlyList, strval($pageId))) {
565
566
                // Explode, process etc.:
567
                $res[$key] = [];
568
                $res[$key]['subCfg'] = $subCfg;
569
                $res[$key]['paramParsed'] = GeneralUtility::explodeUrl2Array($crawlerCfg[$key]);
570
                $res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'], $pageId);
571
                $res[$key]['origin'] = 'pagets';
572
573
                // recognize MP value
574
                if (! $this->MP) {
575
                    $res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], ['?id=' . $pageId]);
576
                } else {
577
                    $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

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

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

1408
                            $tree->getTree(/** @scrutinizer ignore-type */ $pid, $depth);
Loading history...
1409
                            $treeCache[$pid][$depth] = $tree->tree;
1410
                        }
1411
1412
                        foreach ($treeCache[$pid][$depth] as $data) {
1413
                            $pidList[] = $data['row']['uid'];
1414
                        }
1415
                    }
1416
                }
1417
            }
1418
1419
            $expandedExcludeStringCache[$excludeString] = array_unique($pidList);
1420
        }
1421
1422
        return $expandedExcludeStringCache[$excludeString];
1423
    }
1424
1425
    /**
1426
     * Create the rows for display of the page tree
1427
     * For each page a number of rows are shown displaying GET variable configuration
1428
     */
1429
    public function drawURLs_addRowsForPage(array $pageRow, string $pageTitle): string
1430
    {
1431
        $skipMessage = '';
1432
1433
        // Get list of configurations
1434
        $configurations = $this->getUrlsForPageRow($pageRow, $skipMessage);
1435
1436
        if (! empty($this->incomingConfigurationSelection)) {
1437
            // remove configuration that does not match the current selection
1438
            foreach ($configurations as $confKey => $confArray) {
1439
                if (! in_array($confKey, $this->incomingConfigurationSelection, true)) {
1440
                    unset($configurations[$confKey]);
1441
                }
1442
            }
1443
        }
1444
1445
        // Traverse parameter combinations:
1446
        $c = 0;
1447
        $content = '';
1448
        if (! empty($configurations)) {
1449
            foreach ($configurations as $confKey => $confArray) {
1450
1451
                // Title column:
1452
                if (! $c) {
1453
                    $titleClm = '<td rowspan="' . count($configurations) . '">' . $pageTitle . '</td>';
1454
                } else {
1455
                    $titleClm = '';
1456
                }
1457
1458
                if (! in_array($pageRow['uid'], $this->expandExcludeString($confArray['subCfg']['exclude']), true)) {
1459
1460
                    // URL list:
1461
                    $urlList = $this->urlListFromUrlArray(
1462
                        $confArray,
1463
                        $pageRow,
1464
                        $this->scheduledTime,
1465
                        $this->reqMinute,
1466
                        $this->submitCrawlUrls,
1467
                        $this->downloadCrawlUrls,
1468
                        $this->duplicateTrack,
1469
                        $this->downloadUrls,
1470
                        $this->incomingProcInstructions // if empty the urls won't be filtered by processing instructions
1471
                    );
1472
1473
                    // Expanded parameters:
1474
                    $paramExpanded = '';
1475
                    $calcAccu = [];
1476
                    $calcRes = 1;
1477
                    foreach ($confArray['paramExpanded'] as $gVar => $gVal) {
1478
                        $paramExpanded .= '
1479
                            <tr>
1480
                                <td>' . htmlspecialchars('&' . $gVar . '=') . '<br/>' .
1481
                            '(' . count($gVal) . ')' .
1482
                            '</td>
1483
                                <td nowrap="nowrap">' . nl2br(htmlspecialchars(implode(chr(10), $gVal))) . '</td>
1484
                            </tr>
1485
                        ';
1486
                        $calcRes *= count($gVal);
1487
                        $calcAccu[] = count($gVal);
1488
                    }
1489
                    $paramExpanded = '<table>' . $paramExpanded . '</table>';
1490
                    $paramExpanded .= 'Comb: ' . implode('*', $calcAccu) . '=' . $calcRes;
1491
1492
                    // Options
1493
                    $optionValues = '';
1494
                    if ($confArray['subCfg']['userGroups']) {
1495
                        $optionValues .= 'User Groups: ' . $confArray['subCfg']['userGroups'] . '<br/>';
1496
                    }
1497
                    if ($confArray['subCfg']['procInstrFilter']) {
1498
                        $optionValues .= 'ProcInstr: ' . $confArray['subCfg']['procInstrFilter'] . '<br/>';
1499
                    }
1500
1501
                    // Compile row:
1502
                    $content .= '
1503
                        <tr>
1504
                            ' . $titleClm . '
1505
                            <td>' . htmlspecialchars($confKey) . '</td>
1506
                            <td>' . nl2br(htmlspecialchars(rawurldecode(trim(str_replace('&', chr(10) . '&', GeneralUtility::implodeArrayForUrl('', $confArray['paramParsed'])))))) . '</td>
1507
                            <td>' . $paramExpanded . '</td>
1508
                            <td nowrap="nowrap">' . $urlList . '</td>
1509
                            <td nowrap="nowrap">' . $optionValues . '</td>
1510
                            <td nowrap="nowrap">' . DebugUtility::viewArray($confArray['subCfg']['procInstrParams.']) . '</td>
1511
                        </tr>';
1512
                } else {
1513
                    $content .= '<tr>
1514
                            ' . $titleClm . '
1515
                            <td>' . htmlspecialchars($confKey) . '</td>
1516
                            <td colspan="5"><em>No entries</em> (Page is excluded in this configuration)</td>
1517
                        </tr>';
1518
                }
1519
1520
                $c++;
1521
            }
1522
        } else {
1523
            $message = ! empty($skipMessage) ? ' (' . $skipMessage . ')' : '';
1524
1525
            // Compile row:
1526
            $content .= '
1527
                <tr>
1528
                    <td>' . $pageTitle . '</td>
1529
                    <td colspan="6"><em>No entries</em>' . $message . '</td>
1530
                </tr>';
1531
        }
1532
1533
        return $content;
1534
    }
1535
1536
    /*****************************
1537
     *
1538
     * CLI functions
1539
     *
1540
     *****************************/
1541
1542
    /**
1543
     * Running the functionality of the CLI (crawling URLs from queue)
1544
     */
1545
    public function CLI_run(int $countInARun, int $sleepTime, int $sleepAfterFinish): int
1546
    {
1547
        $result = 0;
1548
        $counter = 0;
1549
1550
        // First, run hooks:
1551
        $this->CLI_runHooks();
1552
1553
        // Clean up the queue
1554
        $this->queueRepository->cleanupQueue();
1555
1556
        // Select entries:
1557
        $rows = $this->queueRepository->fetchRecordsToBeCrawled($countInARun);
1558
1559
        if (! empty($rows)) {
1560
            $quidList = [];
1561
1562
            foreach ($rows as $r) {
1563
                $quidList[] = $r['qid'];
1564
            }
1565
1566
            $processId = $this->CLI_buildProcessId();
1567
1568
            //save the number of assigned queue entries to determine how many have been processed later
1569
            $numberOfAffectedRows = $this->queueRepository->updateProcessIdAndSchedulerForQueueIds($quidList, $processId);
1570
            $this->processRepository->updateProcessAssignItemsCount($numberOfAffectedRows, $processId);
1571
1572
            if ($numberOfAffectedRows !== count($quidList)) {
1573
                $this->CLI_debug('Nothing processed due to multi-process collision (' . $this->CLI_buildProcessId() . ')');
1574
                return ($result | self::CLI_STATUS_ABORTED);
1575
            }
1576
1577
            foreach ($rows as $r) {
1578
                $result |= $this->readUrl($r['qid']);
1579
1580
                $counter++;
1581
                usleep((int) $sleepTime); // Just to relax the system
1582
1583
                // if during the start and the current read url the cli has been disable we need to return from the function
1584
                // mark the process NOT as ended.
1585
                if ($this->getDisabled()) {
1586
                    return ($result | self::CLI_STATUS_ABORTED);
1587
                }
1588
1589
                if (! $this->processRepository->isProcessActive($this->CLI_buildProcessId())) {
1590
                    $this->CLI_debug('conflict / timeout (' . $this->CLI_buildProcessId() . ')');
1591
                    $result |= self::CLI_STATUS_ABORTED;
1592
                    break; //possible timeout
1593
                }
1594
            }
1595
1596
            sleep((int) $sleepAfterFinish);
1597
1598
            $msg = 'Rows: ' . $counter;
1599
            $this->CLI_debug($msg . ' (' . $this->CLI_buildProcessId() . ')');
1600
        } else {
1601
            $this->CLI_debug('Nothing within queue which needs to be processed (' . $this->CLI_buildProcessId() . ')');
1602
        }
1603
1604
        if ($counter > 0) {
1605
            $result |= self::CLI_STATUS_PROCESSED;
1606
        }
1607
1608
        return $result;
1609
    }
1610
1611
    /**
1612
     * Activate hooks
1613
     */
1614
    public function CLI_runHooks(): void
1615
    {
1616
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['cli_hooks'] ?? [] as $objRef) {
1617
            $hookObj = GeneralUtility::makeInstance($objRef);
1618
            if (is_object($hookObj)) {
1619
                $hookObj->crawler_init($this);
1620
            }
1621
        }
1622
    }
1623
1624
    /**
1625
     * Try to acquire a new process with the given id
1626
     * also performs some auto-cleanup for orphan processes
1627
     * @param string $id identification string for the process
1628
     * @return boolean
1629
     * @todo preemption might not be the most elegant way to clean up
1630
     */
1631
    public function CLI_checkAndAcquireNewProcess($id)
1632
    {
1633
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
1634
        $ret = true;
1635
1636
        $systemProcessId = getmypid();
1637
        if ($systemProcessId < 1) {
1638
            return false;
1639
        }
1640
1641
        $processCount = 0;
1642
        $orphanProcesses = [];
1643
1644
        $statement = $queryBuilder
1645
            ->select('process_id', 'ttl')
1646
            ->from('tx_crawler_process')
1647
            ->where(
1648
                'active = 1 AND deleted = 0'
1649
            )
1650
            ->execute();
1651
1652
        $currentTime = $this->getCurrentTime();
1653
1654
        while ($row = $statement->fetch()) {
1655
            if ($row['ttl'] < $currentTime) {
1656
                $orphanProcesses[] = $row['process_id'];
1657
            } else {
1658
                $processCount++;
1659
            }
1660
        }
1661
1662
        // if there are less than allowed active processes then add a new one
1663
        if ($processCount < (int) $this->extensionSettings['processLimit']) {
1664
            $this->CLI_debug('add process ' . $this->CLI_buildProcessId() . ' (' . ($processCount + 1) . '/' . (int) $this->extensionSettings['processLimit'] . ')');
1665
1666
            GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_process')->insert(
1667
                'tx_crawler_process',
1668
                [
1669
                    'process_id' => $id,
1670
                    'active' => 1,
1671
                    'ttl' => $currentTime + (int) $this->extensionSettings['processMaxRunTime'],
1672
                    'system_process_id' => $systemProcessId,
1673
                ]
1674
            );
1675
        } else {
1676
            $this->CLI_debug('Processlimit reached (' . ($processCount) . '/' . (int) $this->extensionSettings['processLimit'] . ')');
1677
            $ret = false;
1678
        }
1679
1680
        $this->processRepository->deleteProcessesMarkedAsDeleted();
1681
        $this->CLI_releaseProcesses($orphanProcesses);
1682
1683
        return $ret;
1684
    }
1685
1686
    /**
1687
     * Release a process and the required resources
1688
     *
1689
     * @param mixed $releaseIds string with a single process-id or array with multiple process-ids
1690
     * @return boolean
1691
     */
1692
    public function CLI_releaseProcesses($releaseIds)
1693
    {
1694
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
1695
1696
        if (! is_array($releaseIds)) {
1697
            $releaseIds = [$releaseIds];
1698
        }
1699
1700
        if (empty($releaseIds)) {
1701
            return false;   //nothing to release
1702
        }
1703
1704
        // some kind of 2nd chance algo - this way you need at least 2 processes to have a real cleanup
1705
        // this ensures that a single process can't mess up the entire process table
1706
1707
        // mark all processes as deleted which have no "waiting" queue-entires and which are not active
1708
1709
        $queryBuilder
1710
            ->update($this->tableName, 'q')
1711
            ->where(
1712
                'q.process_id IN(SELECT p.process_id FROM tx_crawler_process as p WHERE p.active = 0)'
1713
            )
1714
            ->set('q.process_scheduled', 0)
1715
            ->set('q.process_id', '')
1716
            ->execute();
1717
1718
        // FIXME: Not entirely sure that this is equivalent to the previous version
1719
        $queryBuilder->resetQueryPart('set');
1720
1721
        $queryBuilder
1722
            ->update('tx_crawler_process')
1723
            ->where(
1724
                $queryBuilder->expr()->eq('active', 0),
1725
                'process_id IN(SELECT q.process_id FROM tx_crawler_queue as q WHERE q.exec_time = 0)'
1726
            )
1727
            ->set('system_process_id', 0)
1728
            ->execute();
1729
1730
        $this->processRepository->markRequestedProcessesAsNotActive($releaseIds);
1731
        $this->queueRepository->unsetProcessScheduledAndProcessIdForQueueEntries($releaseIds);
1732
1733
        return true;
1734
    }
1735
1736
    /**
1737
     * Create a unique Id for the current process
1738
     *
1739
     * @return string  the ID
1740
     */
1741 1
    public function CLI_buildProcessId()
1742
    {
1743 1
        if (! $this->processID) {
1744
            $this->processID = GeneralUtility::shortMD5(microtime(true));
1745
        }
1746 1
        return $this->processID;
1747
    }
1748
1749
    /**
1750
     * Prints a message to the stdout (only if debug-mode is enabled)
1751
     *
1752
     * @param string $msg the message
1753
     */
1754
    public function CLI_debug($msg): void
1755
    {
1756
        if ((int) $this->extensionSettings['processDebug']) {
1757
            echo $msg . "\n";
1758
            flush();
1759
        }
1760
    }
1761
1762
    /**
1763
     * Cleans up entries that stayed for too long in the queue. These are:
1764
     * - processed entries that are over 1.5 days in age
1765
     * - scheduled entries that are over 7 days old
1766
     *
1767
     * @deprecated
1768
     */
1769 1
    public function cleanUpOldQueueEntries(): void
1770
    {
1771 1
        $processedAgeInSeconds = $this->extensionSettings['cleanUpProcessedAge'] * 86400; // 24*60*60 Seconds in 24 hours
1772 1
        $scheduledAgeInSeconds = $this->extensionSettings['cleanUpScheduledAge'] * 86400;
1773
1774 1
        $now = time();
1775 1
        $condition = '(exec_time<>0 AND exec_time<' . ($now - $processedAgeInSeconds) . ') OR scheduled<=' . ($now - $scheduledAgeInSeconds);
1776 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

1776
        /** @scrutinizer ignore-deprecated */ $this->flushQueue($condition);
Loading history...
1777 1
    }
1778
1779
    /**
1780
     * Removes queue entries
1781
     *
1782
     * @param string $where SQL related filter for the entries which should be removed
1783
     *
1784
     * @deprecated
1785
     */
1786 5
    protected function flushQueue($where = ''): void
1787
    {
1788 5
        $realWhere = strlen((string) $where) > 0 ? $where : '1=1';
1789
1790 5
        $queryBuilder = $this->getQueryBuilder($this->tableName);
1791
1792
        $groups = $queryBuilder
1793 5
            ->selectLiteral('DISTINCT set_id')
1794 5
            ->from($this->tableName)
1795 5
            ->where($realWhere)
1796 5
            ->execute()
1797 5
            ->fetchAll();
1798 5
        if (is_array($groups)) {
0 ignored issues
show
introduced by
The condition is_array($groups) is always true.
Loading history...
1799 5
            foreach ($groups as $group) {
1800
                $subSet = $queryBuilder
1801 4
                    ->select('qid', 'set_id')
1802 4
                    ->from($this->tableName)
1803 4
                    ->where(
1804 4
                        $realWhere,
1805 4
                        $queryBuilder->expr()->eq('set_id', $group['set_id'])
1806
                    )
1807 4
                    ->execute()
1808 4
                    ->fetchAll();
1809
1810 4
                $payLoad = ['subSet' => $subSet];
1811 4
                SignalSlotUtility::emitSignal(
1812 4
                    self::class,
1813 4
                    SignalSlotUtility::SIGNAL_QUEUE_ENTRY_FLUSH,
1814 4
                    $payLoad
1815
                );
1816
            }
1817
        }
1818
1819
        $queryBuilder
1820 5
            ->delete($this->tableName)
1821 5
            ->where($realWhere)
1822 5
            ->execute();
1823 5
    }
1824
1825
    /**
1826
     * This method determines duplicates for a queue entry with the same parameters and this timestamp.
1827
     * If the timestamp is in the past, it will check if there is any unprocessed queue entry in the past.
1828
     * If the timestamp is in the future it will check, if the queued entry has exactly the same timestamp
1829
     *
1830
     * @param int $tstamp
1831
     * @param array $fieldArray
1832
     *
1833
     * @return array
1834
     */
1835 5
    protected function getDuplicateRowsIfExist($tstamp, $fieldArray)
1836
    {
1837 5
        $rows = [];
1838
1839 5
        $currentTime = $this->getCurrentTime();
1840
1841 5
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
1842
        $queryBuilder
1843 5
            ->select('qid')
1844 5
            ->from('tx_crawler_queue');
1845
        //if this entry is scheduled with "now"
1846 5
        if ($tstamp <= $currentTime) {
1847 2
            if ($this->extensionSettings['enableTimeslot']) {
1848 1
                $timeBegin = $currentTime - 100;
1849 1
                $timeEnd = $currentTime + 100;
1850
                $queryBuilder
1851 1
                    ->where(
1852 1
                        'scheduled BETWEEN ' . $timeBegin . ' AND ' . $timeEnd . ''
1853
                    )
1854 1
                    ->orWhere(
1855 1
                        $queryBuilder->expr()->lte('scheduled', $currentTime)
1856
                    );
1857
            } else {
1858
                $queryBuilder
1859 1
                    ->where(
1860 2
                        $queryBuilder->expr()->lte('scheduled', $currentTime)
1861
                    );
1862
            }
1863 3
        } elseif ($tstamp > $currentTime) {
1864
            //entry with a timestamp in the future need to have the same schedule time
1865
            $queryBuilder
1866 3
                ->where(
1867 3
                    $queryBuilder->expr()->eq('scheduled', $tstamp)
1868
                );
1869
        }
1870
1871
        $queryBuilder
1872 5
            ->andWhere('NOT exec_time')
1873 5
            ->andWhere('NOT process_id')
1874 5
            ->andWhere($queryBuilder->expr()->eq('page_id', $queryBuilder->createNamedParameter($fieldArray['page_id'], \PDO::PARAM_INT)))
1875 5
            ->andWhere($queryBuilder->expr()->eq('parameters_hash', $queryBuilder->createNamedParameter($fieldArray['parameters_hash'], \PDO::PARAM_STR)));
1876
1877 5
        $statement = $queryBuilder->execute();
1878
1879 5
        while ($row = $statement->fetch()) {
1880 5
            $rows[] = $row['qid'];
1881
        }
1882
1883 5
        return $rows;
1884
    }
1885
1886
    /**
1887
     * Returns a md5 hash generated from a serialized configuration array.
1888
     *
1889
     * @return string
1890
     */
1891 6
    protected function getConfigurationHash(array $configuration)
1892
    {
1893 6
        unset($configuration['paramExpanded']);
1894 6
        unset($configuration['URLs']);
1895 6
        return md5(serialize($configuration));
1896
    }
1897
1898
    /**
1899
     * Build a URL from a Page and the Query String. If the page has a Site configuration, it can be built by using
1900
     * the Site instance.
1901
     *
1902
     * @param int $httpsOrHttp see tx_crawler_configuration.force_ssl
1903
     * @throws \TYPO3\CMS\Core\Exception\SiteNotFoundException
1904
     * @throws \TYPO3\CMS\Core\Routing\InvalidRouteArgumentsException
1905
     */
1906 8
    protected function getUrlFromPageAndQueryParameters(int $pageId, string $queryString, ?string $alternativeBaseUrl, int $httpsOrHttp): UriInterface
1907
    {
1908 8
        $site = GeneralUtility::makeInstance(SiteMatcher::class)->matchByPageId((int) $pageId);
1909 8
        if ($site instanceof Site) {
1910 5
            $queryString = ltrim($queryString, '?&');
1911 5
            $queryParts = [];
1912 5
            parse_str($queryString, $queryParts);
1913 5
            unset($queryParts['id']);
1914
            // workaround as long as we don't have native language support in crawler configurations
1915 5
            if (isset($queryParts['L'])) {
1916
                $queryParts['_language'] = $queryParts['L'];
1917
                unset($queryParts['L']);
1918
                $siteLanguage = $site->getLanguageById((int) $queryParts['_language']);
0 ignored issues
show
Unused Code introduced by
The assignment to $siteLanguage is dead and can be removed.
Loading history...
1919
            } else {
1920 5
                $siteLanguage = $site->getDefaultLanguage();
1921
            }
1922 5
            $url = $site->getRouter()->generateUri($pageId, $queryParts);
1923 5
            if (! empty($alternativeBaseUrl)) {
1924 3
                $alternativeBaseUrl = new Uri($alternativeBaseUrl);
1925 3
                $url = $url->withHost($alternativeBaseUrl->getHost());
1926 3
                $url = $url->withScheme($alternativeBaseUrl->getScheme());
1927 3
                $url = $url->withPort($alternativeBaseUrl->getPort());
1928 3
                if ($userInfo = $alternativeBaseUrl->getUserInfo()) {
1929 5
                    $url = $url->withUserInfo($userInfo);
1930
                }
1931
            }
1932
        } else {
1933
            // Technically this is not possible with site handling, but kept for backwards-compatibility reasons
1934
            // Once EXT:crawler is v10-only compatible, this should be removed completely
1935 3
            $baseUrl = ($alternativeBaseUrl ?: GeneralUtility::getIndpEnv('TYPO3_SITE_URL'));
1936 3
            $cacheHashCalculator = GeneralUtility::makeInstance(CacheHashCalculator::class);
1937 3
            $queryString .= '&cHash=' . $cacheHashCalculator->generateForParameters($queryString);
1938 3
            $url = rtrim($baseUrl, '/') . '/index.php' . $queryString;
1939 3
            $url = new Uri($url);
1940
        }
1941
1942 8
        if ($httpsOrHttp === -1) {
1943 2
            $url = $url->withScheme('http');
1944 6
        } elseif ($httpsOrHttp === 1) {
1945 6
            $url = $url->withScheme('https');
1946
        }
1947
1948 8
        return $url;
1949
    }
1950
1951 1
    protected function swapIfFirstIsLargerThanSecond(array $reg): array
1952
    {
1953
        // Swap if first is larger than last:
1954 1
        if ($reg[1] > $reg[2]) {
1955
            $temp = $reg[2];
1956
            $reg[2] = $reg[1];
1957
            $reg[1] = $temp;
1958
        }
1959
1960 1
        return $reg;
1961
    }
1962
1963
    /**
1964
     * @return BackendUserAuthentication
1965
     */
1966 1
    private function getBackendUser()
1967
    {
1968
        // Make sure the _cli_ user is loaded
1969 1
        Bootstrap::initializeBackendAuthentication();
1970 1
        if ($this->backendUser === null) {
1971 1
            $this->backendUser = $GLOBALS['BE_USER'];
1972
        }
1973 1
        return $this->backendUser;
1974
    }
1975
1976
    /**
1977
     * Get querybuilder for given table
1978
     *
1979
     * @return \TYPO3\CMS\Core\Database\Query\QueryBuilder
1980
     */
1981 12
    private function getQueryBuilder(string $table)
1982
    {
1983 12
        return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1984
    }
1985
}
1986