Debugger.php 25 KB

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