Debugger.php 23 KB

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