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.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 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
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeNumber
  • CakeTime
  • ClassRegistry
  • Debugger
  • File
  • Folder
  • Hash
  • 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: 
217:         $info = compact('code', 'description', 'file', 'line');
218:         if (!in_array($info, $self->errors)) {
219:             $self->errors[] = $info;
220:         } else {
221:             return;
222:         }
223: 
224:         switch ($code) {
225:             case E_PARSE:
226:             case E_ERROR:
227:             case E_CORE_ERROR:
228:             case E_COMPILE_ERROR:
229:             case E_USER_ERROR:
230:                 $error = 'Fatal Error';
231:                 $level = LOG_ERR;
232:             break;
233:             case E_WARNING:
234:             case E_USER_WARNING:
235:             case E_COMPILE_WARNING:
236:             case E_RECOVERABLE_ERROR:
237:                 $error = 'Warning';
238:                 $level = LOG_WARNING;
239:             break;
240:             case E_NOTICE:
241:             case E_USER_NOTICE:
242:                 $error = 'Notice';
243:                 $level = LOG_NOTICE;
244:             break;
245:             case E_DEPRECATED:
246:             case E_USER_DEPRECATED:
247:                 $error = 'Deprecated';
248:                 $level = LOG_NOTICE;
249:             break;
250:             default:
251:                 return;
252:         }
253: 
254:         $data = compact(
255:             'level', 'error', 'code', 'description', 'file', 'path', 'line', 'context'
256:         );
257:         echo $self->outputError($data);
258: 
259:         if ($error == 'Fatal Error') {
260:             exit();
261:         }
262:         return true;
263:     }
264: 
265: /**
266:  * Outputs a stack trace based on the supplied options.
267:  *
268:  * ### Options
269:  *
270:  * - `depth` - The number of stack frames to return. Defaults to 999
271:  * - `format` - The format you want the return.  Defaults to the currently selected format.  If
272:  *    format is 'array' or 'points' the return will be an array.
273:  * - `args` - Should arguments for functions be shown?  If true, the arguments for each method call
274:  *   will be displayed.
275:  * - `start` - The stack frame to start generating a trace from.  Defaults to 0
276:  *
277:  * @param array $options Format for outputting stack trace
278:  * @return mixed Formatted stack trace
279:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::trace
280:  */
281:     public static function trace($options = array()) {
282:         $self = Debugger::getInstance();
283:         $defaults = array(
284:             'depth'     => 999,
285:             'format'    => $self->_outputFormat,
286:             'args'      => false,
287:             'start'     => 0,
288:             'scope'     => null,
289:             'exclude'   => array('call_user_func_array', 'trigger_error')
290:         );
291:         $options = Hash::merge($defaults, $options);
292: 
293:         $backtrace = debug_backtrace();
294:         $count = count($backtrace);
295:         $back = array();
296: 
297:         $_trace = array(
298:             'line'     => '??',
299:             'file'     => '[internal]',
300:             'class'    => null,
301:             'function' => '[main]'
302:         );
303: 
304:         for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
305:             $trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
306:             $signature = $reference = '[main]';
307: 
308:             if (isset($backtrace[$i + 1])) {
309:                 $next = array_merge($_trace, $backtrace[$i + 1]);
310:                 $signature = $reference = $next['function'];
311: 
312:                 if (!empty($next['class'])) {
313:                     $signature = $next['class'] . '::' . $next['function'];
314:                     $reference = $signature . '(';
315:                     if ($options['args'] && isset($next['args'])) {
316:                         $args = array();
317:                         foreach ($next['args'] as $arg) {
318:                             $args[] = Debugger::exportVar($arg);
319:                         }
320:                         $reference .= join(', ', $args);
321:                     }
322:                     $reference .= ')';
323:                 }
324:             }
325:             if (in_array($signature, $options['exclude'])) {
326:                 continue;
327:             }
328:             if ($options['format'] == 'points' && $trace['file'] != '[internal]') {
329:                 $back[] = array('file' => $trace['file'], 'line' => $trace['line']);
330:             } elseif ($options['format'] == 'array') {
331:                 $back[] = $trace;
332:             } else {
333:                 if (isset($self->_templates[$options['format']]['traceLine'])) {
334:                     $tpl = $self->_templates[$options['format']]['traceLine'];
335:                 } else {
336:                     $tpl = $self->_templates['base']['traceLine'];
337:                 }
338:                 $trace['path'] = self::trimPath($trace['file']);
339:                 $trace['reference'] = $reference;
340:                 unset($trace['object'], $trace['args']);
341:                 $back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}'));
342:             }
343:         }
344: 
345:         if ($options['format'] == 'array' || $options['format'] == 'points') {
346:             return $back;
347:         }
348:         return implode("\n", $back);
349:     }
350: 
351: /**
352:  * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
353:  * path with 'CORE'.
354:  *
355:  * @param string $path Path to shorten
356:  * @return string Normalized path
357:  */
358:     public static function trimPath($path) {
359:         if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) {
360:             return $path;
361:         }
362: 
363:         if (strpos($path, APP) === 0) {
364:             return str_replace(APP, 'APP' . DS, $path);
365:         } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) {
366:             return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path);
367:         } elseif (strpos($path, ROOT) === 0) {
368:             return str_replace(ROOT, 'ROOT', $path);
369:         }
370: 
371:         return $path;
372:     }
373: 
374: /**
375:  * Grabs an excerpt from a file and highlights a given line of code.
376:  *
377:  * Usage:
378:  *
379:  * `Debugger::excerpt('/path/to/file', 100, 4);`
380:  *
381:  * The above would return an array of 8 items. The 4th item would be the provided line,
382:  * and would be wrapped in `<span class="code-highlight"></span>`.  All of the lines
383:  * are processed with highlight_string() as well, so they have basic PHP syntax highlighting
384:  * applied.
385:  *
386:  * @param string $file Absolute path to a PHP file
387:  * @param integer $line Line number to highlight
388:  * @param integer $context Number of lines of context to extract above and below $line
389:  * @return array Set of lines highlighted
390:  * @see http://php.net/highlight_string
391:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::excerpt
392:  */
393:     public static function excerpt($file, $line, $context = 2) {
394:         $lines = array();
395:         if (!file_exists($file)) {
396:             return array();
397:         }
398:         $data = file_get_contents($file);
399:         if (empty($data)) {
400:             return $lines;
401:         }
402:         if (strpos($data, "\n") !== false) {
403:             $data = explode("\n", $data);
404:         }
405:         if (!isset($data[$line])) {
406:             return $lines;
407:         }
408:         for ($i = $line - ($context + 1); $i < $line + $context; $i++) {
409:             if (!isset($data[$i])) {
410:                 continue;
411:             }
412:             $string = str_replace(array("\r\n", "\n"), "", self::_highlight($data[$i]));
413:             if ($i == $line) {
414:                 $lines[] = '<span class="code-highlight">' . $string . '</span>';
415:             } else {
416:                 $lines[] = $string;
417:             }
418:         }
419:         return $lines;
420:     }
421: 
422: /**
423:  * 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:         if (function_exists('hphp_log') || function_exists('hphp_gettid')) {
431:             return htmlentities($str);
432:         }
433:         $added = false;
434:         if (strpos($str, '<?php') === false) {
435:             $added = true;
436:             $str = "<?php \n" . $str;
437:         }
438:         $highlight = highlight_string($str, true);
439:         if ($added) {
440:             $highlight = str_replace(
441:                 '&lt;?php&nbsp;<br />',
442:                 '',
443:                 $highlight
444:             );
445:         }
446:         return $highlight;
447:     }
448: 
449: /**
450:  * Converts a variable to a string for debug output.
451:  *
452:  * *Note:* The following keys will have their contents
453:  * replaced with `*****`:
454:  *
455:  *  - password
456:  *  - login
457:  *  - host
458:  *  - database
459:  *  - port
460:  *  - prefix
461:  *  - schema
462:  *
463:  * This is done to protect database credentials, which could be accidentally
464:  * shown in an error message if CakePHP is deployed in development mode.
465:  *
466:  * @param string $var Variable to convert
467:  * @param integer $depth The depth to output to. Defaults to 3.
468:  * @return string Variable as a formatted string
469:  * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar
470:  */
471:     public static function exportVar($var, $depth = 3) {
472:         return self::_export($var, $depth, 0);
473:     }
474: 
475: /**
476:  * Protected export function used to keep track of indentation and recursion.
477:  *
478:  * @param mixed $var The variable to dump.
479:  * @param integer $depth The remaining depth.
480:  * @param integer $indent The current indentation level.
481:  * @return string The dumped variable.
482:  */
483:     protected static function _export($var, $depth, $indent) {
484:         switch (self::getType($var)) {
485:             case 'boolean':
486:                 return ($var) ? 'true' : 'false';
487:             case 'integer':
488:                 return '(int) ' . $var;
489:             case 'float':
490:                 return '(float) ' . $var;
491:             case 'string':
492:                 if (trim($var) == '') {
493:                     return "''";
494:                 }
495:                 return "'" . $var . "'";
496:             case 'array':
497:                 return self::_array($var, $depth - 1, $indent + 1);
498:             case 'resource':
499:                 return strtolower(gettype($var));
500:             case 'null':
501:                 return 'null';
502:             default:
503:                 return self::_object($var, $depth - 1, $indent + 1);
504:         }
505:     }
506: 
507: /**
508:  * Export an array type object.  Filters out keys used in datasource configuration.
509:  *
510:  * The following keys are replaced with ***'s
511:  *
512:  * - password
513:  * - login
514:  * - host
515:  * - database
516:  * - port
517:  * - prefix
518:  * - schema
519:  *
520:  * @param array $var The array to export.
521:  * @param integer $depth The current depth, used for recursion tracking.
522:  * @param integer $indent The current indentation level.
523:  * @return string Exported array.
524:  */
525:     protected static function _array(array $var, $depth, $indent) {
526:         $secrets = array(
527:             'password' => '*****',
528:             'login'  => '*****',
529:             'host' => '*****',
530:             'database' => '*****',
531:             'port' => '*****',
532:             'prefix' => '*****',
533:             'schema' => '*****'
534:         );
535:         $replace = array_intersect_key($secrets, $var);
536:         $var = $replace + $var;
537: 
538:         $out = "array(";
539:         $n = $break = $end = null;
540:         if (!empty($var)) {
541:             $n = "\n";
542:             $break = "\n" . str_repeat("\t", $indent);
543:             $end = "\n" . str_repeat("\t", $indent - 1);
544:         }
545:         $vars = array();
546: 
547:         if ($depth >= 0) {
548:             foreach ($var as $key => $val) {
549:                 // Sniff for globals as !== explodes in < 5.4
550:                 if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
551:                     $val = '[recursion]';
552:                 } else if ($val !== $var) {
553:                     $val = self::_export($val, $depth, $indent);
554:                 }
555:                 $vars[] = $break . self::exportVar($key) .
556:                     ' => ' .
557:                     $val;
558:             }
559:         } else {
560:             $vars[] = $break . '[maximum depth reached]';
561:         }
562:         return $out . implode(',', $vars) . $end . ')';
563:     }
564: 
565: /**
566:  * Handles object to string conversion.
567:  *
568:  * @param string $var Object to convert
569:  * @param integer $depth The current depth, used for tracking recursion.
570:  * @param integer $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 = self::_export($value, $depth - 1, $indent);
587:                 $props[] = "$key => " . $value;
588:             }
589:             $out .= $break . implode($break, $props) . $end;
590:         }
591:         $out .= '}';
592:         return $out;
593:     }
594: 
595: /**
596:  * Get/Set the output format for Debugger error rendering.
597:  *
598:  * @param string $format The format you want errors to be output as.
599:  *   Leave null to get the current format.
600:  * @return mixed Returns null when setting.  Returns the current format when getting.
601:  * @throws CakeException when choosing a format that doesn't exist.
602:  */
603:     public static function outputAs($format = null) {
604:         $self = Debugger::getInstance();
605:         if ($format === null) {
606:             return $self->_outputFormat;
607:         }
608:         if ($format !== false && !isset($self->_templates[$format])) {
609:             throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
610:         }
611:         $self->_outputFormat = $format;
612:     }
613: 
614: /**
615:  * Add an output format or update a format in Debugger.
616:  *
617:  * `Debugger::addFormat('custom', $data);`
618:  *
619:  * Where $data is an array of strings that use String::insert() variable
620:  * replacement.  The template vars should be in a `{:id}` style.
621:  * An error formatter can have the following keys:
622:  *
623:  * - 'error' - Used for the container for the error message. Gets the following template
624:  *   variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
625:  * - 'info' - A combination of `code`, `context` and `trace`. Will be set with
626:  *   the contents of the other template keys.
627:  * - 'trace' - The container for a stack trace. Gets the following template
628:  *   variables: `trace`
629:  * - 'context' - The container element for the context variables.
630:  *   Gets the following templates: `id`, `context`
631:  * - 'links' - An array of HTML links that are used for creating links to other resources.
632:  *   Typically this is used to create javascript links to open other sections.
633:  *   Link keys, are: `code`, `context`, `help`.  See the js output format for an
634:  *   example.
635:  * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
636:  *   template variables: `reference`, `path`, `line`
637:  *
638:  * Alternatively if you want to use a custom callback to do all the formatting, you can use
639:  * the callback key, and provide a callable:
640:  *
641:  * `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));`
642:  *
643:  * The callback can expect two parameters.  The first is an array of all
644:  * the error data. The second contains the formatted strings generated using
645:  * the other template strings.  Keys like `info`, `links`, `code`, `context` and `trace`
646:  * will be present depending on the other templates in the format type.
647:  *
648:  * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
649:  *    straight HTML output, or 'txt' for unformatted text.
650:  * @param array $strings Template strings, or a callback to be used for the output format.
651:  * @return The resulting format string set.
652:  */
653:     public static function addFormat($format, array $strings) {
654:         $self = Debugger::getInstance();
655:         if (isset($self->_templates[$format])) {
656:             if (isset($strings['links'])) {
657:                 $self->_templates[$format]['links'] = array_merge(
658:                     $self->_templates[$format]['links'],
659:                     $strings['links']
660:                 );
661:                 unset($strings['links']);
662:             }
663:             $self->_templates[$format] = array_merge($self->_templates[$format], $strings);
664:         } else {
665:             $self->_templates[$format] = $strings;
666:         }
667:         return $self->_templates[$format];
668:     }
669: 
670: /**
671:  * Switches output format, updates format strings.
672:  * Can be used to switch the active output format:
673:  *
674:  * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
675:  *    straight HTML output, or 'txt' for unformatted text.
676:  * @param array $strings Template strings to be used for the output format.
677:  * @return string
678:  * @deprecated Use Debugger::outputAs() and  Debugger::addFormat(). Will be removed
679:  *   in 3.0
680:  */
681:     public function output($format = null, $strings = array()) {
682:         $self = Debugger::getInstance();
683:         $data = null;
684: 
685:         if (is_null($format)) {
686:             return Debugger::outputAs();
687:         }
688: 
689:         if (!empty($strings)) {
690:             return Debugger::addFormat($format, $strings);
691:         }
692: 
693:         if ($format === true && !empty($self->_data)) {
694:             $data = $self->_data;
695:             $self->_data = array();
696:             $format = false;
697:         }
698:         Debugger::outputAs($format);
699:         return $data;
700:     }
701: 
702: /**
703:  * Takes a processed array of data from an error and displays it in the chosen format.
704:  *
705:  * @param string $data
706:  * @return void
707:  */
708:     public function outputError($data) {
709:         $defaults = array(
710:             'level' => 0,
711:             'error' => 0,
712:             'code' => 0,
713:             'description' => '',
714:             'file' => '',
715:             'line' => 0,
716:             'context' => array(),
717:             'start' => 2,
718:         );
719:         $data += $defaults;
720: 
721:         $files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
722:         $code = '';
723:         $file = null;
724:         if (isset($files[0]['file'])) {
725:             $file = $files[0];
726:         } elseif (isset($files[1]['file'])) {
727:             $file = $files[1];
728:         }
729:         if ($file) {
730:             $code = $this->excerpt($file['file'], $file['line'] - 1, 1);
731:         }
732:         $trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
733:         $insertOpts = array('before' => '{:', 'after' => '}');
734:         $context = array();
735:         $links = array();
736:         $info = '';
737: 
738:         foreach ((array)$data['context'] as $var => $value) {
739:             $context[] = "\${$var} = " . $this->exportVar($value, 3);
740:         }
741: 
742:         switch ($this->_outputFormat) {
743:             case false:
744:                 $this->_data[] = compact('context', 'trace') + $data;
745:                 return;
746:             case 'log':
747:                 $this->log(compact('context', 'trace') + $data);
748:                 return;
749:         }
750: 
751:         $data['trace'] = $trace;
752:         $data['id'] = 'cakeErr' . uniqid();
753:         $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
754: 
755:         if (isset($tpl['links'])) {
756:             foreach ($tpl['links'] as $key => $val) {
757:                 $links[$key] = String::insert($val, $data, $insertOpts);
758:             }
759:         }
760: 
761:         if (!empty($tpl['escapeContext'])) {
762:             $context = h($context);
763:         }
764: 
765:         $infoData = compact('code', 'context', 'trace');
766:         foreach ($infoData as $key => $value) {
767:             if (empty($value) || !isset($tpl[$key])) {
768:                 continue;
769:             }
770:             if (is_array($value)) {
771:                 $value = join("\n", $value);
772:             }
773:             $info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
774:         }
775:         $links = join(' ', $links);
776: 
777:         if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
778:             return call_user_func($tpl['callback'], $data, compact('links', 'info'));
779:         }
780:         echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
781:     }
782: 
783: /**
784:  * Get the type of the given variable. Will return the classname
785:  * for objects.
786:  *
787:  * @param mixed $var The variable to get the type of
788:  * @return string The type of variable.
789:  */
790:     public static function getType($var) {
791:         if (is_object($var)) {
792:             return get_class($var);
793:         }
794:         if (is_null($var)) {
795:             return 'null';
796:         }
797:         if (is_string($var)) {
798:             return 'string';
799:         }
800:         if (is_array($var)) {
801:             return 'array';
802:         }
803:         if (is_int($var)) {
804:             return 'integer';
805:         }
806:         if (is_bool($var)) {
807:             return 'boolean';
808:         }
809:         if (is_float($var)) {
810:             return 'float';
811:         }
812:         if (is_resource($var)) {
813:             return 'resource';
814:         }
815:         return 'unknown';
816:     }
817: 
818: /**
819:  * Verifies that the application's salt and cipher seed value has been changed from the default value.
820:  *
821:  * @return void
822:  */
823:     public static function checkSecurityKeys() {
824:         if (Configure::read('Security.salt') == 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
825:             trigger_error(__d('cake_dev', 'Please change the value of \'Security.salt\' in app/Config/core.php to a salt value specific to your application'), E_USER_NOTICE);
826:         }
827: 
828:         if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
829:             trigger_error(__d('cake_dev', 'Please change the value of \'Security.cipherSeed\' in app/Config/core.php to a numeric (digits only) seed value specific to your application'), E_USER_NOTICE);
830:         }
831:     }
832: 
833: }
834: 
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