PageRenderTime 72ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/yii-1.1.4/framework/base/CErrorHandler.php

https://github.com/sassman/django-benchmark
PHP | 339 lines | 184 code | 22 blank | 133 comment | 35 complexity | 7c35a57ecaaca53b1dd6aefb912a0a03 MD5 | raw file
  1. <?php
  2. /**
  3. * This file contains the error handler application component.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2010 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. Yii::import('CHtml',true);
  11. /**
  12. * CErrorHandler handles uncaught PHP errors and exceptions.
  13. *
  14. * It displays these errors using appropriate views based on the
  15. * nature of the error and the mode the application runs at.
  16. * It also chooses the most preferred language for displaying the error.
  17. *
  18. * CErrorHandler uses two sets of views:
  19. * <ul>
  20. * <li>development views, named as <code>exception.php</code>;
  21. * <li>production views, named as <code>error&lt;StatusCode&gt;.php</code>;
  22. * </ul>
  23. * where &lt;StatusCode&gt; stands for the HTTP error code (e.g. error500.php).
  24. * Localized views are named similarly but located under a subdirectory
  25. * whose name is the language code (e.g. zh_cn/error500.php).
  26. *
  27. * Development views are displayed when the application is in debug mode
  28. * (i.e. YII_DEBUG is defined as true). Detailed error information with source code
  29. * are displayed in these views. Production views are meant to be shown
  30. * to end-users and are used when the application is in production mode.
  31. * For security reasons, they only display the error message without any
  32. * sensitive information.
  33. *
  34. * CErrorHandler looks for the view templates from the following locations in order:
  35. * <ol>
  36. * <li><code>themes/ThemeName/views/system</code>: when a theme is active.</li>
  37. * <li><code>protected/views/system</code></li>
  38. * <li><code>framework/views</code></li>
  39. * </ol>
  40. * If the view is not found in a directory, it will be looked for in the next directory.
  41. *
  42. * The property {@link maxSourceLines} can be changed to specify the number
  43. * of source code lines to be displayed in development views.
  44. *
  45. * CErrorHandler is a core application component that can be accessed via
  46. * {@link CApplication::getErrorHandler()}.
  47. *
  48. * @author Qiang Xue <qiang.xue@gmail.com>
  49. * @version $Id: CErrorHandler.php 2426 2010-09-05 12:51:26Z qiang.xue $
  50. * @package system.base
  51. * @since 1.0
  52. */
  53. class CErrorHandler extends CApplicationComponent
  54. {
  55. /**
  56. * @var integer maximum number source code lines to be displayed. Defaults to 25.
  57. */
  58. public $maxSourceLines=25;
  59. /**
  60. * @var string the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'.
  61. */
  62. public $adminInfo='the webmaster';
  63. /**
  64. * @var boolean whether to discard any existing page output before error display. Defaults to true.
  65. */
  66. public $discardOutput=true;
  67. /**
  68. * @var string the route (e.g. 'site/error') to the controller action that will be used to display external errors.
  69. * Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error.
  70. * This property defaults to null, meaning CErrorHandler will handle the error display.
  71. * @since 1.0.6
  72. */
  73. public $errorAction;
  74. private $_error;
  75. /**
  76. * Handles the exception/error event.
  77. * This method is invoked by the application whenever it captures
  78. * an exception or PHP error.
  79. * @param CEvent the event containing the exception/error information
  80. */
  81. public function handle($event)
  82. {
  83. // set event as handled to prevent it from being handled by other event handlers
  84. $event->handled=true;
  85. if($this->discardOutput)
  86. {
  87. while(@ob_end_clean()) ;
  88. }
  89. if($event instanceof CExceptionEvent)
  90. $this->handleException($event->exception);
  91. else // CErrorEvent
  92. $this->handleError($event);
  93. }
  94. /**
  95. * Returns the details about the error that is currently being handled.
  96. * The error is returned in terms of an array, with the following information:
  97. * <ul>
  98. * <li>code - the HTTP status code (e.g. 403, 500)</li>
  99. * <li>type - the error type (e.g. 'CHttpException', 'PHP Error')</li>
  100. * <li>message - the error message</li>
  101. * <li>file - the name of the PHP script file where the error occurs</li>
  102. * <li>line - the line number of the code where the error occurs</li>
  103. * <li>trace - the call stack of the error</li>
  104. * <li>source - the context source code where the error occurs</li>
  105. * </ul>
  106. * @return array the error details. Null if there is no error.
  107. * @since 1.0.6
  108. */
  109. public function getError()
  110. {
  111. return $this->_error;
  112. }
  113. /**
  114. * Handles the exception.
  115. * @param Exception the exception captured
  116. */
  117. protected function handleException($exception)
  118. {
  119. $app=Yii::app();
  120. if($app instanceof CWebApplication)
  121. {
  122. if(($trace=$this->getExactTrace($exception))===null)
  123. {
  124. $fileName=$exception->getFile();
  125. $errorLine=$exception->getLine();
  126. }
  127. else
  128. {
  129. $fileName=$trace['file'];
  130. $errorLine=$trace['line'];
  131. }
  132. $this->_error=$data=array(
  133. 'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
  134. 'type'=>get_class($exception),
  135. 'errorCode'=>$exception->getCode(),
  136. 'message'=>$exception->getMessage(),
  137. 'file'=>$fileName,
  138. 'line'=>$errorLine,
  139. 'trace'=>$exception->getTraceAsString(),
  140. 'source'=>$this->getSourceLines($fileName,$errorLine),
  141. );
  142. if(!headers_sent())
  143. header("HTTP/1.0 {$data['code']} ".get_class($exception));
  144. if($exception instanceof CHttpException || !YII_DEBUG)
  145. $this->render('error',$data);
  146. else
  147. $this->render('exception',$data);
  148. }
  149. else
  150. $app->displayException($exception);
  151. }
  152. /**
  153. * Handles the PHP error.
  154. * @param CErrorEvent the PHP error event
  155. */
  156. protected function handleError($event)
  157. {
  158. $trace=debug_backtrace();
  159. // skip the first 3 stacks as they do not tell the error position
  160. if(count($trace)>3)
  161. $trace=array_slice($trace,3);
  162. $traceString='';
  163. foreach($trace as $i=>$t)
  164. {
  165. if(!isset($t['file']))
  166. $t['file']='unknown';
  167. if(!isset($t['line']))
  168. $t['line']=0;
  169. if(!isset($t['function']))
  170. $t['function']='unknown';
  171. $traceString.="#$i {$t['file']}({$t['line']}): ";
  172. if(isset($t['object']) && is_object($t['object']))
  173. $traceString.=get_class($t['object']).'->';
  174. $traceString.="{$t['function']}()\n";
  175. }
  176. $app=Yii::app();
  177. if($app instanceof CWebApplication)
  178. {
  179. $this->_error=$data=array(
  180. 'code'=>500,
  181. 'type'=>'PHP Error',
  182. 'message'=>$event->message,
  183. 'file'=>$event->file,
  184. 'line'=>$event->line,
  185. 'trace'=>$traceString,
  186. 'source'=>$this->getSourceLines($event->file,$event->line),
  187. );
  188. if(!headers_sent())
  189. header("HTTP/1.0 500 PHP Error");
  190. if(YII_DEBUG)
  191. $this->render('exception',$data);
  192. else
  193. $this->render('error',$data);
  194. }
  195. else
  196. $app->displayError($event->code,$event->message,$event->file,$event->line);
  197. }
  198. /**
  199. * @param Exception the uncaught exception
  200. * @return array the exact trace where the problem occurs
  201. */
  202. protected function getExactTrace($exception)
  203. {
  204. $traces=$exception->getTrace();
  205. foreach($traces as $trace)
  206. {
  207. // property access exception
  208. if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
  209. return $trace;
  210. }
  211. return null;
  212. }
  213. /**
  214. * Renders the view.
  215. * @param string the view name (file name without extension).
  216. * See {@link getViewFile} for how a view file is located given its name.
  217. * @param array data to be passed to the view
  218. */
  219. protected function render($view,$data)
  220. {
  221. if($view==='error' && $this->errorAction!==null)
  222. Yii::app()->runController($this->errorAction);
  223. else
  224. {
  225. // additional information to be passed to view
  226. $data['version']=$this->getVersionInfo();
  227. $data['time']=time();
  228. $data['admin']=$this->adminInfo;
  229. include($this->getViewFile($view,$data['code']));
  230. }
  231. }
  232. /**
  233. * Determines which view file should be used.
  234. * @param string view name (either 'exception' or 'error')
  235. * @param integer HTTP status code
  236. * @return string view file path
  237. */
  238. protected function getViewFile($view,$code)
  239. {
  240. $viewPaths=array(
  241. Yii::app()->getTheme()===null ? null : Yii::app()->getTheme()->getSystemViewPath(),
  242. Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null,
  243. YII_PATH.DIRECTORY_SEPARATOR.'views',
  244. );
  245. foreach($viewPaths as $i=>$viewPath)
  246. {
  247. if($viewPath!==null)
  248. {
  249. $viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null);
  250. if(is_file($viewFile))
  251. return $viewFile;
  252. }
  253. }
  254. }
  255. /**
  256. * Looks for the view under the specified directory.
  257. * @param string the directory containing the views
  258. * @param string view name (either 'exception' or 'error')
  259. * @param integer HTTP status code
  260. * @param string the language that the view file is in
  261. * @return string view file path
  262. */
  263. protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null)
  264. {
  265. $app=Yii::app();
  266. if($view==='error')
  267. {
  268. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage);
  269. if(!is_file($viewFile))
  270. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
  271. }
  272. else
  273. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."exception.php",$srcLanguage);
  274. return $viewFile;
  275. }
  276. /**
  277. * @return string server version information. If the application is in production mode, nothing is returned.
  278. */
  279. protected function getVersionInfo()
  280. {
  281. if(YII_DEBUG)
  282. {
  283. $version='<a href="http://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion();
  284. if(isset($_SERVER['SERVER_SOFTWARE']))
  285. $version=$_SERVER['SERVER_SOFTWARE'].' '.$version;
  286. }
  287. else
  288. $version='';
  289. return $version;
  290. }
  291. /**
  292. * Returns the source lines around the error line.
  293. * At most {@link maxSourceLines} lines will be returned.
  294. * @param string source file path
  295. * @param integer the error line number
  296. * @return array source lines around the error line, indxed by line numbers
  297. */
  298. protected function getSourceLines($file,$line)
  299. {
  300. // determine the max number of lines to display
  301. $maxLines=$this->maxSourceLines;
  302. if($maxLines<1)
  303. $maxLines=1;
  304. else if($maxLines>100)
  305. $maxLines=100;
  306. $line--; // adjust line number to 0-based from 1-based
  307. if($line<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$line)
  308. return array();
  309. $halfLines=(int)($maxLines/2);
  310. $beginLine=$line-$halfLines>0?$line-$halfLines:0;
  311. $endLine=$line+$halfLines<$lineCount?$line+$halfLines:$lineCount-1;
  312. $sourceLines=array();
  313. for($i=$beginLine;$i<=$endLine;++$i)
  314. $sourceLines[$i+1]=$lines[$i];
  315. return $sourceLines;
  316. }
  317. }