[CLEANUP] Ensure variables initalized and fix code smell
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / TimeTracker / TimeTracker.php
1 <?php
2 namespace TYPO3\CMS\Core\TimeTracker;
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 use TYPO3\CMS\Core\Imaging\Icon;
17 use TYPO3\CMS\Core\Imaging\IconFactory;
18 use TYPO3\CMS\Core\SingletonInterface;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Frontend Timetracking functions
23 *
24 * Is used to register how much time is used with operations in TypoScript
25 */
26 class TimeTracker implements SingletonInterface
27 {
28 /**
29 * If set to true (see constructor) then then the timetracking is enabled
30 * @var bool
31 */
32 protected $isEnabled = false;
33
34 /**
35 * Is loaded with the millisecond time when this object is created
36 *
37 * @var int
38 */
39 public $starttime = 0;
40
41 /**
42 * Log Rendering flag. If set, ->push() and ->pull() is called from the cObj->cObjGetSingle().
43 * This determines whether or not the TypoScript parsing activity is logged. But it also slows down the rendering
44 *
45 * @var bool
46 */
47 public $LR = 1;
48
49 /**
50 * @var array
51 */
52 public $printConf = [
53 'showParentKeys' => 1,
54 'contentLength' => 10000,
55 // Determines max length of displayed content before it gets cropped.
56 'contentLength_FILE' => 400,
57 // Determines max length of displayed content FROM FILE cObjects before it gets cropped. Reason is that most FILE cObjects are huge and often used as template-code.
58 'flag_tree' => 1,
59 'flag_messages' => 1,
60 'flag_content' => 0,
61 'allTime' => 0,
62 'keyLgd' => 40
63 ];
64
65 /**
66 * @var array
67 */
68 public $wrapError = [
69 0 => ['', ''],
70 1 => ['<strong>', '</strong>'],
71 2 => ['<strong style="color:#ff6600;">', '</strong>'],
72 3 => ['<strong style="color:#ff0000;">', '</strong>']
73 ];
74
75 /**
76 * @var array
77 */
78 public $wrapIcon = [
79 0 => '',
80 1 => 'actions-document-info',
81 2 => 'status-dialog-warning',
82 3 => 'status-dialog-error'
83 ];
84
85 /**
86 * @var int
87 */
88 public $uniqueCounter = 0;
89
90 /**
91 * @var array
92 */
93 public $tsStack = [[]];
94
95 /**
96 * @var int
97 */
98 public $tsStackLevel = 0;
99
100 /**
101 * @var array
102 */
103 public $tsStackLevelMax = [];
104
105 /**
106 * @var array
107 */
108 public $tsStackLog = [];
109
110 /**
111 * @var int
112 */
113 public $tsStackPointer = 0;
114
115 /**
116 * @var array
117 */
118 public $currentHashPointer = [];
119
120 /**
121 * Log entries that take than this number of milliseconds (own time) will be highlighted during log display. Set 0 to disable highlighting.
122 *
123 * @var int
124 */
125 public $highlightLongerThan = 0;
126
127 /*******************************************
128 *
129 * Logging parsing times in the scripts
130 *
131 *******************************************/
132
133 /**
134 * TimeTracker constructor.
135 *
136 * @param bool $isEnabled
137 */
138 public function __construct($isEnabled = true)
139 {
140 $this->isEnabled = $isEnabled;
141 }
142
143 /**
144 * Sets the starting time
145 *
146 * @return void
147 */
148 public function start()
149 {
150 if (!$this->isEnabled) {
151 return;
152 }
153 $this->starttime = $this->getMilliseconds();
154 }
155
156 /**
157 * Pushes an element to the TypoScript tracking array
158 *
159 * @param string $tslabel Label string for the entry, eg. TypoScript property name
160 * @param string $value Additional value(?)
161 * @return void
162 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::cObjGetSingle(), pull()
163 */
164 public function push($tslabel, $value = '')
165 {
166 if (!$this->isEnabled) {
167 return;
168 }
169 array_push($this->tsStack[$this->tsStackPointer], $tslabel);
170 array_push($this->currentHashPointer, 'timetracker_' . $this->uniqueCounter++);
171 $this->tsStackLevel++;
172 $this->tsStackLevelMax[] = $this->tsStackLevel;
173 // setTSlog
174 $k = end($this->currentHashPointer);
175 $this->tsStackLog[$k] = [
176 'level' => $this->tsStackLevel,
177 'tsStack' => $this->tsStack,
178 'value' => $value,
179 'starttime' => microtime(true),
180 'stackPointer' => $this->tsStackPointer
181 ];
182 }
183
184 /**
185 * Pulls an element from the TypoScript tracking array
186 *
187 * @param string $content The content string generated within the push/pull part.
188 * @return void
189 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::cObjGetSingle(), push()
190 */
191 public function pull($content = '')
192 {
193 if (!$this->isEnabled) {
194 return;
195 }
196 $k = end($this->currentHashPointer);
197 $this->tsStackLog[$k]['endtime'] = microtime(true);
198 $this->tsStackLog[$k]['content'] = $content;
199 $this->tsStackLevel--;
200 array_pop($this->tsStack[$this->tsStackPointer]);
201 array_pop($this->currentHashPointer);
202 }
203
204 /**
205 * Logs the TypoScript entry
206 *
207 * @param string $content The message string
208 * @param int $num Message type: 0: information, 1: message, 2: warning, 3: error
209 * @return void
210 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::CONTENT()
211 */
212 public function setTSlogMessage($content, $num = 0)
213 {
214 if (!$this->isEnabled) {
215 return;
216 }
217 end($this->currentHashPointer);
218 $k = current($this->currentHashPointer);
219 $placeholder = '';
220 // Enlarge the "details" column by adding a span
221 if (strlen($content) > 30) {
222 $placeholder = '<br /><span style="width: 300px; height: 1px; display: inline-block;"></span>';
223 }
224 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
225 $this->tsStackLog[$k]['message'][] = $iconFactory->getIcon($this->wrapIcon[$num], Icon::SIZE_SMALL)->render() . $this->wrapError[$num][0] . htmlspecialchars($content) . $this->wrapError[$num][1] . $placeholder;
226 }
227
228 /**
229 * Set TSselectQuery - for messages in TypoScript debugger.
230 *
231 * @param array $data Query array
232 * @param string $msg Message/Label to attach
233 * @return void
234 */
235 public function setTSselectQuery(array $data, $msg = '')
236 {
237 if (!$this->isEnabled) {
238 return;
239 }
240 end($this->currentHashPointer);
241 $k = current($this->currentHashPointer);
242 if ($msg !== '') {
243 $data['msg'] = $msg;
244 }
245 $this->tsStackLog[$k]['selectQuery'][] = $data;
246 }
247
248 /**
249 * Increases the stack pointer
250 *
251 * @return void
252 * @see decStackPointer(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContent(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::cObjGetSingle()
253 */
254 public function incStackPointer()
255 {
256 if (!$this->isEnabled) {
257 return;
258 }
259 $this->tsStackPointer++;
260 $this->tsStack[$this->tsStackPointer] = [];
261 }
262
263 /**
264 * Decreases the stack pointer
265 *
266 * @return void
267 * @see incStackPointer(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContent(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::cObjGetSingle()
268 */
269 public function decStackPointer()
270 {
271 if (!$this->isEnabled) {
272 return;
273 }
274 unset($this->tsStack[$this->tsStackPointer]);
275 $this->tsStackPointer--;
276 }
277
278 /**
279 * Gets a microtime value as milliseconds value.
280 *
281 * @param float $microtime The microtime value - if not set the current time is used
282 * @return int The microtime value as milliseconds value
283 */
284 public function getMilliseconds($microtime = null)
285 {
286 if (!$this->isEnabled) {
287 return 0;
288 }
289 if (!isset($microtime)) {
290 $microtime = microtime(true);
291 }
292 return round($microtime * 1000);
293 }
294
295 /**
296 * Gets the difference between a given microtime value and the starting time as milliseconds.
297 *
298 * @param float $microtime The microtime value - if not set the current time is used
299 * @return int The difference between a given microtime value and starting time as milliseconds
300 */
301 public function getDifferenceToStarttime($microtime = null)
302 {
303 return $this->getMilliseconds($microtime) - $this->starttime;
304 }
305
306 /*******************************************
307 *
308 * Printing the parsing time information (for Admin Panel)
309 *
310 *******************************************/
311 /**
312 * Print TypoScript parsing log
313 *
314 * @return string HTML table with the information about parsing times.
315 */
316 public function printTSlog()
317 {
318 if (!$this->isEnabled) {
319 return '';
320 }
321 // Calculate times and keys for the tsStackLog
322 foreach ($this->tsStackLog as $uniqueId => &$data) {
323 $data['endtime'] = $this->getDifferenceToStarttime($data['endtime']);
324 $data['starttime'] = $this->getDifferenceToStarttime($data['starttime']);
325 $data['deltatime'] = $data['endtime'] - $data['starttime'];
326 if (is_array($data['tsStack'])) {
327 $data['key'] = implode($data['stackPointer'] ? '.' : '/', end($data['tsStack']));
328 }
329 }
330 unset($data);
331 // Create hierarchical array of keys pointing to the stack
332 $arr = [];
333 foreach ($this->tsStackLog as $uniqueId => $data) {
334 $this->createHierarchyArray($arr, $data['level'], $uniqueId);
335 }
336 // Parsing the registeret content and create icon-html for the tree
337 $this->tsStackLog[$arr['0.'][0]]['content'] = $this->fixContent($arr['0.'], $this->tsStackLog[$arr['0.'][0]]['content'], '', 0, $arr['0.'][0]);
338 // Displaying the tree:
339 $outputArr = [];
340 $outputArr[] = $this->fw('TypoScript Key');
341 $outputArr[] = $this->fw('Value');
342 if ($this->printConf['allTime']) {
343 $outputArr[] = $this->fw('Time');
344 $outputArr[] = $this->fw('Own');
345 $outputArr[] = $this->fw('Sub');
346 $outputArr[] = $this->fw('Total');
347 } else {
348 $outputArr[] = $this->fw('Own');
349 }
350 $outputArr[] = $this->fw('Details');
351 $out = '';
352 foreach ($outputArr as $row) {
353 $out .= '
354 <th><strong>' . $row . '</strong></th>';
355 }
356 $out = '<tr class="typo3-adminPanel-itemRow">' . $out . '</tr>';
357 $flag_tree = $this->printConf['flag_tree'];
358 $flag_messages = $this->printConf['flag_messages'];
359 $flag_content = $this->printConf['flag_content'];
360 $keyLgd = $this->printConf['keyLgd'];
361 $c = 0;
362 foreach ($this->tsStackLog as $uniqueId => $data) {
363 if ($this->highlightLongerThan && (int)$data['owntime'] > (int)$this->highlightLongerThan) {
364 $logRowClass = 'typo3-adminPanel-logRow-highlight';
365 } else {
366 $logRowClass = $c % 2 ? 'line-odd' : 'line-even';
367 }
368 $logRowClass .= ' typo3-adminPanel-section-content-title';
369 $item = '';
370 // If first...
371 if (!$c) {
372 $data['icons'] = '';
373 $data['key'] = 'Script Start';
374 $data['value'] = '';
375 }
376 // Key label:
377 $keyLabel = '';
378 if (!$flag_tree && $data['stackPointer']) {
379 $temp = [];
380 foreach ($data['tsStack'] as $k => $v) {
381 $temp[] = GeneralUtility::fixed_lgd_cs(implode($v, $k ? '.' : '/'), -$keyLgd);
382 }
383 array_pop($temp);
384 $temp = array_reverse($temp);
385 array_pop($temp);
386 if (!empty($temp)) {
387 $keyLabel = '<br /><span style="color:#999999;">' . implode($temp, '<br />') . '</span>';
388 }
389 }
390 if ($flag_tree) {
391 $tmp = GeneralUtility::trimExplode('.', $data['key'], true);
392 $theLabel = end($tmp);
393 } else {
394 $theLabel = $data['key'];
395 }
396 $theLabel = GeneralUtility::fixed_lgd_cs($theLabel, -$keyLgd);
397 $theLabel = $data['stackPointer'] ? '<span class="stackPointer">' . $theLabel . '</span>' : $theLabel;
398 $keyLabel = $theLabel . $keyLabel;
399 $item .= '<td class="' . $logRowClass . '">' . ($flag_tree ? $data['icons'] : '') . $this->fw($keyLabel) . '</td>';
400 // Key value:
401 $keyValue = $data['value'];
402 $item .= '<td class="' . $logRowClass . ' typo3-adminPanel-tsLogTime">' . $this->fw(htmlspecialchars($keyValue)) . '</td>';
403 if ($this->printConf['allTime']) {
404 $item .= '<td class="' . $logRowClass . ' typo3-adminPanel-tsLogTime"> ' . $this->fw($data['starttime']) . '</td>';
405 $item .= '<td class="' . $logRowClass . ' typo3-adminPanel-tsLogTime"> ' . $this->fw($data['owntime']) . '</td>';
406 $item .= '<td class="' . $logRowClass . ' typo3-adminPanel-tsLogTime"> ' . $this->fw(($data['subtime'] ? '+' . $data['subtime'] : '')) . '</td>';
407 $item .= '<td class="' . $logRowClass . ' typo3-adminPanel-tsLogTime"> ' . $this->fw(($data['subtime'] ? '=' . $data['deltatime'] : '')) . '</td>';
408 } else {
409 $item .= '<td class="' . $logRowClass . ' typo3-adminPanel-tsLogTime"> ' . $this->fw($data['owntime']) . '</td>';
410 }
411 // Messages:
412 $msgArr = [];
413 $msg = '';
414 if ($flag_messages && is_array($data['message'])) {
415 foreach ($data['message'] as $v) {
416 $msgArr[] = nl2br($v);
417 }
418 }
419 if ($flag_content && (string)$data['content'] !== '') {
420 $maxlen = 120;
421 // Break lines which are too longer than $maxlen chars (can happen if content contains long paths...)
422 if (preg_match_all('/(\\S{' . $maxlen . ',})/', $data['content'], $reg)) {
423 foreach ($reg[1] as $key => $match) {
424 $match = preg_replace('/(.{' . $maxlen . '})/', '$1 ', $match);
425 $data['content'] = str_replace($reg[0][$key], $match, $data['content']);
426 }
427 }
428 $msgArr[] = '<span style="color:#000066;">' . nl2br($data['content']) . '</span>';
429 }
430 if (!empty($msgArr)) {
431 $msg = implode($msgArr, '<hr />');
432 }
433 $item .= '<td valign="top" class="' . $logRowClass . '" style="text-align:left;">' . $this->fw($msg) . '</td>';
434 $out .= '<tr class="typo3-adminPanel-itemRow">' . $item . '</tr>';
435 $c++;
436 }
437 $out = '<table class="typo3-adminPanel-table typo3-adminPanel-tsLog">' . $out . '</table>';
438 return $out;
439 }
440
441 /**
442 * Recursively generates the content to display
443 *
444 * @param array $arr Array which is modified with content. Reference
445 * @param string $content Current content string for the level
446 * @param string $depthData Prefixed icons for new PM icons
447 * @param bool $first Set this for the first call from outside.
448 * @param string $vKey Seems to be the previous tsStackLog key
449 * @return string Returns the $content string generated/modified. Also the $arr array is modified!
450 */
451 protected function fixContent(&$arr, $content, $depthData = '', $first = 0, $vKey = '')
452 {
453 $ac = 0;
454 $c = 0;
455 // First, find number of entries
456 foreach ($arr as $k => $v) {
457 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($k)) {
458 $ac++;
459 }
460 }
461 // Traverse through entries
462 $subtime = 0;
463 foreach ($arr as $k => $v) {
464 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($k)) {
465 $c++;
466 $deeper = is_array($arr[$k . '.']) ? 1 : 0;
467 $LN = $ac == $c ? 'blank' : 'line';
468
469 $BTM = $ac == $c ? 'bottom' : '';
470 $PM = is_array($arr[$k . '.']) ? '<i class="fa fa-' . ($deeper ? 'minus' : 'plus') . '-square-o"></i>' : '<span class="treeline-icon treeline-icon-join' . ($BTM ? 'bottom' : '') . '"></span>';
471
472 $this->tsStackLog[$v]['icons'] = $depthData . ($first ? '' : $PM);
473 if ($this->tsStackLog[$v]['content'] !== '') {
474 $content = str_replace($this->tsStackLog[$v]['content'], $v, $content);
475 }
476 if (is_array($arr[$k . '.'])) {
477 $this->tsStackLog[$v]['content'] = $this->fixContent($arr[$k . '.'], $this->tsStackLog[$v]['content'], $depthData . ($first ? '' : '<span class="treeline-icon treeline-icon-' . $LN . '"></span>'), 0, $v);
478 } else {
479 $this->tsStackLog[$v]['content'] = $this->fixCLen($this->tsStackLog[$v]['content'], $this->tsStackLog[$v]['value']);
480 $this->tsStackLog[$v]['subtime'] = '';
481 $this->tsStackLog[$v]['owntime'] = $this->tsStackLog[$v]['deltatime'];
482 }
483 $subtime += $this->tsStackLog[$v]['deltatime'];
484 }
485 }
486 // Set content with special chars
487 if (isset($this->tsStackLog[$vKey])) {
488 $this->tsStackLog[$vKey]['subtime'] = $subtime;
489 $this->tsStackLog[$vKey]['owntime'] = $this->tsStackLog[$vKey]['deltatime'] - $subtime;
490 }
491 $content = $this->fixCLen($content, $this->tsStackLog[$vKey]['value']);
492 // Traverse array again, this time substitute the unique hash with the red key
493 foreach ($arr as $k => $v) {
494 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($k)) {
495 if ($this->tsStackLog[$v]['content'] !== '') {
496 $content = str_replace($v, '<strong style="color:red;">[' . $this->tsStackLog[$v]['key'] . ']</strong>', $content);
497 }
498 }
499 }
500 // Return the content
501 return $content;
502 }
503
504 /**
505 * Wraps the input content string in green colored span-tags IF the length o fthe input string exceeds $this->printConf['contentLength'] (or $this->printConf['contentLength_FILE'] if $v == "FILE"
506 *
507 * @param string $c The content string
508 * @param string $v Command: If "FILE" then $this->printConf['contentLength_FILE'] is used for content length comparison, otherwise $this->printConf['contentLength']
509 * @return string
510 */
511 protected function fixCLen($c, $v)
512 {
513 $len = $v === 'FILE' ? $this->printConf['contentLength_FILE'] : $this->printConf['contentLength'];
514 if (strlen($c) > $len) {
515 $c = '<span style="color:green;">' . htmlspecialchars(GeneralUtility::fixed_lgd_cs($c, $len)) . '</span>';
516 } else {
517 $c = htmlspecialchars($c);
518 }
519 return $c;
520 }
521
522 /**
523 * Wraps input string in a <span> tag
524 *
525 * @param string $str The string to be wrapped
526 * @return string
527 */
528 protected function fw($str)
529 {
530 return '<span>' . $str . '</span>';
531 }
532
533 /**
534 * Helper function for internal data manipulation
535 *
536 * @param array $arr Array (passed by reference) and modified
537 * @param int $pointer Pointer value
538 * @param string $uniqueId Unique ID string
539 * @return void
540 * @access private
541 * @see printTSlog()
542 */
543 protected function createHierarchyArray(&$arr, $pointer, $uniqueId)
544 {
545 if (!is_array($arr)) {
546 $arr = [];
547 }
548 if ($pointer > 0) {
549 end($arr);
550 $k = key($arr);
551 $this->createHierarchyArray($arr[(int)$k . '.'], $pointer - 1, $uniqueId);
552 } else {
553 $arr[] = $uniqueId;
554 }
555 }
556 }