Debugger.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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 Debugger class name.
  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. * @param mixed $var the variable to dump
  151. * @param int $depth The depth to output to. Defaults to 3.
  152. * @return void
  153. * @see Debugger::exportVar()
  154. * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::dump
  155. */
  156. public static function dump($var, $depth = 3) {
  157. pr(self::exportVar($var, $depth));
  158. }
  159. /**
  160. * Creates an entry in the log file. The log entry will contain a stack trace from where it was called.
  161. * as well as export the variable using exportVar. By default the log is written to the debug log.
  162. *
  163. * @param mixed $var Variable or content to log
  164. * @param int $level type of log to use. Defaults to LOG_DEBUG
  165. * @param int $depth The depth to output to. Defaults to 3.
  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, $depth = 3) {
  170. $source = self::trace(array('start' => 1)) . "\n";
  171. CakeLog::write($level, "\n" . $source . self::exportVar($var, $depth));
  172. }
  173. /**
  174. * Overrides PHP's default error handling.
  175. *
  176. * @param int $code Code of error
  177. * @param string $description Error description
  178. * @param string $file File on which error occurred
  179. * @param int $line Line that triggered the error
  180. * @param array $context Context
  181. * @return bool 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 int $line Line number to highlight
  349. * @param int $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 int $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 int $depth The remaining depth.
  438. * @param int $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 int $depth The current depth, used for recursion tracking.
  481. * @param int $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. $break = $end = null;
  498. if (!empty($var)) {
  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. } elseif ($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 int $depth The current depth, used for tracking recursion.
  525. * @param int $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. $filters = array(
  545. ReflectionProperty::IS_PROTECTED => 'protected',
  546. ReflectionProperty::IS_PRIVATE => 'private',
  547. );
  548. foreach ($filters as $filter => $visibility) {
  549. $reflectionProperties = $ref->getProperties($filter);
  550. foreach ($reflectionProperties as $reflectionProperty) {
  551. $reflectionProperty->setAccessible(true);
  552. $property = $reflectionProperty->getValue($var);
  553. $value = self::_export($property, $depth - 1, $indent);
  554. $key = $reflectionProperty->name;
  555. $props[] = sprintf('[%s] %s => %s', $visibility, $key, $value);
  556. }
  557. }
  558. }
  559. $out .= $break . implode($break, $props) . $end;
  560. }
  561. $out .= '}';
  562. return $out;
  563. }
  564. /**
  565. * Get/Set the output format for Debugger error rendering.
  566. *
  567. * @param string $format The format you want errors to be output as.
  568. * Leave null to get the current format.
  569. * @return mixed Returns null when setting. Returns the current format when getting.
  570. * @throws CakeException when choosing a format that doesn't exist.
  571. */
  572. public static function outputAs($format = null) {
  573. $self = Debugger::getInstance();
  574. if ($format === null) {
  575. return $self->_outputFormat;
  576. }
  577. if ($format !== false && !isset($self->_templates[$format])) {
  578. throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
  579. }
  580. $self->_outputFormat = $format;
  581. }
  582. /**
  583. * Add an output format or update a format in Debugger.
  584. *
  585. * `Debugger::addFormat('custom', $data);`
  586. *
  587. * Where $data is an array of strings that use String::insert() variable
  588. * replacement. The template vars should be in a `{:id}` style.
  589. * An error formatter can have the following keys:
  590. *
  591. * - 'error' - Used for the container for the error message. Gets the following template
  592. * variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
  593. * - 'info' - A combination of `code`, `context` and `trace`. Will be set with
  594. * the contents of the other template keys.
  595. * - 'trace' - The container for a stack trace. Gets the following template
  596. * variables: `trace`
  597. * - 'context' - The container element for the context variables.
  598. * Gets the following templates: `id`, `context`
  599. * - 'links' - An array of HTML links that are used for creating links to other resources.
  600. * Typically this is used to create javascript links to open other sections.
  601. * Link keys, are: `code`, `context`, `help`. See the js output format for an
  602. * example.
  603. * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
  604. * template variables: `reference`, `path`, `line`
  605. *
  606. * Alternatively if you want to use a custom callback to do all the formatting, you can use
  607. * the callback key, and provide a callable:
  608. *
  609. * `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));`
  610. *
  611. * The callback can expect two parameters. The first is an array of all
  612. * the error data. The second contains the formatted strings generated using
  613. * the other template strings. Keys like `info`, `links`, `code`, `context` and `trace`
  614. * will be present depending on the other templates in the format type.
  615. *
  616. * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
  617. * straight HTML output, or 'txt' for unformatted text.
  618. * @param array $strings Template strings, or a callback to be used for the output format.
  619. * @return The resulting format string set.
  620. */
  621. public static function addFormat($format, array $strings) {
  622. $self = Debugger::getInstance();
  623. if (isset($self->_templates[$format])) {
  624. if (isset($strings['links'])) {
  625. $self->_templates[$format]['links'] = array_merge(
  626. $self->_templates[$format]['links'],
  627. $strings['links']
  628. );
  629. unset($strings['links']);
  630. }
  631. $self->_templates[$format] = array_merge($self->_templates[$format], $strings);
  632. } else {
  633. $self->_templates[$format] = $strings;
  634. }
  635. return $self->_templates[$format];
  636. }
  637. /**
  638. * Switches output format, updates format strings.
  639. * Can be used to switch the active output format:
  640. *
  641. * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
  642. * straight HTML output, or 'txt' for unformatted text.
  643. * @param array $strings Template strings to be used for the output format.
  644. * @return string
  645. * @deprecated Use Debugger::outputAs() and Debugger::addFormat(). Will be removed
  646. * in 3.0
  647. */
  648. public static function output($format = null, $strings = array()) {
  649. $self = Debugger::getInstance();
  650. $data = null;
  651. if ($format === null) {
  652. return Debugger::outputAs();
  653. }
  654. if (!empty($strings)) {
  655. return Debugger::addFormat($format, $strings);
  656. }
  657. if ($format === true && !empty($self->_data)) {
  658. $data = $self->_data;
  659. $self->_data = array();
  660. $format = false;
  661. }
  662. Debugger::outputAs($format);
  663. return $data;
  664. }
  665. /**
  666. * Takes a processed array of data from an error and displays it in the chosen format.
  667. *
  668. * @param string $data Data to output.
  669. * @return void
  670. */
  671. public function outputError($data) {
  672. $defaults = array(
  673. 'level' => 0,
  674. 'error' => 0,
  675. 'code' => 0,
  676. 'description' => '',
  677. 'file' => '',
  678. 'line' => 0,
  679. 'context' => array(),
  680. 'start' => 2,
  681. );
  682. $data += $defaults;
  683. $files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
  684. $code = '';
  685. $file = null;
  686. if (isset($files[0]['file'])) {
  687. $file = $files[0];
  688. } elseif (isset($files[1]['file'])) {
  689. $file = $files[1];
  690. }
  691. if ($file) {
  692. $code = $this->excerpt($file['file'], $file['line'] - 1, 1);
  693. }
  694. $trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
  695. $insertOpts = array('before' => '{:', 'after' => '}');
  696. $context = array();
  697. $links = array();
  698. $info = '';
  699. foreach ((array)$data['context'] as $var => $value) {
  700. $context[] = "\${$var} = " . $this->exportVar($value, 3);
  701. }
  702. switch ($this->_outputFormat) {
  703. case false:
  704. $this->_data[] = compact('context', 'trace') + $data;
  705. return;
  706. case 'log':
  707. $this->log(compact('context', 'trace') + $data);
  708. return;
  709. }
  710. $data['trace'] = $trace;
  711. $data['id'] = 'cakeErr' . uniqid();
  712. $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
  713. if (isset($tpl['links'])) {
  714. foreach ($tpl['links'] as $key => $val) {
  715. $links[$key] = String::insert($val, $data, $insertOpts);
  716. }
  717. }
  718. if (!empty($tpl['escapeContext'])) {
  719. $context = h($context);
  720. }
  721. $infoData = compact('code', 'context', 'trace');
  722. foreach ($infoData as $key => $value) {
  723. if (empty($value) || !isset($tpl[$key])) {
  724. continue;
  725. }
  726. if (is_array($value)) {
  727. $value = implode("\n", $value);
  728. }
  729. $info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
  730. }
  731. $links = implode(' ', $links);
  732. if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
  733. return call_user_func($tpl['callback'], $data, compact('links', 'info'));
  734. }
  735. echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
  736. }
  737. /**
  738. * Get the type of the given variable. Will return the class name
  739. * for objects.
  740. *
  741. * @param mixed $var The variable to get the type of
  742. * @return string The type of variable.
  743. */
  744. public static function getType($var) {
  745. if (is_object($var)) {
  746. return get_class($var);
  747. }
  748. if ($var === null) {
  749. return 'null';
  750. }
  751. if (is_string($var)) {
  752. return 'string';
  753. }
  754. if (is_array($var)) {
  755. return 'array';
  756. }
  757. if (is_int($var)) {
  758. return 'integer';
  759. }
  760. if (is_bool($var)) {
  761. return 'boolean';
  762. }
  763. if (is_float($var)) {
  764. return 'float';
  765. }
  766. if (is_resource($var)) {
  767. return 'resource';
  768. }
  769. return 'unknown';
  770. }
  771. /**
  772. * Verifies that the application's salt and cipher seed value has been changed from the default value.
  773. *
  774. * @return void
  775. */
  776. public static function checkSecurityKeys() {
  777. if (Configure::read('Security.salt') === 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
  778. 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);
  779. }
  780. if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
  781. 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);
  782. }
  783. }
  784. }