1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19:
20:
21: App::uses('CakeLog', 'Log');
22: App::uses('String', 'Utility');
23:
24: 25: 26: 27: 28: 29: 30: 31:
32: class Debugger {
33:
34: 35: 36: 37: 38:
39: public $errors = array();
40:
41: 42: 43: 44: 45:
46: protected $_outputFormat = 'js';
47:
48: 49: 50: 51: 52: 53:
54: protected $_templates = array(
55: 'log' => array(
56: 'trace' => '{:reference} - {:path}, line {:line}',
57: 'error' => "{:error} ({:code}): {:description} in [{:file}, line {:line}]"
58: ),
59: 'js' => array(
60: 'error' => '',
61: 'info' => '',
62: 'trace' => '<pre class="stack-trace">{:trace}</pre>',
63: 'code' => '',
64: 'context' => '',
65: 'links' => array(),
66: 'escapeContext' => true,
67: ),
68: 'html' => array(
69: 'trace' => '<pre class="cake-error trace"><b>Trace</b> <p>{:trace}</p></pre>',
70: 'context' => '<pre class="cake-error context"><b>Context</b> <p>{:context}</p></pre>',
71: 'escapeContext' => true,
72: ),
73: 'txt' => array(
74: 'error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}",
75: 'code' => '',
76: 'info' => ''
77: ),
78: 'base' => array(
79: 'traceLine' => '{:reference} - {:path}, line {:line}',
80: 'trace' => "Trace:\n{:trace}\n",
81: 'context' => "Context:\n{:context}\n",
82: )
83: );
84:
85: 86: 87: 88: 89:
90: protected $_data = array();
91:
92: 93: 94: 95:
96: public function __construct() {
97: $docRef = ini_get('docref_root');
98:
99: if (empty($docRef) && function_exists('ini_set')) {
100: ini_set('docref_root', 'http://php.net/');
101: }
102: if (!defined('E_RECOVERABLE_ERROR')) {
103: define('E_RECOVERABLE_ERROR', 4096);
104: }
105:
106: $e = '<pre class="cake-error">';
107: $e .= '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')';
108: $e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == ';
109: $e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} ';
110: $e .= '[<b>{:path}</b>, line <b>{:line}</b>]';
111:
112: $e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
113: $e .= '{:links}{:info}</div>';
114: $e .= '</pre>';
115: $this->_templates['js']['error'] = $e;
116:
117: $t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
118: $t .= '{:context}{:code}{:trace}</div>';
119: $this->_templates['js']['info'] = $t;
120:
121: $links = array();
122: $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')';
123: $link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == ';
124: $link .= '\'none\' ? \'\' : \'none\')">Code</a>';
125: $links['code'] = $link;
126:
127: $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')';
128: $link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == ';
129: $link .= '\'none\' ? \'\' : \'none\')">Context</a>';
130: $links['context'] = $link;
131:
132: $this->_templates['js']['links'] = $links;
133:
134: $this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" ';
135: $this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>';
136:
137: $this->_templates['js']['code'] = '<pre id="{:id}-code" class="cake-code-dump" ';
138: $this->_templates['js']['code'] .= 'style="display: none;">{:code}</pre>';
139:
140: $e = '<pre class="cake-error"><b>{:error}</b> ({:code}) : {:description} ';
141: $e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>';
142: $this->_templates['html']['error'] = $e;
143:
144: $this->_templates['html']['context'] = '<pre class="cake-context"><b>Context</b> ';
145: $this->_templates['html']['context'] .= '<p>{:context}</p></pre>';
146: }
147:
148: 149: 150: 151: 152: 153:
154: public static function getInstance($class = null) {
155: static $instance = array();
156: if (!empty($class)) {
157: if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) {
158: $instance[0] = new $class();
159: }
160: }
161: if (!$instance) {
162: $instance[0] = new Debugger();
163: }
164: return $instance[0];
165: }
166:
167: 168: 169: 170: 171: 172: 173: 174: 175:
176: public static function dump($var, $depth = 3) {
177: pr(self::exportVar($var, $depth));
178: }
179:
180: 181: 182: 183: 184: 185: 186: 187: 188: 189:
190: public static function log($var, $level = LOG_DEBUG, $depth = 3) {
191: $source = self::trace(array('start' => 1)) . "\n";
192: CakeLog::write($level, "\n" . $source . self::exportVar($var, $depth));
193: }
194:
195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205:
206: public static function showError($code, $description, $file = null, $line = null, $context = null) {
207: $self = Debugger::getInstance();
208:
209: if (empty($file)) {
210: $file = '[internal]';
211: }
212: if (empty($line)) {
213: $line = '??';
214: }
215:
216: $info = compact('code', 'description', 'file', 'line');
217: if (!in_array($info, $self->errors)) {
218: $self->errors[] = $info;
219: } else {
220: return;
221: }
222:
223: switch ($code) {
224: case E_PARSE:
225: case E_ERROR:
226: case E_CORE_ERROR:
227: case E_COMPILE_ERROR:
228: case E_USER_ERROR:
229: $error = 'Fatal Error';
230: $level = LOG_ERR;
231: break;
232: case E_WARNING:
233: case E_USER_WARNING:
234: case E_COMPILE_WARNING:
235: case E_RECOVERABLE_ERROR:
236: $error = 'Warning';
237: $level = LOG_WARNING;
238: break;
239: case E_NOTICE:
240: case E_USER_NOTICE:
241: $error = 'Notice';
242: $level = LOG_NOTICE;
243: break;
244: case E_DEPRECATED:
245: case E_USER_DEPRECATED:
246: $error = 'Deprecated';
247: $level = LOG_NOTICE;
248: break;
249: default:
250: return;
251: }
252:
253: $data = compact(
254: 'level', 'error', 'code', 'description', 'file', 'path', 'line', 'context'
255: );
256: echo $self->outputError($data);
257:
258: if ($error === 'Fatal Error') {
259: exit();
260: }
261: return true;
262: }
263:
264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279:
280: public static function trace($options = array()) {
281: $self = Debugger::getInstance();
282: $defaults = array(
283: 'depth' => 999,
284: 'format' => $self->_outputFormat,
285: 'args' => false,
286: 'start' => 0,
287: 'scope' => null,
288: 'exclude' => array('call_user_func_array', 'trigger_error')
289: );
290: $options = Hash::merge($defaults, $options);
291:
292: $backtrace = debug_backtrace();
293: $count = count($backtrace);
294: $back = array();
295:
296: $_trace = array(
297: 'line' => '??',
298: 'file' => '[internal]',
299: 'class' => null,
300: 'function' => '[main]'
301: );
302:
303: for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
304: $trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
305: $signature = $reference = '[main]';
306:
307: if (isset($backtrace[$i + 1])) {
308: $next = array_merge($_trace, $backtrace[$i + 1]);
309: $signature = $reference = $next['function'];
310:
311: if (!empty($next['class'])) {
312: $signature = $next['class'] . '::' . $next['function'];
313: $reference = $signature . '(';
314: if ($options['args'] && isset($next['args'])) {
315: $args = array();
316: foreach ($next['args'] as $arg) {
317: $args[] = Debugger::exportVar($arg);
318: }
319: $reference .= implode(', ', $args);
320: }
321: $reference .= ')';
322: }
323: }
324: if (in_array($signature, $options['exclude'])) {
325: continue;
326: }
327: if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
328: $back[] = array('file' => $trace['file'], 'line' => $trace['line']);
329: } elseif ($options['format'] === 'array') {
330: $back[] = $trace;
331: } else {
332: if (isset($self->_templates[$options['format']]['traceLine'])) {
333: $tpl = $self->_templates[$options['format']]['traceLine'];
334: } else {
335: $tpl = $self->_templates['base']['traceLine'];
336: }
337: $trace['path'] = self::trimPath($trace['file']);
338: $trace['reference'] = $reference;
339: unset($trace['object'], $trace['args']);
340: $back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}'));
341: }
342: }
343:
344: if ($options['format'] === 'array' || $options['format'] === 'points') {
345: return $back;
346: }
347: return implode("\n", $back);
348: }
349:
350: 351: 352: 353: 354: 355: 356:
357: public static function trimPath($path) {
358: if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) {
359: return $path;
360: }
361:
362: if (strpos($path, APP) === 0) {
363: return str_replace(APP, 'APP' . DS, $path);
364: } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) {
365: return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path);
366: } elseif (strpos($path, ROOT) === 0) {
367: return str_replace(ROOT, 'ROOT', $path);
368: }
369:
370: return $path;
371: }
372:
373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391:
392: public static function excerpt($file, $line, $context = 2) {
393: $lines = array();
394: if (!file_exists($file)) {
395: return array();
396: }
397: $data = file_get_contents($file);
398: if (empty($data)) {
399: return $lines;
400: }
401: if (strpos($data, "\n") !== false) {
402: $data = explode("\n", $data);
403: }
404: if (!isset($data[$line])) {
405: return $lines;
406: }
407: for ($i = $line - ($context + 1); $i < $line + $context; $i++) {
408: if (!isset($data[$i])) {
409: continue;
410: }
411: $string = str_replace(array("\r\n", "\n"), "", self::_highlight($data[$i]));
412: if ($i == $line) {
413: $lines[] = '<span class="code-highlight">' . $string . '</span>';
414: } else {
415: $lines[] = $string;
416: }
417: }
418: return $lines;
419: }
420:
421: 422: 423: 424: 425: 426: 427:
428: protected static function _highlight($str) {
429: if (function_exists('hphp_log') || function_exists('hphp_gettid')) {
430: return htmlentities($str);
431: }
432: $added = false;
433: if (strpos($str, '<?php') === false) {
434: $added = true;
435: $str = "<?php \n" . $str;
436: }
437: $highlight = highlight_string($str, true);
438: if ($added) {
439: $highlight = str_replace(
440: '<?php <br />',
441: '',
442: $highlight
443: );
444: }
445: return $highlight;
446: }
447:
448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469:
470: public static function exportVar($var, $depth = 3) {
471: return self::_export($var, $depth, 0);
472: }
473:
474: 475: 476: 477: 478: 479: 480: 481:
482: protected static function _export($var, $depth, $indent) {
483: switch (self::getType($var)) {
484: case 'boolean':
485: return ($var) ? 'true' : 'false';
486: case 'integer':
487: return '(int) ' . $var;
488: case 'float':
489: return '(float) ' . $var;
490: case 'string':
491: if (trim($var) === '') {
492: return "''";
493: }
494: return "'" . $var . "'";
495: case 'array':
496: return self::_array($var, $depth - 1, $indent + 1);
497: case 'resource':
498: return strtolower(gettype($var));
499: case 'null':
500: return 'null';
501: case 'unknown':
502: return 'unknown';
503: default:
504: return self::_object($var, $depth - 1, $indent + 1);
505: }
506: }
507:
508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525:
526: protected static function _array(array $var, $depth, $indent) {
527: $secrets = array(
528: 'password' => '*****',
529: 'login' => '*****',
530: 'host' => '*****',
531: 'database' => '*****',
532: 'port' => '*****',
533: 'prefix' => '*****',
534: 'schema' => '*****'
535: );
536: $replace = array_intersect_key($secrets, $var);
537: $var = $replace + $var;
538:
539: $out = "array(";
540: $break = $end = null;
541: if (!empty($var)) {
542: $break = "\n" . str_repeat("\t", $indent);
543: $end = "\n" . str_repeat("\t", $indent - 1);
544: }
545: $vars = array();
546:
547: if ($depth >= 0) {
548: foreach ($var as $key => $val) {
549:
550: if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
551: $val = '[recursion]';
552: } elseif ($val !== $var) {
553: $val = self::_export($val, $depth, $indent);
554: }
555: $vars[] = $break . self::exportVar($key) .
556: ' => ' .
557: $val;
558: }
559: } else {
560: $vars[] = $break . '[maximum depth reached]';
561: }
562: return $out . implode(',', $vars) . $end . ')';
563: }
564:
565: 566: 567: 568: 569: 570: 571: 572: 573:
574: protected static function _object($var, $depth, $indent) {
575: $out = '';
576: $props = array();
577:
578: $className = get_class($var);
579: $out .= 'object(' . $className . ') {';
580:
581: if ($depth > 0) {
582: $end = "\n" . str_repeat("\t", $indent - 1);
583: $break = "\n" . str_repeat("\t", $indent);
584: $objectVars = get_object_vars($var);
585: foreach ($objectVars as $key => $value) {
586: $value = self::_export($value, $depth - 1, $indent);
587: $props[] = "$key => " . $value;
588: }
589:
590: if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
591: $ref = new ReflectionObject($var);
592:
593: $filters = array(
594: ReflectionProperty::IS_PROTECTED => 'protected',
595: ReflectionProperty::IS_PRIVATE => 'private',
596: );
597: foreach ($filters as $filter => $visibility) {
598: $reflectionProperties = $ref->getProperties($filter);
599: foreach ($reflectionProperties as $reflectionProperty) {
600: $reflectionProperty->setAccessible(true);
601: $property = $reflectionProperty->getValue($var);
602:
603: $value = self::_export($property, $depth - 1, $indent);
604: $key = $reflectionProperty->name;
605: $props[] = sprintf('[%s] %s => %s', $visibility, $key, $value);
606: }
607: }
608: }
609:
610: $out .= $break . implode($break, $props) . $end;
611: }
612: $out .= '}';
613: return $out;
614: }
615:
616: 617: 618: 619: 620: 621: 622: 623:
624: public static function outputAs($format = null) {
625: $self = Debugger::getInstance();
626: if ($format === null) {
627: return $self->_outputFormat;
628: }
629: if ($format !== false && !isset($self->_templates[$format])) {
630: throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
631: }
632: $self->_outputFormat = $format;
633: }
634:
635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673:
674: public static function addFormat($format, array $strings) {
675: $self = Debugger::getInstance();
676: if (isset($self->_templates[$format])) {
677: if (isset($strings['links'])) {
678: $self->_templates[$format]['links'] = array_merge(
679: $self->_templates[$format]['links'],
680: $strings['links']
681: );
682: unset($strings['links']);
683: }
684: $self->_templates[$format] = array_merge($self->_templates[$format], $strings);
685: } else {
686: $self->_templates[$format] = $strings;
687: }
688: return $self->_templates[$format];
689: }
690:
691: 692: 693: 694: 695: 696: 697: 698: 699: 700: 701:
702: public static function output($format = null, $strings = array()) {
703: $self = Debugger::getInstance();
704: $data = null;
705:
706: if ($format === null) {
707: return Debugger::outputAs();
708: }
709:
710: if (!empty($strings)) {
711: return Debugger::addFormat($format, $strings);
712: }
713:
714: if ($format === true && !empty($self->_data)) {
715: $data = $self->_data;
716: $self->_data = array();
717: $format = false;
718: }
719: Debugger::outputAs($format);
720: return $data;
721: }
722:
723: 724: 725: 726: 727: 728:
729: public function outputError($data) {
730: $defaults = array(
731: 'level' => 0,
732: 'error' => 0,
733: 'code' => 0,
734: 'description' => '',
735: 'file' => '',
736: 'line' => 0,
737: 'context' => array(),
738: 'start' => 2,
739: );
740: $data += $defaults;
741:
742: $files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
743: $code = '';
744: $file = null;
745: if (isset($files[0]['file'])) {
746: $file = $files[0];
747: } elseif (isset($files[1]['file'])) {
748: $file = $files[1];
749: }
750: if ($file) {
751: $code = $this->excerpt($file['file'], $file['line'] - 1, 1);
752: }
753: $trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
754: $insertOpts = array('before' => '{:', 'after' => '}');
755: $context = array();
756: $links = array();
757: $info = '';
758:
759: foreach ((array)$data['context'] as $var => $value) {
760: $context[] = "\${$var} = " . $this->exportVar($value, 3);
761: }
762:
763: switch ($this->_outputFormat) {
764: case false:
765: $this->_data[] = compact('context', 'trace') + $data;
766: return;
767: case 'log':
768: $this->log(compact('context', 'trace') + $data);
769: return;
770: }
771:
772: $data['trace'] = $trace;
773: $data['id'] = 'cakeErr' . uniqid();
774: $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
775:
776: if (isset($tpl['links'])) {
777: foreach ($tpl['links'] as $key => $val) {
778: $links[$key] = String::insert($val, $data, $insertOpts);
779: }
780: }
781:
782: if (!empty($tpl['escapeContext'])) {
783: $context = h($context);
784: }
785:
786: $infoData = compact('code', 'context', 'trace');
787: foreach ($infoData as $key => $value) {
788: if (empty($value) || !isset($tpl[$key])) {
789: continue;
790: }
791: if (is_array($value)) {
792: $value = implode("\n", $value);
793: }
794: $info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
795: }
796: $links = implode(' ', $links);
797:
798: if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
799: return call_user_func($tpl['callback'], $data, compact('links', 'info'));
800: }
801: echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
802: }
803:
804: 805: 806: 807: 808: 809: 810:
811: public static function getType($var) {
812: if (is_object($var)) {
813: return get_class($var);
814: }
815: if ($var === null) {
816: return 'null';
817: }
818: if (is_string($var)) {
819: return 'string';
820: }
821: if (is_array($var)) {
822: return 'array';
823: }
824: if (is_int($var)) {
825: return 'integer';
826: }
827: if (is_bool($var)) {
828: return 'boolean';
829: }
830: if (is_float($var)) {
831: return 'float';
832: }
833: if (is_resource($var)) {
834: return 'resource';
835: }
836: return 'unknown';
837: }
838:
839: 840: 841: 842: 843:
844: public static function checkSecurityKeys() {
845: if (Configure::read('Security.salt') === 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
846: 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);
847: }
848:
849: if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
850: 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);
851: }
852: }
853:
854: }
855: