PageRenderTime 64ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/yii/framework/base/CErrorHandler.php

https://github.com/pittwt/myjackshop
PHP | 447 lines | 254 code | 39 blank | 154 comment | 58 complexity | a8bc9b8025742e2c9a896c873a881235 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-2011 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 3008 2011-02-26 19:54:10Z alexander.makarow $
  50. * @package system.base
  51. * @since 1.0
  52. */
  53. class CErrorHandler extends CApplicationComponent
  54. {
  55. /**
  56. * @var integer maximum number of source code lines to be displayed. Defaults to 25.
  57. */
  58. public $maxSourceLines=25;
  59. /**
  60. * @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
  61. * @since 1.1.6
  62. */
  63. public $maxTraceSourceLines = 10;
  64. /**
  65. * @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'.
  66. */
  67. public $adminInfo='the webmaster';
  68. /**
  69. * @var boolean whether to discard any existing page output before error display. Defaults to true.
  70. */
  71. public $discardOutput=true;
  72. /**
  73. * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
  74. * Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error.
  75. * This property defaults to null, meaning CErrorHandler will handle the error display.
  76. * @since 1.0.6
  77. */
  78. public $errorAction;
  79. private $_error;
  80. /**
  81. * Handles the exception/error event.
  82. * This method is invoked by the application whenever it captures
  83. * an exception or PHP error.
  84. * @param CEvent $event the event containing the exception/error information
  85. */
  86. public function handle($event)
  87. {
  88. // set event as handled to prevent it from being handled by other event handlers
  89. $event->handled=true;
  90. if($this->discardOutput)
  91. {
  92. while(@ob_end_clean()) ;
  93. }
  94. if($event instanceof CExceptionEvent)
  95. $this->handleException($event->exception);
  96. else // CErrorEvent
  97. $this->handleError($event);
  98. }
  99. /**
  100. * Returns the details about the error that is currently being handled.
  101. * The error is returned in terms of an array, with the following information:
  102. * <ul>
  103. * <li>code - the HTTP status code (e.g. 403, 500)</li>
  104. * <li>type - the error type (e.g. 'CHttpException', 'PHP Error')</li>
  105. * <li>message - the error message</li>
  106. * <li>file - the name of the PHP script file where the error occurs</li>
  107. * <li>line - the line number of the code where the error occurs</li>
  108. * <li>trace - the call stack of the error</li>
  109. * <li>source - the context source code where the error occurs</li>
  110. * </ul>
  111. * @return array the error details. Null if there is no error.
  112. * @since 1.0.6
  113. */
  114. public function getError()
  115. {
  116. return $this->_error;
  117. }
  118. /**
  119. * Handles the exception.
  120. * @param Exception $exception the exception captured
  121. */
  122. protected function handleException($exception)
  123. {
  124. $app=Yii::app();
  125. if($app instanceof CWebApplication)
  126. {
  127. if(($trace=$this->getExactTrace($exception))===null)
  128. {
  129. $fileName=$exception->getFile();
  130. $errorLine=$exception->getLine();
  131. }
  132. else
  133. {
  134. $fileName=$trace['file'];
  135. $errorLine=$trace['line'];
  136. }
  137. $trace = $exception->getTrace();
  138. foreach($trace as $i=>$t)
  139. {
  140. if(!isset($t['file']))
  141. $trace[$i]['file']='unknown';
  142. if(!isset($t['line']))
  143. $trace[$i]['line']=0;
  144. if(!isset($t['function']))
  145. $trace[$i]['function']='unknown';
  146. unset($trace[$i]['object']);
  147. }
  148. $this->_error=$data=array(
  149. 'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
  150. 'type'=>get_class($exception),
  151. 'errorCode'=>$exception->getCode(),
  152. 'message'=>$exception->getMessage(),
  153. 'file'=>$fileName,
  154. 'line'=>$errorLine,
  155. 'trace'=>$exception->getTraceAsString(),
  156. 'traces'=>$trace,
  157. );
  158. if(!headers_sent())
  159. header("HTTP/1.0 {$data['code']} ".get_class($exception));
  160. if($exception instanceof CHttpException || !YII_DEBUG)
  161. $this->render('error',$data);
  162. else if($this->isAjaxRequest())
  163. $app->displayException($exception);
  164. else
  165. $this->render('exception',$data);
  166. }
  167. else
  168. $app->displayException($exception);
  169. }
  170. /**
  171. * Handles the PHP error.
  172. * @param CErrorEvent $event the PHP error event
  173. */
  174. protected function handleError($event)
  175. {
  176. $trace=debug_backtrace();
  177. // skip the first 3 stacks as they do not tell the error position
  178. if(count($trace)>3)
  179. $trace=array_slice($trace,3);
  180. $traceString='';
  181. foreach($trace as $i=>$t)
  182. {
  183. if(!isset($t['file']))
  184. $trace[$i]['file']='unknown';
  185. if(!isset($t['line']))
  186. $trace[$i]['line']=0;
  187. if(!isset($t['function']))
  188. $trace[$i]['function']='unknown';
  189. $traceString.="#$i {$trace[$i]['file']}({$trace[$i]['line']}): ";
  190. if(isset($t['object']) && is_object($t['object']))
  191. $traceString.=get_class($t['object']).'->';
  192. $traceString.="{$trace[$i]['function']}()\n";
  193. unset($trace[$i]['object']);
  194. }
  195. $app=Yii::app();
  196. if($app instanceof CWebApplication)
  197. {
  198. $this->_error=$data=array(
  199. 'code'=>500,
  200. 'type'=>'PHP Error',
  201. 'message'=>$event->message,
  202. 'file'=>$event->file,
  203. 'line'=>$event->line,
  204. 'trace'=>$traceString,
  205. 'traces'=>$trace,
  206. );
  207. if(!headers_sent())
  208. header("HTTP/1.0 500 PHP Error");
  209. if($this->isAjaxRequest())
  210. $app->displayError($event->code,$event->message,$event->file,$event->line);
  211. else if(YII_DEBUG)
  212. $this->render('exception',$data);
  213. else
  214. $this->render('error',$data);
  215. }
  216. else
  217. $app->displayError($event->code,$event->message,$event->file,$event->line);
  218. }
  219. /**
  220. * whether the current request is an AJAX (XMLHttpRequest) request.
  221. * @return boolean whether the current request is an AJAX request.
  222. */
  223. protected function isAjaxRequest()
  224. {
  225. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  226. }
  227. /**
  228. * Returns the exact trace where the problem occurs.
  229. * @param Exception $exception the uncaught exception
  230. * @return array the exact trace where the problem occurs
  231. */
  232. protected function getExactTrace($exception)
  233. {
  234. $traces=$exception->getTrace();
  235. foreach($traces as $trace)
  236. {
  237. // property access exception
  238. if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
  239. return $trace;
  240. }
  241. return null;
  242. }
  243. /**
  244. * Renders the view.
  245. * @param string $view the view name (file name without extension).
  246. * See {@link getViewFile} for how a view file is located given its name.
  247. * @param array $data data to be passed to the view
  248. */
  249. protected function render($view,$data)
  250. {
  251. if($view==='error' && $this->errorAction!==null)
  252. Yii::app()->runController($this->errorAction);
  253. else
  254. {
  255. // additional information to be passed to view
  256. $data['version']=$this->getVersionInfo();
  257. $data['time']=time();
  258. $data['admin']=$this->adminInfo;
  259. include($this->getViewFile($view,$data['code']));
  260. }
  261. }
  262. /**
  263. * Determines which view file should be used.
  264. * @param string $view view name (either 'exception' or 'error')
  265. * @param integer $code HTTP status code
  266. * @return string view file path
  267. */
  268. protected function getViewFile($view,$code)
  269. {
  270. $viewPaths=array(
  271. Yii::app()->getTheme()===null ? null : Yii::app()->getTheme()->getSystemViewPath(),
  272. Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null,
  273. YII_PATH.DIRECTORY_SEPARATOR.'views',
  274. );
  275. foreach($viewPaths as $i=>$viewPath)
  276. {
  277. if($viewPath!==null)
  278. {
  279. $viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null);
  280. if(is_file($viewFile))
  281. return $viewFile;
  282. }
  283. }
  284. }
  285. /**
  286. * Looks for the view under the specified directory.
  287. * @param string $viewPath the directory containing the views
  288. * @param string $view view name (either 'exception' or 'error')
  289. * @param integer $code HTTP status code
  290. * @param string $srcLanguage the language that the view file is in
  291. * @return string view file path
  292. */
  293. protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null)
  294. {
  295. $app=Yii::app();
  296. if($view==='error')
  297. {
  298. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage);
  299. if(!is_file($viewFile))
  300. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
  301. }
  302. else
  303. $viewFile=$viewPath.DIRECTORY_SEPARATOR."exception.php";
  304. return $viewFile;
  305. }
  306. /**
  307. * Returns server version information.
  308. * If the application is in production mode, empty string is returned.
  309. * @return string server version information. Empty if in production mode.
  310. */
  311. protected function getVersionInfo()
  312. {
  313. if(YII_DEBUG)
  314. {
  315. $version='<a href="http://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion();
  316. if(isset($_SERVER['SERVER_SOFTWARE']))
  317. $version=$_SERVER['SERVER_SOFTWARE'].' '.$version;
  318. }
  319. else
  320. $version='';
  321. return $version;
  322. }
  323. /**
  324. * Converts arguments array to its string representation
  325. *
  326. * @param array $args arguments array to be converted
  327. * @return string string representation of the arguments array
  328. */
  329. protected function argumentsToString($args)
  330. {
  331. $count=0;
  332. foreach($args as $key => $value)
  333. {
  334. $count++;
  335. if($count>=5)
  336. {
  337. if($count>5)
  338. unset($args[$key]);
  339. else
  340. $args[$key]='...';
  341. continue;
  342. }
  343. if(is_object($value))
  344. $args[$key] = get_class($value);
  345. else if(is_bool($value))
  346. $args[$key] = $value ? 'true' : 'false';
  347. else if(is_string($value))
  348. {
  349. if(strlen($value)>64)
  350. $args[$key] = '"'.substr($value,0,64).'..."';
  351. else
  352. $args[$key] = '"'.$value.'"';
  353. }
  354. else if(is_array($value))
  355. $args[$key] = 'array('.$this->argumentsToString($value).')';
  356. else if($value===null)
  357. $args[$key] = 'null';
  358. else if(is_resource($value))
  359. $args[$key] = 'resource';
  360. if(is_string($key))
  361. $args[$key] = '"'.$key.'" => '.$args[$key];
  362. }
  363. $out = implode(", ", $args);
  364. return $out;
  365. }
  366. /**
  367. * Returns a value indicating whether the call stack is from application code.
  368. * @param array $trace the trace data
  369. * @return boolean whether the call stack is from application code.
  370. */
  371. protected function isCoreCode($trace)
  372. {
  373. if(isset($trace['file']))
  374. {
  375. $systemPath=realpath(dirname(__FILE__).'/..');
  376. return $trace['file']==='unknown' || strpos(realpath($trace['file']),$systemPath.DIRECTORY_SEPARATOR)===0;
  377. }
  378. return false;
  379. }
  380. /**
  381. * Renders the source code around the error line.
  382. * @param string $file source file path
  383. * @param integer $errorLine the error line number
  384. * @param integer $maxLines maximum number of lines to display
  385. * @return string the rendering result
  386. */
  387. protected function renderSourceCode($file,$errorLine,$maxLines)
  388. {
  389. $errorLine--; // adjust line number to 0-based from 1-based
  390. if($errorLine<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$errorLine)
  391. return '';
  392. $halfLines=(int)($maxLines/2);
  393. $beginLine=$errorLine-$halfLines>0 ? $errorLine-$halfLines:0;
  394. $endLine=$errorLine+$halfLines<$lineCount?$errorLine+$halfLines:$lineCount-1;
  395. $lineNumberWidth=strlen($endLine+1);
  396. $output='';
  397. for($i=$beginLine;$i<=$endLine;++$i)
  398. {
  399. $isErrorLine = $i===$errorLine;
  400. $code=sprintf("<span class=\"ln".($isErrorLine?' error-ln':'')."\">%0{$lineNumberWidth}d</span> %s",$i+1,CHtml::encode(str_replace("\t",' ',$lines[$i])));
  401. if(!$isErrorLine)
  402. $output.=$code;
  403. else
  404. $output.='<span class="error">'.$code.'</span>';
  405. }
  406. return '<div class="code"><pre>'.$output.'</pre></div>';
  407. }
  408. }