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