Debugger.php 25 KB

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