Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16591 anikendra 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
 
21
App::uses('CakeLog', 'Log');
22
App::uses('CakeText', 'Utility');
23
 
24
/**
25
 * Provide custom logging and error handling.
26
 *
27
 * Debugger overrides PHP's default error handling to provide stack traces and enhanced logging
28
 *
29
 * @package       Cake.Utility
30
 * @link          http://book.cakephp.org/2.0/en/development/debugging.html#debugger-class
31
 */
32
class Debugger {
33
 
34
/**
35
 * A list of errors generated by the application.
36
 *
37
 * @var array
38
 */
39
	public $errors = array();
40
 
41
/**
42
 * The current output format.
43
 *
44
 * @var string
45
 */
46
	protected $_outputFormat = 'js';
47
 
48
/**
49
 * Templates used when generating trace or error strings. Can be global or indexed by the format
50
 * value used in $_outputFormat.
51
 *
52
 * @var string
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
 * Holds current output data when outputFormat is false.
87
 *
88
 * @var string
89
 */
90
	protected $_data = array();
91
 
92
/**
93
 * Constructor.
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
 * Returns a reference to the Debugger singleton object instance.
150
 *
151
 * @param string $class Debugger class name.
152
 * @return object
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
 * Recursively formats and outputs the contents of the supplied variable.
169
 *
170
 * @param mixed $var the variable to dump
171
 * @param int $depth The depth to output to. Defaults to 3.
172
 * @return void
173
 * @see Debugger::exportVar()
174
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::dump
175
 */
176
	public static function dump($var, $depth = 3) {
177
		pr(static::exportVar($var, $depth));
178
	}
179
 
180
/**
181
 * Creates an entry in the log file. The log entry will contain a stack trace from where it was called.
182
 * as well as export the variable using exportVar. By default the log is written to the debug log.
183
 *
184
 * @param mixed $var Variable or content to log
185
 * @param int $level type of log to use. Defaults to LOG_DEBUG
186
 * @param int $depth The depth to output to. Defaults to 3.
187
 * @return void
188
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::log
189
 */
190
	public static function log($var, $level = LOG_DEBUG, $depth = 3) {
191
		$source = static::trace(array('start' => 1)) . "\n";
192
		CakeLog::write($level, "\n" . $source . static::exportVar($var, $depth));
193
	}
194
 
195
/**
196
 * Overrides PHP's default error handling.
197
 *
198
 * @param int $code Code of error
199
 * @param string $description Error description
200
 * @param string $file File on which error occurred
201
 * @param int $line Line that triggered the error
202
 * @param array $context Context
203
 * @return bool true if error was handled
204
 * @deprecated 3.0.0 Will be removed in 3.0. This function is superseded by Debugger::outputError().
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
 * Outputs a stack trace based on the supplied options.
266
 *
267
 * ### Options
268
 *
269
 * - `depth` - The number of stack frames to return. Defaults to 999
270
 * - `format` - The format you want the return. Defaults to the currently selected format. If
271
 *    format is 'array' or 'points' the return will be an array.
272
 * - `args` - Should arguments for functions be shown?  If true, the arguments for each method call
273
 *   will be displayed.
274
 * - `start` - The stack frame to start generating a trace from. Defaults to 0
275
 *
276
 * @param array $options Format for outputting stack trace
277
 * @return mixed Formatted stack trace
278
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::trace
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'] = static::trimPath($trace['file']);
338
				$trace['reference'] = $reference;
339
				unset($trace['object'], $trace['args']);
340
				$back[] = CakeText::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
 * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
352
 * path with 'CORE'.
353
 *
354
 * @param string $path Path to shorten
355
 * @return string Normalized path
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
 * Grabs an excerpt from a file and highlights a given line of code.
375
 *
376
 * Usage:
377
 *
378
 * `Debugger::excerpt('/path/to/file', 100, 4);`
379
 *
380
 * The above would return an array of 8 items. The 4th item would be the provided line,
381
 * and would be wrapped in `<span class="code-highlight"></span>`. All of the lines
382
 * are processed with highlight_string() as well, so they have basic PHP syntax highlighting
383
 * applied.
384
 *
385
 * @param string $file Absolute path to a PHP file
386
 * @param int $line Line number to highlight
387
 * @param int $context Number of lines of context to extract above and below $line
388
 * @return array Set of lines highlighted
389
 * @see http://php.net/highlight_string
390
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::excerpt
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"), "", static::_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
 * Wraps the highlight_string function in case the server API does not
423
 * implement the function as it is the case of the HipHop interpreter
424
 *
425
 * @param string $str the string to convert
426
 * @return string
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
				'&lt;?php&nbsp;<br />',
441
				'',
442
				$highlight
443
			);
444
		}
445
		return $highlight;
446
	}
447
 
448
/**
449
 * Converts a variable to a string for debug output.
450
 *
451
 * *Note:* The following keys will have their contents
452
 * replaced with `*****`:
453
 *
454
 *  - password
455
 *  - login
456
 *  - host
457
 *  - database
458
 *  - port
459
 *  - prefix
460
 *  - schema
461
 *
462
 * This is done to protect database credentials, which could be accidentally
463
 * shown in an error message if CakePHP is deployed in development mode.
464
 *
465
 * @param string $var Variable to convert
466
 * @param int $depth The depth to output to. Defaults to 3.
467
 * @return string Variable as a formatted string
468
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar
469
 */
470
	public static function exportVar($var, $depth = 3) {
471
		return static::_export($var, $depth, 0);
472
	}
473
 
474
/**
475
 * Protected export function used to keep track of indentation and recursion.
476
 *
477
 * @param mixed $var The variable to dump.
478
 * @param int $depth The remaining depth.
479
 * @param int $indent The current indentation level.
480
 * @return string The dumped variable.
481
 */
482
	protected static function _export($var, $depth, $indent) {
483
		switch (static::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 static::_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 static::_object($var, $depth - 1, $indent + 1);
505
		}
506
	}
507
 
508
/**
509
 * Export an array type object. Filters out keys used in datasource configuration.
510
 *
511
 * The following keys are replaced with ***'s
512
 *
513
 * - password
514
 * - login
515
 * - host
516
 * - database
517
 * - port
518
 * - prefix
519
 * - schema
520
 *
521
 * @param array $var The array to export.
522
 * @param int $depth The current depth, used for recursion tracking.
523
 * @param int $indent The current indentation level.
524
 * @return string Exported array.
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
				// Sniff for globals as !== explodes in < 5.4
550
				if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
551
					$val = '[recursion]';
552
				} elseif ($val !== $var) {
553
					$val = static::_export($val, $depth, $indent);
554
				}
555
				$vars[] = $break . static::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
 * Handles object to string conversion.
567
 *
568
 * @param string $var Object to convert
569
 * @param int $depth The current depth, used for tracking recursion.
570
 * @param int $indent The current indentation level.
571
 * @return string
572
 * @see Debugger::exportVar()
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 = static::_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 = static::_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
 * Get/Set the output format for Debugger error rendering.
618
 *
619
 * @param string $format The format you want errors to be output as.
620
 *   Leave null to get the current format.
621
 * @return mixed Returns null when setting. Returns the current format when getting.
622
 * @throws CakeException when choosing a format that doesn't exist.
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
 * Add an output format or update a format in Debugger.
637
 *
638
 * `Debugger::addFormat('custom', $data);`
639
 *
640
 * Where $data is an array of strings that use CakeText::insert() variable
641
 * replacement. The template vars should be in a `{:id}` style.
642
 * An error formatter can have the following keys:
643
 *
644
 * - 'error' - Used for the container for the error message. Gets the following template
645
 *   variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
646
 * - 'info' - A combination of `code`, `context` and `trace`. Will be set with
647
 *   the contents of the other template keys.
648
 * - 'trace' - The container for a stack trace. Gets the following template
649
 *   variables: `trace`
650
 * - 'context' - The container element for the context variables.
651
 *   Gets the following templates: `id`, `context`
652
 * - 'links' - An array of HTML links that are used for creating links to other resources.
653
 *   Typically this is used to create javascript links to open other sections.
654
 *   Link keys, are: `code`, `context`, `help`. See the js output format for an
655
 *   example.
656
 * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
657
 *   template variables: `reference`, `path`, `line`
658
 *
659
 * Alternatively if you want to use a custom callback to do all the formatting, you can use
660
 * the callback key, and provide a callable:
661
 *
662
 * `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));`
663
 *
664
 * The callback can expect two parameters. The first is an array of all
665
 * the error data. The second contains the formatted strings generated using
666
 * the other template strings. Keys like `info`, `links`, `code`, `context` and `trace`
667
 * will be present depending on the other templates in the format type.
668
 *
669
 * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
670
 *    straight HTML output, or 'txt' for unformatted text.
671
 * @param array $strings Template strings, or a callback to be used for the output format.
672
 * @return The resulting format string set.
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
 * Switches output format, updates format strings.
693
 * Can be used to switch the active output format:
694
 *
695
 * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
696
 *    straight HTML output, or 'txt' for unformatted text.
697
 * @param array $strings Template strings to be used for the output format.
698
 * @return string
699
 * @deprecated 3.0.0 Use Debugger::outputAs() and Debugger::addFormat(). Will be removed
700
 *   in 3.0
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
 * Takes a processed array of data from an error and displays it in the chosen format.
725
 *
726
 * @param string $data Data to output.
727
 * @return void
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] = CakeText::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 .= CakeText::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 CakeText::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
802
	}
803
 
804
/**
805
 * Get the type of the given variable. Will return the class name
806
 * for objects.
807
 *
808
 * @param mixed $var The variable to get the type of
809
 * @return string The type of variable.
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
 * Verifies that the application's salt and cipher seed value has been changed from the default value.
841
 *
842
 * @return void
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
}