CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.1 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeNumber
  • CakeTime
  • ClassRegistry
  • Debugger
  • File
  • Folder
  • Inflector
  • ObjectCollection
  • Sanitize
  • Security
  • Set
  • String
  • Validation
  • Xml
  1: <?php
  2: /**
  3:  * Framework debugging and PHP error-handling class
  4:  *
  5:  * Provides enhanced logging, stack traces, and rendering debug views
  6:  *
  7:  * PHP 5
  8:  *
  9:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 10:  * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 11:  *
 12:  * Licensed under The MIT License
 13:  * Redistributions of files must retain the above copyright notice.
 14:  *
 15:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 16:  * @link          http://cakephp.org CakePHP(tm) Project
 17:  * @package       Cake.Utility
 18:  * @since         CakePHP(tm) v 1.2.4560
 19:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 20:  */
 21: 
 22: App::uses('CakeLog', 'Log');
 23: App::uses('String', 'Utility');
 24: 
 25: /**
 26:  * Provide custom logging and error handling.
 27:  *
 28:  * Debugger overrides PHP's default error handling to provide stack traces and enhanced logging
 29:  *
 30:  * @package       Cake.Utility
 31:  * @link          http://book.cakephp.org/2.0/en/development/debugging.html#debugger-class
 32:  */
 33: class Debugger {
 34: 
 35: /**
 36:  * A list of errors generated by the application.
 37:  *
 38:  * @var array
 39:  */
 40:     public $errors = array();
 41: 
 42: /**
 43:  * The current output format.
 44:  *
 45:  * @var string
 46:  */
 47:     protected $_outputFormat = 'js';
 48: 
 49: /**
 50:  * Templates used when generating trace or error strings.  Can be global or indexed by the format
 51:  * value used in $_outputFormat.
 52:  *
 53:  * @var string
 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:  * Holds current output data when outputFormat is false.
 89:  *
 90:  * @var string
 91:  */
 92:     protected $_data = array();
 93: 
 94: /**
 95:  * Constructor.
 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:  * Returns a reference to the Debugger singleton object instance.
152:  *
153:  * @param string $class
154:  * @return object
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:  * Recursively formats and outputs the contents of the supplied variable.
171:  *
172:  *
173:  * @param mixed $var the variable to dump
174:  * @return void
175:  * @see Debugger::exportVar()
176:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::dump
177:  */
178:     public static function dump($var) {
179:         pr(self::exportVar($var));
180:     }
181: 
182: /**
183:  * Creates an entry in the log file.  The log entry will contain a stack trace from where it was called.
184:  * as well as export the variable using exportVar. By default the log is written to the debug log.
185:  *
186:  * @param mixed $var Variable or content to log
187:  * @param integer $level type of log to use. Defaults to LOG_DEBUG
188:  * @return void
189:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::log
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:  * Overrides PHP's default error handling.
198:  *
199:  * @param integer $code Code of error
200:  * @param string $description Error description
201:  * @param string $file File on which error occurred
202:  * @param integer $line Line that triggered the error
203:  * @param array $context Context
204:  * @return boolean true if error was handled
205:  * @deprecated This function is superseded by Debugger::outputError()
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:         $path = self::trimPath($file);
217: 
218:         $info = compact('code', 'description', 'file', 'line');
219:         if (!in_array($info, $self->errors)) {
220:             $self->errors[] = $info;
221:         } else {
222:             return;
223:         }
224: 
225:         switch ($code) {
226:             case E_PARSE:
227:             case E_ERROR:
228:             case E_CORE_ERROR:
229:             case E_COMPILE_ERROR:
230:             case E_USER_ERROR:
231:                 $error = 'Fatal Error';
232:                 $level = LOG_ERROR;
233:             break;
234:             case E_WARNING:
235:             case E_USER_WARNING:
236:             case E_COMPILE_WARNING:
237:             case E_RECOVERABLE_ERROR:
238:                 $error = 'Warning';
239:                 $level = LOG_WARNING;
240:             break;
241:             case E_NOTICE:
242:             case E_USER_NOTICE:
243:                 $error = 'Notice';
244:                 $level = LOG_NOTICE;
245:             break;
246:             case E_DEPRECATED:
247:             case E_USER_DEPRECATED:
248:                 $error = 'Deprecated';
249:                 $level = LOG_NOTICE;
250:             break;
251:             default:
252:                 return;
253:             break;
254:         }
255: 
256:         $data = compact(
257:             'level', 'error', 'code', 'description', 'file', 'path', 'line', 'context'
258:         );
259:         echo $self->outputError($data);
260: 
261:         if ($error == 'Fatal Error') {
262:             exit();
263:         }
264:         return true;
265:     }
266: 
267: /**
268:  * Outputs a stack trace based on the supplied options.
269:  *
270:  * ### Options
271:  *
272:  * - `depth` - The number of stack frames to return. Defaults to 999
273:  * - `format` - The format you want the return.  Defaults to the currently selected format.  If
274:  *    format is 'array' or 'points' the return will be an array.
275:  * - `args` - Should arguments for functions be shown?  If true, the arguments for each method call
276:  *   will be displayed.
277:  * - `start` - The stack frame to start generating a trace from.  Defaults to 0
278:  *
279:  * @param array $options Format for outputting stack trace
280:  * @return mixed Formatted stack trace
281:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::trace
282:  */
283:     public static function trace($options = array()) {
284:         $self = Debugger::getInstance();
285:         $defaults = array(
286:             'depth'     => 999,
287:             'format'    => $self->_outputFormat,
288:             'args'      => false,
289:             'start'     => 0,
290:             'scope'     => null,
291:             'exclude'   => array('call_user_func_array', 'trigger_error')
292:         );
293:         $options = Set::merge($defaults, $options);
294: 
295:         $backtrace = debug_backtrace();
296:         $count = count($backtrace);
297:         $back = array();
298: 
299:         $_trace = array(
300:             'line'     => '??',
301:             'file'     => '[internal]',
302:             'class'    => null,
303:             'function' => '[main]'
304:         );
305: 
306:         for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
307:             $trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
308:             $signature = $reference = '[main]';
309: 
310:             if (isset($backtrace[$i + 1])) {
311:                 $next = array_merge($_trace, $backtrace[$i + 1]);
312:                 $signature = $reference = $next['function'];
313: 
314:                 if (!empty($next['class'])) {
315:                     $signature = $next['class'] . '::' . $next['function'];
316:                     $reference = $signature . '(';
317:                     if ($options['args'] && isset($next['args'])) {
318:                         $args = array();
319:                         foreach ($next['args'] as $arg) {
320:                             $args[] = Debugger::exportVar($arg);
321:                         }
322:                         $reference .= join(', ', $args);
323:                     }
324:                     $reference .= ')';
325:                 }
326:             }
327:             if (in_array($signature, $options['exclude'])) {
328:                 continue;
329:             }
330:             if ($options['format'] == 'points' && $trace['file'] != '[internal]') {
331:                 $back[] = array('file' => $trace['file'], 'line' => $trace['line']);
332:             } elseif ($options['format'] == 'array') {
333:                 $back[] = $trace;
334:             } else {
335:                 if (isset($self->_templates[$options['format']]['traceLine'])) {
336:                     $tpl = $self->_templates[$options['format']]['traceLine'];
337:                 } else {
338:                     $tpl = $self->_templates['base']['traceLine'];
339:                 }
340:                 $trace['path'] = self::trimPath($trace['file']);
341:                 $trace['reference'] = $reference;
342:                 unset($trace['object'], $trace['args']);
343:                 $back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}'));
344:             }
345:         }
346: 
347:         if ($options['format'] == 'array' || $options['format'] == 'points') {
348:             return $back;
349:         }
350:         return implode("\n", $back);
351:     }
352: 
353: /**
354:  * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
355:  * path with 'CORE'.
356:  *
357:  * @param string $path Path to shorten
358:  * @return string Normalized path
359:  */
360:     public static function trimPath($path) {
361:         if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) {
362:             return $path;
363:         }
364: 
365:         if (strpos($path, APP) === 0) {
366:             return str_replace(APP, 'APP' . DS, $path);
367:         } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) {
368:             return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path);
369:         } elseif (strpos($path, ROOT) === 0) {
370:             return str_replace(ROOT, 'ROOT', $path);
371:         }
372: 
373:         if (strpos($path, CAKE) === 0) {
374:             return str_replace($corePath, 'CORE' . DS, $path);
375:         }
376:         return $path;
377:     }
378: 
379: /**
380:  * Grabs an excerpt from a file and highlights a given line of code.
381:  *
382:  * Usage:
383:  *
384:  * `Debugger::excerpt('/path/to/file', 100, 4);`
385:  *
386:  * The above would return an array of 8 items. The 4th item would be the provided line,
387:  * and would be wrapped in `<span class="code-highlight"></span>`.  All of the lines
388:  * are processed with highlight_string() as well, so they have basic PHP syntax highlighting
389:  * applied.
390:  *
391:  * @param string $file Absolute path to a PHP file
392:  * @param integer $line Line number to highlight
393:  * @param integer $context Number of lines of context to extract above and below $line
394:  * @return array Set of lines highlighted
395:  * @see http://php.net/highlight_string
396:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::excerpt
397:  */
398:     public static function excerpt($file, $line, $context = 2) {
399:         $lines = array();
400:         if (!file_exists($file)) {
401:             return array();
402:         }
403:         $data = @explode("\n", file_get_contents($file));
404: 
405:         if (empty($data) || !isset($data[$line])) {
406:             return;
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:  * Wraps the highlight_string funciton in case the server API does not
424:  * implement the function as it is the case of the HipHop interpreter
425:  *
426:  * @param string $str the string to convert
427:  * @return string
428:  */
429:     protected static function _highlight($str) {
430:         static $supportHighlight = null;
431:         if (!$supportHighlight && function_exists('hphp_log')) {
432:             $supportHighlight = false;
433:             return htmlentities($str);
434:         }
435:         $supportHighlight = true;
436:         return highlight_string($str, true);
437:     }
438: 
439: /**
440:  * Converts a variable to a string for debug output.
441:  *
442:  * *Note:* The following keys will have their contents
443:  * replaced with `*****`:
444:  *
445:  *  - password
446:  *  - login
447:  *  - host
448:  *  - database
449:  *  - port
450:  *  - prefix
451:  *  - schema
452:  *
453:  * This is done to protect database credentials, which could be accidentally
454:  * shown in an error message if CakePHP is deployed in development mode.
455:  *
456:  * @param string $var Variable to convert
457:  * @param integer $depth The depth to output to. Defaults to 3.
458:  * @return string Variable as a formatted string
459:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar
460:  */
461:     public static function exportVar($var, $depth = 3) {
462:         return self::_export($var, $depth, 0);
463:     }
464: 
465: /**
466:  * Protected export function used to keep track of indentation and recursion.
467:  *
468:  * @param mixed $var The variable to dump.
469:  * @param integer $depth The remaining depth.
470:  * @param integer $indent The current indentation level.
471:  * @return string The dumped variable.
472:  */
473:     protected static function _export($var, $depth, $indent) {
474:         switch (self::getType($var)) {
475:             case 'boolean':
476:                 return ($var) ? 'true' : 'false';
477:             break;
478:             case 'integer':
479:                 return '(int) ' . $var;
480:             case 'float':
481:                 return '(float) ' . $var;
482:             break;
483:             case 'string':
484:                 if (trim($var) == '') {
485:                     return "''";
486:                 }
487:                 return "'" . $var . "'";
488:             break;
489:             case 'array':
490:                 return self::_array($var, $depth - 1, $indent + 1);
491:             break;
492:             case 'resource':
493:                 return strtolower(gettype($var));
494:             break;
495:             case 'null':
496:                 return 'null';
497:             default:
498:                 return self::_object($var, $depth - 1, $indent + 1);
499:             break;
500:         }
501:     }
502: 
503: /**
504:  * Export an array type object.  Filters out keys used in datasource configuration.
505:  *
506:  * The following keys are replaced with ***'s
507:  *
508:  * - password
509:  * - login
510:  * - host
511:  * - database
512:  * - port
513:  * - prefix
514:  * - schema
515:  *
516:  * @param array $var The array to export.
517:  * @param integer $depth The current depth, used for recursion tracking.
518:  * @param integer $indent The current indentation level.
519:  * @return string Exported array.
520:  */
521:     protected static function _array(array $var, $depth, $indent) {
522:         $secrets = array(
523:             'password' => '*****',
524:             'login'  => '*****',
525:             'host' => '*****',
526:             'database' => '*****',
527:             'port' => '*****',
528:             'prefix' => '*****',
529:             'schema' => '*****'
530:         );
531:         $replace = array_intersect_key($secrets, $var);
532:         $var = $replace + $var;
533: 
534:         $out = "array(";
535:         $n = $break = $end = null;
536:         if (!empty($var)) {
537:             $n = "\n";
538:             $break = "\n" . str_repeat("\t", $indent);
539:             $end = "\n" . str_repeat("\t", $indent - 1);
540:         }
541:         $vars = array();
542: 
543:         if ($depth >= 0) {
544:             foreach ($var as $key => $val) {
545:                 $vars[] = $break . self::exportVar($key) .
546:                     ' => ' .
547:                     self::_export($val, $depth, $indent);
548:             }
549:         } else {
550:             $vars[] = $break . '[maximum depth reached]';
551:         }
552:         return $out . implode(',', $vars) . $end . ')';
553:     }
554: 
555: /**
556:  * Handles object to string conversion.
557:  *
558:  * @param string $var Object to convert
559:  * @param integer $depth The current depth, used for tracking recursion.
560:  * @param integer $indent The current indentation level.
561:  * @return string
562:  * @see Debugger::exportVar()
563:  */
564:     protected static function _object($var, $depth, $indent) {
565:         $out = '';
566:         $props = array();
567: 
568:         $className = get_class($var);
569:         $out .= 'object(' . $className . ') {';
570: 
571:         if ($depth > 0) {
572:             $end = "\n" . str_repeat("\t", $indent - 1);
573:             $break = "\n" . str_repeat("\t", $indent);
574:             $objectVars = get_object_vars($var);
575:             foreach ($objectVars as $key => $value) {
576:                 $value = self::_export($value, $depth - 1, $indent);
577:                 $props[] = "$key => " . $value;
578:             }
579:             $out .= $break . implode($break, $props) . $end;
580:         }
581:         $out .= '}';
582:         return $out;
583:     }
584: 
585: /**
586:  * Get/Set the output format for Debugger error rendering.
587:  *
588:  * @param string $format The format you want errors to be output as.
589:  *   Leave null to get the current format.
590:  * @return mixed Returns null when setting.  Returns the current format when getting.
591:  * @throws CakeException when choosing a format that doesn't exist.
592:  */
593:     public static function outputAs($format = null) {
594:         $self = Debugger::getInstance();
595:         if ($format === null) {
596:             return $self->_outputFormat;
597:         }
598:         if ($format !== false && !isset($self->_templates[$format])) {
599:             throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
600:         }
601:         $self->_outputFormat = $format;
602:     }
603: 
604: /**
605:  * Add an output format or update a format in Debugger.
606:  *
607:  * `Debugger::addFormat('custom', $data);`
608:  *
609:  * Where $data is an array of strings that use String::insert() variable
610:  * replacement.  The template vars should be in a `{:id}` style.
611:  * An error formatter can have the following keys:
612:  *
613:  * - 'error' - Used for the container for the error message. Gets the following template
614:  *   variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
615:  * - 'info' - A combination of `code`, `context` and `trace`. Will be set with
616:  *   the contents of the other template keys.
617:  * - 'trace' - The container for a stack trace. Gets the following template
618:  *   variables: `trace`
619:  * - 'context' - The container element for the context variables.
620:  *   Gets the following templates: `id`, `context`
621:  * - 'links' - An array of HTML links that are used for creating links to other resources.
622:  *   Typically this is used to create javascript links to open other sections.
623:  *   Link keys, are: `code`, `context`, `help`.  See the js output format for an
624:  *   example.
625:  * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
626:  *   template variables: `reference`, `path`, `line`
627:  *
628:  * Alternatively if you want to use a custom callback to do all the formatting, you can use
629:  * the callback key, and provide a callable:
630:  *
631:  * `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));`
632:  *
633:  * The callback can expect two parameters.  The first is an array of all
634:  * the error data. The second contains the formatted strings generated using
635:  * the other template strings.  Keys like `info`, `links`, `code`, `context` and `trace`
636:  * will be present depending on the other templates in the format type.
637:  *
638:  * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
639:  *    straight HTML output, or 'txt' for unformatted text.
640:  * @param array $strings Template strings, or a callback to be used for the output format.
641:  * @return The resulting format string set.
642:  */
643:     public static function addFormat($format, array $strings) {
644:         $self = Debugger::getInstance();
645:         if (isset($self->_templates[$format])) {
646:             if (isset($strings['links'])) {
647:                 $self->_templates[$format]['links'] = array_merge(
648:                     $self->_templates[$format]['links'],
649:                     $strings['links']
650:                 );
651:                 unset($strings['links']);
652:             }
653:             $self->_templates[$format] = array_merge($self->_templates[$format], $strings);
654:         } else {
655:             $self->_templates[$format] = $strings;
656:         }
657:         return $self->_templates[$format];
658:     }
659: 
660: /**
661:  * Switches output format, updates format strings.
662:  * Can be used to switch the active output format:
663:  *
664:  * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
665:  *    straight HTML output, or 'txt' for unformatted text.
666:  * @param array $strings Template strings to be used for the output format.
667:  * @return string
668:  * @deprecated Use Debugger::outputAs() and  Debugger::addFormat(). Will be removed
669:  *   in 3.0
670:  */
671:     public function output($format = null, $strings = array()) {
672:         $self = Debugger::getInstance();
673:         $data = null;
674: 
675:         if (is_null($format)) {
676:             return Debugger::outputAs();
677:         }
678: 
679:         if (!empty($strings)) {
680:             return Debugger::addFormat($format, $strings);
681:         }
682: 
683:         if ($format === true && !empty($self->_data)) {
684:             $data = $self->_data;
685:             $self->_data = array();
686:             $format = false;
687:         }
688:         Debugger::outputAs($format);
689:         return $data;
690:     }
691: 
692: /**
693:  * Takes a processed array of data from an error and displays it in the chosen format.
694:  *
695:  * @param string $data
696:  * @return void
697:  */
698:     public function outputError($data) {
699:         $defaults = array(
700:             'level' => 0,
701:             'error' => 0,
702:             'code' => 0,
703:             'description' => '',
704:             'file' => '',
705:             'line' => 0,
706:             'context' => array(),
707:             'start' => 2,
708:         );
709:         $data += $defaults;
710: 
711:         $files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
712:         $code = '';
713:         if (isset($files[1]['file'])) {
714:             $code = $this->excerpt($files[1]['file'], $files[1]['line'] - 1, 1);
715:         }
716:         $trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
717:         $insertOpts = array('before' => '{:', 'after' => '}');
718:         $context = array();
719:         $links = array();
720:         $info = '';
721: 
722:         foreach ((array)$data['context'] as $var => $value) {
723:             $context[] = "\${$var} = " . $this->exportVar($value, 1);
724:         }
725: 
726:         switch ($this->_outputFormat) {
727:             case false:
728:                 $this->_data[] = compact('context', 'trace') + $data;
729:                 return;
730:             case 'log':
731:                 $this->log(compact('context', 'trace') + $data);
732:                 return;
733:         }
734: 
735:         $data['trace'] = $trace;
736:         $data['id'] = 'cakeErr' . uniqid();
737:         $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
738: 
739:         if (isset($tpl['links'])) {
740:             foreach ($tpl['links'] as $key => $val) {
741:                 $links[$key] = String::insert($val, $data, $insertOpts);
742:             }
743:         }
744: 
745:         if (!empty($tpl['escapeContext'])) {
746:             $context = h($context);
747:         }
748: 
749:         $infoData = compact('code', 'context', 'trace');
750:         foreach ($infoData as $key => $value) {
751:             if (empty($value) || !isset($tpl[$key])) {
752:                 continue;
753:             }
754:             if (is_array($value)) {
755:                 $value = join("\n", $value);
756:             }
757:             $info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
758:         }
759:         $links = join(' ', $links);
760: 
761:         if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
762:             return call_user_func($tpl['callback'], $data, compact('links', 'info'));
763:         }
764:         echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
765:     }
766: 
767: /**
768:  * Get the type of the given variable. Will return the classname
769:  * for objects.
770:  *
771:  * @param mixed $var The variable to get the type of
772:  * @return string The type of variable.
773:  */
774:     public static function getType($var) {
775:         if (is_object($var)) {
776:             return get_class($var);
777:         }
778:         if (is_null($var)) {
779:             return 'null';
780:         }
781:         if (is_string($var)) {
782:             return 'string';
783:         }
784:         if (is_array($var)) {
785:             return 'array';
786:         }
787:         if (is_int($var)) {
788:             return 'integer';
789:         }
790:         if (is_bool($var)) {
791:             return 'boolean';
792:         }
793:         if (is_float($var)) {
794:             return 'float';
795:         }
796:         if (is_resource($var)) {
797:             return 'resource';
798:         }
799:         return 'unknown';
800:     }
801: 
802: /**
803:  * Verifies that the application's salt and cipher seed value has been changed from the default value.
804:  *
805:  * @return void
806:  */
807:     public static function checkSecurityKeys() {
808:         if (Configure::read('Security.salt') == 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
809:             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);
810:         }
811: 
812:         if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
813:             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);
814:         }
815:     }
816: 
817: }
818: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs