[FEATURE] Add signal for pre proccesing records
[Packages/TYPO3.CMS.git] / typo3 / sysext / linkvalidator / Classes / LinkAnalyzer.php
1 <?php
2 namespace TYPO3\CMS\Linkvalidator;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Html\HtmlParser;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20 use TYPO3\CMS\Lang\LanguageService;
21
22 /**
23 * This class provides Processing plugin implementation
24 */
25 class LinkAnalyzer {
26
27 /**
28 * Array of tables and fields to search for broken links
29 *
30 * @var array
31 */
32 protected $searchFields = array();
33
34 /**
35 * List of comma separated page uids (rootline downwards)
36 *
37 * @var string
38 */
39 protected $pidList = '';
40
41 /**
42 * Array of tables and the number of external links they contain
43 *
44 * @var array
45 */
46 protected $linkCounts = array();
47
48 /**
49 * Array of tables and the number of broken external links they contain
50 *
51 * @var array
52 */
53 protected $brokenLinkCounts = array();
54
55 /**
56 * Array of tables and records containing broken links
57 *
58 * @var array
59 */
60 protected $recordsWithBrokenLinks = array();
61
62 /**
63 * Array for hooks for own checks
64 *
65 * @var \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype[]
66 */
67 protected $hookObjectsArr = array();
68
69 /**
70 * Array with information about the current page
71 *
72 * @var array
73 */
74 protected $extPageInTreeInfo = array();
75
76 /**
77 * Reference to the current element with table:uid, e.g. pages:85
78 *
79 * @var string
80 */
81 protected $recordReference = '';
82
83 /**
84 * Linked page together with a possible anchor, e.g. 85#c105
85 *
86 * @var string
87 */
88 protected $pageWithAnchor = '';
89
90 /**
91 * The currently active TSConfig. Will be passed to the init function.
92 *
93 * @var array
94 */
95 protected $tsConfig = array();
96
97 /**
98 * Fill hookObjectsArr with different link types and possible XClasses.
99 */
100 public function __construct() {
101 $this->getLanguageService()->includeLLFile('EXT:linkvalidator/Resources/Private/Language/Module/locallang.xlf');
102 // Hook to handle own checks
103 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['checkLinks'])) {
104 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['checkLinks'] as $key => $classRef) {
105 $this->hookObjectsArr[$key] = GeneralUtility::getUserObj($classRef);
106 }
107 }
108 }
109
110 /**
111 * Store all the needed configuration values in class variables
112 *
113 * @param array $searchField List of fields in which to search for links
114 * @param string $pid List of comma separated page uids in which to search for links
115 * @param array $tsConfig The currently active TSConfig.
116 * @return void
117 */
118 public function init(array $searchField, $pid, $tsConfig) {
119 $this->searchFields = $searchField;
120 $this->pidList = $pid;
121 $this->tsConfig = $tsConfig;
122 }
123
124 /**
125 * Find all supported broken links and store them in tx_linkvalidator_link
126 *
127 * @param array $checkOptions List of hook object to activate
128 * @param bool $considerHidden Defines whether to look into hidden fields
129 * @return void
130 */
131 public function getLinkStatistics($checkOptions = array(), $considerHidden = FALSE) {
132 $results = array();
133 if (!empty($checkOptions)) {
134 $checkKeys = array_keys($checkOptions);
135 $checkLinkTypeCondition = ' AND link_type IN (\'' . implode('\',\'', $checkKeys) . '\')';
136 $this->getDatabaseConnection()->exec_DELETEquery(
137 'tx_linkvalidator_link',
138 '(record_pid IN (' . $this->pidList . ')' .
139 ' OR ( record_uid IN (' . $this->pidList . ') AND table_name like \'pages\'))' .
140 $checkLinkTypeCondition
141 );
142 // Traverse all configured tables
143 foreach ($this->searchFields as $table => $fields) {
144 if ($table === 'pages') {
145 $where = 'deleted = 0 AND uid IN (' . $this->pidList . ')';
146 } else {
147 $where = 'deleted = 0 AND pid IN (' . $this->pidList . ')';
148 }
149 if (!$considerHidden) {
150 $where .= BackendUtility::BEenableFields($table);
151 }
152 // If table is not configured, assume the extension is not installed
153 // and therefore no need to check it
154 if (!is_array($GLOBALS['TCA'][$table])) {
155 continue;
156 }
157 // Re-init selectFields for table
158 $selectFields = 'uid, pid';
159 $selectFields .= ', ' . $GLOBALS['TCA'][$table]['ctrl']['label'] . ', ' . implode(', ', $fields);
160
161 // @todo #64091: only select rows that have content in at least one of the relevant fields (via OR)
162 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows($selectFields, $table, $where);
163 if (!empty($rows)) {
164 foreach ($rows as $row) {
165 $this->analyzeRecord($results, $table, $fields, $row);
166 }
167 }
168 }
169 foreach ($this->hookObjectsArr as $key => $hookObj) {
170 if (is_array($results[$key]) && empty($checkOptions) || is_array($results[$key]) && $checkOptions[$key]) {
171 // Check them
172 foreach ($results[$key] as $entryKey => $entryValue) {
173 $table = $entryValue['table'];
174 $record = array();
175 $record['headline'] = BackendUtility::getRecordTitle($table, $entryValue['row']);
176 $record['record_pid'] = $entryValue['row']['pid'];
177 $record['record_uid'] = $entryValue['uid'];
178 $record['table_name'] = $table;
179 $record['link_title'] = $entryValue['link_title'];
180 $record['field'] = $entryValue['field'];
181 $record['last_check'] = time();
182 $this->recordReference = $entryValue['substr']['recordRef'];
183 $this->pageWithAnchor = $entryValue['pageAndAnchor'];
184 if (!empty($this->pageWithAnchor)) {
185 // Page with anchor, e.g. 18#1580
186 $url = $this->pageWithAnchor;
187 } else {
188 $url = $entryValue['substr']['tokenValue'];
189 }
190 $this->linkCounts[$table]++;
191 $checkUrl = $hookObj->checkLink($url, $entryValue, $this);
192 // Broken link found
193 if (!$checkUrl) {
194 $response = array();
195 $response['valid'] = FALSE;
196 $response['errorParams'] = $hookObj->getErrorParams();
197 $this->brokenLinkCounts[$table]++;
198 $record['link_type'] = $key;
199 $record['url'] = $url;
200 $record['url_response'] = serialize($response);
201 $this->getDatabaseConnection()->exec_INSERTquery('tx_linkvalidator_link', $record);
202 } elseif (GeneralUtility::_GP('showalllinks')) {
203 $response = array();
204 $response['valid'] = TRUE;
205 $this->brokenLinkCounts[$table]++;
206 $record['url'] = $url;
207 $record['link_type'] = $key;
208 $record['url_response'] = serialize($response);
209 $this->getDatabaseConnection()->exec_INSERTquery('tx_linkvalidator_link', $record);
210 }
211 }
212 }
213 }
214 }
215 }
216
217 /**
218 * Find all supported broken links for a specific record
219 *
220 * @param array $results Array of broken links
221 * @param string $table Table name of the record
222 * @param array $fields Array of fields to analyze
223 * @param array $record Record to analyse
224 * @return void
225 */
226 public function analyzeRecord(array &$results, $table, array $fields, array $record) {
227 list($results, $record) = $this->emitBeforeAnalyzeRecordSignal($results, $record, $table, $fields);
228
229 // Put together content of all relevant fields
230 $haystack = '';
231 /** @var $htmlParser HtmlParser */
232 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
233 $idRecord = $record['uid'];
234 // Get all references
235 foreach ($fields as $field) {
236 $haystack .= $record[$field] . ' --- ';
237 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
238 $valueField = $record[$field];
239 // Check if a TCA configured field has soft references defined (see TYPO3 Core API document)
240 if ($conf['softref'] && (string)$valueField !== '') {
241 // Explode the list of soft references/parameters
242 $softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']);
243 if ($softRefs !== FALSE) {
244 // Traverse soft references
245 foreach ($softRefs as $spKey => $spParams) {
246 /** @var $softRefObj \TYPO3\CMS\Core\Database\SoftReferenceIndex */
247 $softRefObj = BackendUtility::softRefParserObj($spKey);
248 // If there is an object returned...
249 if (is_object($softRefObj)) {
250 // Do processing
251 $resultArray = $softRefObj->findRef($table, $field, $idRecord, $valueField, $spKey, $spParams);
252 if (!empty($resultArray['elements'])) {
253 if ($spKey == 'typolink_tag') {
254 $this->analyseTypoLinks($resultArray, $results, $htmlParser, $record, $field, $table);
255 } else {
256 $this->analyseLinks($resultArray, $results, $record, $field, $table);
257 }
258 }
259 }
260 }
261 }
262 }
263 }
264 }
265
266 /**
267 * Returns the TSConfig that was passed to the init() method.
268 *
269 * This can be used by link checkers that get a reference of this
270 * object passed to the checkLink() method.
271 *
272 * @return array
273 */
274 public function getTSConfig() {
275 return $this->tsConfig;
276 }
277
278 /**
279 * Find all supported broken links for a specific link list
280 *
281 * @param array $resultArray findRef parsed records
282 * @param array $results Array of broken links
283 * @param array $record UID of the current record
284 * @param string $field The current field
285 * @param string $table The current table
286 * @return void
287 */
288 protected function analyseLinks(array $resultArray, array &$results, array $record, $field, $table) {
289 foreach ($resultArray['elements'] as $element) {
290 $r = $element['subst'];
291 $type = '';
292 $idRecord = $record['uid'];
293 if (!empty($r)) {
294 /** @var $hookObj \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype */
295 foreach ($this->hookObjectsArr as $keyArr => $hookObj) {
296 $type = $hookObj->fetchType($r, $type, $keyArr);
297 // Store the type that was found
298 // This prevents overriding by internal validator
299 if (!empty($type)) {
300 $r['type'] = $type;
301 }
302 }
303 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['substr'] = $r;
304 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['row'] = $record;
305 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['table'] = $table;
306 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['field'] = $field;
307 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['uid'] = $idRecord;
308 }
309 }
310 }
311
312 /**
313 * Find all supported broken links for a specific typoLink
314 *
315 * @param array $resultArray findRef parsed records
316 * @param array $results Array of broken links
317 * @param HtmlParser $htmlParser Instance of html parser
318 * @param array $record The current record
319 * @param string $field The current field
320 * @param string $table The current table
321 * @return void
322 */
323 protected function analyseTypoLinks(array $resultArray, array &$results, $htmlParser, array $record, $field, $table) {
324 $currentR = array();
325 $linkTags = $htmlParser->splitIntoBlock('link', $resultArray['content']);
326 $idRecord = $record['uid'];
327 $type = '';
328 $title = '';
329 $countLinkTags = count($linkTags);
330 for ($i = 1; $i < $countLinkTags; $i += 2) {
331 $referencedRecordType = '';
332 foreach ($resultArray['elements'] as $element) {
333 $type = '';
334 $r = $element['subst'];
335 if (!empty($r['tokenID'])) {
336 if (substr_count($linkTags[$i], $r['tokenID'])) {
337 // Type of referenced record
338 if (strpos($r['recordRef'], 'pages') !== FALSE) {
339 $currentR = $r;
340 // Contains number of the page
341 $referencedRecordType = $r['tokenValue'];
342 $wasPage = TRUE;
343 } elseif (strpos($r['recordRef'], 'tt_content') !== FALSE && (isset($wasPage) && $wasPage === TRUE)) {
344 $referencedRecordType = $referencedRecordType . '#c' . $r['tokenValue'];
345 $wasPage = FALSE;
346 } else {
347 $currentR = $r;
348 }
349 $title = strip_tags($linkTags[$i]);
350 }
351 }
352 }
353 /** @var $hookObj \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype */
354 foreach ($this->hookObjectsArr as $keyArr => $hookObj) {
355 $type = $hookObj->fetchType($currentR, $type, $keyArr);
356 // Store the type that was found
357 // This prevents overriding by internal validator
358 if (!empty($type)) {
359 $currentR['type'] = $type;
360 }
361 }
362 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['substr'] = $currentR;
363 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['row'] = $record;
364 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['table'] = $table;
365 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['field'] = $field;
366 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['uid'] = $idRecord;
367 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['link_title'] = $title;
368 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['pageAndAnchor'] = $referencedRecordType;
369 }
370 }
371
372 /**
373 * Fill a marker array with the number of links found in a list of pages
374 *
375 * @param string $curPage Comma separated list of page uids
376 * @return array Marker array with the number of links found
377 */
378 public function getLinkCounts($curPage) {
379 $markerArray = array();
380 if (empty($this->pidList)) {
381 $this->pidList = $curPage;
382 }
383 $this->pidList = rtrim($this->pidList, ',');
384
385 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
386 'count(uid) as nbBrokenLinks,link_type',
387 'tx_linkvalidator_link',
388 'record_pid in (' . $this->pidList . ')',
389 'link_type'
390 );
391 if (!empty($rows)) {
392 foreach ($rows as $row) {
393 $markerArray[$row['link_type']] = $row['nbBrokenLinks'];
394 $markerArray['brokenlinkCount'] += $row['nbBrokenLinks'];
395 }
396 }
397 return $markerArray;
398 }
399
400 /**
401 * Calls TYPO3\CMS\Backend\FrontendBackendUserAuthentication::extGetTreeList.
402 * Although this duplicates the function TYPO3\CMS\Backend\FrontendBackendUserAuthentication::extGetTreeList
403 * this is necessary to create the object that is used recursively by the original function.
404 *
405 * Generates a list of page uids from $id. List does not include $id itself.
406 * The only pages excluded from the list are deleted pages.
407 *
408 * @param int $id Start page id
409 * @param int $depth Depth to traverse down the page tree.
410 * @param int $begin is an optional integer that determines at which
411 * @param string $permsClause Perms clause
412 * @param bool $considerHidden Whether to consider hidden pages or not
413 * @return string Returns the list with a comma in the end (if any pages selected!)
414 */
415 public function extGetTreeList($id, $depth, $begin = 0, $permsClause, $considerHidden = FALSE) {
416 $depth = (int)$depth;
417 $begin = (int)$begin;
418 $id = (int)$id;
419 $theList = '';
420 if ($depth > 0) {
421 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
422 'uid,title,hidden,extendToSubpages',
423 'pages',
424 'pid=' . $id . ' AND deleted=0 AND ' . $permsClause
425 );
426 if (!empty($rows)) {
427 foreach ($rows as $row) {
428 if ($begin <= 0 && ($row['hidden'] == 0 || $considerHidden)) {
429 $theList .= $row['uid'] . ',';
430 $this->extPageInTreeInfo[] = array($row['uid'], htmlspecialchars($row['title'], $depth));
431 }
432 if ($depth > 1 && (!($row['hidden'] == 1 && $row['extendToSubpages'] == 1) || $considerHidden)) {
433 $theList .= $this->extGetTreeList($row['uid'], $depth - 1, $begin - 1, $permsClause, $considerHidden);
434 }
435 }
436 }
437 }
438 return $theList;
439 }
440
441 /**
442 * Check if rootline contains a hidden page
443 *
444 * @param array $pageInfo Array with uid, title, hidden, extendToSubpages from pages table
445 * @return bool TRUE if rootline contains a hidden page, FALSE if not
446 */
447 public function getRootLineIsHidden(array $pageInfo) {
448 $hidden = FALSE;
449 if ($pageInfo['extendToSubpages'] == 1 && $pageInfo['hidden'] == 1) {
450 $hidden = TRUE;
451 } else {
452 if ($pageInfo['pid'] > 0) {
453 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
454 'uid,title,hidden,extendToSubpages',
455 'pages',
456 'uid=' . $pageInfo['pid']
457 );
458 if (!empty($rows)) {
459 foreach ($rows as $row) {
460 $hidden = $this->getRootLineIsHidden($row);
461 }
462 }
463 }
464 }
465 return $hidden;
466 }
467
468 /**
469 * Emits a signal before the record is analyzed
470 *
471 * @param array $results Array of broken links
472 * @param array $record Record to analyse
473 * @param string $table Table name of the record
474 * @param array $fields Array of fields to analyze
475 * @return array
476 */
477 protected function emitBeforeAnalyzeRecordSignal($results, $record, $table, $fields) {
478 return $this->getSignalSlotDispatcher()->dispatch(
479 self::class,
480 'beforeAnalyzeRecord',
481 array($results, $record, $table, $fields, $this)
482 );
483 }
484
485 /**
486 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
487 */
488 protected function getSignalSlotDispatcher() {
489 return $this->getObjectManager()->get(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
490 }
491
492 /**
493 * @return \TYPO3\CMS\Extbase\Object\ObjectManager
494 */
495 protected function getObjectManager() {
496 return GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
497 }
498
499 /**
500 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
501 */
502 protected function getDatabaseConnection() {
503 return $GLOBALS['TYPO3_DB'];
504 }
505
506 /**
507 * @return LanguageService
508 */
509 protected function getLanguageService() {
510 return $GLOBALS['LANG'];
511 }
512 }