[BUGFIX] Prevent double content link checks
[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
19 /**
20 * This class provides Processing plugin implementation
21 *
22 * @author Michael Miousse <michael.miousse@infoglobe.ca>
23 * @author Jochen Rieger <j.rieger@connecta.ag>
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 $GLOBALS['LANG']->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] = \TYPO3\CMS\Core\Utility\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 (count($checkOptions) > 0) {
134 $checkKeys = array_keys($checkOptions);
135 $checkLinkTypeCondition = ' AND link_type IN (\'' . implode('\',\'', $checkKeys) . '\')';
136 $GLOBALS['TYPO3_DB']->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 // @todo only select rows that have content in at least one of the relevant fields (via OR)
161 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selectFields, $table, $where);
162 // Get record rows of table
163 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
164 // Analyse each record
165 $this->analyzeRecord($results, $table, $fields, $row);
166 }
167 $GLOBALS['TYPO3_DB']->sql_free_result($res);
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'] = $entryValue['row'][$GLOBALS['TCA'][$table]['ctrl']['label']];
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 $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_linkvalidator_link', $record);
202 } elseif (\TYPO3\CMS\Core\Utility\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 $GLOBALS['TYPO3_DB']->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 // Put together content of all relevant fields
228 $haystack = '';
229 /** @var $htmlParser \TYPO3\CMS\Core\Html\HtmlParser */
230 $htmlParser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Html\HtmlParser::class);
231 $idRecord = $record['uid'];
232 // Get all references
233 foreach ($fields as $field) {
234 $haystack .= $record[$field] . ' --- ';
235 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
236 $valueField = $record[$field];
237 // Check if a TCA configured field has soft references defined (see TYPO3 Core API document)
238 if ($conf['softref'] && strlen($valueField)) {
239 // Explode the list of soft references/parameters
240 $softRefs = BackendUtility::explodeSoftRefParserList($conf['softref']);
241 // Traverse soft references
242 foreach ($softRefs as $spKey => $spParams) {
243 /** @var $softRefObj \TYPO3\CMS\Core\Database\SoftReferenceIndex */
244 $softRefObj = BackendUtility::softRefParserObj($spKey);
245 // If there is an object returned...
246 if (is_object($softRefObj)) {
247 // Do processing
248 $resultArray = $softRefObj->findRef($table, $field, $idRecord, $valueField, $spKey, $spParams);
249 if (!empty($resultArray['elements'])) {
250 if ($spKey == 'typolink_tag') {
251 $this->analyseTypoLinks($resultArray, $results, $htmlParser, $record, $field, $table);
252 } else {
253 $this->analyseLinks($resultArray, $results, $record, $field, $table);
254 }
255 }
256 }
257 }
258 }
259 }
260 }
261
262 /**
263 * Returns the TSConfig that was passed to the init() method.
264 *
265 * This can be used by link checkers that get a reference of this
266 * object passed to the checkLink() method.
267 *
268 * @return array
269 */
270 public function getTSConfig() {
271 return $this->tsConfig;
272 }
273
274 /**
275 * Find all supported broken links for a specific link list
276 *
277 * @param array $resultArray findRef parsed records
278 * @param array $results Array of broken links
279 * @param array $record UID of the current record
280 * @param string $field The current field
281 * @param string $table The current table
282 * @return void
283 */
284 protected function analyseLinks(array $resultArray, array &$results, array $record, $field, $table) {
285 foreach ($resultArray['elements'] as $element) {
286 $r = $element['subst'];
287 $type = '';
288 $idRecord = $record['uid'];
289 if (!empty($r)) {
290 /** @var $hookObj \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype */
291 foreach ($this->hookObjectsArr as $keyArr => $hookObj) {
292 $type = $hookObj->fetchType($r, $type, $keyArr);
293 // Store the type that was found
294 // This prevents overriding by internal validator
295 if (!empty($type)) {
296 $r['type'] = $type;
297 }
298 }
299 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['substr'] = $r;
300 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['row'] = $record;
301 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['table'] = $table;
302 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['field'] = $field;
303 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['uid'] = $idRecord;
304 }
305 }
306 }
307
308 /**
309 * Find all supported broken links for a specific typoLink
310 *
311 * @param array $resultArray findRef parsed records
312 * @param array $results Array of broken links
313 * @param \TYPO3\CMS\Core\Html\HtmlParser $htmlParser Instance of html parser
314 * @param array $record The current record
315 * @param string $field The current field
316 * @param string $table The current table
317 * @return void
318 */
319 protected function analyseTypoLinks(array $resultArray, array &$results, $htmlParser, array $record, $field, $table) {
320 $currentR = array();
321 $linkTags = $htmlParser->splitIntoBlock('link', $resultArray['content']);
322 $idRecord = $record['uid'];
323 $type = '';
324 $title = '';
325 for ($i = 1; $i < count($linkTags); $i += 2) {
326 $referencedRecordType = '';
327 foreach ($resultArray['elements'] as $element) {
328 $type = '';
329 $r = $element['subst'];
330 if (!empty($r['tokenID'])) {
331 if (substr_count($linkTags[$i], $r['tokenID'])) {
332 // Type of referenced record
333 if (strpos($r['recordRef'], 'pages') !== FALSE) {
334 $currentR = $r;
335 // Contains number of the page
336 $referencedRecordType = $r['tokenValue'];
337 $wasPage = TRUE;
338 } elseif (strpos($r['recordRef'], 'tt_content') !== FALSE && (isset($wasPage) && $wasPage === TRUE)) {
339 $referencedRecordType = $referencedRecordType . '#c' . $r['tokenValue'];
340 $wasPage = FALSE;
341 } else {
342 $currentR = $r;
343 }
344 $title = strip_tags($linkTags[$i]);
345 }
346 }
347 }
348 /** @var $hookObj \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype */
349 foreach ($this->hookObjectsArr as $keyArr => $hookObj) {
350 $type = $hookObj->fetchType($currentR, $type, $keyArr);
351 // Store the type that was found
352 // This prevents overriding by internal validator
353 if (!empty($type)) {
354 $currentR['type'] = $type;
355 }
356 }
357 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['substr'] = $currentR;
358 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['row'] = $record;
359 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['table'] = $table;
360 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['field'] = $field;
361 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['uid'] = $idRecord;
362 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['link_title'] = $title;
363 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['pageAndAnchor'] = $referencedRecordType;
364 }
365 }
366
367 /**
368 * Fill a marker array with the number of links found in a list of pages
369 *
370 * @param string $curPage Comma separated list of page uids
371 * @return array Marker array with the number of links found
372 */
373 public function getLinkCounts($curPage) {
374 $markerArray = array();
375 if (empty($this->pidList)) {
376 $this->pidList = $curPage;
377 }
378 $this->pidList = rtrim($this->pidList, ',');
379 if (($res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
380 'count(uid) as nbBrokenLinks,link_type',
381 'tx_linkvalidator_link',
382 'record_pid in (' . $this->pidList . ')', 'link_type')
383 )) {
384 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
385 $markerArray[$row['link_type']] = $row['nbBrokenLinks'];
386 $markerArray['brokenlinkCount'] += $row['nbBrokenLinks'];
387 }
388 }
389 $GLOBALS['TYPO3_DB']->sql_free_result($res);
390 return $markerArray;
391 }
392
393 /**
394 * Calls TYPO3\CMS\Backend\FrontendBackendUserAuthentication::extGetTreeList.
395 * Although this duplicates the function TYPO3\CMS\Backend\FrontendBackendUserAuthentication::extGetTreeList
396 * this is necessary to create the object that is used recursively by the original function.
397 *
398 * Generates a list of page uids from $id. List does not include $id itself.
399 * The only pages excluded from the list are deleted pages.
400 *
401 * @param int $id Start page id
402 * @param int $depth Depth to traverse down the page tree.
403 * @param int $begin is an optional integer that determines at which
404 * @param string $permsClause Perms clause
405 * @param bool $considerHidden Whether to consider hidden pages or not
406 * @return string Returns the list with a comma in the end (if any pages selected!)
407 */
408 public function extGetTreeList($id, $depth, $begin = 0, $permsClause, $considerHidden = FALSE) {
409 $depth = (int)$depth;
410 $begin = (int)$begin;
411 $id = (int)$id;
412 $theList = '';
413 if ($depth > 0) {
414 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
415 'uid,title,hidden,extendToSubpages',
416 'pages', 'pid=' . $id . ' AND deleted=0 AND ' . $permsClause
417 );
418 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
419 if ($begin <= 0 && ($row['hidden'] == 0 || $considerHidden == 1)) {
420 $theList .= $row['uid'] . ',';
421 $this->extPageInTreeInfo[] = array($row['uid'], htmlspecialchars($row['title'], $depth));
422 }
423 if ($depth > 1 && (!($row['hidden'] == 1 && $row['extendToSubpages'] == 1) || $considerHidden == 1)) {
424 $theList .= $this->extGetTreeList($row['uid'], $depth - 1, $begin - 1, $permsClause, $considerHidden);
425 }
426 }
427 $GLOBALS['TYPO3_DB']->sql_free_result($res);
428 }
429 return $theList;
430 }
431
432 /**
433 * Check if rootline contains a hidden page
434 *
435 * @param array $pageInfo Array with uid, title, hidden, extendToSubpages from pages table
436 * @return bool TRUE if rootline contains a hidden page, FALSE if not
437 */
438 public function getRootLineIsHidden(array $pageInfo) {
439 $hidden = FALSE;
440 if ($pageInfo['extendToSubpages'] == 1 && $pageInfo['hidden'] == 1) {
441 $hidden = TRUE;
442 } else {
443 if ($pageInfo['pid'] > 0) {
444 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title,hidden,extendToSubpages', 'pages', 'uid=' . $pageInfo['pid']);
445 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
446 $hidden = $this->getRootLineIsHidden($row);
447 }
448 $GLOBALS['TYPO3_DB']->sql_free_result($res);
449 } else {
450 $hidden = FALSE;
451 }
452 }
453 return $hidden;
454 }
455
456 }