Revert "[TASK] Remove loadTCA calls"
[Packages/TYPO3.CMS.git] / typo3 / sysext / linkvalidator / Classes / LinkAnalyzer.php
1 <?php
2 namespace TYPO3\CMS\Linkvalidator;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2010 - 2011 Michael Miousse (michael.miousse@infoglobe.ca)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 *
19 * This script is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * This copyright notice MUST APPEAR in all copies of the script!
25 ***************************************************************/
26
27 $GLOBALS['LANG']->includeLLFile('EXT:linkvalidator/modfuncreport/locallang.xml');
28
29 /**
30 * This class provides Processing plugin implementation
31 *
32 * @author Michael Miousse <michael.miousse@infoglobe.ca>
33 * @author Jochen Rieger <j.rieger@connecta.ag>
34 */
35 class LinkAnalyzer {
36
37 /**
38 * Array of tables and fields to search for broken links
39 *
40 * @var array
41 */
42 protected $searchFields = array();
43
44 /**
45 * List of comma separated page uids (rootline downwards)
46 *
47 * @var string
48 */
49 protected $pidList = '';
50
51 /**
52 * Array of tables and the number of external links they contain
53 *
54 * @var array
55 */
56 protected $linkCounts = array();
57
58 /**
59 * Array of tables and the number of broken external links they contain
60 *
61 * @var array
62 */
63 protected $brokenLinkCounts = array();
64
65 /**
66 * Array of tables and records containing broken links
67 *
68 * @var array
69 */
70 protected $recordsWithBrokenLinks = array();
71
72 /**
73 * Array for hooks for own checks
74 *
75 * @var \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype[]
76 */
77 protected $hookObjectsArr = array();
78
79 /**
80 * Array with information about the current page
81 *
82 * @var array
83 */
84 protected $extPageInTreeInfo = array();
85
86 /**
87 * Reference to the current element with table:uid, e.g. pages:85
88 *
89 * @var string
90 */
91 protected $recordReference = '';
92
93 /**
94 * Linked page together with a possible anchor, e.g. 85#c105
95 *
96 * @var string
97 */
98 protected $pageWithAnchor = '';
99
100 /**
101 * Fill hookObjectsArr with different link types and possible XClasses.
102 */
103 public function __construct() {
104 // Hook to handle own checks
105 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['checkLinks'])) {
106 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['checkLinks'] as $key => $classRef) {
107 $this->hookObjectsArr[$key] = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef);
108 }
109 }
110 }
111
112 /**
113 * Store all the needed configuration values in class variables
114 *
115 * @param array $searchField List of fields in which to search for links
116 * @param string $pid List of comma separated page uids in which to search for links
117 * @return void
118 */
119 public function init(array $searchField, $pid) {
120 $this->searchFields = $searchField;
121 $this->pidList = $pid;
122 foreach ($searchField as $tableName => $table) {
123 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($tableName);
124 }
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 boolean $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 $GLOBALS['TYPO3_DB']->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 .= \TYPO3\CMS\Backend\Utility\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 // TODO: only select rows that have content in at least one of the relevant fields (via OR)
164 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($selectFields, $table, $where);
165 // Get record rows of table
166 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
167 // Analyse each record
168 $this->analyzeRecord($results, $table, $fields, $row);
169 }
170 $GLOBALS['TYPO3_DB']->sql_free_result($res);
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'] = $entryValue['row'][$GLOBALS['TCA'][$table]['ctrl']['label']];
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 $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_linkvalidator_link', $record);
205 } elseif (\TYPO3\CMS\Core\Utility\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 $GLOBALS['TYPO3_DB']->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 \TYPO3\CMS\Core\Html\HtmlParser $htmlParser */
233 $htmlParser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Html\\HtmlParser');
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 = \TYPO3\CMS\Backend\Utility\BackendUtility::explodeSoftRefParserList($conf['softref']);
244 // Traverse soft references
245 foreach ($softRefs as $spKey => $spParams) {
246 /** @var \TYPO3\CMS\Core\Database\SoftReferenceIndex $softRefObj Create or get the soft reference object */
247 $softRefObj = \TYPO3\CMS\Backend\Utility\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 * Find all supported broken links for a specific link list
267 *
268 * @param array $resultArray findRef parsed records
269 * @param array $results Array of broken links
270 * @param array $record UID of the current record
271 * @param string $field The current field
272 * @param string $table The current table
273 * @return void
274 */
275 protected function analyseLinks(array $resultArray, array &$results, array $record, $field, $table) {
276 foreach ($resultArray['elements'] as $element) {
277 $r = $element['subst'];
278 $type = '';
279 $idRecord = $record['uid'];
280 if (!empty($r)) {
281 /** @var \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype $hookObj */
282 foreach ($this->hookObjectsArr as $keyArr => $hookObj) {
283 $type = $hookObj->fetchType($r, $type, $keyArr);
284 // Store the type that was found
285 // This prevents overriding by internal validator
286 if (!empty($type)) {
287 $r['type'] = $type;
288 }
289 }
290 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['substr'] = $r;
291 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['row'] = $record;
292 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['table'] = $table;
293 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['field'] = $field;
294 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $r['tokenID']]['uid'] = $idRecord;
295 }
296 }
297 }
298
299 /**
300 * Find all supported broken links for a specific typoLink
301 *
302 * @param array $resultArray findRef parsed records
303 * @param array $results Array of broken links
304 * @param \TYPO3\CMS\Core\Html\HtmlParser $htmlParser Instance of html parser
305 * @param array $record The current record
306 * @param string $field The current field
307 * @param string $table The current table
308 * @return void
309 */
310 protected function analyseTypoLinks(array $resultArray, array &$results, $htmlParser, array $record, $field, $table) {
311 $currentR = array();
312 $linkTags = $htmlParser->splitIntoBlock('link', $resultArray['content']);
313 $idRecord = $record['uid'];
314 $type = '';
315 $title = '';
316 for ($i = 1; $i < count($linkTags); $i += 2) {
317 $referencedRecordType = '';
318 foreach ($resultArray['elements'] as $element) {
319 $type = '';
320 $r = $element['subst'];
321 if (!empty($r['tokenID'])) {
322 if (substr_count($linkTags[$i], $r['tokenID'])) {
323 // Type of referenced record
324 if (strpos($r['recordRef'], 'pages') !== FALSE) {
325 $currentR = $r;
326 // Contains number of the page
327 $referencedRecordType = $r['tokenValue'];
328 $wasPage = TRUE;
329 } elseif (strpos($r['recordRef'], 'tt_content') !== FALSE && (isset($wasPage) && $wasPage === TRUE)) {
330 $referencedRecordType = $referencedRecordType . '#c' . $r['tokenValue'];
331 $wasPage = FALSE;
332 } else {
333 $currentR = $r;
334 }
335 $title = strip_tags($linkTags[$i]);
336 }
337 }
338 }
339 /** @var \TYPO3\CMS\Linkvalidator\Linktype\AbstractLinktype $hookObj */
340 foreach ($this->hookObjectsArr as $keyArr => $hookObj) {
341 $type = $hookObj->fetchType($currentR, $type, $keyArr);
342 // Store the type that was found
343 // This prevents overriding by internal validator
344 if (!empty($type)) {
345 $currentR['type'] = $type;
346 }
347 }
348 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['substr'] = $currentR;
349 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['row'] = $record;
350 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['table'] = $table;
351 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['field'] = $field;
352 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['uid'] = $idRecord;
353 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['link_title'] = $title;
354 $results[$type][$table . ':' . $field . ':' . $idRecord . ':' . $currentR['tokenID']]['pageAndAnchor'] = $referencedRecordType;
355 }
356 }
357
358 /**
359 * Fill a marker array with the number of links found in a list of pages
360 *
361 * @param string $curPage Comma separated list of page uids
362 * @return array Marker array with the number of links found
363 */
364 public function getLinkCounts($curPage) {
365 $markerArray = array();
366 if (empty($this->pidList)) {
367 $this->pidList = $curPage;
368 }
369 $this->pidList = rtrim($this->pidList, ',');
370 if (($res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
371 'count(uid) as nbBrokenLinks,link_type',
372 'tx_linkvalidator_link',
373 'record_pid in (' . $this->pidList . ')', 'link_type')
374 )) {
375 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
376 $markerArray[$row['link_type']] = $row['nbBrokenLinks'];
377 $markerArray['brokenlinkCount'] += $row['nbBrokenLinks'];
378 }
379 }
380 $GLOBALS['TYPO3_DB']->sql_free_result($res);
381 return $markerArray;
382 }
383
384 /**
385 * Calls TYPO3\CMS\Backend\FrontendBackendUserAuthentication::extGetTreeList.
386 * Although this duplicates the function TYPO3\CMS\Backend\FrontendBackendUserAuthentication::extGetTreeList
387 * this is necessary to create the object that is used recursively by the original function.
388 *
389 * Generates a list of page uids from $id. List does not include $id itself.
390 * The only pages excluded from the list are deleted pages.
391 *
392 * @param integer $id Start page id
393 * @param integer $depth Depth to traverse down the page tree.
394 * @param integer $begin is an optional integer that determines at which
395 * @param string $permsClause Perms clause
396 * @param boolean $considerHidden Whether to consider hidden pages or not
397 * @return string Returns the list with a comma in the end (if any pages selected!)
398 */
399 public function extGetTreeList($id, $depth, $begin = 0, $permsClause, $considerHidden = FALSE) {
400 $depth = intval($depth);
401 $begin = intval($begin);
402 $id = intval($id);
403 $theList = '';
404 if ($depth > 0) {
405 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
406 'uid,title,hidden,extendToSubpages',
407 'pages', 'pid=' . $id . ' AND deleted=0 AND ' . $permsClause
408 );
409 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
410 if ($begin <= 0 && ($row['hidden'] == 0 || $considerHidden == 1)) {
411 $theList .= $row['uid'] . ',';
412 $this->extPageInTreeInfo[] = array($row['uid'], htmlspecialchars($row['title'], $depth));
413 }
414 if ($depth > 1 && (!($row['hidden'] == 1 && $row['extendToSubpages'] == 1) || $considerHidden == 1)) {
415 $theList .= $this->extGetTreeList($row['uid'], $depth - 1, $begin - 1, $permsClause, $considerHidden);
416 }
417 }
418 $GLOBALS['TYPO3_DB']->sql_free_result($res);
419 }
420 return $theList;
421 }
422
423 /**
424 * @param array $pageInfo Array with uid, title, hidden, extendToSubpages from pages table
425 * @return boolean TRUE if rootline contains a hidden page, FALSE if not
426 */
427 public function getRootLineIsHidden(array $pageInfo) {
428 $hidden = FALSE;
429 if ($pageInfo['extendToSubpages'] == 1 && $pageInfo['hidden'] == 1) {
430 $hidden = TRUE;
431 } else {
432 if ($pageInfo['pid'] > 0) {
433 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title,hidden,extendToSubpages', 'pages', 'uid=' . $pageInfo['pid']);
434 while (($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) !== FALSE) {
435 $hidden = $this->getRootLineIsHidden($row);
436 }
437 $GLOBALS['TYPO3_DB']->sql_free_result($res);
438 } else {
439 $hidden = FALSE;
440 }
441 }
442 return $hidden;
443 }
444
445 }
446 ?>