Debugger.php 25 KB

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