forked from tomasnorre/crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.tx_crawler_lib.php
2490 lines (2118 loc) · 97.9 KB
/
class.tx_crawler_lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/***************************************************************
* Copyright notice
*
* (c) 2016 AOE GmbH <[email protected]>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Class tx_crawler_lib
*/
class tx_crawler_lib {
var $setID = 0;
var $processID ='';
var $max_CLI_exec_time = 3600; // One hour is max stalled time for the CLI (If the process has had the status "start" for 3600 seconds it will be regarded stalled and a new process is started.
var $duplicateTrack = array();
var $downloadUrls = array();
var $incomingProcInstructions = array();
var $incomingConfigurationSelection = array();
var $registerQueueEntriesInternallyOnly = array();
var $queueEntries = array();
var $urlList = array();
var $debugMode=FALSE;
var $extensionSettings=array();
var $MP = false; // mount point
protected $processFilename;
/**
* Holds the internal access mode can be 'gui','cli' or 'cli_im'
*
* @var string
*/
protected $accessMode;
/**
* @var \TYPO3\CMS\Core\Database\DatabaseConnection
*/
private $db;
/**
* @var TYPO3\CMS\Core\Authentication\BackendUserAuthentication
*/
private $backendUser;
const CLI_STATUS_NOTHING_PROCCESSED = 0;
const CLI_STATUS_REMAIN = 1; //queue not empty
const CLI_STATUS_PROCESSED = 2; //(some) queue items where processed
const CLI_STATUS_ABORTED = 4; //instance didn't finish
const CLI_STATUS_POLLABLE_PROCESSED = 8;
/**
* Method to set the accessMode can be gui, cli or cli_im
*
* @return string
*/
public function getAccessMode() {
return $this->accessMode;
}
/**
* @param string $accessMode
*/
public function setAccessMode($accessMode) {
$this->accessMode = $accessMode;
}
/**
* Set disabled status to prevent processes from being processed
*
* @param bool $disabled (optional, defaults to true)
* @return void
*/
public function setDisabled($disabled = true) {
if ($disabled) {
\TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($this->processFilename, '');
} else {
if (is_file($this->processFilename)) {
unlink($this->processFilename);
}
}
}
/**
* Get disable status
*
* @return bool true if disabled
*/
public function getDisabled() {
if (is_file($this->processFilename)) {
return true;
} else {
return false;
}
}
/**
* @param string $filenameWithPath
*
* @return void
*/
public function setProcessFilename($filenameWithPath)
{
$this->processFilename = $filenameWithPath;
}
/**
* @return string
*/
public function getProcessFilename()
{
return $this->processFilename;
}
/************************************
*
* Getting URLs based on Page TSconfig
*
************************************/
public function __construct() {
$this->db = $GLOBALS['TYPO3_DB'];
$this->backendUser = $GLOBALS['BE_USER'];
$this->processFilename = PATH_site.'typo3temp/tx_crawler.proc';
$settings = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['crawler']);
$settings = is_array($settings) ? $settings : array();
// read ext_em_conf_template settings and set
$this->setExtensionSettings($settings);
// set defaults:
if (\TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($this->extensionSettings['countInARun']) == 0) {
$this->extensionSettings['countInARun'] = 100;
}
$this->extensionSettings['processLimit'] = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->extensionSettings['processLimit'],1,99,1);
}
/**
* Sets the extensions settings (unserialized pendant of $TYPO3_CONF_VARS['EXT']['extConf']['crawler']).
*
* @param array $extensionSettings
* @return void
*/
public function setExtensionSettings(array $extensionSettings) {
$this->extensionSettings = $extensionSettings;
}
/**
* Check if the given page should be crawled
*
* @param array $pageRow
* @return false|string false if the page should be crawled (not excluded), true / skipMessage if it should be skipped
*/
public function checkIfPageShouldBeSkipped(array $pageRow) {
$skipPage = false;
$skipMessage = 'Skipped'; // message will be overwritten later
// if page is hidden
if (!$this->extensionSettings['crawlHiddenPages']) {
if ($pageRow['hidden']) {
$skipPage = true;
$skipMessage = 'Because page is hidden';
}
}
if (!$skipPage) {
if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('3,4', $pageRow['doktype']) || $pageRow['doktype']>=199) {
$skipPage = true;
$skipMessage = 'Because doktype is not allowed';
}
}
if (!$skipPage) {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['excludeDoktype'])) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['excludeDoktype'] as $key => $doktypeList) {
if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList($doktypeList, $pageRow['doktype'])) {
$skipPage = true;
$skipMessage = 'Doktype was excluded by "'.$key.'"';
break;
}
}
}
}
if (!$skipPage) {
// veto hook
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pageVeto'])) {
foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['pageVeto'] as $key => $func) {
$params = array(
'pageRow' => $pageRow
);
// expects "false" if page is ok and "true" or a skipMessage if this page should _not_ be crawled
$veto = \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($func, $params, $this);
if ($veto !== false) {
$skipPage = true;
if (is_string($veto)) {
$skipMessage = $veto;
} else {
$skipMessage = 'Veto from hook "'.htmlspecialchars($key).'"';
}
// no need to execute other hooks if a previous one return a veto
break;
}
}
}
}
return $skipPage ? $skipMessage : false;
}
/**
* Wrapper method for getUrlsForPageId()
* It returns an array of configurations and no urls!
*
* @param array $pageRow Page record with at least dok-type and uid columns.
* @param string $skipMessage
* @return array Result (see getUrlsForPageId())
* @see getUrlsForPageId()
*/
public function getUrlsForPageRow(array $pageRow, &$skipMessage = '') {
$message = $this->checkIfPageShouldBeSkipped($pageRow);
if ($message === false) {
$res = $this->getUrlsForPageId($pageRow['uid']);
$skipMessage = '';
} else {
$skipMessage = $message;
$res = array();
}
return $res;
}
/**
* This method is used to count if there are ANY unprocessed queue entries
* of a given page_id and the configuration which matches a given hash.
* If there if none, we can skip an inner detail check
*
* @param int $uid
* @param string $configurationHash
* @return boolean
*/
protected function noUnprocessedQueueEntriesForPageWithConfigurationHashExist($uid,$configurationHash) {
$configurationHash = $this->db->fullQuoteStr($configurationHash,'tx_crawler_queue');
$res = $this->db->exec_SELECTquery('count(*) as anz','tx_crawler_queue',"page_id=".intval($uid)." AND configuration_hash=".$configurationHash." AND exec_time=0");
$row = $this->db->sql_fetch_assoc($res);
return ($row['anz'] == 0);
}
/**
* Creates a list of URLs from input array (and submits them to queue if asked for)
* See Web > Info module script + "indexed_search"'s crawler hook-client using this!
*
* @param array $vv Information about URLs from pageRow to crawl.
* @param array $pageRow Page row
* @param integer $scheduledTime Unix time to schedule indexing to, typically time()
* @param integer $reqMinute Number of requests per minute (creates the interleave between requests)
* @param boolean $submitCrawlUrls If set, submits the URLs to queue
* @param boolean $downloadCrawlUrls If set (and submitcrawlUrls is false) will fill $downloadUrls with entries)
* @param array $duplicateTrack Array which is passed by reference and contains the an id per url to secure we will not crawl duplicates
* @param array $downloadUrls Array which will be filled with URLS for download if flag is set.
* @param array $incomingProcInstructions Array of processing instructions
* @return string List of URLs (meant for display in backend module)
*
*/
function urlListFromUrlArray(
array $vv,
array $pageRow,
$scheduledTime,
$reqMinute,
$submitCrawlUrls,
$downloadCrawlUrls,
array &$duplicateTrack,
array &$downloadUrls,
array $incomingProcInstructions) {
// realurl support (thanks to Ingo Renner)
if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('realurl') && $vv['subCfg']['realurl']) {
/** @var tx_realurl $urlObj */
$urlObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_realurl');
if (!empty($vv['subCfg']['baseUrl'])) {
$urlParts = parse_url($vv['subCfg']['baseUrl']);
$host = strtolower($urlParts['host']);
$urlObj->host = $host;
// First pass, finding configuration OR pointer string:
$urlObj->extConf = isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$urlObj->host]) ? $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$urlObj->host] : $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
// If it turned out to be a string pointer, then look up the real config:
if (is_string($urlObj->extConf)) {
$urlObj->extConf = is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$urlObj->extConf]) ? $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$urlObj->extConf] : $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
}
}
if (!$GLOBALS['TSFE']->sys_page) {
$GLOBALS['TSFE']->sys_page = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Page\PageRepository');
}
if (!$GLOBALS['TSFE']->csConvObj) {
$GLOBALS['TSFE']->csConvObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Core\Charset\CharsetConverter');
}
if (!$GLOBALS['TSFE']->tmpl->rootLine[0]['uid']) {
$GLOBALS['TSFE']->tmpl->rootLine[0]['uid'] = $urlObj->extConf['pagePath']['rootpage_id'];
}
}
if (is_array($vv['URLs'])) {
$configurationHash = md5(serialize($vv));
$skipInnerCheck = $this->noUnprocessedQueueEntriesForPageWithConfigurationHashExist($pageRow['uid'],$configurationHash);
foreach($vv['URLs'] as $urlQuery) {
if ($this->drawURLs_PIfilter($vv['subCfg']['procInstrFilter'], $incomingProcInstructions)) {
// Calculate cHash:
if ($vv['subCfg']['cHash']) {
/* @var $cacheHash \TYPO3\CMS\Frontend\Page\CacheHashCalculator */
$cacheHash = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Page\CacheHashCalculator');
$urlQuery .= '&cHash=' . $cacheHash->generateForParameters($urlQuery);
}
// Create key by which to determine unique-ness:
$uKey = $urlQuery.'|'.$vv['subCfg']['userGroups'].'|'.$vv['subCfg']['baseUrl'].'|'.$vv['subCfg']['procInstrFilter'];
// realurl support (thanks to Ingo Renner)
$urlQuery = 'index.php' . $urlQuery;
if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('realurl') && $vv['subCfg']['realurl']) {
$params = array(
'LD' => array(
'totalURL' => $urlQuery
),
'TCEmainHook' => true
);
$urlObj->encodeSpURL($params);
$urlQuery = $params['LD']['totalURL'];
}
// Scheduled time:
$schTime = $scheduledTime + round(count($duplicateTrack)*(60/$reqMinute));
$schTime = floor($schTime/60)*60;
if (isset($duplicateTrack[$uKey])) {
//if the url key is registered just display it and do not resubmit is
$urlList = '<em><span class="typo3-dimmed">'.htmlspecialchars($urlQuery).'</span></em><br/>';
} else {
$urlList = '['.date('d.m.y H:i', $schTime).'] '.htmlspecialchars($urlQuery);
$this->urlList[] = '['.date('d.m.y H:i', $schTime).'] '.$urlQuery;
$theUrl = ($vv['subCfg']['baseUrl'] ? $vv['subCfg']['baseUrl'] : \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL')) . $urlQuery;
// Submit for crawling!
if ($submitCrawlUrls) {
$added = $this->addUrl(
$pageRow['uid'],
$theUrl,
$vv['subCfg'],
$scheduledTime,
$configurationHash,
$skipInnerCheck
);
if ($added === false) {
$urlList .= ' (Url already existed)';
}
} elseif ($downloadCrawlUrls) {
$downloadUrls[$theUrl] = $theUrl;
}
$urlList .= '<br />';
}
$duplicateTrack[$uKey] = TRUE;
}
}
} else {
$urlList = 'ERROR - no URL generated';
}
return $urlList;
}
/**
* Returns true if input processing instruction is among registered ones.
*
* @param string $piString PI to test
* @param array $incomingProcInstructions Processing instructions
*
* @return boolean TRUE if found
*/
public function drawURLs_PIfilter($piString, array $incomingProcInstructions) {
if (empty($incomingProcInstructions)) {
return TRUE;
}
foreach($incomingProcInstructions as $pi) {
if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList($piString, $pi)) {
return TRUE;
}
}
}
/**
* @param $id
*
* @return array
*/
public function getPageTSconfigForId($id) {
if(!$this->MP){
$pageTSconfig = \TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig($id);
} else {
list(,$mountPointId) = explode('-', $this->MP);
$pageTSconfig = \TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig($mountPointId);
}
// Call a hook to alter configuration
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'])) {
$params = array(
'pageId' => $id,
'pageTSConfig' => &$pageTSconfig
);
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['getPageTSconfigForId'] as $userFunc) {
\TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($userFunc, $params, $this);
}
}
return $pageTSconfig;
}
/**
* This methods returns an array of configurations.
* And no urls!
*
* @param integer $id Page ID
* @return array Configurations from pages and configuration records
*/
protected function getUrlsForPageId($id) {
/**
* Get configuration from tsConfig
*/
// Get page TSconfig for page ID:
$pageTSconfig = $this->getPageTSconfigForId($id);
$res = array();
if (is_array($pageTSconfig) && is_array($pageTSconfig['tx_crawler.']['crawlerCfg.'])) {
$crawlerCfg = $pageTSconfig['tx_crawler.']['crawlerCfg.'];
if (is_array($crawlerCfg['paramSets.'])) {
foreach($crawlerCfg['paramSets.'] as $key => $values) {
if (!is_array($values)) {
// Sub configuration for a single configuration string:
$subCfg = (array)$crawlerCfg['paramSets.'][$key.'.'];
$subCfg['key'] = $key;
if (strcmp($subCfg['procInstrFilter'],'')) {
$subCfg['procInstrFilter'] = implode(',',\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',',$subCfg['procInstrFilter']));
}
$pidOnlyList = implode(',',\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',',$subCfg['pidsOnly'],1));
// process configuration if it is not page-specific or if the specific page is the current page:
if (!strcmp($subCfg['pidsOnly'],'') || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($pidOnlyList,$id)) {
// add trailing slash if not present
if (!empty($subCfg['baseUrl']) && substr($subCfg['baseUrl'], -1) != '/') {
$subCfg['baseUrl'] .= '/';
}
// Explode, process etc.:
$res[$key] = array();
$res[$key]['subCfg'] = $subCfg;
$res[$key]['paramParsed'] = $this->parseParams($values);
$res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'],$id);
$res[$key]['origin'] = 'pagets';
// recognize MP value
if(!$this->MP){
$res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'],array('?id='.$id));
} else {
$res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'],array('?id='.$id.'&MP='.$this->MP));
}
}
}
}
}
}
/**
* Get configuration from tx_crawler_configuration records
*/
// get records along the rootline
$rootLine = \TYPO3\CMS\Backend\Utility\BackendUtility::BEgetRootLine($id);
foreach ($rootLine as $page) {
$configurationRecordsForCurrentPage = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordsByField(
'tx_crawler_configuration',
'pid',
intval($page['uid']),
\TYPO3\CMS\Backend\Utility\BackendUtility::BEenableFields('tx_crawler_configuration') . \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause('tx_crawler_configuration')
);
if (is_array($configurationRecordsForCurrentPage)) {
foreach ($configurationRecordsForCurrentPage as $configurationRecord) {
// check access to the configuration record
if (empty($configurationRecord['begroups']) || $GLOBALS['BE_USER']->isAdmin() || $this->hasGroupAccess($GLOBALS['BE_USER']->user['usergroup_cached_list'], $configurationRecord['begroups'])) {
$pidOnlyList = implode(',',\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',',$configurationRecord['pidsonly'],1));
// process configuration if it is not page-specific or if the specific page is the current page:
if (!strcmp($configurationRecord['pidsonly'],'') || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($pidOnlyList,$id)) {
$key = $configurationRecord['name'];
// don't overwrite previously defined paramSets
if (!isset($res[$key])) {
/* @var $TSparserObject \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
$TSparserObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser');
$TSparserObject->parse($configurationRecord['processing_instruction_parameters_ts']);
$subCfg = array(
'procInstrFilter' => $configurationRecord['processing_instruction_filter'],
'procInstrParams.' => $TSparserObject->setup,
'baseUrl' => $this->getBaseUrlForConfigurationRecord($configurationRecord['base_url'], $configurationRecord['sys_domain_base_url']),
'realurl' => $configurationRecord['realurl'],
'cHash' => $configurationRecord['chash'],
'userGroups' => $configurationRecord['fegroups'],
'exclude' => $configurationRecord['exclude'],
'key' => $key,
);
// add trailing slash if not present
if (!empty($subCfg['baseUrl']) && substr($subCfg['baseUrl'], -1) != '/') {
$subCfg['baseUrl'] .= '/';
}
if (!in_array($id, $this->expandExcludeString($subCfg['exclude']))) {
$res[$key] = array();
$res[$key]['subCfg'] = $subCfg;
$res[$key]['paramParsed'] = $this->parseParams($configurationRecord['configuration']);
$res[$key]['paramExpanded'] = $this->expandParameters($res[$key]['paramParsed'], $id);
$res[$key]['URLs'] = $this->compileUrls($res[$key]['paramExpanded'], array('?id=' . $id));
$res[$key]['origin'] = 'tx_crawler_configuration_'.$configurationRecord['uid'];
}
}
}
}
}
}
}
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['processUrls'])) {
foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['crawler']['processUrls'] as $func) {
$params = array(
'res' => &$res,
);
\TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($func, $params, $this);
}
}
return $res;
}
/**
* Checks if a domain record exist and returns the base-url based on the record. If not the given baseUrl string is used.
*
* @param string $baseUrl
* @param integer $sysDomainUid
* @return string
*/
protected function getBaseUrlForConfigurationRecord($baseUrl, $sysDomainUid) {
$sysDomainUid = intval($sysDomainUid);
if ($sysDomainUid > 0) {
$res = $this->db->exec_SELECTquery(
'*',
'sys_domain',
'uid = '.$sysDomainUid .
\TYPO3\CMS\Backend\Utility\BackendUtility::BEenableFields('sys_domain') .
\TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause('sys_domain')
);
$row = $this->db->sql_fetch_assoc($res);
if ($row['domainName'] != '') {
return 'http://'.$row['domainName'];
}
}
return $baseUrl;
}
/**
* @param $rootId
* @param $depth
*
* @return array
*/
public function getConfigurationsForBranch($rootId, $depth) {
$configurationsForBranch = array();
$pageTSconfig = $this->getPageTSconfigForId($rootId);
if (is_array($pageTSconfig) && is_array($pageTSconfig['tx_crawler.']['crawlerCfg.']) && is_array($pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'])) {
$sets = $pageTSconfig['tx_crawler.']['crawlerCfg.']['paramSets.'];
if(is_array($sets)) {
foreach($sets as $key=>$value) {
if(!is_array($value)) continue;
$configurationsForBranch[] = substr($key,-1)=='.'?substr($key,0,-1):$key;
}
}
}
$pids = array();
$rootLine = \TYPO3\CMS\Backend\Utility\BackendUtility::BEgetRootLine($rootId);
foreach($rootLine as $node) {
$pids[] = $node['uid'];
}
/* @var \TYPO3\CMS\Backend\Tree\View\PageTreeView */
$tree = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Backend\Tree\View\PageTreeView');
$perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
$tree->init('AND ' . $perms_clause);
$tree->getTree($rootId, $depth, '');
foreach($tree->tree as $node) {
$pids[] = $node['row']['uid'];
}
$res = $this->db->exec_SELECTquery(
'*',
'tx_crawler_configuration',
'pid IN ('.implode(',', $pids).') '.
\TYPO3\CMS\Backend\Utility\BackendUtility::BEenableFields('tx_crawler_configuration') .
\TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause('tx_crawler_configuration').' '.
\TYPO3\CMS\Backend\Utility\BackendUtility::versioningPlaceholderClause('tx_crawler_configuration').' '
);
while($row = $this->db->sql_fetch_assoc($res)) {
$configurationsForBranch[] = $row['name'];
}
$this->db->sql_free_result($res);
return $configurationsForBranch;
}
/**
* Check if a user has access to an item
* (e.g. get the group list of the current logged in user from $GLOBALS['TSFE']->gr_list)
*
* @see \TYPO3\CMS\Frontend\Page\PageRepository::getMultipleGroupsWhereClause()
*
* @param string $groupList Comma-separated list of (fe_)group UIDs from a user
* @param string $accessList Comma-separated list of (fe_)group UIDs of the item to access
*
* @return bool TRUE if at least one of the users group UIDs is in the access list or the access list is empty
*/
public function hasGroupAccess($groupList, $accessList) {
if (empty($accessList)) {
return true;
}
foreach(\TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $groupList) as $groupUid) {
if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList($accessList, $groupUid)) {
return true;
}
}
return false;
}
/**
* Parse GET vars of input Query into array with key=>value pairs
*
* @param string $inputQuery Input query string
* @return array Keys are Get var names, values are the values of the GET vars.
*/
public function parseParams($inputQuery) {
// Extract all GET parameters into an ARRAY:
$paramKeyValues = array();
$GETparams = explode('&', $inputQuery);
foreach($GETparams as $paramAndValue) {
list($p,$v) = explode('=', $paramAndValue, 2);
if (strlen($p)) {
$paramKeyValues[rawurldecode($p)] = rawurldecode($v);
}
}
return $paramKeyValues;
}
/**
* Will expand the parameters configuration to individual values. This follows a certain syntax of the value of each parameter.
* Syntax of values:
* - Basically: If the value is wrapped in [...] it will be expanded according to the following syntax, otherwise the value is taken literally
* - Configuration is splitted by "|" and the parts are processed individually and finally added together
* - For each configuration part:
* - "[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"
* - "_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"
* _ENABLELANG:1 picks only original records without their language overlays
* - Default: Literal value
*
* @param array Array with key (GET var name) and values (value of GET var which is configuration for expansion)
* @param integer Current page ID
* @return array Array with key (GET var name) with the value being an array of all possible values for that key.
*/
protected function expandParameters($paramArray, $pid) {
global $TCA;
// Traverse parameter names:
foreach($paramArray as $p => $v) {
$v = trim($v);
// If value is encapsulated in square brackets it means there are some ranges of values to find, otherwise the value is literal
if (substr($v,0,1)==='[' && substr($v,-1)===']') {
// So, find the value inside brackets and reset the paramArray value as an array.
$v = substr($v,1,-1);
$paramArray[$p] = array();
// Explode parts and traverse them:
$parts = explode('|',$v);
foreach($parts as $pV) {
// Look for integer range: (fx. 1-34 or -40--30 // reads minus 40 to minus 30)
if (preg_match('/^(-?[0-9]+)\s*-\s*(-?[0-9]+)$/',trim($pV),$reg)) { // Integer range:
// Swap if first is larger than last:
if ($reg[1] > $reg[2]) {
$temp = $reg[2];
$reg[2] = $reg[1];
$reg[1] = $temp;
}
// Traverse range, add values:
$runAwayBrake = 1000; // Limit to size of range!
for($a=$reg[1]; $a<=$reg[2];$a++) {
$paramArray[$p][] = $a;
$runAwayBrake--;
if ($runAwayBrake<=0) {
break;
}
}
} elseif (substr(trim($pV),0,7)=='_TABLE:') {
// Parse parameters:
$subparts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(';',$pV);
$subpartParams = array();
foreach($subparts as $spV) {
list($pKey,$pVal) = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':',$spV);
$subpartParams[$pKey] = $pVal;
}
// Table exists:
if (isset($TCA[$subpartParams['_TABLE']])) {
$lookUpPid = isset($subpartParams['_PID']) ? intval($subpartParams['_PID']) : $pid;
$pidField = isset($subpartParams['_PIDFIELD']) ? trim($subpartParams['_PIDFIELD']) : 'pid';
$where = isset($subpartParams['_WHERE']) ? $subpartParams['_WHERE'] : '';
$addTable = isset($subpartParams['_ADDTABLE']) ? $subpartParams['_ADDTABLE'] : '';
$fieldName = $subpartParams['_FIELD'] ? $subpartParams['_FIELD'] : 'uid';
if ($fieldName==='uid' || $TCA[$subpartParams['_TABLE']]['columns'][$fieldName]) {
$andWhereLanguage = '';
$transOrigPointerField = $TCA[$subpartParams['_TABLE']]['ctrl']['transOrigPointerField'];
if ($subpartParams['_ENABLELANG'] && $transOrigPointerField) {
$andWhereLanguage = ' AND ' . $this->db->quoteStr($transOrigPointerField, $subpartParams['_TABLE']) .' <= 0 ';
}
$where = $this->db->quoteStr($pidField, $subpartParams['_TABLE']) .'='.intval($lookUpPid) . ' ' .
$andWhereLanguage . $where;
$rows = $this->db->exec_SELECTgetRows(
$fieldName,
$subpartParams['_TABLE'] . $addTable,
$where . \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($subpartParams['_TABLE']),
'',
'',
'',
$fieldName
);
if (is_array($rows)) {
$paramArray[$p] = array_merge($paramArray[$p],array_keys($rows));
}
}
}
} else { // Just add value:
$paramArray[$p][] = $pV;
}
// Hook for processing own expandParameters place holder
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['crawler/class.tx_crawler_lib.php']['expandParameters'])) {
$_params = array(
'pObj' => &$this,
'paramArray' => &$paramArray,
'currentKey' => $p,
'currentValue' => $pV,
'pid' => $pid
);
foreach($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['crawler/class.tx_crawler_lib.php']['expandParameters'] as $key => $_funcRef) {
\TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($_funcRef, $_params, $this);
}
}
}
// Make unique set of values and sort array by key:
$paramArray[$p] = array_unique($paramArray[$p]);
ksort($paramArray);
} else {
// Set the literal value as only value in array:
$paramArray[$p] = array($v);
}
}
return $paramArray;
}
/**
* Compiling URLs from parameter array (output of expandParameters())
* The number of URLs will be the multiplication of the number of parameter values for each key
*
* @param array $paramArray Output of expandParameters(): Array with keys (GET var names) and for each an array of values
* @param array $urls URLs accumulated in this array (for recursion)
* @return array URLs accumulated, if number of urls exceed 'maxCompileUrls' it will return false as an error!
*/
public function compileUrls($paramArray, $urls = array()) {
if (count($paramArray) && is_array($urls)) {
// shift first off stack:
reset($paramArray);
$varName = key($paramArray);
$valueSet = array_shift($paramArray);
// Traverse value set:
$newUrls = array();
foreach($urls as $url) {
foreach($valueSet as $val) {
$newUrls[] = $url.(strcmp($val,'') ? '&'.rawurlencode($varName).'='.rawurlencode($val) : '');
if (count($newUrls) > \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($this->extensionSettings['maxCompileUrls'], 1, 1000000000, 10000)) {
break;
}
}
}
$urls = $newUrls;
$urls = $this->compileUrls($paramArray, $urls);
}
return $urls;
}
/************************************
*
* Crawler log
*
************************************/
/**
* Return array of records from crawler queue for input page ID
*
* @param integer $id Page ID for which to look up log entries.
* @param string $filter Filter: "all" => all entries, "pending" => all that is not yet run, "finished" => all complete ones
* @param boolean $doFlush If TRUE, then entries selected at DELETED(!) instead of selected!
* @param boolean $doFullFlush
* @param integer $itemsPerPage Limit the amount of entries per page default is 10
* @return array
*/
public function getLogEntriesForPageId($id, $filter = '', $doFlush = FALSE, $doFullFlush = FALSE, $itemsPerPage = 10) {
// FIXME: Write Unit tests for Filters
switch($filter) {
case 'pending':
$addWhere = ' AND exec_time=0';
break;
case 'finished':
$addWhere = ' AND exec_time>0';
break;
default:
$addWhere = '';
break;
}
// FIXME: Write unit test that ensures that the right records are deleted.
if ($doFlush) {
$this->flushQueue( ($doFullFlush?'1=1':('page_id='.intval($id))) .$addWhere);
return array();
} else {
return $this->db->exec_SELECTgetRows('*',
'tx_crawler_queue',
'page_id=' . intval($id) . $addWhere, '', 'scheduled DESC',
(intval($itemsPerPage)>0 ? intval($itemsPerPage) : ''));
}
}
/**
* Return array of records from crawler queue for input set ID
*
* @param integer Set ID for which to look up log entries.
* @param string Filter: "all" => all entries, "pending" => all that is not yet run, "finished" => all complete ones
* @param boolean If TRUE, then entries selected at DELETED(!) instead of selected!
* @param integer Limit the amount of entires per page default is 10
* @return array
*/
public function getLogEntriesForSetId($set_id,$filter='',$doFlush=FALSE, $doFullFlush=FALSE, $itemsPerPage=10) {
// FIXME: Write Unit tests for Filters
switch($filter) {
case 'pending':
$addWhere = ' AND exec_time=0';
break;
case 'finished':
$addWhere = ' AND exec_time>0';
break;
default:
$addWhere = '';
break;
}
// FIXME: Write unit test that ensures that the right records are deleted.
if ($doFlush) {
$this->flushQueue($doFullFlush?'':('set_id='.intval($set_id).$addWhere));
return array();
} else {
return $this->db->exec_SELECTgetRows('*',
'tx_crawler_queue',
'set_id='.intval($set_id).$addWhere,'','scheduled DESC',
(intval($itemsPerPage)>0 ? intval($itemsPerPage) : ''));
}
}
/**
* Removes queue entires
*
* @param $where SQL related filter for the entries which should be removed
* @return void
*/
protected function flushQueue($where='') {
$realWhere = strlen($where)>0?$where:'1=1';
if(tx_crawler_domain_events_dispatcher::getInstance()->hasObserver('queueEntryFlush')) {
$groups = $this->db->exec_SELECTgetRows('DISTINCT set_id','tx_crawler_queue',$realWhere);
foreach($groups as $group) {
tx_crawler_domain_events_dispatcher::getInstance()->post('queueEntryFlush',$group['set_id'], $this->db->exec_SELECTgetRows('uid, set_id','tx_crawler_queue',$realWhere.' AND set_id="'.$group['set_id'].'"'));
}
}
$this->db->exec_DELETEquery('tx_crawler_queue', $realWhere);
}
/**
* Adding call back entries to log (called from hooks typically, see indexed search class "class.crawler.php"
*
* @param integer Set ID
* @param array Parameters to pass to call back function
* @param string Call back object reference, eg. 'EXT:indexed_search/class.crawler.php:&tx_indexedsearch_crawler'
* @param integer Page ID to attach it to
* @param integer Time at which to activate
* @return void
*/
public function addQueueEntry_callBack($setId,$params,$callBack,$page_id=0,$schedule=0) {
if (!is_array($params)) $params = array();
$params['_CALLBACKOBJ'] = $callBack;
// Compile value array:
$fieldArray = array(
'page_id' => intval($page_id),
'parameters' => serialize($params),
'scheduled' => intval($schedule) ? intval($schedule) : $this->getCurrentTime(),
'exec_time' => 0,
'set_id' => intval($setId),
'result_data' => '',