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('CakeText', '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: public function __construct() {
96: $docRef = ini_get('docref_root');
97:
98: if (empty($docRef) && function_exists('ini_set')) {
99: ini_set('docref_root', 'http://php.net/');
100: }
101: if (!defined('E_RECOVERABLE_ERROR')) {
102: define('E_RECOVERABLE_ERROR', 4096);
103: }
104:
105: $e = '<pre class="cake-error">';
106: $e .= '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')';
107: $e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == ';
108: $e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} ';
109: $e .= '[<b>{:path}</b>, line <b>{:line}</b>]';
110:
111: $e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
112: $e .= '{:links}{:info}</div>';
113: $e .= '</pre>';
114: $this->_templates['js']['error'] = $e;
115:
116: $t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
117: $t .= '{:context}{:code}{:trace}</div>';
118: $this->_templates['js']['info'] = $t;
119:
120: $links = array();
121: $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')';
122: $link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == ';
123: $link .= '\'none\' ? \'\' : \'none\')">Code</a>';
124: $links['code'] = $link;
125:
126: $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')';
127: $link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == ';
128: $link .= '\'none\' ? \'\' : \'none\')">Context</a>';
129: $links['context'] = $link;
130:
131: $this->_templates['js']['links'] = $links;
132:
133: $this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" ';
134: $this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>';
135:
136: $this->_templates['js']['code'] = '<pre id="{:id}-code" class="cake-code-dump" ';
137: $this->_templates['js']['code'] .= 'style="display: none;">{:code}</pre>';
138:
139: $e = '<pre class="cake-error"><b>{:error}</b> ({:code}) : {:description} ';
140: $e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>';
141: $this->_templates['html']['error'] = $e;
142:
143: $this->_templates['html']['context'] = '<pre class="cake-context"><b>Context</b> ';
144: $this->_templates['html']['context'] .= '<p>{:context}</p></pre>';
145: }
146:
147: 148: 149: 150: 151: 152:
153: public static function getInstance($class = null) {
154: static $instance = array();
155: if (!empty($class)) {
156: if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) {
157: $instance[0] = new $class();
158: }
159: }
160: if (!$instance) {
161: $instance[0] = new Debugger();
162: }
163: return $instance[0];
164: }
165:
166: 167: 168: 169: 170: 171: 172: 173: 174:
175: public static function dump($var, $depth = 3) {
176: pr(static::exportVar($var, $depth));
177: }
178:
179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190:
191: public static function log($var, $level = LOG_DEBUG, $depth = 3) {
192: $source = static::trace(array('start' => 1)) . "\n";
193: CakeLog::write($level, "\n" . $source . static::exportVar($var, $depth));
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 null;
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 null;
252: }
253:
254: $data = compact(
255: 'level', 'error', 'code', 'description', 'file', '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 .= implode(', ', $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'] = static::trimPath($trace['file']);
339: $trace['reference'] = $reference;
340: unset($trace['object'], $trace['args']);
341: $back[] = CakeText::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"), "", static::_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: public static function exportVar($var, $depth = 3) {
470: return static::_export($var, $depth, 0);
471: }
472:
473: 474: 475: 476: 477: 478: 479: 480:
481: protected static function _export($var, $depth, $indent) {
482: switch (static::getType($var)) {
483: case 'boolean':
484: return ($var) ? 'true' : 'false';
485: case 'integer':
486: return '(int) ' . $var;
487: case 'float':
488: return '(float) ' . $var;
489: case 'string':
490: if (trim($var) === '') {
491: return "''";
492: }
493: return "'" . $var . "'";
494: case 'array':
495: return static::_array($var, $depth - 1, $indent + 1);
496: case 'resource':
497: return strtolower(gettype($var));
498: case 'null':
499: return 'null';
500: case 'unknown':
501: return 'unknown';
502: default:
503: return static::_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: protected static function _array(array $var, $depth, $indent) {
524: $secrets = array(
525: 'password' => '*****',
526: 'login' => '*****',
527: 'host' => '*****',
528: 'database' => '*****',
529: 'port' => '*****'
530: );
531: $replace = array_intersect_key($secrets, $var);
532: $var = $replace + $var;
533:
534: $out = "array(";
535: $break = $end = null;
536: if (!empty($var)) {
537: $break = "\n" . str_repeat("\t", $indent);
538: $end = "\n" . str_repeat("\t", $indent - 1);
539: }
540: $vars = array();
541:
542: if ($depth >= 0) {
543: foreach ($var as $key => $val) {
544:
545: if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
546: $val = '[recursion]';
547: } elseif ($val !== $var) {
548: $val = static::_export($val, $depth, $indent);
549: }
550: $vars[] = $break . static::exportVar($key) .
551: ' => ' .
552: $val;
553: }
554: } else {
555: $vars[] = $break . '[maximum depth reached]';
556: }
557: return $out . implode(',', $vars) . $end . ')';
558: }
559:
560: 561: 562: 563: 564: 565: 566: 567: 568:
569: protected static function _object($var, $depth, $indent) {
570: $out = '';
571: $props = array();
572:
573: $className = get_class($var);
574: $out .= 'object(' . $className . ') {';
575:
576: if ($depth > 0) {
577: $end = "\n" . str_repeat("\t", $indent - 1);
578: $break = "\n" . str_repeat("\t", $indent);
579: $objectVars = get_object_vars($var);
580: foreach ($objectVars as $key => $value) {
581: $value = static::_export($value, $depth - 1, $indent);
582: $props[] = "$key => " . $value;
583: }
584:
585: if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
586: $ref = new ReflectionObject($var);
587:
588: $filters = array(
589: ReflectionProperty::IS_PROTECTED => 'protected',
590: ReflectionProperty::IS_PRIVATE => 'private',
591: );
592: foreach ($filters as $filter => $visibility) {
593: $reflectionProperties = $ref->getProperties($filter);
594: foreach ($reflectionProperties as $reflectionProperty) {
595: $reflectionProperty->setAccessible(true);
596: $property = $reflectionProperty->getValue($var);
597:
598: $value = static::_export($property, $depth - 1, $indent);
599: $key = $reflectionProperty->name;
600: $props[] = sprintf('[%s] %s => %s', $visibility, $key, $value);
601: }
602: }
603: }
604:
605: $out .= $break . implode($break, $props) . $end;
606: }
607: $out .= '}';
608: return $out;
609: }
610:
611: 612: 613: 614: 615: 616: 617: 618:
619: public static function outputAs($format = null) {
620: $self = Debugger::getInstance();
621: if ($format === null) {
622: return $self->_outputFormat;
623: }
624: if ($format !== false && !isset($self->_templates[$format])) {
625: throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
626: }
627: $self->_outputFormat = $format;
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: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668:
669: public static function addFormat($format, array $strings) {
670: $self = Debugger::getInstance();
671: if (isset($self->_templates[$format])) {
672: if (isset($strings['links'])) {
673: $self->_templates[$format]['links'] = array_merge(
674: $self->_templates[$format]['links'],
675: $strings['links']
676: );
677: unset($strings['links']);
678: }
679: $self->_templates[$format] = array_merge($self->_templates[$format], $strings);
680: } else {
681: $self->_templates[$format] = $strings;
682: }
683: return $self->_templates[$format];
684: }
685:
686: 687: 688: 689: 690: 691: 692: 693: 694: 695: 696:
697: public static function output($format = null, $strings = array()) {
698: $self = Debugger::getInstance();
699: $data = null;
700:
701: if ($format === null) {
702: return Debugger::outputAs();
703: }
704:
705: if (!empty($strings)) {
706: return Debugger::addFormat($format, $strings);
707: }
708:
709: if ($format === true && !empty($self->_data)) {
710: $data = $self->_data;
711: $self->_data = array();
712: $format = false;
713: }
714: Debugger::outputAs($format);
715: return $data;
716: }
717:
718: 719: 720: 721: 722: 723:
724: public function outputError($data) {
725: $defaults = array(
726: 'level' => 0,
727: 'error' => 0,
728: 'code' => 0,
729: 'description' => '',
730: 'file' => '',
731: 'line' => 0,
732: 'context' => array(),
733: 'start' => 2,
734: );
735: $data += $defaults;
736:
737: $files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
738: $code = '';
739: $file = null;
740: if (isset($files[0]['file'])) {
741: $file = $files[0];
742: } elseif (isset($files[1]['file'])) {
743: $file = $files[1];
744: }
745: if ($file) {
746: $code = $this->excerpt($file['file'], $file['line'] - 1, 1);
747: }
748: $trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
749: $insertOpts = array('before' => '{:', 'after' => '}');
750: $context = array();
751: $links = array();
752: $info = '';
753:
754: foreach ((array)$data['context'] as $var => $value) {
755: $context[] = "\${$var} = " . $this->exportVar($value, 3);
756: }
757:
758: switch ($this->_outputFormat) {
759: case false:
760: $this->_data[] = compact('context', 'trace') + $data;
761: return;
762: case 'log':
763: $this->log(compact('context', 'trace') + $data);
764: return;
765: }
766:
767: $data['trace'] = $trace;
768: $data['id'] = 'cakeErr' . uniqid();
769: $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
770:
771: if (isset($tpl['links'])) {
772: foreach ($tpl['links'] as $key => $val) {
773: $links[$key] = CakeText::insert($val, $data, $insertOpts);
774: }
775: }
776:
777: if (!empty($tpl['escapeContext'])) {
778: $context = h($context);
779: $data['description'] = h($data['description']);
780: }
781:
782: $infoData = compact('code', 'context', 'trace');
783: foreach ($infoData as $key => $value) {
784: if (empty($value) || !isset($tpl[$key])) {
785: continue;
786: }
787: if (is_array($value)) {
788: $value = implode("\n", $value);
789: }
790: $info .= CakeText::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
791: }
792: $links = implode(' ', $links);
793:
794: if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
795: return call_user_func($tpl['callback'], $data, compact('links', 'info'));
796: }
797: echo CakeText::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
798: }
799:
800: 801: 802: 803: 804: 805: 806:
807: public static function getType($var) {
808: if (is_object($var)) {
809: return get_class($var);
810: }
811: if ($var === null) {
812: return 'null';
813: }
814: if (is_string($var)) {
815: return 'string';
816: }
817: if (is_array($var)) {
818: return 'array';
819: }
820: if (is_int($var)) {
821: return 'integer';
822: }
823: if (is_bool($var)) {
824: return 'boolean';
825: }
826: if (is_float($var)) {
827: return 'float';
828: }
829: if (is_resource($var)) {
830: return 'resource';
831: }
832: return 'unknown';
833: }
834:
835: 836: 837: 838: 839:
840: public static function checkSecurityKeys() {
841: if (Configure::read('Security.salt') === 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
842: trigger_error(__d('cake_dev', 'Please change the value of %s in %s to a salt value specific to your application.', '\'Security.salt\'', CONFIG . 'core.php'), E_USER_NOTICE);
843: }
844:
845: if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
846: 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\'', CONFIG . 'core.php'), E_USER_NOTICE);
847: }
848: }
849:
850: }
851: