Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 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('String', '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
		'log' => array(),
84
	);
85
 
86
/**
87
 * Holds current output data when outputFormat is false.
88
 *
89
 * @var string
90
 */
91
	protected $_data = array();
92
 
93
/**
94
 * Constructor.
95
 *
96
 */
97
	public function __construct() {
98
		$docRef = ini_get('docref_root');
99
 
100
		if (empty($docRef) && function_exists('ini_set')) {
101
			ini_set('docref_root', 'http://php.net/');
102
		}
103
		if (!defined('E_RECOVERABLE_ERROR')) {
104
			define('E_RECOVERABLE_ERROR', 4096);
105
		}
106
 
107
		$e = '<pre class="cake-error">';
108
		$e .= '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')';
109
		$e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == ';
110
		$e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} ';
111
		$e .= '[<b>{:path}</b>, line <b>{:line}</b>]';
112
 
113
		$e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
114
		$e .= '{:links}{:info}</div>';
115
		$e .= '</pre>';
116
		$this->_templates['js']['error'] = $e;
117
 
118
		$t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
119
		$t .= '{:context}{:code}{:trace}</div>';
120
		$this->_templates['js']['info'] = $t;
121
 
122
		$links = array();
123
		$link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')';
124
		$link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == ';
125
		$link .= '\'none\' ? \'\' : \'none\')">Code</a>';
126
		$links['code'] = $link;
127
 
128
		$link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')';
129
		$link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == ';
130
		$link .= '\'none\' ? \'\' : \'none\')">Context</a>';
131
		$links['context'] = $link;
132
 
133
		$this->_templates['js']['links'] = $links;
134
 
135
		$this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" ';
136
		$this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>';
137
 
138
		$this->_templates['js']['code'] = '<pre id="{:id}-code" class="cake-code-dump" ';
139
		$this->_templates['js']['code'] .= 'style="display: none;">{:code}</pre>';
140
 
141
		$e = '<pre class="cake-error"><b>{:error}</b> ({:code}) : {:description} ';
142
		$e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>';
143
		$this->_templates['html']['error'] = $e;
144
 
145
		$this->_templates['html']['context'] = '<pre class="cake-context"><b>Context</b> ';
146
		$this->_templates['html']['context'] .= '<p>{:context}</p></pre>';
147
	}
148
 
149
/**
150
 * Returns a reference to the Debugger singleton object instance.
151
 *
152
 * @param string $class
153
 * @return object
154
 */
155
	public static function getInstance($class = null) {
156
		static $instance = array();
157
		if (!empty($class)) {
158
			if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) {
159
				$instance[0] = new $class();
160
			}
161
		}
162
		if (!$instance) {
163
			$instance[0] = new Debugger();
164
		}
165
		return $instance[0];
166
	}
167
 
168
/**
169
 * Recursively formats and outputs the contents of the supplied variable.
170
 *
171
 *
172
 * @param mixed $var the variable to dump
173
 * @return void
174
 * @see Debugger::exportVar()
175
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::dump
176
 */
177
	public static function dump($var) {
178
		pr(self::exportVar($var));
179
	}
180
 
181
/**
182
 * Creates an entry in the log file. The log entry will contain a stack trace from where it was called.
183
 * as well as export the variable using exportVar. By default the log is written to the debug log.
184
 *
185
 * @param mixed $var Variable or content to log
186
 * @param integer $level type of log to use. Defaults to LOG_DEBUG
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) {
191
		$source = self::trace(array('start' => 1)) . "\n";
192
		CakeLog::write($level, "\n" . $source . self::exportVar($var));
193
	}
194
 
195
/**
196
 * Overrides PHP's default error handling.
197
 *
198
 * @param integer $code Code of error
199
 * @param string $description Error description
200
 * @param string $file File on which error occurred
201
 * @param integer $line Line that triggered the error
202
 * @param array $context Context
203
 * @return boolean true if error was handled
204
 * @deprecated 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'] = 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
 * 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 integer $line Line number to highlight
387
 * @param integer $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"), "", 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
 * 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 integer $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 self::_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 integer $depth The remaining depth.
479
 * @param integer $indent The current indentation level.
480
 * @return string The dumped variable.
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
 * 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 integer $depth The current depth, used for recursion tracking.
523
 * @param integer $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
		$n = $break = $end = null;
541
		if (!empty($var)) {
542
			$n = "\n";
543
			$break = "\n" . str_repeat("\t", $indent);
544
			$end = "\n" . str_repeat("\t", $indent - 1);
545
		}
546
		$vars = array();
547
 
548
		if ($depth >= 0) {
549
			foreach ($var as $key => $val) {
550
				// Sniff for globals as !== explodes in < 5.4
551
				if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
552
					$val = '[recursion]';
553
				} elseif ($val !== $var) {
554
					$val = self::_export($val, $depth, $indent);
555
				}
556
				$vars[] = $break . self::exportVar($key) .
557
					' => ' .
558
					$val;
559
			}
560
		} else {
561
			$vars[] = $break . '[maximum depth reached]';
562
		}
563
		return $out . implode(',', $vars) . $end . ')';
564
	}
565
 
566
/**
567
 * Handles object to string conversion.
568
 *
569
 * @param string $var Object to convert
570
 * @param integer $depth The current depth, used for tracking recursion.
571
 * @param integer $indent The current indentation level.
572
 * @return string
573
 * @see Debugger::exportVar()
574
 */
575
	protected static function _object($var, $depth, $indent) {
576
		$out = '';
577
		$props = array();
578
 
579
		$className = get_class($var);
580
		$out .= 'object(' . $className . ') {';
581
 
582
		if ($depth > 0) {
583
			$end = "\n" . str_repeat("\t", $indent - 1);
584
			$break = "\n" . str_repeat("\t", $indent);
585
			$objectVars = get_object_vars($var);
586
			foreach ($objectVars as $key => $value) {
587
				$value = self::_export($value, $depth - 1, $indent);
588
				$props[] = "$key => " . $value;
589
			}
590
 
591
			if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
592
				$ref = new ReflectionObject($var);
593
 
594
				$filters = array(
595
					ReflectionProperty::IS_PROTECTED => 'protected',
596
					ReflectionProperty::IS_PRIVATE => 'private',
597
				);
598
				foreach ($filters as $filter => $visibility) {
599
					$reflectionProperties = $ref->getProperties($filter);
600
					foreach ($reflectionProperties as $reflectionProperty) {
601
						$reflectionProperty->setAccessible(true);
602
						$property = $reflectionProperty->getValue($var);
603
 
604
						$value = self::_export($property, $depth - 1, $indent);
605
						$key = $reflectionProperty->name;
606
						$props[] = sprintf('[%s] %s => %s', $visibility, $key, $value);
607
					}
608
				}
609
			}
610
 
611
			$out .= $break . implode($break, $props) . $end;
612
		}
613
		$out .= '}';
614
		return $out;
615
	}
616
 
617
/**
618
 * Get/Set the output format for Debugger error rendering.
619
 *
620
 * @param string $format The format you want errors to be output as.
621
 *   Leave null to get the current format.
622
 * @return mixed Returns null when setting. Returns the current format when getting.
623
 * @throws CakeException when choosing a format that doesn't exist.
624
 */
625
	public static function outputAs($format = null) {
626
		$self = Debugger::getInstance();
627
		if ($format === null) {
628
			return $self->_outputFormat;
629
		}
630
		if ($format !== false && !isset($self->_templates[$format])) {
631
			throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
632
		}
633
		$self->_outputFormat = $format;
634
	}
635
 
636
/**
637
 * Add an output format or update a format in Debugger.
638
 *
639
 * `Debugger::addFormat('custom', $data);`
640
 *
641
 * Where $data is an array of strings that use String::insert() variable
642
 * replacement. The template vars should be in a `{:id}` style.
643
 * An error formatter can have the following keys:
644
 *
645
 * - 'error' - Used for the container for the error message. Gets the following template
646
 *   variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
647
 * - 'info' - A combination of `code`, `context` and `trace`. Will be set with
648
 *   the contents of the other template keys.
649
 * - 'trace' - The container for a stack trace. Gets the following template
650
 *   variables: `trace`
651
 * - 'context' - The container element for the context variables.
652
 *   Gets the following templates: `id`, `context`
653
 * - 'links' - An array of HTML links that are used for creating links to other resources.
654
 *   Typically this is used to create javascript links to open other sections.
655
 *   Link keys, are: `code`, `context`, `help`. See the js output format for an
656
 *   example.
657
 * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
658
 *   template variables: `reference`, `path`, `line`
659
 *
660
 * Alternatively if you want to use a custom callback to do all the formatting, you can use
661
 * the callback key, and provide a callable:
662
 *
663
 * `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));`
664
 *
665
 * The callback can expect two parameters. The first is an array of all
666
 * the error data. The second contains the formatted strings generated using
667
 * the other template strings. Keys like `info`, `links`, `code`, `context` and `trace`
668
 * will be present depending on the other templates in the format type.
669
 *
670
 * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
671
 *    straight HTML output, or 'txt' for unformatted text.
672
 * @param array $strings Template strings, or a callback to be used for the output format.
673
 * @return The resulting format string set.
674
 */
675
	public static function addFormat($format, array $strings) {
676
		$self = Debugger::getInstance();
677
		if (isset($self->_templates[$format])) {
678
			if (isset($strings['links'])) {
679
				$self->_templates[$format]['links'] = array_merge(
680
					$self->_templates[$format]['links'],
681
					$strings['links']
682
				);
683
				unset($strings['links']);
684
			}
685
			$self->_templates[$format] = array_merge($self->_templates[$format], $strings);
686
		} else {
687
			$self->_templates[$format] = $strings;
688
		}
689
		return $self->_templates[$format];
690
	}
