| Total Complexity | 199 | 
| Total Lines | 1907 | 
| Duplicated Lines | 0 % | 
| Changes | 15 | ||
| Bugs | 0 | Features | 0 | 
Complex classes like CrawlerController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CrawlerController, and based on these observations, apply Extract Interface, too.
| 1 | <?php | ||
| 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 = [ | ||
|  | |||
| 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 | |||
| 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 | public function __construct() | ||
| 273 |     { | ||
| 274 | $objectManager = GeneralUtility::makeInstance(ObjectManager::class); | ||
| 275 | $crawlStrategyFactory = GeneralUtility::makeInstance(CrawlStrategyFactory::class); | ||
| 276 | $this->queueRepository = $objectManager->get(QueueRepository::class); | ||
| 277 | $this->processRepository = $objectManager->get(ProcessRepository::class); | ||
| 278 | $this->configurationRepository = $objectManager->get(ConfigurationRepository::class); | ||
| 279 | $this->pageRepository = GeneralUtility::makeInstance(PageRepository::class); | ||
| 280 | $this->queueExecutor = GeneralUtility::makeInstance(QueueExecutor::class, $crawlStrategyFactory); | ||
| 281 | $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class); | ||
| 282 | $this->crawler = GeneralUtility::makeInstance(Crawler::class); | ||
| 283 | |||
| 284 | $this->processFilename = Environment::getVarPath() . '/lock/tx_crawler.proc'; | ||
| 285 | |||
| 286 | /** @var ExtensionConfigurationProvider $configurationProvider */ | ||
| 287 | $configurationProvider = GeneralUtility::makeInstance(ExtensionConfigurationProvider::class); | ||
| 288 | $settings = $configurationProvider->getExtensionConfiguration(); | ||
| 289 | $this->extensionSettings = is_array($settings) ? $settings : []; | ||
| 290 | |||
| 291 | // set defaults: | ||
| 292 |         if (MathUtility::convertToPositiveInteger($this->extensionSettings['countInARun']) === 0) { | ||
| 293 | $this->extensionSettings['countInARun'] = 100; | ||
| 294 | } | ||
| 295 | |||
| 296 | $this->extensionSettings['processLimit'] = MathUtility::forceIntegerInRange($this->extensionSettings['processLimit'], 1, 99, 1); | ||
| 297 | $this->maximumUrlsToCompile = MathUtility::forceIntegerInRange($this->extensionSettings['maxCompileUrls'], 1, 1000000000, 10000); | ||
| 298 | } | ||
| 299 | |||
| 300 | /** | ||
| 301 | * Method to set the accessMode can be gui, cli or cli_im | ||
| 302 | * | ||
| 303 | * @return string | ||
| 304 | * @deprecated | ||
| 305 | */ | ||
| 306 | public function getAccessMode() | ||
| 307 |     { | ||
| 308 | return $this->accessMode; | ||
| 309 | } | ||
| 310 | |||
| 311 | /** | ||
| 312 | * @param string $accessMode | ||
| 313 | * @deprecated | ||
| 314 | */ | ||
| 315 | public function setAccessMode($accessMode): void | ||
| 316 |     { | ||
| 317 | $this->accessMode = $accessMode; | ||
| 318 | } | ||
| 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 | public function setDisabled($disabled = true): void | ||
| 327 |     { | ||
| 328 |         if ($disabled) { | ||
| 329 | GeneralUtility::writeFile($this->processFilename, ''); | ||
| 330 |         } else { | ||
| 331 |             if (is_file($this->processFilename)) { | ||
| 332 | unlink($this->processFilename); | ||
| 333 | } | ||
| 334 | } | ||
| 335 | } | ||
| 336 | |||
| 337 | /** | ||
| 338 | * Get disable status | ||
| 339 | * | ||
| 340 | * @return bool true if disabled | ||
| 341 | * @deprecated | ||
| 342 | */ | ||
| 343 | public function getDisabled() | ||
| 344 |     { | ||
| 345 | return is_file($this->processFilename); | ||
| 346 | } | ||
| 347 | |||
| 348 | /** | ||
| 349 | * @param string $filenameWithPath | ||
| 350 | * @deprecated | ||
| 351 | */ | ||
| 352 | public function setProcessFilename($filenameWithPath): void | ||
| 353 |     { | ||
| 354 | $this->processFilename = $filenameWithPath; | ||
| 355 | } | ||
| 356 | |||
| 357 | /** | ||
| 358 | * @return string | ||
| 359 | * @deprecated | ||
| 360 | */ | ||
| 361 | public function getProcessFilename() | ||
| 362 |     { | ||
| 363 | return $this->processFilename; | ||
| 364 | } | ||
| 365 | |||
| 366 | /** | ||
| 367 | * Sets the extensions settings (unserialized pendant of $TYPO3_CONF_VARS['EXT']['extConf']['crawler']). | ||
| 368 | */ | ||
| 369 | public function setExtensionSettings(array $extensionSettings): void | ||
| 370 |     { | ||
| 371 | $this->extensionSettings = $extensionSettings; | ||
| 372 | } | ||
| 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 | public function checkIfPageShouldBeSkipped(array $pageRow) | ||
| 380 |     { | ||
| 381 | // if page is hidden | ||
| 382 |         if (! $this->extensionSettings['crawlHiddenPages'] && $pageRow['hidden']) { | ||
| 383 | return 'Because page is hidden'; | ||
| 384 | } | ||
| 385 | |||
| 386 |         if (GeneralUtility::inList('3,4,199,254,255', $pageRow['doktype'])) { | ||
| 387 | return 'Because doktype is not allowed'; | ||
| 388 | } | ||
| 389 | |||
| 390 |         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['excludeDoktype'] ?? [] as $key => $doktypeList) { | ||
| 391 |             if (GeneralUtility::inList($doktypeList, $pageRow['doktype'])) { | ||
| 392 | return 'Doktype was excluded by "' . $key . '"'; | ||
| 393 | } | ||
| 394 | } | ||
| 395 | |||
| 396 | // veto hook | ||
| 397 |         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pageVeto'] ?? [] as $key => $func) { | ||
| 398 | $params = [ | ||
| 399 | 'pageRow' => $pageRow, | ||
| 400 | ]; | ||
| 401 | // expects "false" if page is ok and "true" or a skipMessage if this page should _not_ be crawled | ||
| 402 | $veto = GeneralUtility::callUserFunction($func, $params, $this); | ||
| 403 |             if ($veto !== false) { | ||
| 404 |                 if (is_string($veto)) { | ||
| 405 | return $veto; | ||
| 406 | } | ||
| 407 | return 'Veto from hook "' . htmlspecialchars($key) . '"'; | ||
| 408 | } | ||
| 409 | } | ||
| 410 | |||
| 411 | 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 | public function getUrlsForPageRow(array $pageRow, &$skipMessage = '') | ||
| 424 |     { | ||
| 425 |         if (! is_int($pageRow['uid'])) { | ||
| 426 | $skipMessage = 'PageUid ' . $pageRow['uid'] . ' was not an integer'; | ||
| 427 | return []; | ||
| 428 | } | ||
| 429 | |||
| 430 | $message = $this->checkIfPageShouldBeSkipped($pageRow); | ||
| 431 |         if ($message === false) { | ||
| 432 | $res = $this->getUrlsForPageId($pageRow['uid']); | ||
| 433 | $skipMessage = ''; | ||
| 434 |         } else { | ||
| 435 | $skipMessage = $message; | ||
| 436 | $res = []; | ||
| 437 | } | ||
| 438 | |||
| 439 | 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 | 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 |         if (! is_array($vv['URLs'])) { | ||
| 469 | return 'ERROR - no URL generated'; | ||
| 470 | } | ||
| 471 | $urlLog = []; | ||
| 472 | $pageId = (int) $pageRow['uid']; | ||
| 473 | $configurationHash = $this->getConfigurationHash($vv); | ||
| 474 | $skipInnerCheck = $this->queueRepository->noUnprocessedQueueEntriesForPageWithConfigurationHashExist($pageId, $configurationHash); | ||
| 475 | |||
| 476 | $urlService = new UrlService(); | ||
| 477 | |||
| 478 |         foreach ($vv['URLs'] as $urlQuery) { | ||
| 479 |             if (! $this->drawURLs_PIfilter($vv['subCfg']['procInstrFilter'], $incomingProcInstructions)) { | ||
| 480 | continue; | ||
| 481 | } | ||
| 482 | $url = (string) $urlService->getUrlFromPageAndQueryParameters( | ||
| 483 | $pageId, | ||
| 484 | $urlQuery, | ||
| 485 | $vv['subCfg']['baseUrl'] ?? null, | ||
| 486 | $vv['subCfg']['force_ssl'] ?? 0 | ||
| 487 | ); | ||
| 488 | |||
| 489 | // Create key by which to determine unique-ness: | ||
| 490 | $uKey = $url . '|' . $vv['subCfg']['userGroups'] . '|' . $vv['subCfg']['procInstrFilter']; | ||
| 491 | |||
| 492 |             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 | $schTime = $scheduledTime + round(count($duplicateTrack) * (60 / $reqMinute)); | ||
| 498 | $schTime = intval($schTime / 60) * 60; | ||
| 499 | $formattedDate = BackendUtility::datetime($schTime); | ||
| 500 | $this->urlList[] = '[' . $formattedDate . '] ' . $url; | ||
| 501 | $urlList = '[' . $formattedDate . '] ' . htmlspecialchars($url); | ||
| 502 | |||
| 503 | // Submit for crawling! | ||
| 504 |                 if ($submitCrawlUrls) { | ||
| 505 | $added = $this->addUrl( | ||
| 506 | $pageId, | ||
| 507 | $url, | ||
| 508 | $vv['subCfg'], | ||
| 509 | $scheduledTime, | ||
| 510 | $configurationHash, | ||
| 511 | $skipInnerCheck | ||
| 512 | ); | ||
| 513 |                     if ($added === false) { | ||
| 514 | $urlList .= ' (URL already existed)'; | ||
| 515 | } | ||
| 516 |                 } elseif ($downloadCrawlUrls) { | ||
| 517 | $downloadUrls[$url] = $url; | ||
| 518 | } | ||
| 519 | $urlLog[] = $urlList; | ||
| 520 | } | ||
| 521 | $duplicateTrack[$uKey] = true; | ||
| 522 | } | ||
| 523 | |||
| 524 |         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 | public function drawURLs_PIfilter($piString, array $incomingProcInstructions) | ||
| 535 |     { | ||
| 536 |         if (empty($incomingProcInstructions)) { | ||
| 537 | return true; | ||
| 538 | } | ||
| 539 | |||
| 540 |         foreach ($incomingProcInstructions as $pi) { | ||
| 541 |             if (GeneralUtility::inList($piString, $pi)) { | ||
| 542 | return true; | ||
| 543 | } | ||
| 544 | } | ||
| 545 | return false; | ||
| 546 | } | ||
| 547 | |||
| 548 | public function getPageTSconfigForId($id): array | ||
| 549 |     { | ||
| 550 |         if (! $this->MP) { | ||
| 551 | $pageTSconfig = BackendUtility::getPagesTSconfig($id); | ||
| 552 |         } else { | ||
| 553 | // TODO: Please check, this makes no sense to split a boolean value. | ||
| 554 |             [, $mountPointId] = explode('-', $this->MP); | ||
| 555 | $pageTSconfig = BackendUtility::getPagesTSconfig($mountPointId); | ||
| 556 | } | ||
| 557 | |||
| 558 | // Call a hook to alter configuration | ||
| 559 |         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 | return $pageTSconfig; | ||
| 569 | } | ||
| 570 | |||
| 571 | /** | ||
| 572 | * This methods returns an array of configurations. | ||
| 573 | * Adds no urls! | ||
| 574 | */ | ||
| 575 | public function getUrlsForPageId(int $pageId): array | ||
| 576 |     { | ||
| 577 | // Get page TSconfig for page ID | ||
| 578 | $pageTSconfig = $this->getPageTSconfigForId($pageId); | ||
| 579 | |||
| 580 | $res = []; | ||
| 581 | |||
| 582 | // Fetch Crawler Configuration from pageTSconfig | ||
| 583 | $crawlerCfg = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? []; | ||
| 584 |         foreach ($crawlerCfg as $key => $values) { | ||
| 585 |             if (! is_array($values)) { | ||
| 586 | continue; | ||
| 587 | } | ||
| 588 |             $key = str_replace('.', '', $key); | ||
| 589 | // Sub configuration for a single configuration string: | ||
| 590 | $subCfg = (array) $crawlerCfg[$key . '.']; | ||
| 591 | $subCfg['key'] = $key; | ||
| 592 | |||
| 593 |             if (strcmp($subCfg['procInstrFilter'] ?? '', '')) { | ||
| 594 |                 $subCfg['procInstrFilter'] = implode(',', GeneralUtility::trimExplode(',', $subCfg['procInstrFilter'])); | ||
| 595 | } | ||
| 596 |             $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 |             if (! strcmp((string) $subCfg['pidsOnly'], '') || GeneralUtility::inList($pidOnlyList, strval($pageId))) { | ||
| 601 | |||
| 602 | // Explode, process etc.: | ||
| 603 | $res[$key] = []; | ||
| 604 | $res[$key]['subCfg'] = $subCfg; | ||
| 605 | $res[$key]['paramParsed'] = GeneralUtility::explodeUrl2Array($crawlerCfg[$key]); | ||
| 606 | $res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'], $pageId); | ||
| 607 | $res[$key]['origin'] = 'pagets'; | ||
| 608 | |||
| 609 | // recognize MP value | ||
| 610 |                 if (! $this->MP) { | ||
| 611 | $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]); | ||
| 614 | } | ||
| 615 | } | ||
| 616 | } | ||
| 617 | |||
| 618 | // Get configuration from tx_crawler_configuration records up the rootline | ||
| 619 | $crawlerConfigurations = $this->configurationRepository->getCrawlerConfigurationRecordsFromRootLine($pageId); | ||
| 620 |         foreach ($crawlerConfigurations as $configurationRecord) { | ||
| 621 | |||
| 622 | // check access to the configuration record | ||
| 623 |             if (empty($configurationRecord['begroups']) || $this->getBackendUser()->isAdmin() || $this->hasGroupAccess($this->getBackendUser()->user['usergroup_cached_list'], $configurationRecord['begroups'])) { | ||
| 624 |                 $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 |                 if (! strcmp($configurationRecord['pidsonly'], '') || GeneralUtility::inList($pidOnlyList, strval($pageId))) { | ||
| 629 | $key = $configurationRecord['name']; | ||
| 630 | |||
| 631 | // don't overwrite previously defined paramSets | ||
| 632 |                     if (! isset($res[$key])) { | ||
| 633 | |||
| 634 | /* @var $TSparserObject TypoScriptParser */ | ||
| 635 | $TSparserObject = GeneralUtility::makeInstance(TypoScriptParser::class); | ||
| 636 | $TSparserObject->parse($configurationRecord['processing_instruction_parameters_ts']); | ||
| 637 | |||
| 638 | $subCfg = [ | ||
| 639 | 'procInstrFilter' => $configurationRecord['processing_instruction_filter'], | ||
| 640 | 'procInstrParams.' => $TSparserObject->setup, | ||
| 641 | 'baseUrl' => $configurationRecord['base_url'], | ||
| 642 | 'force_ssl' => (int) $configurationRecord['force_ssl'], | ||
| 643 | 'userGroups' => $configurationRecord['fegroups'], | ||
| 644 | 'exclude' => $configurationRecord['exclude'], | ||
| 645 | 'key' => $key, | ||
| 646 | ]; | ||
| 647 | |||
| 648 |                         if (! in_array($pageId, $this->expandExcludeString($subCfg['exclude']), true)) { | ||
| 649 | $res[$key] = []; | ||
| 650 | $res[$key]['subCfg'] = $subCfg; | ||
| 651 | $res[$key]['paramParsed'] = GeneralUtility::explodeUrl2Array($configurationRecord['configuration']); | ||
| 652 | $res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'], $pageId); | ||
| 653 | $res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], ['?id=' . $pageId]); | ||
| 654 | $res[$key]['origin'] = 'tx_crawler_configuration_' . $configurationRecord['uid']; | ||
| 655 | } | ||
| 656 | } | ||
| 657 | } | ||
| 658 | } | ||
| 659 | } | ||
| 660 | |||
| 661 |         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['processUrls'] ?? [] as $func) { | ||
| 662 | $params = [ | ||
| 663 | 'res' => &$res, | ||
| 664 | ]; | ||
| 665 | GeneralUtility::callUserFunction($func, $params, $this); | ||
| 666 | } | ||
| 667 | return $res; | ||
| 668 | } | ||
| 669 | |||
| 670 | /** | ||
| 671 | * Find all configurations of subpages of a page | ||
| 672 | * TODO: Write Functional Tests | ||
| 673 | */ | ||
| 674 | public function getConfigurationsForBranch(int $rootid, int $depth): array | ||
| 675 |     { | ||
| 676 | $configurationsForBranch = []; | ||
| 677 | $pageTSconfig = $this->getPageTSconfigForId($rootid); | ||
| 678 | $sets = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'] ?? []; | ||
| 679 |         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 | $pids = []; | ||
| 686 | $rootLine = BackendUtility::BEgetRootLine($rootid); | ||
| 687 |         foreach ($rootLine as $node) { | ||
| 688 | $pids[] = $node['uid']; | ||
| 689 | } | ||
| 690 | /* @var PageTreeView $tree */ | ||
| 691 | $tree = GeneralUtility::makeInstance(PageTreeView::class); | ||
| 692 | $perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW); | ||
| 693 |         $tree->init(empty($perms_clause) ? '' : ('AND ' . $perms_clause)); | ||
| 694 | $tree->getTree($rootid, $depth, ''); | ||
| 695 |         foreach ($tree->tree as $node) { | ||
| 696 | $pids[] = $node['row']['uid']; | ||
| 697 | } | ||
| 698 | |||
| 699 |         $queryBuilder = $this->getQueryBuilder('tx_crawler_configuration'); | ||
| 700 | $statement = $queryBuilder | ||
| 701 |             ->select('name') | ||
| 702 |             ->from('tx_crawler_configuration') | ||
| 703 | ->where( | ||
| 704 |                 $queryBuilder->expr()->in('pid', $queryBuilder->createNamedParameter($pids, Connection::PARAM_INT_ARRAY)) | ||
| 705 | ) | ||
| 706 | ->execute(); | ||
| 707 | |||
| 708 |         while ($row = $statement->fetch()) { | ||
| 709 | $configurationsForBranch[] = $row['name']; | ||
| 710 | } | ||
| 711 | 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 | public function hasGroupAccess($groupList, $accessList) | ||
| 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 | public function expandParameters($paramArray, $pid) | ||
| 754 |     { | ||
| 755 | // Traverse parameter names: | ||
| 756 |         foreach ($paramArray as $p => $v) { | ||
| 757 | $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 |             if (strpos($v, '[') === 0 && substr($v, -1) === ']') { | ||
| 761 | // So, find the value inside brackets and reset the paramArray value as an array. | ||
| 762 | $v = substr($v, 1, -1); | ||
| 763 | $paramArray[$p] = []; | ||
| 764 | |||
| 765 | // Explode parts and traverse them: | ||
| 766 |                 $parts = explode('|', $v); | ||
| 767 |                 foreach ($parts as $pV) { | ||
| 768 | |||
| 769 | // Look for integer range: (fx. 1-34 or -40--30 // reads minus 40 to minus 30) | ||
| 770 |                     if (preg_match('/^(-?[0-9]+)\s*-\s*(-?[0-9]+)$/', trim($pV), $reg)) { | ||
| 771 | $reg = $this->swapIfFirstIsLargerThanSecond($reg); | ||
| 772 | |||
| 773 | // Traverse range, add values: | ||
| 774 | // Limit to size of range! | ||
| 775 | $runAwayBrake = 1000; | ||
| 776 |                         for ($a = $reg[1]; $a <= $reg[2]; $a++) { | ||
| 777 | $paramArray[$p][] = $a; | ||
| 778 | $runAwayBrake--; | ||
| 779 |                             if ($runAwayBrake <= 0) { | ||
| 780 | break; | ||
| 781 | } | ||
| 782 | } | ||
| 783 |                     } elseif (strpos(trim($pV), '_TABLE:') === 0) { | ||
| 784 | |||
| 785 | // Parse parameters: | ||
| 786 |                         $subparts = GeneralUtility::trimExplode(';', $pV); | ||
| 787 | $subpartParams = []; | ||
| 788 |                         foreach ($subparts as $spV) { | ||
| 789 |                             [$pKey, $pVal] = GeneralUtility::trimExplode(':', $spV); | ||
| 790 | $subpartParams[$pKey] = $pVal; | ||
| 791 | } | ||
| 792 | |||
| 793 | // Table exists: | ||
| 794 |                         if (isset($GLOBALS['TCA'][$subpartParams['_TABLE']])) { | ||
| 795 | $lookUpPid = isset($subpartParams['_PID']) ? intval($subpartParams['_PID']) : intval($pid); | ||
| 796 | $recursiveDepth = isset($subpartParams['_RECURSIVE']) ? intval($subpartParams['_RECURSIVE']) : 0; | ||
| 797 | $pidField = isset($subpartParams['_PIDFIELD']) ? trim($subpartParams['_PIDFIELD']) : 'pid'; | ||
| 798 | $where = $subpartParams['_WHERE'] ?? ''; | ||
| 799 | $addTable = $subpartParams['_ADDTABLE'] ?? ''; | ||
| 800 | |||
| 801 | $fieldName = $subpartParams['_FIELD'] ? $subpartParams['_FIELD'] : 'uid'; | ||
| 802 |                             if ($fieldName === 'uid' || $GLOBALS['TCA'][$subpartParams['_TABLE']]['columns'][$fieldName]) { | ||
| 803 | $queryBuilder = $this->getQueryBuilder($subpartParams['_TABLE']); | ||
| 804 | |||
| 805 |                                 if ($recursiveDepth > 0) { | ||
| 806 | /** @var QueryGenerator $queryGenerator */ | ||
| 807 | $queryGenerator = GeneralUtility::makeInstance(QueryGenerator::class); | ||
| 808 | $pidList = $queryGenerator->getTreeList($lookUpPid, $recursiveDepth, 0, 1); | ||
| 809 |                                     $pidArray = GeneralUtility::intExplode(',', $pidList); | ||
| 810 |                                 } else { | ||
| 811 | $pidArray = [(string) $lookUpPid]; | ||
| 812 | } | ||
| 813 | |||
| 814 | $queryBuilder->getRestrictions() | ||
| 815 | ->removeAll() | ||
| 816 | ->add(GeneralUtility::makeInstance(DeletedRestriction::class)); | ||
| 817 | |||
| 818 | $queryBuilder | ||
| 819 | ->select($fieldName) | ||
| 820 | ->from($subpartParams['_TABLE']) | ||
| 821 | ->where( | ||
| 822 | $queryBuilder->expr()->in($pidField, $queryBuilder->createNamedParameter($pidArray, Connection::PARAM_INT_ARRAY)), | ||
| 823 | $where | ||
| 824 | ); | ||
| 825 | |||
| 826 |                                 if (! empty($addTable)) { | ||
| 827 | // TODO: Check if this works as intended! | ||
| 828 |                                     $queryBuilder->add('from', $addTable); | ||
| 829 | } | ||
| 830 | $transOrigPointerField = $GLOBALS['TCA'][$subpartParams['_TABLE']]['ctrl']['transOrigPointerField']; | ||
| 831 | |||
| 832 |                                 if ($subpartParams['_ENABLELANG'] && $transOrigPointerField) { | ||
| 833 | $queryBuilder->andWhere( | ||
| 834 | $queryBuilder->expr()->lte( | ||
| 835 | $transOrigPointerField, | ||
| 836 | 0 | ||
| 837 | ) | ||
| 838 | ); | ||
| 839 | } | ||
| 840 | |||
| 841 | $statement = $queryBuilder->execute(); | ||
| 842 | |||
| 843 | $rows = []; | ||
| 844 |                                 while ($row = $statement->fetch()) { | ||
| 845 | $rows[$row[$fieldName]] = $row; | ||
| 846 | } | ||
| 847 | |||
| 848 |                                 if (is_array($rows)) { | ||
| 849 | $paramArray[$p] = array_merge($paramArray[$p], array_keys($rows)); | ||
| 850 | } | ||
| 851 | } | ||
| 852 | } | ||
| 853 |                     } else { | ||
| 854 | // Just add value: | ||
| 855 | $paramArray[$p][] = $pV; | ||
| 856 | } | ||
| 857 | // Hook for processing own expandParameters place holder | ||
| 858 |                     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 | $paramArray[$p] = array_unique($paramArray[$p]); | ||
| 874 | ksort($paramArray); | ||
| 875 |             } else { | ||
| 876 | // Set the literal value as only value in array: | ||
| 877 | $paramArray[$p] = [$v]; | ||
| 878 | } | ||
| 879 | } | ||
| 880 | |||
| 881 | 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 | public function compileUrls($paramArray, array $urls) | ||
| 893 |     { | ||
| 894 |         if (empty($paramArray)) { | ||
| 895 | return $urls; | ||
| 896 | } | ||
| 897 | // shift first off stack: | ||
| 898 | reset($paramArray); | ||
| 899 | $varName = key($paramArray); | ||
| 900 | $valueSet = array_shift($paramArray); | ||
| 901 | |||
| 902 | // Traverse value set: | ||
| 903 | $newUrls = []; | ||
| 904 |         foreach ($urls as $url) { | ||
| 905 |             foreach ($valueSet as $val) { | ||
| 906 | $newUrls[] = $url . (strcmp((string) $val, '') ? '&' . rawurlencode($varName) . '=' . rawurlencode((string) $val) : ''); | ||
| 907 | |||
| 908 |                 if (count($newUrls) > $this->maximumUrlsToCompile) { | ||
| 909 | break; | ||
| 910 | } | ||
| 911 | } | ||
| 912 | } | ||
| 913 | 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 | public function getLogEntriesForPageId($id, QueueFilter $queueFilter, $doFlush = false, $doFullFlush = false, $itemsPerPage = 10) | ||
| 934 |     { | ||
| 935 | $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName); | ||
| 936 | $queryBuilder | ||
| 937 |             ->select('*') | ||
| 938 | ->from($this->tableName) | ||
| 939 | ->where( | ||
| 940 |                 $queryBuilder->expr()->eq('page_id', $queryBuilder->createNamedParameter($id, PDO::PARAM_INT)) | ||
| 941 | ) | ||
| 942 |             ->orderBy('scheduled', 'DESC'); | ||
| 943 | |||
| 944 | $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class) | ||
| 945 | ->getConnectionForTable($this->tableName) | ||
| 946 | ->getExpressionBuilder(); | ||
| 947 | $query = $expressionBuilder->andX(); | ||
| 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 |         switch ($queueFilter) { | ||
| 952 | case 'pending': | ||
| 953 |                 $queryBuilder->andWhere($queryBuilder->expr()->eq('exec_time', 0)); | ||
| 954 | break; | ||
| 955 | case 'finished': | ||
| 956 |                 $queryBuilder->andWhere($queryBuilder->expr()->gt('exec_time', 0)); | ||
| 957 | break; | ||
| 958 | } | ||
| 959 | |||
| 960 |         if ($doFlush) { | ||
| 961 | $this->queueRepository->flushQueue($queueFilter); | ||
| 962 | } | ||
| 963 |         if ($itemsPerPage > 0) { | ||
| 964 | $queryBuilder | ||
| 965 | ->setMaxResults((int) $itemsPerPage); | ||
| 966 | } | ||
| 967 | |||
| 968 | 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 | public function getLogEntriesForSetId(int $set_id, string $filter = '', bool $doFlush = false, bool $doFullFlush = false, int $itemsPerPage = 10) | ||
| 983 |     { | ||
| 984 | $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName); | ||
| 985 | $queryBuilder | ||
| 986 |             ->select('*') | ||
| 987 | ->from($this->tableName) | ||
| 988 | ->where( | ||
| 989 |                 $queryBuilder->expr()->eq('set_id', $queryBuilder->createNamedParameter($set_id, PDO::PARAM_INT)) | ||
| 990 | ) | ||
| 991 |             ->orderBy('scheduled', 'DESC'); | ||
| 992 | |||
| 993 | $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class) | ||
| 994 | ->getConnectionForTable($this->tableName) | ||
| 995 | ->getExpressionBuilder(); | ||
| 996 | $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 | $addWhere = ''; | ||
| 1001 |         switch ($filter) { | ||
| 1002 | case 'pending': | ||
| 1003 |                 $queryBuilder->andWhere($queryBuilder->expr()->eq('exec_time', 0)); | ||
| 1004 |                 $addWhere = $query->add($expressionBuilder->eq('exec_time', 0)); | ||
| 1005 | break; | ||
| 1006 | case 'finished': | ||
| 1007 |                 $queryBuilder->andWhere($queryBuilder->expr()->gt('exec_time', 0)); | ||
| 1008 |                 $addWhere = $query->add($expressionBuilder->gt('exec_time', 0)); | ||
| 1009 | break; | ||
| 1010 | } | ||
| 1011 |         if ($doFlush) { | ||
| 1012 |             $addWhere = $query->add($expressionBuilder->eq('set_id', (int) $set_id)); | ||
| 1013 | $this->flushQueue($doFullFlush ? '' : $addWhere); | ||
| 1014 | return []; | ||
| 1015 | } | ||
| 1016 |         if ($itemsPerPage > 0) { | ||
| 1017 | $queryBuilder | ||
| 1018 | ->setMaxResults((int) $itemsPerPage); | ||
| 1019 | } | ||
| 1020 | |||
| 1021 | 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)) { | ||
| 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 | public function addUrl( | ||
| 1072 | $id, | ||
| 1073 | $url, | ||
| 1074 | array $subCfg, | ||
| 1075 | $tstamp, | ||
| 1076 | $configurationHash = '', | ||
| 1077 | $skipInnerDuplicationCheck = false | ||
| 1078 |     ) { | ||
| 1079 | $urlAdded = false; | ||
| 1080 | $rows = []; | ||
| 1081 | |||
| 1082 | // Creating parameters: | ||
| 1083 | $parameters = [ | ||
| 1084 | 'url' => $url, | ||
| 1085 | ]; | ||
| 1086 | |||
| 1087 | // fe user group simulation: | ||
| 1088 |         $uGs = implode(',', array_unique(GeneralUtility::intExplode(',', $subCfg['userGroups'], true))); | ||
| 1089 |         if ($uGs) { | ||
| 1090 | $parameters['feUserGroupList'] = $uGs; | ||
| 1091 | } | ||
| 1092 | |||
| 1093 | // Setting processing instructions | ||
| 1094 |         $parameters['procInstructions'] = GeneralUtility::trimExplode(',', $subCfg['procInstrFilter']); | ||
| 1095 |         if (is_array($subCfg['procInstrParams.'])) { | ||
| 1096 | $parameters['procInstrParams'] = $subCfg['procInstrParams.']; | ||
| 1097 | } | ||
| 1098 | |||
| 1099 | // Compile value array: | ||
| 1100 | $parameters_serialized = json_encode($parameters); | ||
| 1101 | $fieldArray = [ | ||
| 1102 | 'page_id' => (int) $id, | ||
| 1103 | 'parameters' => $parameters_serialized, | ||
| 1104 | 'parameters_hash' => GeneralUtility::shortMD5($parameters_serialized), | ||
| 1105 | 'configuration_hash' => $configurationHash, | ||
| 1106 | 'scheduled' => $tstamp, | ||
| 1107 | 'exec_time' => 0, | ||
| 1108 | 'set_id' => (int) $this->setID, | ||
| 1109 | 'result_data' => '', | ||
| 1110 | 'configuration' => $subCfg['key'], | ||
| 1111 | ]; | ||
| 1112 | |||
| 1113 |         if ($this->registerQueueEntriesInternallyOnly) { | ||
| 1114 | //the entries will only be registered and not stored to the database | ||
| 1115 | $this->queueEntries[] = $fieldArray; | ||
| 1116 |         } else { | ||
| 1117 |             if (! $skipInnerDuplicationCheck) { | ||
| 1118 | // check if there is already an equal entry | ||
| 1119 | $rows = $this->queueRepository->getDuplicateQueueItemsIfExists( | ||
| 1120 | (bool) $this->extensionSettings['enableTimeslot'], | ||
| 1121 | $tstamp, | ||
| 1122 | $this->getCurrentTime(), | ||
| 1123 | $fieldArray['page_id'], | ||
| 1124 | $fieldArray['parameters_hash'] | ||
| 1125 | ); | ||
| 1126 | } | ||
| 1127 | |||
| 1128 |             if (empty($rows)) { | ||
| 1129 |                 $connectionForCrawlerQueue = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_crawler_queue'); | ||
| 1130 | $connectionForCrawlerQueue->insert( | ||
| 1131 | 'tx_crawler_queue', | ||
| 1132 | $fieldArray | ||
| 1133 | ); | ||
| 1134 |                 $uid = $connectionForCrawlerQueue->lastInsertId('tx_crawler_queue', 'qid'); | ||
| 1135 | $rows[] = $uid; | ||
| 1136 | $urlAdded = true; | ||
| 1137 | |||
| 1138 | $signalPayload = ['uid' => $uid, 'fieldArray' => $fieldArray]; | ||
| 1139 | SignalSlotUtility::emitSignal( | ||
| 1140 | self::class, | ||
| 1141 | SignalSlotUtility::SIGNAL_URL_ADDED_TO_QUEUE, | ||
| 1142 | $signalPayload | ||
| 1143 | ); | ||
| 1144 |             } else { | ||
| 1145 | $signalPayload = ['rows' => $rows, 'fieldArray' => $fieldArray]; | ||
| 1146 | SignalSlotUtility::emitSignal( | ||
| 1147 | self::class, | ||
| 1148 | SignalSlotUtility::SIGNAL_DUPLICATE_URL_IN_QUEUE, | ||
| 1149 | $signalPayload | ||
| 1150 | ); | ||
| 1151 | } | ||
| 1152 | } | ||
| 1153 | |||
| 1154 | return $urlAdded; | ||
| 1155 | } | ||
| 1156 | |||
| 1157 | /** | ||
| 1158 | * Returns the current system time | ||
| 1159 | * | ||
| 1160 | * @return int | ||
| 1161 | */ | ||
| 1162 | public function getCurrentTime() | ||
| 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) | ||
| 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, | ||
| 1405 | } | ||
| 1406 | |||
| 1407 | /** | ||
| 1408 | * Expands exclude string | ||
| 1409 | * | ||
| 1410 | * @param string $excludeString Exclude string | ||
| 1411 | * @return array | ||
| 1412 | */ | ||
| 1413 | public function expandExcludeString($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() . ')'); | ||
| 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() . ')'); | ||
| 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() . ')'); | ||
| 1638 |         } else { | ||
| 1639 |             $this->CLI_debug('Nothing within queue which needs to be processed (' . $this->CLI_buildProcessId() . ')'); | ||
| 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'] . ')'); | ||
| 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'] . ')'); | ||
| 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 | public function CLI_buildProcessId() | ||
| 1775 |     { | ||
| 1776 |         if (! $this->processID) { | ||
| 1777 | $this->processID = GeneralUtility::shortMD5(microtime(true)); | ||
| 1778 | } | ||
| 1779 | 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 | public function cleanUpOldQueueEntries(): void | ||
| 1805 |     { | ||
| 1806 | // 24*60*60 Seconds in 24 hours | ||
| 1807 | $processedAgeInSeconds = $this->extensionSettings['cleanUpProcessedAge'] * 86400; | ||
| 1808 | $scheduledAgeInSeconds = $this->extensionSettings['cleanUpScheduledAge'] * 86400; | ||
| 1809 | |||
| 1810 | $now = time(); | ||
| 1811 | $condition = '(exec_time<>0 AND exec_time<' . ($now - $processedAgeInSeconds) . ') OR scheduled<=' . ($now - $scheduledAgeInSeconds); | ||
| 1812 | $this->flushQueue($condition); | ||
| 1813 | } | ||
| 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 | protected function flushQueue($where = ''): void | ||
| 1823 |     { | ||
| 1824 | $realWhere = strlen((string) $where) > 0 ? $where : '1=1'; | ||
| 1825 | |||
| 1826 | $queryBuilder = $this->getQueryBuilder($this->tableName); | ||
| 1827 | |||
| 1828 | $groups = $queryBuilder | ||
| 1829 |             ->selectLiteral('DISTINCT set_id') | ||
| 1830 | ->from($this->tableName) | ||
| 1831 | ->where($realWhere) | ||
| 1832 | ->execute() | ||
| 1833 | ->fetchAll(); | ||
| 1834 |         if (is_array($groups)) { | ||
| 1835 |             foreach ($groups as $group) { | ||
| 1836 | $subSet = $queryBuilder | ||
| 1837 |                     ->select('qid', 'set_id') | ||
| 1838 | ->from($this->tableName) | ||
| 1839 | ->where( | ||
| 1840 | $realWhere, | ||
| 1841 |                         $queryBuilder->expr()->eq('set_id', $group['set_id']) | ||
| 1842 | ) | ||
| 1843 | ->execute() | ||
| 1844 | ->fetchAll(); | ||
| 1845 | |||
| 1846 | $payLoad = ['subSet' => $subSet]; | ||
| 1847 | SignalSlotUtility::emitSignal( | ||
| 1848 | self::class, | ||
| 1849 | SignalSlotUtility::SIGNAL_QUEUE_ENTRY_FLUSH, | ||
| 1850 | $payLoad | ||
| 1851 | ); | ||
| 1852 | } | ||
| 1853 | } | ||
| 1854 | |||
| 1855 | $queryBuilder | ||
| 1856 | ->delete($this->tableName) | ||
| 1857 | ->where($realWhere) | ||
| 1858 | ->execute(); | ||
| 1859 | } | ||
| 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 | protected function getDuplicateRowsIfExist($tstamp, $fieldArray) | ||
| 1873 |     { | ||
| 1874 | $rows = []; | ||
| 1875 | |||
| 1876 | $currentTime = $this->getCurrentTime(); | ||
| 1877 | |||
| 1878 | $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName); | ||
| 1879 | $queryBuilder | ||
| 1880 |             ->select('qid') | ||
| 1881 |             ->from('tx_crawler_queue'); | ||
| 1882 | //if this entry is scheduled with "now" | ||
| 1883 |         if ($tstamp <= $currentTime) { | ||
| 1884 |             if ($this->extensionSettings['enableTimeslot']) { | ||
| 1885 | $timeBegin = $currentTime - 100; | ||
| 1886 | $timeEnd = $currentTime + 100; | ||
| 1887 | $queryBuilder | ||
| 1888 | ->where( | ||
| 1889 | 'scheduled BETWEEN ' . $timeBegin . ' AND ' . $timeEnd . '' | ||
| 1890 | ) | ||
| 1891 | ->orWhere( | ||
| 1892 |                         $queryBuilder->expr()->lte('scheduled', $currentTime) | ||
| 1893 | ); | ||
| 1894 |             } else { | ||
| 1895 | $queryBuilder | ||
| 1896 | ->where( | ||
| 1897 |                         $queryBuilder->expr()->lte('scheduled', $currentTime) | ||
| 1898 | ); | ||
| 1899 | } | ||
| 1900 |         } elseif ($tstamp > $currentTime) { | ||
| 1901 | //entry with a timestamp in the future need to have the same schedule time | ||
| 1902 | $queryBuilder | ||
| 1903 | ->where( | ||
| 1904 |                     $queryBuilder->expr()->eq('scheduled', $tstamp) | ||
| 1905 | ); | ||
| 1906 | } | ||
| 1907 | |||
| 1908 | $queryBuilder | ||
| 1909 |             ->andWhere('NOT exec_time') | ||
| 1910 |             ->andWhere('NOT process_id') | ||
| 1911 |             ->andWhere($queryBuilder->expr()->eq('page_id', $queryBuilder->createNamedParameter($fieldArray['page_id'], PDO::PARAM_INT))) | ||
| 1912 |             ->andWhere($queryBuilder->expr()->eq('parameters_hash', $queryBuilder->createNamedParameter($fieldArray['parameters_hash'], PDO::PARAM_STR))); | ||
| 1913 | |||
| 1914 | $statement = $queryBuilder->execute(); | ||
| 1915 | |||
| 1916 |         while ($row = $statement->fetch()) { | ||
| 1917 | $rows[] = $row['qid']; | ||
| 1918 | } | ||
| 1919 | |||
| 1920 | return $rows; | ||
| 1921 | } | ||
| 1922 | |||
| 1923 | /** | ||
| 1924 | * Returns a md5 hash generated from a serialized configuration array. | ||
| 1925 | * | ||
| 1926 | * @return string | ||
| 1927 | */ | ||
| 1928 | protected function getConfigurationHash(array $configuration) | ||
| 1929 |     { | ||
| 1930 | unset($configuration['paramExpanded']); | ||
| 1931 | unset($configuration['URLs']); | ||
| 1932 | 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 | protected function swapIfFirstIsLargerThanSecond(array $reg): array | ||
| 1962 | } | ||
| 1963 | |||
| 1964 | /** | ||
| 1965 | * @return BackendUserAuthentication | ||
| 1966 | */ | ||
| 1967 | private function getBackendUser() | ||
| 1968 |     { | ||
| 1969 | // Make sure the _cli_ user is loaded | ||
| 1970 | Bootstrap::initializeBackendAuthentication(); | ||
| 1971 |         if ($this->backendUser === null) { | ||
| 1972 | $this->backendUser = $GLOBALS['BE_USER']; | ||
| 1973 | } | ||
| 1974 | return $this->backendUser; | ||
| 1975 | } | ||
| 1976 | |||
| 1977 | /** | ||
| 1978 | * Get querybuilder for given table | ||
| 1979 | * | ||
| 1980 | * @return QueryBuilder | ||
| 1981 | */ | ||
| 1982 | private function getQueryBuilder(string $table) | ||
| 1985 | } | ||
| 1986 | } | ||
| 1987 |