6f95610134e73cd0815e5413c7b97d858f58fe0b
[Packages/TYPO3.CMS.git] / typo3 / sysext / lowlevel / Classes / CleanerCommand.php
1 <?php
2 namespace TYPO3\CMS\Lowlevel;
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\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
20 use TYPO3\CMS\Core\Database\ReferenceIndex;
21 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\MathUtility;
24
25 /**
26 * Core functions for cleaning and analysing
27 */
28 class CleanerCommand extends \TYPO3\CMS\Core\Controller\CommandLineController
29 {
30 /**
31 * @var bool
32 */
33 public $genTree_traverseDeleted = true;
34
35 /**
36 * @var bool
37 */
38 public $genTree_traverseVersions = true;
39
40 /**
41 * @var string
42 */
43 public $label_infoString = 'The list of records is organized as [table]:[uid]:[field]:[flexpointer]:[softref_key]';
44
45 /**
46 * @var array
47 */
48 public $pagetreePlugins = [];
49
50 /**
51 * @var array
52 */
53 public $cleanerModules = [];
54
55 /**
56 * @var array
57 */
58 public $performanceStatistics = [];
59
60 /**
61 * @var array
62 */
63 protected $workspaceIndex = [0 => true];
64
65 /**
66 * Constructor
67 */
68 public function __construct()
69 {
70 // Running parent class constructor
71 parent::__construct();
72 $this->cleanerModules = (array)$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['lowlevel']['cleanerModules'];
73 // Adding options to help archive:
74 $this->cli_options[] = ['-r', 'Execute this tool, otherwise help is shown'];
75 $this->cli_options[] = ['-v level', 'Verbosity level 0-3', 'The value of level can be:
76 0 = all output
77 1 = info and greater (default)
78 2 = warnings and greater
79 3 = errors'];
80 $this->cli_options[] = ['--refindex mode', 'Mode for reference index handling for operations that require a clean reference index ("update"/"ignore")', 'Options are "check" (default), "update" and "ignore". By default, the reference index is checked before running analysis that require a clean index. If the check fails, the analysis is not run. You can choose to bypass this completely (using value "ignore") or ask to have the index updated right away before the analysis (using value "update")'];
81 $this->cli_options[] = ['--AUTOFIX [testName]', 'Repairs errors that can be automatically fixed.', 'Only add this option after having run the test without it so you know what will happen when you add this option! The optional parameter "[testName]" works for some tool keys to limit the fixing to a particular test.'];
82 $this->cli_options[] = ['--dryrun', 'With --AUTOFIX it will only simulate a repair process', 'You may like to use this to see what the --AUTOFIX option will be doing. It will output the whole process like if a fix really occurred but nothing is in fact happening'];
83 $this->cli_options[] = ['--YES', 'Implicit YES to all questions', 'Use this with EXTREME care. The option "-i" is not affected by this option.'];
84 $this->cli_options[] = ['-i', 'Interactive', 'Will ask you before running the AUTOFIX on each element.'];
85 $this->cli_options[] = ['--filterRegex expr', 'Define an expression for preg_match() that must match the element ID in order to auto repair it', 'The element ID is the string in quotation marks when the text \'Cleaning ... in "ELEMENT ID"\'. "expr" is the expression for preg_match(). To match for example "Nature3.JPG" and "Holiday3.JPG" you can use "/.*3.JPG/". To match for example "Image.jpg" and "Image.JPG" you can use "/.*.jpg/i". Try a --dryrun first to see what the matches are!'];
86 $this->cli_options[] = ['--showhowto', 'Displays HOWTO file for cleaner script.'];
87 // Setting help texts:
88 $this->cli_help['name'] = 'lowlevel_cleaner -- Analysis and clean-up tools for TYPO3 installations';
89 $this->cli_help['synopsis'] = 'toolkey ###OPTIONS###';
90 $this->cli_help['description'] = 'Dispatches to various analysis and clean-up tools which can plug into the API of this script. Typically you can run tests that will take longer than the usual max execution time of PHP. Such tasks could be checking for orphan records in the page tree or flushing all published versions in the system. For the complete list of options, please explore each of the \'toolkey\' keywords below:
91
92 ' . implode('
93 ', array_keys($this->cleanerModules));
94 $this->cli_help['examples'] = '/.../cli_dispatch.phpsh lowlevel_cleaner missing_files -s -r
95 This will show you missing files in the TYPO3 system and only report back if errors were found.';
96 $this->cli_help['author'] = 'Kasper Skaarhoej, (c) 2006';
97 }
98
99 /**************************
100 *
101 * CLI functionality
102 *
103 *************************/
104 /**
105 * CLI engine
106 *
107 * @param array $argv Command line arguments
108 * @return string
109 */
110 public function cli_main($argv)
111 {
112 $this->cli_setArguments($argv);
113
114 // Force user to admin state and set workspace to "Live":
115 $GLOBALS['BE_USER']->user['admin'] = 1;
116 $GLOBALS['BE_USER']->setWorkspace(0);
117 // Print Howto:
118 if ($this->cli_isArg('--showhowto')) {
119 $howto = file_get_contents(ExtensionManagementUtility::extPath('lowlevel') . 'README.rst');
120 echo wordwrap($howto, 120) . LF;
121 die;
122 }
123 // Print help
124 $analysisType = (string)$this->cli_args['_DEFAULT'][1];
125 if (!$analysisType) {
126 $this->cli_validateArgs();
127 $this->cli_help();
128 die;
129 }
130
131 if (is_array($this->cleanerModules[$analysisType])) {
132 $cleanerMode = GeneralUtility::getUserObj($this->cleanerModules[$analysisType][0]);
133 $cleanerMode->cli_validateArgs();
134 // Run it...
135 if ($this->cli_isArg('-r')) {
136 if (!$cleanerMode->checkRefIndex || $this->cli_referenceIndexCheck()) {
137 $res = $cleanerMode->main();
138 $this->cli_printInfo($analysisType, $res);
139 // Autofix...
140 if ($this->cli_isArg('--AUTOFIX')) {
141 if ($this->cli_isArg('--YES') || $this->cli_keyboardInput_yes('
142
143 NOW Running --AUTOFIX on result. OK?' . ($this->cli_isArg('--dryrun') ? ' (--dryrun simulation)' : ''))) {
144 $cleanerMode->main_autofix($res);
145 } else {
146 $this->cli_echo('ABORTING AutoFix...
147 ', 1);
148 }
149 }
150 }
151 } else {
152 // Help only...
153 $cleanerMode->cli_help();
154 die;
155 }
156 } else {
157 $this->cli_echo('ERROR: Analysis Type \'' . $analysisType . '\' is unknown.
158 ', 1);
159 die;
160 }
161 }
162
163 /**
164 * Checks reference index
165 *
166 * @return bool TRUE if reference index was OK (either OK, updated or ignored)
167 */
168 public function cli_referenceIndexCheck()
169 {
170 // Reference index option:
171 $refIndexMode = isset($this->cli_args['--refindex']) ? $this->cli_args['--refindex'][0] : 'check';
172 switch ($refIndexMode) {
173 case 'check':
174
175 case 'update':
176 $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
177 list($headerContent, $bodyContent, $errorCount) = $refIndexObj->updateIndex($refIndexMode === 'check', $this->cli_echo());
178 if ($errorCount && $refIndexMode === 'check') {
179 $ok = false;
180 $this->cli_echo('ERROR: Reference Index Check failed! (run with \'--refindex update\' to fix)
181 ', 1);
182 } else {
183 $ok = true;
184 }
185 break;
186 case 'ignore':
187 $this->cli_echo('Reference Index Check: Bypassing reference index check...
188 ');
189 $ok = true;
190 break;
191 default:
192 $this->cli_echo('ERROR: Wrong value for --refindex argument.
193 ', 1);
194 die();
195
196 }
197 return $ok;
198 }
199
200 /**
201 * @param string $matchString
202 * @return string If string, it's the reason for not executing. Returning FALSE means it should execute.
203 */
204 public function cli_noExecutionCheck($matchString)
205 {
206 // Check for filter:
207 if ($this->cli_isArg('--filterRegex') && ($regex = $this->cli_argValue('--filterRegex', 0))) {
208 if (!preg_match($regex, $matchString)) {
209 return 'BYPASS: Filter Regex "' . $regex . '" did not match string "' . $matchString . '"';
210 }
211 }
212 // Check for interactive mode
213 if ($this->cli_isArg('-i')) {
214 if (!$this->cli_keyboardInput_yes(' EXECUTE?')) {
215 return 'BYPASS...';
216 }
217 }
218 // Check for
219 if ($this->cli_isArg('--dryrun')) {
220 return 'BYPASS: --dryrun set';
221 }
222 }
223
224 /**
225 * Formats a result array from a test so it fits output in the shell
226 *
227 * @param string $header Name of the test (eg. function name)
228 * @param array $res Result array from an analyze function
229 * @return void Outputs with echo - capture content with output buffer if needed.
230 */
231 public function cli_printInfo($header, $res)
232 {
233 $detailLevel = MathUtility::forceIntegerInRange($this->cli_isArg('-v') ? $this->cli_argValue('-v') : 1, 0, 3);
234 $silent = !$this->cli_echo();
235 $severity = [
236 0 => 'MESSAGE',
237 1 => 'INFO',
238 2 => 'WARNING',
239 3 => 'ERROR'
240 ];
241 // Header output:
242 if ($detailLevel <= 1) {
243 $this->cli_echo('*********************************************
244 ' . $header . LF . '*********************************************
245 ');
246 $this->cli_echo(wordwrap(trim($res['message'])) . LF . LF);
247 }
248 // Traverse headers for output:
249 if (is_array($res['headers'])) {
250 foreach ($res['headers'] as $key => $value) {
251 if ($detailLevel <= (int)$value[2]) {
252 if (is_array($res[$key]) && (count($res[$key]) || !$silent)) {
253 // Header and explanaion:
254 $this->cli_echo('---------------------------------------------' . LF, 1);
255 $this->cli_echo('[' . $header . ']' . LF, 1);
256 $this->cli_echo($value[0] . ' [' . $severity[$value[2]] . ']' . LF, 1);
257 $this->cli_echo('---------------------------------------------' . LF, 1);
258 if (trim($value[1])) {
259 $this->cli_echo('Explanation: ' . wordwrap(trim($value[1])) . LF . LF, 1);
260 }
261 }
262 // Content:
263 if (is_array($res[$key])) {
264 if (count($res[$key])) {
265 if ($this->cli_echo('', 1)) {
266 print_r($res[$key]);
267 }
268 } else {
269 $this->cli_echo('(None)' . LF . LF);
270 }
271 } else {
272 $this->cli_echo($res[$key] . LF . LF);
273 }
274 }
275 }
276 }
277 }
278
279 /**************************
280 *
281 * Page tree traversal
282 *
283 *************************/
284 /**
285 * Traverses the FULL/part of page tree, mainly to register ALL validly connected records (to find orphans) but also to register deleted records, versions etc.
286 * Output (in $this->recStats) can be useful for multiple purposes.
287 *
288 * @param int $rootID Root page id from where to start traversal. Use "0" (zero) to have full page tree (necessary when spotting orphans, otherwise you can run it on parts only)
289 * @param int $depth Depth to traverse. zero is do not traverse at all. 1 = 1 sublevel, 1000= 1000 sublevels (all...)
290 * @param int $echoLevel If >0, will echo information about the traversal process.
291 * @param string $callBack Call back function (from this class or subclass)
292 * @return void
293 */
294 public function genTree($rootID, $depth = 1000, $echoLevel = 0, $callBack = '')
295 {
296 $pt = GeneralUtility::milliseconds();
297 $this->performanceStatistics['genTree()'] = '';
298 // Initialize:
299 if (ExtensionManagementUtility::isLoaded('workspaces')) {
300 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
301 ->getQueryBuilderForTable('sys_workspace');
302
303 $queryBuilder->getRestrictions()
304 ->removeAll()
305 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
306
307 $workspaceRecords = $queryBuilder
308 ->select('uid', 'title')
309 ->from('sys_workspace')
310 ->execute()
311 ->fetchAll();
312
313 foreach ($workspaceRecords as $workspaceRecord) {
314 $this->workspaceIndex[$workspaceRecord['uid']] = true;
315 }
316 }
317
318 $this->recStats = [
319 'all' => [],
320 // All records connected in tree including versions (the reverse are orphans). All Info and Warning categories below are included here (and therefore safe if you delete the reverse of the list)
321 'deleted' => [],
322 // Subset of "alL" that are deleted-flagged [Info]
323 'versions' => [],
324 // Subset of "all" which are offline versions (pid=-1). [Info]
325 'versions_published' => [],
326 // Subset of "versions" that is a count of 1 or more (has been published) [Info]
327 'versions_liveWS' => [],
328 // Subset of "versions" that exists in live workspace [Info]
329 'versions_lost_workspace' => [],
330 // Subset of "versions" that doesn't belong to an existing workspace [Warning: Fix by move to live workspace]
331 'versions_inside_versioned_page' => [],
332 // Subset of "versions" This is versions of elements found inside an already versioned branch / page. In real life this can work out, but is confusing and the backend should prevent this from happening to people. [Warning: Fix by deleting those versions (or publishing them)]
333 'illegal_record_under_versioned_page' => [],
334 // If a page is "element" or "page" version and records are found attached to it, they might be illegally attached, so this will tell you. [Error: Fix by deleting orphans since they are not registered in "all" category]
335 'misplaced_at_rootlevel' => [],
336 // Subset of "all": Those that should not be at root level but are. [Warning: Fix by moving record into page tree]
337 'misplaced_inside_tree' => []
338 ];
339 // Start traversal:
340 $pt2 = GeneralUtility::milliseconds();
341 $this->performanceStatistics['genTree_traverse()'] = '';
342 $this->performanceStatistics['genTree_traverse():TraverseTables'] = '';
343 $this->genTree_traverse($rootID, $depth, $echoLevel, $callBack);
344 $this->performanceStatistics['genTree_traverse()'] = GeneralUtility::milliseconds() - $pt2;
345 // Sort recStats (for diff'able displays)
346 foreach ($this->recStats as $kk => $vv) {
347 foreach ($this->recStats[$kk] as $tables => $recArrays) {
348 ksort($this->recStats[$kk][$tables]);
349 }
350 ksort($this->recStats[$kk]);
351 }
352 if ($echoLevel > 0) {
353 echo LF . LF;
354 }
355 // Processing performance statistics:
356 $this->performanceStatistics['genTree()'] = GeneralUtility::milliseconds() - $pt;
357 // Count records:
358 foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
359 // Select all records belonging to page:
360 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
361 ->getQueryBuilderForTable($tableName);
362
363 $amount = $queryBuilder
364 ->count('*')
365 ->from($tableName)
366 ->execute()
367 ->fetchColumn(0);
368 $this->performanceStatistics['MySQL_count'][$tableName] = $amount;
369 $this->performanceStatistics['CSV'] .= LF . $tableName . ',' . $this->performanceStatistics['genTree_traverse():TraverseTables:']['MySQL'][$tableName] . ',' . $this->performanceStatistics['genTree_traverse():TraverseTables:']['Proc'][$tableName] . ',' . $this->performanceStatistics['MySQL_count'][$tableName];
370 }
371 $this->performanceStatistics['recStats_size']['(ALL)'] = strlen(serialize($this->recStats));
372 foreach ($this->recStats as $key => $arrcontent) {
373 $this->performanceStatistics['recStats_size'][$key] = strlen(serialize($arrcontent));
374 }
375 }
376
377 /**
378 * Recursive traversal of page tree:
379 *
380 * @param int $rootID Page root id (must be online, valid page record - or zero for page tree root)
381 * @param int $depth Depth
382 * @param int $echoLevel Echo Level
383 * @param string $callBack Call back function (from this class or subclass)
384 * @param string $versionSwapmode DON'T set from outside, internal. (indicates we are inside a version of a page) - will be "SWAPMODE:-1" or empty
385 * @param int $rootIsVersion DON'T set from outside, internal. (1: Indicates that rootID is a version of a page, 2: ...that it is even a version of a version (which triggers a warning!)
386 * @param string $accumulatedPath Internal string that accumulates the path
387 * @return void
388 * @access private
389 * @todo $versionSwapmode needs to be cleaned up, since page and branch version (0, 1) does not exist anymore
390 */
391 public function genTree_traverse($rootID, $depth, $echoLevel = 0, $callBack = '', $versionSwapmode = '', $rootIsVersion = 0, $accumulatedPath = '')
392 {
393 // Register page:
394 $this->recStats['all']['pages'][$rootID] = $rootID;
395 $pageRecord = BackendUtility::getRecordRaw('pages', 'uid=' . (int)$rootID, 'deleted,title,t3ver_count,t3ver_wsid');
396 $accumulatedPath .= '/' . $pageRecord['title'];
397 // Register if page is deleted:
398 if ($pageRecord['deleted']) {
399 $this->recStats['deleted']['pages'][$rootID] = $rootID;
400 }
401 // If rootIsVersion is set it means that the input rootID is that of a version of a page. See below where the recursive call is made.
402 if ($rootIsVersion) {
403 $this->recStats['versions']['pages'][$rootID] = $rootID;
404 // If it has been published and is in archive now...
405 if ($pageRecord['t3ver_count'] >= 1 && $pageRecord['t3ver_wsid'] == 0) {
406 $this->recStats['versions_published']['pages'][$rootID] = $rootID;
407 }
408 // If it has been published and is in archive now...
409 if ($pageRecord['t3ver_wsid'] == 0) {
410 $this->recStats['versions_liveWS']['pages'][$rootID] = $rootID;
411 }
412 // If it doesn't belong to a workspace...
413 if (!isset($this->workspaceIndex[$pageRecord['t3ver_wsid']])) {
414 $this->recStats['versions_lost_workspace']['pages'][$rootID] = $rootID;
415 }
416 // In case the rootID is a version inside a versioned page
417 if ($rootIsVersion == 2) {
418 $this->recStats['versions_inside_versioned_page']['pages'][$rootID] = $rootID;
419 }
420 }
421 if ($echoLevel > 0) {
422 echo LF . $accumulatedPath . ' [' . $rootID . ']' . ($pageRecord['deleted'] ? ' (DELETED)' : '') . ($this->recStats['versions_published']['pages'][$rootID] ? ' (PUBLISHED)' : '');
423 }
424 if ($echoLevel > 1 && $this->recStats['versions_lost_workspace']['pages'][$rootID]) {
425 echo LF . ' ERROR! This version belongs to non-existing workspace (' . $pageRecord['t3ver_wsid'] . ')!';
426 }
427 if ($echoLevel > 1 && $this->recStats['versions_inside_versioned_page']['pages'][$rootID]) {
428 echo LF . ' WARNING! This version is inside an already versioned page or branch!';
429 }
430 // Call back:
431 if ($callBack) {
432 $this->{$callBack}('pages', $rootID, $echoLevel, $versionSwapmode, $rootIsVersion);
433 }
434 $pt3 = GeneralUtility::milliseconds();
435 // Traverse tables of records that belongs to page:
436 foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
437 if ($tableName !== 'pages') {
438 // Select all records belonging to page:
439 $pt4 = GeneralUtility::milliseconds();
440
441 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
442 ->getQueryBuilderForTable($tableName);
443
444 $queryBuilder->getRestrictions()->removeAll();
445
446 $queryBuilder
447 ->select('uid')
448 ->from($tableName)
449 ->where(
450 $queryBuilder->expr()->eq(
451 'pid',
452 $queryBuilder->createNamedParameter($rootID, \PDO::PARAM_INT)
453 )
454 );
455
456 if ($GLOBALS['TCA'][$tableName]['ctrl']['delete']) {
457 $queryBuilder->addSelect($GLOBALS['TCA'][$tableName]['ctrl']['delete']);
458 }
459
460 if (!$this->genTree_traverseDeleted) {
461 $queryBuilder->getRestrictions()->add(DeletedRestriction::class);
462 }
463
464 $result = $queryBuilder->execute();
465
466 $this->performanceStatistics['genTree_traverse():TraverseTables:']['MySQL']['(ALL)'] += GeneralUtility::milliseconds() - $pt4;
467 $this->performanceStatistics['genTree_traverse():TraverseTables:']['MySQL'][$tableName] += GeneralUtility::milliseconds() - $pt4;
468 $pt5 = GeneralUtility::milliseconds();
469 $count = $result->rowCount();
470 if ($count) {
471 if ($echoLevel == 2) {
472 echo LF . ' \\-' . $tableName . ' (' . $count . ')';
473 }
474 }
475 while ($rowSub = $result->fetch()) {
476 if ($echoLevel == 3) {
477 echo LF . ' \\-' . $tableName . ':' . $rowSub['uid'];
478 }
479 // If the rootID represents a version, we must check if the record from this table is allowed to belong to this:
480 if ($versionSwapmode === 'SWAPMODE:-1') {
481 // This is illegal records under a versioned page - therefore not registered in $this->recStats['all'] so they should be orphaned:
482 $this->recStats['illegal_record_under_versioned_page'][$tableName][$rowSub['uid']] = $rowSub['uid'];
483 if ($echoLevel > 1) {
484 echo LF . ' ERROR! Illegal record (' . $tableName . ':' . $rowSub['uid'] . ') under versioned page!';
485 }
486 } else {
487 $this->recStats['all'][$tableName][$rowSub['uid']] = $rowSub['uid'];
488 // Register deleted:
489 if ($GLOBALS['TCA'][$tableName]['ctrl']['delete'] && $rowSub[$GLOBALS['TCA'][$tableName]['ctrl']['delete']]) {
490 $this->recStats['deleted'][$tableName][$rowSub['uid']] = $rowSub['uid'];
491 if ($echoLevel == 3) {
492 echo ' (DELETED)';
493 }
494 }
495 // Check location of records regarding tree root:
496 if (!$GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'] && $rootID == 0) {
497 $this->recStats['misplaced_at_rootlevel'][$tableName][$rowSub['uid']] = $rowSub['uid'];
498 if ($echoLevel > 1) {
499 echo LF . ' ERROR! Misplaced record (' . $tableName . ':' . $rowSub['uid'] . ') on rootlevel!';
500 }
501 }
502 if ($GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'] == 1 && $rootID > 0) {
503 $this->recStats['misplaced_inside_tree'][$tableName][$rowSub['uid']] = $rowSub['uid'];
504 if ($echoLevel > 1) {
505 echo LF . ' ERROR! Misplaced record (' . $tableName . ':' . $rowSub['uid'] . ') inside page tree!';
506 }
507 }
508 // Traverse plugins:
509 if ($callBack) {
510 $this->{$callBack}($tableName, $rowSub['uid'], $echoLevel, $versionSwapmode, $rootIsVersion);
511 }
512 // Add any versions of those records:
513 if ($this->genTree_traverseVersions) {
514 $versions = BackendUtility::selectVersionsOfRecord($tableName, $rowSub['uid'], 'uid,t3ver_wsid,t3ver_count' . ($GLOBALS['TCA'][$tableName]['ctrl']['delete'] ? ',' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] : ''), null, true);
515 if (is_array($versions)) {
516 foreach ($versions as $verRec) {
517 if (!$verRec['_CURRENT_VERSION']) {
518 if ($echoLevel == 3) {
519 echo LF . ' \\-[#OFFLINE VERSION: WS#' . $verRec['t3ver_wsid'] . '/Cnt:' . $verRec['t3ver_count'] . '] ' . $tableName . ':' . $verRec['uid'] . ')';
520 }
521 $this->recStats['all'][$tableName][$verRec['uid']] = $verRec['uid'];
522 // Register deleted:
523 if ($GLOBALS['TCA'][$tableName]['ctrl']['delete'] && $verRec[$GLOBALS['TCA'][$tableName]['ctrl']['delete']]) {
524 $this->recStats['deleted'][$tableName][$verRec['uid']] = $verRec['uid'];
525 if ($echoLevel == 3) {
526 echo ' (DELETED)';
527 }
528 }
529 // Register version:
530 $this->recStats['versions'][$tableName][$verRec['uid']] = $verRec['uid'];
531 if ($verRec['t3ver_count'] >= 1 && $verRec['t3ver_wsid'] == 0) {
532 // Only register published versions in LIVE workspace (published versions in draft workspaces are allowed)
533 $this->recStats['versions_published'][$tableName][$verRec['uid']] = $verRec['uid'];
534 if ($echoLevel == 3) {
535 echo ' (PUBLISHED)';
536 }
537 }
538 if ($verRec['t3ver_wsid'] == 0) {
539 $this->recStats['versions_liveWS'][$tableName][$verRec['uid']] = $verRec['uid'];
540 }
541 if (!isset($this->workspaceIndex[$verRec['t3ver_wsid']])) {
542 $this->recStats['versions_lost_workspace'][$tableName][$verRec['uid']] = $verRec['uid'];
543 if ($echoLevel > 1) {
544 echo LF . ' ERROR! Version (' . $tableName . ':' . $verRec['uid'] . ') belongs to non-existing workspace (' . $verRec['t3ver_wsid'] . ')!';
545 }
546 }
547 // In case we are inside a versioned branch, there should not exists versions inside that "branch".
548 if ($versionSwapmode) {
549 $this->recStats['versions_inside_versioned_page'][$tableName][$verRec['uid']] = $verRec['uid'];
550 if ($echoLevel > 1) {
551 echo LF . ' ERROR! This version (' . $tableName . ':' . $verRec['uid'] . ') is inside an already versioned page or branch!';
552 }
553 }
554 // Traverse plugins:
555 if ($callBack) {
556 $this->{$callBack}($tableName, $verRec['uid'], $echoLevel, $versionSwapmode, $rootIsVersion);
557 }
558 }
559 }
560 }
561 unset($versions);
562 }
563 }
564 }
565 $this->performanceStatistics['genTree_traverse():TraverseTables:']['Proc']['(ALL)'] += GeneralUtility::milliseconds() - $pt5;
566 $this->performanceStatistics['genTree_traverse():TraverseTables:']['Proc'][$tableName] += GeneralUtility::milliseconds() - $pt5;
567 }
568 }
569 unset($resSub);
570 unset($rowSub);
571 $this->performanceStatistics['genTree_traverse():TraverseTables'] += GeneralUtility::milliseconds() - $pt3;
572 // Find subpages to root ID and traverse (only when rootID is not a version or is a branch-version):
573 if (!$versionSwapmode || $versionSwapmode == 'SWAPMODE:1') {
574 if ($depth > 0) {
575 $depth--;
576 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
577 ->getQueryBuilderForTable('pages');
578
579 $queryBuilder->getRestrictions()->removeAll();
580 if (!$this->genTree_traverseDeleted) {
581 $queryBuilder->getRestrictions()->add(DeletedRestriction::class);
582 }
583
584 $queryBuilder
585 ->select('uid')
586 ->from('pages')
587 ->where(
588 $queryBuilder->expr()->eq(
589 'pid',
590 $queryBuilder->createNamedParameter($rootID, \PDO::PARAM_INT)
591 )
592 )
593 ->orderBy('sorting');
594
595 $result = $queryBuilder->execute();
596 while ($row = $result->fetch()) {
597 $this->genTree_traverse($row['uid'], $depth, $echoLevel, $callBack, $versionSwapmode, 0, $accumulatedPath);
598 }
599 }
600 // Add any versions of pages
601 if ($rootID > 0 && $this->genTree_traverseVersions) {
602 $versions = BackendUtility::selectVersionsOfRecord('pages', $rootID, 'uid,t3ver_oid,t3ver_wsid,t3ver_count', null, true);
603 if (is_array($versions)) {
604 foreach ($versions as $verRec) {
605 if (!$verRec['_CURRENT_VERSION']) {
606 $this->genTree_traverse($verRec['uid'], $depth, $echoLevel, $callBack, 'SWAPMODE:-1', $versionSwapmode ? 2 : 1, $accumulatedPath . ' [#OFFLINE VERSION: WS#' . $verRec['t3ver_wsid'] . '/Cnt:' . $verRec['t3ver_count'] . ']');
607 }
608 }
609 }
610 }
611 }
612 }
613
614 /**************************
615 *
616 * Helper functions
617 *
618 *************************/
619 /**
620 * Compile info-string
621 *
622 * @param array $rec Input record from sys_refindex
623 * @return string String identifying the main record of the reference
624 */
625 public function infoStr($rec)
626 {
627 return $rec['tablename'] . ':' . $rec['recuid'] . ':' . $rec['field'] . ':' . $rec['flexpointer'] . ':' . $rec['softref_key'] . ($rec['deleted'] ? ' (DELETED)' : '');
628 }
629 }