691
 
692
/**
693
 * Switches output format, updates format strings.
694
 * Can be used to switch the active output format:
695
 *
696
 * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
697
 *    straight HTML output, or 'txt' for unformatted text.
698
 * @param array $strings Template strings to be used for the output format.
699
 * @return string
700
 * @deprecated Use Debugger::outputAs() and Debugger::addFormat(). Will be removed
701
 *   in 3.0
702
 */
703
	public function output($format = null, $strings = array()) {
704
		$self = Debugger::getInstance();
705
		$data = null;
706
 
707
		if ($format === null) {
708
			return Debugger::outputAs();
709
		}
710
 
711
		if (!empty($strings)) {
712
			return Debugger::addFormat($format, $strings);
713
		}
714
 
715
		if ($format === true && !empty($self->_data)) {
716
			$data = $self->_data;
717
			$self->_data = array();
718
			$format = false;
719
		}
720
		Debugger::outputAs($format);
721
		return $data;
722
	}
723
 
724
/**
725
 * Takes a processed array of data from an error and displays it in the chosen format.
726
 *
727
 * @param string $data
728
 * @return void
729
 */
730
	public function outputError($data) {
731
		$defaults = array(
732
			'level' => 0,
733
			'error' => 0,
734
			'code' => 0,
735
			'description' => '',
736
			'file' => '',
737
			'line' => 0,
738
			'context' => array(),
739
			'start' => 2,
740
		);
741
		$data += $defaults;
742
 
743
		$files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
744
		$code = '';
745
		$file = null;
746
		if (isset($files[0]['file'])) {
747
			$file = $files[0];
748
		} elseif (isset($files[1]['file'])) {
749
			$file = $files[1];
750
		}
751
		if ($file) {
752
			$code = $this->excerpt($file['file'], $file['line'] - 1, 1);
753
		}
754
		$trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
755
		$insertOpts = array('before' => '{:', 'after' => '}');
756
		$context = array();
757
		$links = array();
758
		$info = '';
759
 
760
		foreach ((array)$data['context'] as $var => $value) {
761
			$context[] = "\${$var} = " . $this->exportVar($value, 3);
762
		}
763
 
764
		switch ($this->_outputFormat) {
765
			case false:
766
				$this->_data[] = compact('context', 'trace') + $data;
767
				return;
768
			case 'log':
769
				$this->log(compact('context', 'trace') + $data);
770
				return;
771
		}
772
 
773
		$data['trace'] = $trace;
774
		$data['id'] = 'cakeErr' . uniqid();
775
		$tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
776
 
777
		if (isset($tpl['links'])) {
778
			foreach ($tpl['links'] as $key => $val) {
779
				$links[$key] = String::insert($val, $data, $insertOpts);
780
			}
781
		}
782
 
783
		if (!empty($tpl['escapeContext'])) {
784
			$context = h($context);
785
		}
786
 
787
		$infoData = compact('code', 'context', 'trace');
788
		foreach ($infoData as $key => $value) {
789
			if (empty($value) || !isset($tpl[$key])) {
790
				continue;
791
			}
792
			if (is_array($value)) {
793
				$value = implode("\n", $value);
794
			}
795
			$info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
796
		}
797
		$links = implode(' ', $links);
798
 
799
		if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
800
			return call_user_func($tpl['callback'], $data, compact('links', 'info'));
801
		}
802
		echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
803
	}
804
 
805
/**
806
 * Get the type of the given variable. Will return the class name
807
 * for objects.
808
 *
809
 * @param mixed $var The variable to get the type of
810
 * @return string The type of variable.
811
 */
812
	public static function getType($var) {
813
		if (is_object($var)) {
814
			return get_class($var);
815
		}
816
		if ($var === null) {
817
			return 'null';
818
		}
819
		if (is_string($var)) {
820
			return 'string';
821
		}
822
		if (is_array($var)) {
823
			return 'array';
824
		}
825
		if (is_int($var)) {
826
			return 'integer';
827
		}
828
		if (is_bool($var)) {
829
			return 'boolean';
830
		}
831
		if (is_float($var)) {
832
			return 'float';
833
		}
834
		if (is_resource($var)) {
835
			return 'resource';
836
		}
837
		return 'unknown';
838
	}
839
 
840
/**
841
 * Verifies that the application's salt and cipher seed value has been changed from the default value.
842
 *
843
 * @return void
844
 */
845
	public static function checkSecurityKeys() {
846
		if (Configure::read('Security.salt') === 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
847
			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);
848
		}
849
 
850
		if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
851
			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);
852
		}
853
	}
854
 
855
}