Debugger.php 25 KB

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