Debugger.php 25 KB

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