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