PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Error/Debugger.php

https://github.com/ceeram/cakephp
PHP | 762 lines | 463 code | 59 blank | 240 comment | 74 complexity | de2e7b2c90d896c14d53e0f2c3833f6e MD5 | raw file
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Error;
  16. use Cake\Log\Log;
  17. use Cake\Utility\Hash;
  18. use Cake\Utility\Security;
  19. use Cake\Utility\Text;
  20. use Exception;
  21. use InvalidArgumentException;
  22. /**
  23. * Provide custom logging and error handling.
  24. *
  25. * Debugger overrides PHP's default error handling to provide stack traces and enhanced logging
  26. *
  27. * @link http://book.cakephp.org/3.0/en/development/debugging.html#namespace-Cake\Error
  28. */
  29. class Debugger
  30. {
  31. /**
  32. * A list of errors generated by the application.
  33. *
  34. * @var array
  35. */
  36. public $errors = [];
  37. /**
  38. * The current output format.
  39. *
  40. * @var string
  41. */
  42. protected $_outputFormat = 'js';
  43. /**
  44. * Templates used when generating trace or error strings. Can be global or indexed by the format
  45. * value used in $_outputFormat.
  46. *
  47. * @var string
  48. */
  49. protected $_templates = [
  50. 'log' => [
  51. 'trace' => '{:reference} - {:path}, line {:line}',
  52. 'error' => "{:error} ({:code}): {:description} in [{:file}, line {:line}]"
  53. ],
  54. 'js' => [
  55. 'error' => '',
  56. 'info' => '',
  57. 'trace' => '<pre class="stack-trace">{:trace}</pre>',
  58. 'code' => '',
  59. 'context' => '',
  60. 'links' => [],
  61. 'escapeContext' => true,
  62. ],
  63. 'html' => [
  64. 'trace' => '<pre class="cake-error trace"><b>Trace</b> <p>{:trace}</p></pre>',
  65. 'context' => '<pre class="cake-error context"><b>Context</b> <p>{:context}</p></pre>',
  66. 'escapeContext' => true,
  67. ],
  68. 'txt' => [
  69. 'error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}",
  70. 'code' => '',
  71. 'info' => ''
  72. ],
  73. 'base' => [
  74. 'traceLine' => '{:reference} - {:path}, line {:line}',
  75. 'trace' => "Trace:\n{:trace}\n",
  76. 'context' => "Context:\n{:context}\n",
  77. ]
  78. ];
  79. /**
  80. * Holds current output data when outputFormat is false.
  81. *
  82. * @var string
  83. */
  84. protected $_data = [];
  85. /**
  86. * Constructor.
  87. *
  88. */
  89. public function __construct()
  90. {
  91. $docRef = ini_get('docref_root');
  92. if (empty($docRef) && function_exists('ini_set')) {
  93. ini_set('docref_root', 'http://php.net/');
  94. }
  95. if (!defined('E_RECOVERABLE_ERROR')) {
  96. define('E_RECOVERABLE_ERROR', 4096);
  97. }
  98. $e = '<pre class="cake-error">';
  99. $e .= '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')';
  100. $e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == ';
  101. $e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} ';
  102. $e .= '[<b>{:path}</b>, line <b>{:line}</b>]';
  103. $e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
  104. $e .= '{:links}{:info}</div>';
  105. $e .= '</pre>';
  106. $this->_templates['js']['error'] = $e;
  107. $t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
  108. $t .= '{:context}{:code}{:trace}</div>';
  109. $this->_templates['js']['info'] = $t;
  110. $links = [];
  111. $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')';
  112. $link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == ';
  113. $link .= '\'none\' ? \'\' : \'none\')">Code</a>';
  114. $links['code'] = $link;
  115. $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')';
  116. $link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == ';
  117. $link .= '\'none\' ? \'\' : \'none\')">Context</a>';
  118. $links['context'] = $link;
  119. $this->_templates['js']['links'] = $links;
  120. $this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" ';
  121. $this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>';
  122. $this->_templates['js']['code'] = '<pre id="{:id}-code" class="cake-code-dump" ';
  123. $this->_templates['js']['code'] .= 'style="display: none;">{:code}</pre>';
  124. $e = '<pre class="cake-error"><b>{:error}</b> ({:code}) : {:description} ';
  125. $e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>';
  126. $this->_templates['html']['error'] = $e;
  127. $this->_templates['html']['context'] = '<pre class="cake-context"><b>Context</b> ';
  128. $this->_templates['html']['context'] .= '<p>{:context}</p></pre>';
  129. }
  130. /**
  131. * Returns a reference to the Debugger singleton object instance.
  132. *
  133. * @param string|null $class Class name.
  134. * @return object
  135. */
  136. public static function getInstance($class = null)
  137. {
  138. static $instance = [];
  139. if (!empty($class)) {
  140. if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) {
  141. $instance[0] = new $class();
  142. }
  143. }
  144. if (!$instance) {
  145. $instance[0] = new Debugger();
  146. }
  147. return $instance[0];
  148. }
  149. /**
  150. * Recursively formats and outputs the contents of the supplied variable.
  151. *
  152. * @param mixed $var the variable to dump
  153. * @param int $depth The depth to output to. Defaults to 3.
  154. * @return void
  155. * @see Debugger::exportVar()
  156. * @link http://book.cakephp.org/3.0/en/development/debugging.html#outputting-values
  157. */
  158. public static function dump($var, $depth = 3)
  159. {
  160. pr(static::exportVar($var, $depth));
  161. }
  162. /**
  163. * Creates an entry in the log file. The log entry will contain a stack trace from where it was called.
  164. * as well as export the variable using exportVar. By default the log is written to the debug log.
  165. *
  166. * @param mixed $var Variable or content to log
  167. * @param int|string $level type of log to use. Defaults to 'debug'
  168. * @param int $depth The depth to output to. Defaults to 3.
  169. * @return void
  170. */
  171. public static function log($var, $level = 'debug', $depth = 3)
  172. {
  173. $source = static::trace(['start' => 1]) . "\n";
  174. Log::write($level, "\n" . $source . static::exportVar($var, $depth));
  175. }
  176. /**
  177. * Outputs a stack trace based on the supplied options.
  178. *
  179. * ### Options
  180. *
  181. * - `depth` - The number of stack frames to return. Defaults to 999
  182. * - `format` - The format you want the return. Defaults to the currently selected format. If
  183. * format is 'array' or 'points' the return will be an array.
  184. * - `args` - Should arguments for functions be shown? If true, the arguments for each method call
  185. * will be displayed.
  186. * - `start` - The stack frame to start generating a trace from. Defaults to 0
  187. *
  188. * @param array $options Format for outputting stack trace
  189. * @return mixed Formatted stack trace
  190. * @link http://book.cakephp.org/3.0/en/development/debugging.html#generating-stack-traces
  191. */
  192. public static function trace(array $options = [])
  193. {
  194. $self = Debugger::getInstance();
  195. $defaults = [
  196. 'depth' => 999,
  197. 'format' => $self->_outputFormat,
  198. 'args' => false,
  199. 'start' => 0,
  200. 'scope' => null,
  201. 'exclude' => ['call_user_func_array', 'trigger_error']
  202. ];
  203. $options = Hash::merge($defaults, $options);
  204. $backtrace = debug_backtrace();
  205. $count = count($backtrace);
  206. $back = [];
  207. $_trace = [
  208. 'line' => '??',
  209. 'file' => '[internal]',
  210. 'class' => null,
  211. 'function' => '[main]'
  212. ];
  213. for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
  214. $trace = $backtrace[$i] + ['file' => '[internal]', 'line' => '??'];
  215. $signature = $reference = '[main]';
  216. if (isset($backtrace[$i + 1])) {
  217. $next = $backtrace[$i + 1] + $_trace;
  218. $signature = $reference = $next['function'];
  219. if (!empty($next['class'])) {
  220. $signature = $next['class'] . '::' . $next['function'];
  221. $reference = $signature . '(';
  222. if ($options['args'] && isset($next['args'])) {
  223. $args = [];
  224. foreach ($next['args'] as $arg) {
  225. $args[] = Debugger::exportVar($arg);
  226. }
  227. $reference .= implode(', ', $args);
  228. }
  229. $reference .= ')';
  230. }
  231. }
  232. if (in_array($signature, $options['exclude'])) {
  233. continue;
  234. }
  235. if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
  236. $back[] = ['file' => $trace['file'], 'line' => $trace['line']];
  237. } elseif ($options['format'] === 'array') {
  238. $back[] = $trace;
  239. } else {
  240. if (isset($self->_templates[$options['format']]['traceLine'])) {
  241. $tpl = $self->_templates[$options['format']]['traceLine'];
  242. } else {
  243. $tpl = $self->_templates['base']['traceLine'];
  244. }
  245. $trace['path'] = static::trimPath($trace['file']);
  246. $trace['reference'] = $reference;
  247. unset($trace['object'], $trace['args']);
  248. $back[] = Text::insert($tpl, $trace, ['before' => '{:', 'after' => '}']);
  249. }
  250. }
  251. if ($options['format'] === 'array' || $options['format'] === 'points') {
  252. return $back;
  253. }
  254. return implode("\n", $back);
  255. }
  256. /**
  257. * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
  258. * path with 'CORE'.
  259. *
  260. * @param string $path Path to shorten
  261. * @return string Normalized path
  262. */
  263. public static function trimPath($path)
  264. {
  265. if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) {
  266. return $path;
  267. }
  268. if (strpos($path, APP) === 0) {
  269. return str_replace(APP, 'APP/', $path);
  270. } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) {
  271. return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path);
  272. } elseif (strpos($path, ROOT) === 0) {
  273. return str_replace(ROOT, 'ROOT', $path);
  274. }
  275. return $path;
  276. }
  277. /**
  278. * Grabs an excerpt from a file and highlights a given line of code.
  279. *
  280. * Usage:
  281. *
  282. * `Debugger::excerpt('/path/to/file', 100, 4);`
  283. *
  284. * The above would return an array of 8 items. The 4th item would be the provided line,
  285. * and would be wrapped in `<span class="code-highlight"></span>`. All of the lines
  286. * are processed with highlight_string() as well, so they have basic PHP syntax highlighting
  287. * applied.
  288. *
  289. * @param string $file Absolute path to a PHP file
  290. * @param int $line Line number to highlight
  291. * @param int $context Number of lines of context to extract above and below $line
  292. * @return array Set of lines highlighted
  293. * @see http://php.net/highlight_string
  294. * @link http://book.cakephp.org/3.0/en/development/debugging.html#getting-an-excerpt-from-a-file
  295. */
  296. public static function excerpt($file, $line, $context = 2)
  297. {
  298. $lines = [];
  299. if (!file_exists($file)) {
  300. return [];
  301. }
  302. $data = file_get_contents($file);
  303. if (empty($data)) {
  304. return $lines;
  305. }
  306. if (strpos($data, "\n") !== false) {
  307. $data = explode("\n", $data);
  308. }
  309. if (!isset($data[$line])) {
  310. return $lines;
  311. }
  312. $line = $line - 1;
  313. for ($i = $line - $context; $i < $line + $context + 1; $i++) {
  314. if (!isset($data[$i])) {
  315. continue;
  316. }
  317. $string = str_replace(["\r\n", "\n"], "", static::_highlight($data[$i]));
  318. if ($i == $line) {
  319. $lines[] = '<span class="code-highlight">' . $string . '</span>';
  320. } else {
  321. $lines[] = $string;
  322. }
  323. }
  324. return $lines;
  325. }
  326. /**
  327. * Wraps the highlight_string function in case the server API does not
  328. * implement the function as it is the case of the HipHop interpreter
  329. *
  330. * @param string $str the string to convert
  331. * @return string
  332. */
  333. protected static function _highlight($str)
  334. {
  335. if (function_exists('hphp_log') || function_exists('hphp_gettid')) {
  336. return htmlentities($str);
  337. }
  338. $added = false;
  339. if (strpos($str, '<?php') === false) {
  340. $added = true;
  341. $str = "<?php \n" . $str;
  342. }
  343. $highlight = highlight_string($str, true);
  344. if ($added) {
  345. $highlight = str_replace(
  346. ['&lt;?php&nbsp;<br/>', '&lt;?php&nbsp;<br />'],
  347. '',
  348. $highlight
  349. );
  350. }
  351. return $highlight;
  352. }
  353. /**
  354. * Converts a variable to a string for debug output.
  355. *
  356. * *Note:* The following keys will have their contents
  357. * replaced with `*****`:
  358. *
  359. * - password
  360. * - login
  361. * - host
  362. * - database
  363. * - port
  364. * - prefix
  365. * - schema
  366. *
  367. * This is done to protect database credentials, which could be accidentally
  368. * shown in an error message if CakePHP is deployed in development mode.
  369. *
  370. * @param string $var Variable to convert
  371. * @param int $depth The depth to output to. Defaults to 3.
  372. * @return string Variable as a formatted string
  373. */
  374. public static function exportVar($var, $depth = 3)
  375. {
  376. return static::_export($var, $depth, 0);
  377. }
  378. /**
  379. * Protected export function used to keep track of indentation and recursion.
  380. *
  381. * @param mixed $var The variable to dump.
  382. * @param int $depth The remaining depth.
  383. * @param int $indent The current indentation level.
  384. * @return string The dumped variable.
  385. */
  386. protected static function _export($var, $depth, $indent)
  387. {
  388. switch (static::getType($var)) {
  389. case 'boolean':
  390. return ($var) ? 'true' : 'false';
  391. case 'integer':
  392. return '(int) ' . $var;
  393. case 'float':
  394. return '(float) ' . $var;
  395. case 'string':
  396. if (trim($var) === '') {
  397. return "''";
  398. }
  399. return "'" . $var . "'";
  400. case 'array':
  401. return static::_array($var, $depth - 1, $indent + 1);
  402. case 'resource':
  403. return strtolower(gettype($var));
  404. case 'null':
  405. return 'null';
  406. case 'unknown':
  407. return 'unknown';
  408. default:
  409. return static::_object($var, $depth - 1, $indent + 1);
  410. }
  411. }
  412. /**
  413. * Export an array type object. Filters out keys used in datasource configuration.
  414. *
  415. * The following keys are replaced with ***'s
  416. *
  417. * - password
  418. * - login
  419. * - host
  420. * - database
  421. * - port
  422. * - prefix
  423. * - schema
  424. *
  425. * @param array $var The array to export.
  426. * @param int $depth The current depth, used for recursion tracking.
  427. * @param int $indent The current indentation level.
  428. * @return string Exported array.
  429. */
  430. protected static function _array(array $var, $depth, $indent)
  431. {
  432. $out = "[";
  433. $break = $end = null;
  434. if (!empty($var)) {
  435. $break = "\n" . str_repeat("\t", $indent);
  436. $end = "\n" . str_repeat("\t", $indent - 1);
  437. }
  438. $vars = [];
  439. if ($depth >= 0) {
  440. foreach ($var as $key => $val) {
  441. // Sniff for globals as !== explodes in < 5.4
  442. if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
  443. $val = '[recursion]';
  444. } elseif ($val !== $var) {
  445. $val = static::_export($val, $depth, $indent);
  446. }
  447. $vars[] = $break . static::exportVar($key) .
  448. ' => ' .
  449. $val;
  450. }
  451. } else {
  452. $vars[] = $break . '[maximum depth reached]';
  453. }
  454. return $out . implode(',', $vars) . $end . ']';
  455. }
  456. /**
  457. * Handles object to string conversion.
  458. *
  459. * @param string $var Object to convert
  460. * @param int $depth The current depth, used for tracking recursion.
  461. * @param int $indent The current indentation level.
  462. * @return string
  463. * @see Debugger::exportVar()
  464. */
  465. protected static function _object($var, $depth, $indent)
  466. {
  467. $out = '';
  468. $props = [];
  469. $className = get_class($var);
  470. $out .= 'object(' . $className . ') {';
  471. $break = "\n" . str_repeat("\t", $indent);
  472. $end = "\n" . str_repeat("\t", $indent - 1);
  473. if ($depth > 0 && method_exists($var, '__debugInfo')) {
  474. try {
  475. return $out . "\n" .
  476. substr(static::_array($var->__debugInfo(), $depth - 1, $indent), 1, -1) .
  477. $end . '}';
  478. } catch (Exception $e) {
  479. $message = $e->getMessage();
  480. return $out . "\n(unable to export object: $message)\n }";
  481. }
  482. }
  483. if ($depth > 0) {
  484. $objectVars = get_object_vars($var);
  485. foreach ($objectVars as $key => $value) {
  486. $value = static::_export($value, $depth - 1, $indent);
  487. $props[] = "$key => " . $value;
  488. }
  489. $ref = new \ReflectionObject($var);
  490. $filters = [
  491. \ReflectionProperty::IS_PROTECTED => 'protected',
  492. \ReflectionProperty::IS_PRIVATE => 'private',
  493. ];
  494. foreach ($filters as $filter => $visibility) {
  495. $reflectionProperties = $ref->getProperties($filter);
  496. foreach ($reflectionProperties as $reflectionProperty) {
  497. $reflectionProperty->setAccessible(true);
  498. $property = $reflectionProperty->getValue($var);
  499. $value = static::_export($property, $depth - 1, $indent);
  500. $key = $reflectionProperty->name;
  501. $props[] = sprintf('[%s] %s => %s', $visibility, $key, $value);
  502. }
  503. }
  504. $out .= $break . implode($break, $props) . $end;
  505. }
  506. $out .= '}';
  507. return $out;
  508. }
  509. /**
  510. * Get/Set the output format for Debugger error rendering.
  511. *
  512. * @param string|null $format The format you want errors to be output as.
  513. * Leave null to get the current format.
  514. * @return mixed Returns null when setting. Returns the current format when getting.
  515. * @throws \InvalidArgumentException when choosing a format that doesn't exist.
  516. */
  517. public static function outputAs($format = null)
  518. {
  519. $self = Debugger::getInstance();
  520. if ($format === null) {
  521. return $self->_outputFormat;
  522. }
  523. if ($format !== false && !isset($self->_templates[$format])) {
  524. throw new InvalidArgumentException('Invalid Debugger output format.');
  525. }
  526. $self->_outputFormat = $format;
  527. }
  528. /**
  529. * Add an output format or update a format in Debugger.
  530. *
  531. * `Debugger::addFormat('custom', $data);`
  532. *
  533. * Where $data is an array of strings that use Text::insert() variable
  534. * replacement. The template vars should be in a `{:id}` style.
  535. * An error formatter can have the following keys:
  536. *
  537. * - 'error' - Used for the container for the error message. Gets the following template
  538. * variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
  539. * - 'info' - A combination of `code`, `context` and `trace`. Will be set with
  540. * the contents of the other template keys.
  541. * - 'trace' - The container for a stack trace. Gets the following template
  542. * variables: `trace`
  543. * - 'context' - The container element for the context variables.
  544. * Gets the following templates: `id`, `context`
  545. * - 'links' - An array of HTML links that are used for creating links to other resources.
  546. * Typically this is used to create javascript links to open other sections.
  547. * Link keys, are: `code`, `context`, `help`. See the js output format for an
  548. * example.
  549. * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
  550. * template variables: `reference`, `path`, `line`
  551. *
  552. * Alternatively if you want to use a custom callback to do all the formatting, you can use
  553. * the callback key, and provide a callable:
  554. *
  555. * `Debugger::addFormat('custom', ['callback' => [$foo, 'outputError']];`
  556. *
  557. * The callback can expect two parameters. The first is an array of all
  558. * the error data. The second contains the formatted strings generated using
  559. * the other template strings. Keys like `info`, `links`, `code`, `context` and `trace`
  560. * will be present depending on the other templates in the format type.
  561. *
  562. * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
  563. * straight HTML output, or 'txt' for unformatted text.
  564. * @param array $strings Template strings, or a callback to be used for the output format.
  565. * @return array The resulting format string set.
  566. */
  567. public static function addFormat($format, array $strings)
  568. {
  569. $self = Debugger::getInstance();
  570. if (isset($self->_templates[$format])) {
  571. if (isset($strings['links'])) {
  572. $self->_templates[$format]['links'] = array_merge(
  573. $self->_templates[$format]['links'],
  574. $strings['links']
  575. );
  576. unset($strings['links']);
  577. }
  578. $self->_templates[$format] = $strings + $self->_templates[$format];
  579. } else {
  580. $self->_templates[$format] = $strings;
  581. }
  582. return $self->_templates[$format];
  583. }
  584. /**
  585. * Takes a processed array of data from an error and displays it in the chosen format.
  586. *
  587. * @param string $data Data to output.
  588. * @return void
  589. */
  590. public function outputError($data)
  591. {
  592. $defaults = [
  593. 'level' => 0,
  594. 'error' => 0,
  595. 'code' => 0,
  596. 'description' => '',
  597. 'file' => '',
  598. 'line' => 0,
  599. 'context' => [],
  600. 'start' => 2,
  601. ];
  602. $data += $defaults;
  603. $files = $this->trace(['start' => $data['start'], 'format' => 'points']);
  604. $code = '';
  605. $file = null;
  606. if (isset($files[0]['file'])) {
  607. $file = $files[0];
  608. } elseif (isset($files[1]['file'])) {
  609. $file = $files[1];
  610. }
  611. if ($file) {
  612. $code = $this->excerpt($file['file'], $file['line'] - 1, 1);
  613. }
  614. $trace = $this->trace(['start' => $data['start'], 'depth' => '20']);
  615. $insertOpts = ['before' => '{:', 'after' => '}'];
  616. $context = [];
  617. $links = [];
  618. $info = '';
  619. foreach ((array)$data['context'] as $var => $value) {
  620. $context[] = "\${$var} = " . $this->exportVar($value, 3);
  621. }
  622. switch ($this->_outputFormat) {
  623. case false:
  624. $this->_data[] = compact('context', 'trace') + $data;
  625. return;
  626. case 'log':
  627. $this->log(compact('context', 'trace') + $data);
  628. return;
  629. }
  630. $data['trace'] = $trace;
  631. $data['id'] = 'cakeErr' . uniqid();
  632. $tpl = $this->_templates[$this->_outputFormat] + $this->_templates['base'];
  633. if (isset($tpl['links'])) {
  634. foreach ($tpl['links'] as $key => $val) {
  635. $links[$key] = Text::insert($val, $data, $insertOpts);
  636. }
  637. }
  638. if (!empty($tpl['escapeContext'])) {
  639. $context = h($context);
  640. }
  641. $infoData = compact('code', 'context', 'trace');
  642. foreach ($infoData as $key => $value) {
  643. if (empty($value) || !isset($tpl[$key])) {
  644. continue;
  645. }
  646. if (is_array($value)) {
  647. $value = implode("\n", $value);
  648. }
  649. $info .= Text::insert($tpl[$key], [$key => $value] + $data, $insertOpts);
  650. }
  651. $links = implode(' ', $links);
  652. if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
  653. return call_user_func($tpl['callback'], $data, compact('links', 'info'));
  654. }
  655. echo Text::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
  656. }
  657. /**
  658. * Get the type of the given variable. Will return the class name
  659. * for objects.
  660. *
  661. * @param mixed $var The variable to get the type of
  662. * @return string The type of variable.
  663. */
  664. public static function getType($var)
  665. {
  666. if (is_object($var)) {
  667. return get_class($var);
  668. }
  669. if ($var === null) {
  670. return 'null';
  671. }
  672. if (is_string($var)) {
  673. return 'string';
  674. }
  675. if (is_array($var)) {
  676. return 'array';
  677. }
  678. if (is_int($var)) {
  679. return 'integer';
  680. }
  681. if (is_bool($var)) {
  682. return 'boolean';
  683. }
  684. if (is_float($var)) {
  685. return 'float';
  686. }
  687. if (is_resource($var)) {
  688. return 'resource';
  689. }
  690. return 'unknown';
  691. }
  692. /**
  693. * Verifies that the application's salt and cipher seed value has been changed from the default value.
  694. *
  695. * @return void
  696. */
  697. public static function checkSecurityKeys()
  698. {
  699. if (Security::salt() === '__SALT__') {
  700. trigger_error(sprintf('Please change the value of %s in %s to a salt value specific to your application.', '\'Security.salt\'', 'ROOT/config/app.php'), E_USER_NOTICE);
  701. }
  702. }
  703. }