Base for a static organization website

Debugger.php 25KB

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