Debugger.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common;
  9. use DebugBar\DataCollector\ConfigCollector;
  10. use DebugBar\DataCollector\DataCollectorInterface;
  11. use DebugBar\DataCollector\ExceptionsCollector;
  12. use DebugBar\DataCollector\MemoryCollector;
  13. use DebugBar\DataCollector\MessagesCollector;
  14. use DebugBar\DataCollector\PhpInfoCollector;
  15. use DebugBar\DataCollector\RequestDataCollector;
  16. use DebugBar\DataCollector\TimeDataCollector;
  17. use DebugBar\DebugBar;
  18. use DebugBar\JavascriptRenderer;
  19. use DebugBar\StandardDebugBar;
  20. use Grav\Common\Config\Config;
  21. use Grav\Common\Processors\ProcessorInterface;
  22. use Twig\Template;
  23. use Twig\TemplateWrapper;
  24. class Debugger
  25. {
  26. /** @var Grav $grav */
  27. protected $grav;
  28. /** @var Config $config */
  29. protected $config;
  30. /** @var JavascriptRenderer $renderer */
  31. protected $renderer;
  32. /** @var StandardDebugBar $debugbar */
  33. protected $debugbar;
  34. /** @var bool */
  35. protected $enabled;
  36. protected $initialized = false;
  37. /** @var array */
  38. protected $timers = [];
  39. /** @var array $deprecations */
  40. protected $deprecations = [];
  41. /** @var callable */
  42. protected $errorHandler;
  43. /**
  44. * Debugger constructor.
  45. */
  46. public function __construct()
  47. {
  48. $currentTime = microtime(true);
  49. if (!\defined('GRAV_REQUEST_TIME')) {
  50. \define('GRAV_REQUEST_TIME', $currentTime);
  51. }
  52. // Enable debugger until $this->init() gets called.
  53. $this->enabled = true;
  54. $debugbar = new DebugBar();
  55. $debugbar->addCollector(new PhpInfoCollector());
  56. $debugbar->addCollector(new MessagesCollector());
  57. $debugbar->addCollector(new RequestDataCollector());
  58. $debugbar->addCollector(new TimeDataCollector($_SERVER['REQUEST_TIME_FLOAT'] ?? GRAV_REQUEST_TIME));
  59. $debugbar['time']->addMeasure('Server', $debugbar['time']->getRequestStartTime(), GRAV_REQUEST_TIME);
  60. $debugbar['time']->addMeasure('Loading', GRAV_REQUEST_TIME, $currentTime);
  61. $debugbar['time']->addMeasure('Debugger', $currentTime, microtime(true));
  62. $this->debugbar = $debugbar;
  63. // Set deprecation collector.
  64. $this->setErrorHandler();
  65. }
  66. /**
  67. * Initialize the debugger
  68. *
  69. * @return $this
  70. * @throws \DebugBar\DebugBarException
  71. */
  72. public function init()
  73. {
  74. if ($this->initialized) {
  75. return $this;
  76. }
  77. $this->grav = Grav::instance();
  78. $this->config = $this->grav['config'];
  79. // Enable/disable debugger based on configuration.
  80. $this->enabled = (bool)$this->config->get('system.debugger.enabled');
  81. if ($this->enabled()) {
  82. $this->initialized = true;
  83. $plugins_config = (array)$this->config->get('plugins');
  84. ksort($plugins_config);
  85. $debugbar = $this->debugbar;
  86. $debugbar->addCollector(new MemoryCollector());
  87. $debugbar->addCollector(new ExceptionsCollector());
  88. $debugbar->addCollector(new ConfigCollector((array)$this->config->get('system'), 'Config'));
  89. $debugbar->addCollector(new ConfigCollector($plugins_config, 'Plugins'));
  90. $this->addMessage('Grav v' . GRAV_VERSION);
  91. }
  92. return $this;
  93. }
  94. /**
  95. * Set/get the enabled state of the debugger
  96. *
  97. * @param bool $state If null, the method returns the enabled value. If set, the method sets the enabled state
  98. *
  99. * @return bool
  100. */
  101. public function enabled($state = null)
  102. {
  103. if ($state !== null) {
  104. $this->enabled = (bool)$state;
  105. }
  106. return $this->enabled;
  107. }
  108. /**
  109. * Add the debugger assets to the Grav Assets
  110. *
  111. * @return $this
  112. */
  113. public function addAssets()
  114. {
  115. if ($this->enabled()) {
  116. // Only add assets if Page is HTML
  117. $page = $this->grav['page'];
  118. if ($page->templateFormat() !== 'html') {
  119. return $this;
  120. }
  121. /** @var Assets $assets */
  122. $assets = $this->grav['assets'];
  123. // Add jquery library
  124. $assets->add('jquery', 101);
  125. $this->renderer = $this->debugbar->getJavascriptRenderer();
  126. $this->renderer->setIncludeVendors(false);
  127. // Get the required CSS files
  128. list($css_files, $js_files) = $this->renderer->getAssets(null, JavascriptRenderer::RELATIVE_URL);
  129. foreach ((array)$css_files as $css) {
  130. $assets->addCss($css);
  131. }
  132. $assets->addCss('/system/assets/debugger.css');
  133. foreach ((array)$js_files as $js) {
  134. $assets->addJs($js);
  135. }
  136. }
  137. return $this;
  138. }
  139. public function getCaller($limit = 2)
  140. {
  141. $trace = debug_backtrace(false, $limit);
  142. return array_pop($trace);
  143. }
  144. /**
  145. * Adds a data collector
  146. *
  147. * @param DataCollectorInterface $collector
  148. *
  149. * @return $this
  150. * @throws \DebugBar\DebugBarException
  151. */
  152. public function addCollector($collector)
  153. {
  154. $this->debugbar->addCollector($collector);
  155. return $this;
  156. }
  157. /**
  158. * Returns a data collector
  159. *
  160. * @param DataCollectorInterface $collector
  161. *
  162. * @return DataCollectorInterface
  163. * @throws \DebugBar\DebugBarException
  164. */
  165. public function getCollector($collector)
  166. {
  167. return $this->debugbar->getCollector($collector);
  168. }
  169. /**
  170. * Displays the debug bar
  171. *
  172. * @return $this
  173. */
  174. public function render()
  175. {
  176. if ($this->enabled()) {
  177. // Only add assets if Page is HTML
  178. $page = $this->grav['page'];
  179. if (!$this->renderer || $page->templateFormat() !== 'html') {
  180. return $this;
  181. }
  182. $this->addDeprecations();
  183. echo $this->renderer->render();
  184. }
  185. return $this;
  186. }
  187. /**
  188. * Sends the data through the HTTP headers
  189. *
  190. * @return $this
  191. */
  192. public function sendDataInHeaders()
  193. {
  194. if ($this->enabled()) {
  195. $this->addDeprecations();
  196. $this->debugbar->sendDataInHeaders();
  197. }
  198. return $this;
  199. }
  200. /**
  201. * Returns collected debugger data.
  202. *
  203. * @return array
  204. */
  205. public function getData()
  206. {
  207. if (!$this->enabled()) {
  208. return null;
  209. }
  210. $this->addDeprecations();
  211. $this->timers = [];
  212. return $this->debugbar->getData();
  213. }
  214. /**
  215. * Start a timer with an associated name and description
  216. *
  217. * @param string $name
  218. * @param string|null $description
  219. *
  220. * @return $this
  221. */
  222. public function startTimer($name, $description = null)
  223. {
  224. if (strpos($name, '_') === 0 || $this->enabled()) {
  225. $this->debugbar['time']->startMeasure($name, $description);
  226. $this->timers[] = $name;
  227. }
  228. return $this;
  229. }
  230. /**
  231. * Stop the named timer
  232. *
  233. * @param string $name
  234. *
  235. * @return $this
  236. */
  237. public function stopTimer($name)
  238. {
  239. if (\in_array($name, $this->timers, true) && (strpos($name, '_') === 0 || $this->enabled())) {
  240. $this->debugbar['time']->stopMeasure($name);
  241. }
  242. return $this;
  243. }
  244. /**
  245. * Dump variables into the Messages tab of the Debug Bar
  246. *
  247. * @param mixed $message
  248. * @param string $label
  249. * @param bool $isString
  250. *
  251. * @return $this
  252. */
  253. public function addMessage($message, $label = 'info', $isString = true)
  254. {
  255. if ($this->enabled()) {
  256. $this->debugbar['messages']->addMessage($message, $label, $isString);
  257. }
  258. return $this;
  259. }
  260. /**
  261. * Dump exception into the Messages tab of the Debug Bar
  262. *
  263. * @param \Exception $e
  264. * @return Debugger
  265. */
  266. public function addException(\Exception $e)
  267. {
  268. if ($this->initialized && $this->enabled()) {
  269. $this->debugbar['exceptions']->addException($e);
  270. }
  271. return $this;
  272. }
  273. public function setErrorHandler()
  274. {
  275. $this->errorHandler = set_error_handler(
  276. [$this, 'deprecatedErrorHandler']
  277. );
  278. }
  279. /**
  280. * @param int $errno
  281. * @param string $errstr
  282. * @param string $errfile
  283. * @param int $errline
  284. * @return bool
  285. */
  286. public function deprecatedErrorHandler($errno, $errstr, $errfile, $errline)
  287. {
  288. if ($errno !== E_USER_DEPRECATED) {
  289. if ($this->errorHandler) {
  290. return \call_user_func($this->errorHandler, $errno, $errstr, $errfile, $errline);
  291. }
  292. return true;
  293. }
  294. if (!$this->enabled()) {
  295. return true;
  296. }
  297. // Figure out error scope from the error.
  298. $scope = 'unknown';
  299. if (stripos($errstr, 'grav') !== false) {
  300. $scope = 'grav';
  301. } elseif (strpos($errfile, '/twig/') !== false) {
  302. $scope = 'twig';
  303. } elseif (stripos($errfile, '/yaml/') !== false) {
  304. $scope = 'yaml';
  305. } elseif (strpos($errfile, '/vendor/') !== false) {
  306. $scope = 'vendor';
  307. }
  308. // Clean up backtrace to make it more useful.
  309. $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
  310. // Skip current call.
  311. array_shift($backtrace);
  312. // Find yaml file where the error happened.
  313. if ($scope === 'yaml') {
  314. foreach ($backtrace as $current) {
  315. if (isset($current['args'])) {
  316. foreach ($current['args'] as $arg) {
  317. if ($arg instanceof \SplFileInfo) {
  318. $arg = $arg->getPathname();
  319. }
  320. if (\is_string($arg) && preg_match('/.+\.(yaml|md)$/i', $arg)) {
  321. $errfile = $arg;
  322. $errline = 0;
  323. break 2;
  324. }
  325. }
  326. }
  327. }
  328. }
  329. // Filter arguments.
  330. $cut = 0;
  331. $previous = null;
  332. foreach ($backtrace as $i => &$current) {
  333. if (isset($current['args'])) {
  334. $args = [];
  335. foreach ($current['args'] as $arg) {
  336. if (\is_string($arg)) {
  337. $arg = "'" . $arg . "'";
  338. if (mb_strlen($arg) > 100) {
  339. $arg = 'string';
  340. }
  341. } elseif (\is_bool($arg)) {
  342. $arg = $arg ? 'true' : 'false';
  343. } elseif (\is_scalar($arg)) {
  344. $arg = $arg;
  345. } elseif (\is_object($arg)) {
  346. $arg = get_class($arg) . ' $object';
  347. } elseif (\is_array($arg)) {
  348. $arg = '$array';
  349. } else {
  350. $arg = '$object';
  351. }
  352. $args[] = $arg;
  353. }
  354. $current['args'] = $args;
  355. }
  356. $object = $current['object'] ?? null;
  357. unset($current['object']);
  358. $reflection = null;
  359. if ($object instanceof TemplateWrapper) {
  360. $reflection = new \ReflectionObject($object);
  361. $property = $reflection->getProperty('template');
  362. $property->setAccessible(true);
  363. $object = $property->getValue($object);
  364. }
  365. if ($object instanceof Template) {
  366. $file = $current['file'] ?? null;
  367. if (preg_match('`(Template.php|TemplateWrapper.php)$`', $file)) {
  368. $current = null;
  369. continue;
  370. }
  371. $debugInfo = $object->getDebugInfo();
  372. $line = 1;
  373. if (!$reflection) {
  374. foreach ($debugInfo as $codeLine => $templateLine) {
  375. if ($codeLine <= $current['line']) {
  376. $line = $templateLine;
  377. break;
  378. }
  379. }
  380. }
  381. $src = $object->getSourceContext();
  382. //$code = preg_split('/\r\n|\r|\n/', $src->getCode());
  383. //$current['twig']['twig'] = trim($code[$line - 1]);
  384. $current['twig']['file'] = $src->getPath();
  385. $current['twig']['line'] = $line;
  386. $prevFile = $previous['file'] ?? null;
  387. if ($prevFile && $file === $prevFile) {
  388. $prevLine = $previous['line'];
  389. $line = 1;
  390. foreach ($debugInfo as $codeLine => $templateLine) {
  391. if ($codeLine <= $prevLine) {
  392. $line = $templateLine;
  393. break;
  394. }
  395. }
  396. //$previous['twig']['twig'] = trim($code[$line - 1]);
  397. $previous['twig']['file'] = $src->getPath();
  398. $previous['twig']['line'] = $line;
  399. }
  400. $cut = $i;
  401. } elseif ($object instanceof ProcessorInterface) {
  402. $cut = $cut ?: $i;
  403. break;
  404. }
  405. $previous = &$backtrace[$i];
  406. }
  407. unset($current);
  408. if ($cut) {
  409. $backtrace = array_slice($backtrace, 0, $cut + 1);
  410. }
  411. $backtrace = array_values(array_filter($backtrace));
  412. // Skip vendor libraries and the method where error was triggered.
  413. foreach ($backtrace as $i => $current) {
  414. if (!isset($current['file'])) {
  415. continue;
  416. }
  417. if (strpos($current['file'], '/vendor/') !== false) {
  418. $cut = $i + 1;
  419. continue;
  420. }
  421. if (isset($current['function']) && ($current['function'] === 'user_error' || $current['function'] === 'trigger_error')) {
  422. $cut = $i + 1;
  423. continue;
  424. }
  425. break;
  426. }
  427. if ($cut) {
  428. $backtrace = array_slice($backtrace, $cut);
  429. }
  430. $backtrace = array_values(array_filter($backtrace));
  431. $current = reset($backtrace);
  432. // If the issue happened inside twig file, change the file and line to match that file.
  433. $file = $current['twig']['file'] ?? '';
  434. if ($file) {
  435. $errfile = $file;
  436. $errline = $current['twig']['line'] ?? 0;
  437. }
  438. $deprecation = [
  439. 'scope' => $scope,
  440. 'message' => $errstr,
  441. 'file' => $errfile,
  442. 'line' => $errline,
  443. 'trace' => $backtrace,
  444. 'count' => 1
  445. ];
  446. $this->deprecations[] = $deprecation;
  447. // Do not pass forward.
  448. return true;
  449. }
  450. protected function addDeprecations()
  451. {
  452. if (!$this->deprecations) {
  453. return;
  454. }
  455. $collector = new MessagesCollector('deprecated');
  456. $this->addCollector($collector);
  457. $collector->addMessage('Your site is using following deprecated features:');
  458. /** @var array $deprecated */
  459. foreach ($this->deprecations as $deprecated) {
  460. list($message, $scope) = $this->getDepracatedMessage($deprecated);
  461. $collector->addMessage($message, $scope);
  462. }
  463. }
  464. protected function getDepracatedMessage($deprecated)
  465. {
  466. $scope = $deprecated['scope'];
  467. $trace = [];
  468. if (isset($deprecated['trace'])) {
  469. foreach ($deprecated['trace'] as $current) {
  470. $class = $current['class'] ?? '';
  471. $type = $current['type'] ?? '';
  472. $function = $this->getFunction($current);
  473. if (isset($current['file'])) {
  474. $current['file'] = str_replace(GRAV_ROOT . '/', '', $current['file']);
  475. }
  476. unset($current['class'], $current['type'], $current['function'], $current['args']);
  477. if (isset($current['twig'])) {
  478. $trace[] = $current['twig'];
  479. } else {
  480. $trace[] = ['call' => $class . $type . $function] + $current;
  481. }
  482. }
  483. }
  484. $array = [
  485. 'message' => $deprecated['message'],
  486. 'file' => $deprecated['file'],
  487. 'line' => $deprecated['line'],
  488. 'trace' => $trace
  489. ];
  490. return [
  491. array_filter($array),
  492. $scope
  493. ];
  494. }
  495. protected function getFunction($trace)
  496. {
  497. if (!isset($trace['function'])) {
  498. return '';
  499. }
  500. return $trace['function'] . '(' . implode(', ', $trace['args'] ?? []) . ')';
  501. }
  502. }