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
  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 Will be removed in 3.0. This function is superseded by Debugger::outputError().
  182. */
  183. public static function showError($code, $description, $file = null, $line = null, $context = null) {
  184. $self = Debugger::getInstance();
  185. if (empty($file)) {
  186. $file = '[internal]';
  187. }
  188. if (empty($line)) {
  189. $line = '??';
  190. }
  191. $info = compact('code', 'description', 'file', 'line');
  192. if (!in_array($info, $self->errors)) {
  193. $self->errors[] = $info;
  194. } else {
  195. return;
  196. }
  197. switch ($code) {
  198. case E_PARSE:
  199. case E_ERROR:
  200. case E_CORE_ERROR:
  201. case E_COMPILE_ERROR:
  202. case E_USER_ERROR:
  203. $error = 'Fatal Error';
  204. $level = LOG_ERR;
  205. break;
  206. case E_WARNING:
  207. case E_USER_WARNING:
  208. case E_COMPILE_WARNING:
  209. case E_RECOVERABLE_ERROR:
  210. $error = 'Warning';
  211. $level = LOG_WARNING;
  212. break;
  213. case E_NOTICE:
  214. case E_USER_NOTICE:
  215. $error = 'Notice';
  216. $level = LOG_NOTICE;
  217. break;
  218. case E_DEPRECATED:
  219. case E_USER_DEPRECATED:
  220. $error = 'Deprecated';
  221. $level = LOG_NOTICE;
  222. break;
  223. default:
  224. return;
  225. }
  226. $data = compact(
  227. 'level', 'error', 'code', 'description', 'file', 'path', 'line', 'context'
  228. );
  229. echo $self->outputError($data);
  230. if ($error === 'Fatal Error') {
  231. exit();
  232. }
  233. return true;
  234. }
  235. /**
  236. * Outputs a stack trace based on the supplied options.
  237. *
  238. * ### Options
  239. *
  240. * - `depth` - The number of stack frames to return. Defaults to 999
  241. * - `format` - The format you want the return. Defaults to the currently selected format. If
  242. * format is 'array' or 'points' the return will be an array.
  243. * - `args` - Should arguments for functions be shown? If true, the arguments for each method call
  244. * will be displayed.
  245. * - `start` - The stack frame to start generating a trace from. Defaults to 0
  246. *
  247. * @param array $options Format for outputting stack trace
  248. * @return mixed Formatted stack trace
  249. * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::trace
  250. */
  251. public static function trace($options = array()) {
  252. $self = Debugger::getInstance();
  253. $defaults = array(
  254. 'depth' => 999,
  255. 'format' => $self->_outputFormat,
  256. 'args' => false,
  257. 'start' => 0,
  258. 'scope' => null,
  259. 'exclude' => array('call_user_func_array', 'trigger_error')
  260. );
  261. $options = Hash::merge($defaults, $options);
  262. $backtrace = debug_backtrace();
  263. $count = count($backtrace);
  264. $back = array();
  265. $_trace = array(
  266. 'line' => '??',
  267. 'file' => '[internal]',
  268. 'class' => null,
  269. 'function' => '[main]'
  270. );
  271. for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
  272. $trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
  273. $signature = $reference = '[main]';
  274. if (isset($backtrace[$i + 1])) {
  275. $next = array_merge($_trace, $backtrace[$i + 1]);
  276. $signature = $reference = $next['function'];
  277. if (!empty($next['class'])) {
  278. $signature = $next['class'] . '::' . $next['function'];
  279. $reference = $signature . '(';
  280. if ($options['args'] && isset($next['args'])) {
  281. $args = array();
  282. foreach ($next['args'] as $arg) {
  283. $args[] = Debugger::exportVar($arg);
  284. }
  285. $reference .= implode(', ', $args);
  286. }
  287. $reference .= ')';
  288. }
  289. }
  290. if (in_array($signature, $options['exclude'])) {
  291. continue;
  292. }
  293. if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
  294. $back[] = array('file' => $trace['file'], 'line' => $trace['line']);
  295. } elseif ($options['format'] === 'array') {
  296. $back[] = $trace;
  297. } else {
  298. if (isset($self->_templates[$options['format']]['traceLine'])) {
  299. $tpl = $self->_templates[$options['format']]['traceLine'];
  300. } else {
  301. $tpl = $self->_templates['base']['traceLine'];
  302. }
  303. $trace['path'] = self::trimPath($trace['file']);
  304. $trace['reference'] = $reference;
  305. unset($trace['object'], $trace['args']);
  306. $back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}'));
  307. }
  308. }
  309. if ($options['format'] === 'array' || $options['format'] === 'points') {
  310. return $back;
  311. }
  312. return implode("\n", $back);
  313. }
  314. /**
  315. * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
  316. * path with 'CORE'.
  317. *
  318. * @param string $path Path to shorten
  319. * @return string Normalized path
  320. */
  321. public static function trimPath($path) {
  322. if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) {
  323. return $path;
  324. }
  325. if (strpos($path, APP) === 0) {
  326. return str_replace(APP, 'APP' . DS, $path);
  327. } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) {
  328. return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path);
  329. } elseif (strpos($path, ROOT) === 0) {
  330. return str_replace(ROOT, 'ROOT', $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 = file_get_contents($file);
  359. if (empty($data)) {
  360. return $lines;
  361. }
  362. if (strpos($data, "\n") !== false) {
  363. $data = explode("\n", $data);
  364. }
  365. if (!isset($data[$line])) {
  366. return $lines;
  367. }
  368. for ($i = $line - ($context + 1); $i < $line + $context; $i++) {
  369. if (!isset($data[$i])) {
  370. continue;
  371. }
  372. $string = str_replace(array("\r\n", "\n"), "", self::_highlight($data[$i]));
  373. if ($i == $line) {
  374. $lines[] = '<span class="code-highlight">' . $string . '</span>';
  375. } else {
  376. $lines[] = $string;
  377. }
  378. }
  379. return $lines;
  380. }
  381. /**
  382. * Wraps the highlight_string function in case the server API does not
  383. * implement the function as it is the case of the HipHop interpreter
  384. *
  385. * @param string $str the string to convert
  386. * @return string
  387. */
  388. protected static function _highlight($str) {
  389. if (function_exists('hphp_log') || function_exists('hphp_gettid')) {
  390. return htmlentities($str);
  391. }
  392. $added = false;
  393. if (strpos($str, '<?php') === false) {
  394. $added = true;
  395. $str = "<?php \n" . $str;
  396. }
  397. $highlight = highlight_string($str, true);
  398. if ($added) {
  399. $highlight = str_replace(
  400. '&lt;?php&nbsp;<br />',
  401. '',
  402. $highlight
  403. );
  404. }
  405. return $highlight;
  406. }
  407. /**
  408. * Converts a variable to a string for debug output.
  409. *
  410. * *Note:* The following keys will have their contents
  411. * replaced with `*****`:
  412. *
  413. * - password
  414. * - login
  415. * - host
  416. * - database
  417. * - port
  418. * - prefix
  419. * - schema
  420. *
  421. * This is done to protect database credentials, which could be accidentally
  422. * shown in an error message if CakePHP is deployed in development mode.
  423. *
  424. * @param string $var Variable to convert
  425. * @param integer $depth The depth to output to. Defaults to 3.
  426. * @return string Variable as a formatted string
  427. * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar
  428. */
  429. public static function exportVar($var, $depth = 3) {
  430. return self::_export($var, $depth, 0);
  431. }
  432. /**
  433. * Protected export function used to keep track of indentation and recursion.
  434. *
  435. * @param mixed $var The variable to dump.
  436. * @param integer $depth The remaining depth.
  437. * @param integer $indent The current indentation level.
  438. * @return string The dumped variable.
  439. */
  440. protected static function _export($var, $depth, $indent) {
  441. switch (self::getType($var)) {
  442. case 'boolean':
  443. return ($var) ? 'true' : 'false';
  444. case 'integer':
  445. return '(int) ' . $var;
  446. case 'float':
  447. return '(float) ' . $var;
  448. case 'string':
  449. if (trim($var) === '') {
  450. return "''";
  451. }
  452. return "'" . $var . "'";
  453. case 'array':
  454. return self::_array($var, $depth - 1, $indent + 1);
  455. case 'resource':
  456. return strtolower(gettype($var));
  457. case 'null':
  458. return 'null';
  459. case 'unknown':
  460. return 'unknown';
  461. default:
  462. return self::_object($var, $depth - 1, $indent + 1);
  463. }
  464. }
  465. /**
  466. * Export an array type object. Filters out keys used in datasource configuration.
  467. *
  468. * The following keys are replaced with ***'s
  469. *
  470. * - password
  471. * - login
  472. * - host
  473. * - database
  474. * - port
  475. * - prefix
  476. * - schema
  477. *
  478. * @param array $var The array to export.
  479. * @param integer $depth The current depth, used for recursion tracking.
  480. * @param integer $indent The current indentation level.
  481. * @return string Exported array.
  482. */
  483. protected static function _array(array $var, $depth, $indent) {
  484. $secrets = array(
  485. 'password' => '*****',
  486. 'login' => '*****',
  487. 'host' => '*****',
  488. 'database' => '*****',
  489. 'port' => '*****',
  490. 'prefix' => '*****',
  491. 'schema' => '*****'
  492. );
  493. $replace = array_intersect_key($secrets, $var);
  494. $var = $replace + $var;
  495. $out = "array(";
  496. $n = $break = $end = null;
  497. if (!empty($var)) {
  498. $n = "\n";
  499. $break = "\n" . str_repeat("\t", $indent);
  500. $end = "\n" . str_repeat("\t", $indent - 1);
  501. }
  502. $vars = array();
  503. if ($depth >= 0) {
  504. foreach ($var as $key => $val) {
  505. // Sniff for globals as !== explodes in < 5.4
  506. if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
  507. $val = '[recursion]';
  508. } 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 integer $depth The current depth, used for tracking recursion.
  525. * @param integer $indent The current indentation level.
  526. * @return string
  527. * @see Debugger::exportVar()
  528. */
  529. protected static function _object($var, $depth, $indent) {
  530. $out = '';
  531. $props = array();
  532. $className = get_class($var);
  533. $out .= 'object(' . $className . ') {';
  534. if ($depth > 0) {
  535. $end = "\n" . str_repeat("\t", $indent - 1);
  536. $break = "\n" . str_repeat("\t", $indent);
  537. $objectVars = get_object_vars($var);
  538. foreach ($objectVars as $key => $value) {
  539. $value = self::_export($value, $depth - 1, $indent);
  540. $props[] = "$key => " . $value;
  541. }
  542. if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
  543. $ref = new ReflectionObject($var);
  544. $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 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
  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. }