CErrorHandler.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 2008-2013 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. * @property array $error The error details. Null if there is no error.
  49. * @property Exception|null $exception exception instance. Null if there is no exception.
  50. *
  51. * @author Qiang Xue <qiang.xue@gmail.com>
  52. * @package system.base
  53. * @since 1.0
  54. */
  55. class CErrorHandler extends CApplicationComponent
  56. {
  57. /**
  58. * @var integer maximum number of source code lines to be displayed. Defaults to 25.
  59. */
  60. public $maxSourceLines=25;
  61. /**
  62. * @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
  63. * @since 1.1.6
  64. */
  65. public $maxTraceSourceLines = 10;
  66. /**
  67. * @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'.
  68. */
  69. public $adminInfo='the webmaster';
  70. /**
  71. * @var boolean whether to discard any existing page output before error display. Defaults to true.
  72. */
  73. public $discardOutput=true;
  74. /**
  75. * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
  76. * Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error.
  77. * This property defaults to null, meaning CErrorHandler will handle the error display.
  78. */
  79. public $errorAction;
  80. private $_error;
  81. private $_exception;
  82. /**
  83. * Handles the exception/error event.
  84. * This method is invoked by the application whenever it captures
  85. * an exception or PHP error.
  86. * @param CEvent $event the event containing the exception/error information
  87. */
  88. public function handle($event)
  89. {
  90. // set event as handled to prevent it from being handled by other event handlers
  91. $event->handled=true;
  92. if($this->discardOutput)
  93. {
  94. $gzHandler=false;
  95. foreach(ob_list_handlers() as $h)
  96. {
  97. if(strpos($h,'gzhandler')!==false)
  98. $gzHandler=true;
  99. }
  100. // the following manual level counting is to deal with zlib.output_compression set to On
  101. // for an output buffer created by zlib.output_compression set to On ob_end_clean will fail
  102. for($level=ob_get_level();$level>0;--$level)
  103. {
  104. if(!@ob_end_clean())
  105. @ob_clean();
  106. }
  107. // reset headers in case there was an ob_start("ob_gzhandler") before
  108. if($gzHandler && !headers_sent() && ob_list_handlers()===array())
  109. {
  110. if(function_exists('header_remove')) // php >= 5.3
  111. {
  112. header_remove('Vary');
  113. header_remove('Content-Encoding');
  114. }
  115. else
  116. {
  117. header('Vary:');
  118. header('Content-Encoding:');
  119. }
  120. }
  121. }
  122. if($event instanceof CExceptionEvent)
  123. $this->handleException($event->exception);
  124. else // CErrorEvent
  125. $this->handleError($event);
  126. }
  127. /**
  128. * Returns the details about the error that is currently being handled.
  129. * The error is returned in terms of an array, with the following information:
  130. * <ul>
  131. * <li>code - the HTTP status code (e.g. 403, 500)</li>
  132. * <li>type - the error type (e.g. 'CHttpException', 'PHP Error')</li>
  133. * <li>message - the error message</li>
  134. * <li>file - the name of the PHP script file where the error occurs</li>
  135. * <li>line - the line number of the code where the error occurs</li>
  136. * <li>trace - the call stack of the error</li>
  137. * <li>source - the context source code where the error occurs</li>
  138. * </ul>
  139. * @return array the error details. Null if there is no error.
  140. */
  141. public function getError()
  142. {
  143. return $this->_error;
  144. }
  145. /**
  146. * Returns the instance of the exception that is currently being handled.
  147. * @return Exception|null exception instance. Null if there is no exception.
  148. */
  149. public function getException()
  150. {
  151. return $this->_exception;
  152. }
  153. /**
  154. * Handles the exception.
  155. * @param Exception $exception the exception captured
  156. */
  157. protected function handleException($exception)
  158. {
  159. $app=Yii::app();
  160. if($app instanceof CWebApplication)
  161. {
  162. if(($trace=$this->getExactTrace($exception))===null)
  163. {
  164. $fileName=$exception->getFile();
  165. $errorLine=$exception->getLine();
  166. }
  167. else
  168. {
  169. $fileName=$trace['file'];
  170. $errorLine=$trace['line'];
  171. }
  172. $trace = $exception->getTrace();
  173. foreach($trace as $i=>$t)
  174. {
  175. if(!isset($t['file']))
  176. $trace[$i]['file']='unknown';
  177. if(!isset($t['line']))
  178. $trace[$i]['line']=0;
  179. if(!isset($t['function']))
  180. $trace[$i]['function']='unknown';
  181. unset($trace[$i]['object']);
  182. }
  183. $this->_exception=$exception;
  184. $this->_error=$data=array(
  185. 'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
  186. 'type'=>get_class($exception),
  187. 'errorCode'=>$exception->getCode(),
  188. 'message'=>$exception->getMessage(),
  189. 'file'=>$fileName,
  190. 'line'=>$errorLine,
  191. 'trace'=>$exception->getTraceAsString(),
  192. 'traces'=>$trace,
  193. );
  194. if(!headers_sent())
  195. {
  196. $httpVersion=Yii::app()->request->getHttpVersion();
  197. header("HTTP/$httpVersion {$data['code']} ".$this->getHttpHeader($data['code'], get_class($exception)));
  198. }
  199. $this->renderException();
  200. }
  201. else
  202. $app->displayException($exception);
  203. }
  204. /**
  205. * Handles the PHP error.
  206. * @param CErrorEvent $event the PHP error event
  207. */
  208. protected function handleError($event)
  209. {
  210. $trace=debug_backtrace();
  211. // skip the first 3 stacks as they do not tell the error position
  212. if(count($trace)>3)
  213. $trace=array_slice($trace,3);
  214. $traceString='';
  215. foreach($trace as $i=>$t)
  216. {
  217. if(!isset($t['file']))
  218. $trace[$i]['file']='unknown';
  219. if(!isset($t['line']))
  220. $trace[$i]['line']=0;
  221. if(!isset($t['function']))
  222. $trace[$i]['function']='unknown';
  223. $traceString.="#$i {$trace[$i]['file']}({$trace[$i]['line']}): ";
  224. if(isset($t['object']) && is_object($t['object']))
  225. $traceString.=get_class($t['object']).'->';
  226. $traceString.="{$trace[$i]['function']}()\n";
  227. unset($trace[$i]['object']);
  228. }
  229. $app=Yii::app();
  230. if($app instanceof CWebApplication)
  231. {
  232. switch($event->code)
  233. {
  234. case E_WARNING:
  235. $type = 'PHP warning';
  236. break;
  237. case E_NOTICE:
  238. $type = 'PHP notice';
  239. break;
  240. case E_USER_ERROR:
  241. $type = 'User error';
  242. break;
  243. case E_USER_WARNING:
  244. $type = 'User warning';
  245. break;
  246. case E_USER_NOTICE:
  247. $type = 'User notice';
  248. break;
  249. case E_RECOVERABLE_ERROR:
  250. $type = 'Recoverable error';
  251. break;
  252. default:
  253. $type = 'PHP error';
  254. }
  255. $this->_exception=null;
  256. $this->_error=array(
  257. 'code'=>500,
  258. 'type'=>$type,
  259. 'message'=>$event->message,
  260. 'file'=>$event->file,
  261. 'line'=>$event->line,
  262. 'trace'=>$traceString,
  263. 'traces'=>$trace,
  264. );
  265. if(!headers_sent())
  266. {
  267. $httpVersion=Yii::app()->request->getHttpVersion();
  268. header("HTTP/$httpVersion 500 Internal Server Error");
  269. }
  270. $this->renderError();
  271. }
  272. else
  273. $app->displayError($event->code,$event->message,$event->file,$event->line);
  274. }
  275. /**
  276. * whether the current request is an AJAX (XMLHttpRequest) request.
  277. * @return boolean whether the current request is an AJAX request.
  278. */
  279. protected function isAjaxRequest()
  280. {
  281. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  282. }
  283. /**
  284. * Returns the exact trace where the problem occurs.
  285. * @param Exception $exception the uncaught exception
  286. * @return array the exact trace where the problem occurs
  287. */
  288. protected function getExactTrace($exception)
  289. {
  290. $traces=$exception->getTrace();
  291. foreach($traces as $trace)
  292. {
  293. // property access exception
  294. if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
  295. return $trace;
  296. }
  297. return null;
  298. }
  299. /**
  300. * Renders the view.
  301. * @param string $view the view name (file name without extension).
  302. * See {@link getViewFile} for how a view file is located given its name.
  303. * @param array $data data to be passed to the view
  304. */
  305. protected function render($view,$data)
  306. {
  307. $data['version']=$this->getVersionInfo();
  308. $data['time']=time();
  309. $data['admin']=$this->adminInfo;
  310. include($this->getViewFile($view,$data['code']));
  311. }
  312. /**
  313. * Renders the exception information.
  314. * This method will display information from current {@link error} value.
  315. */
  316. protected function renderException()
  317. {
  318. $exception=$this->getException();
  319. if($exception instanceof CHttpException || !YII_DEBUG)
  320. $this->renderError();
  321. else
  322. {
  323. if($this->isAjaxRequest())
  324. Yii::app()->displayException($exception);
  325. else
  326. $this->render('exception',$this->getError());
  327. }
  328. }
  329. /**
  330. * Renders the current error information.
  331. * This method will display information from current {@link error} value.
  332. */
  333. protected function renderError()
  334. {
  335. if($this->errorAction!==null)
  336. Yii::app()->runController($this->errorAction);
  337. else
  338. {
  339. $data=$this->getError();
  340. if($this->isAjaxRequest())
  341. Yii::app()->displayError($data['code'],$data['message'],$data['file'],$data['line']);
  342. elseif(YII_DEBUG)
  343. $this->render('exception',$data);
  344. else
  345. $this->render('error',$data);
  346. }
  347. }
  348. /**
  349. * Determines which view file should be used.
  350. * @param string $view view name (either 'exception' or 'error')
  351. * @param integer $code HTTP status code
  352. * @return string view file path
  353. */
  354. protected function getViewFile($view,$code)
  355. {
  356. $viewPaths=array(
  357. Yii::app()->getTheme()===null ? null : Yii::app()->getTheme()->getSystemViewPath(),
  358. Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null,
  359. YII_PATH.DIRECTORY_SEPARATOR.'views',
  360. );
  361. foreach($viewPaths as $i=>$viewPath)
  362. {
  363. if($viewPath!==null)
  364. {
  365. $viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null);
  366. if(is_file($viewFile))
  367. return $viewFile;
  368. }
  369. }
  370. }
  371. /**
  372. * Looks for the view under the specified directory.
  373. * @param string $viewPath the directory containing the views
  374. * @param string $view view name (either 'exception' or 'error')
  375. * @param integer $code HTTP status code
  376. * @param string $srcLanguage the language that the view file is in
  377. * @return string view file path
  378. */
  379. protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null)
  380. {
  381. $app=Yii::app();
  382. if($view==='error')
  383. {
  384. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage);
  385. if(!is_file($viewFile))
  386. $viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
  387. }
  388. else
  389. $viewFile=$viewPath.DIRECTORY_SEPARATOR."exception.php";
  390. return $viewFile;
  391. }
  392. /**
  393. * Returns server version information.
  394. * If the application is in production mode, empty string is returned.
  395. * @return string server version information. Empty if in production mode.
  396. */
  397. protected function getVersionInfo()
  398. {
  399. if(YII_DEBUG)
  400. {
  401. $version='<a href="http://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion();
  402. if(isset($_SERVER['SERVER_SOFTWARE']))
  403. $version=$_SERVER['SERVER_SOFTWARE'].' '.$version;
  404. }
  405. else
  406. $version='';
  407. return $version;
  408. }
  409. /**
  410. * Converts arguments array to its string representation
  411. *
  412. * @param array $args arguments array to be converted
  413. * @return string string representation of the arguments array
  414. */
  415. protected function argumentsToString($args)
  416. {
  417. $count=0;
  418. $isAssoc=$args!==array_values($args);
  419. foreach($args as $key => $value)
  420. {
  421. $count++;
  422. if($count>=5)
  423. {
  424. if($count>5)
  425. unset($args[$key]);
  426. else
  427. $args[$key]='...';
  428. continue;
  429. }
  430. if(is_object($value))
  431. $args[$key] = get_class($value);
  432. elseif(is_bool($value))
  433. $args[$key] = $value ? 'true' : 'false';
  434. elseif(is_string($value))
  435. {
  436. if(strlen($value)>64)
  437. $args[$key] = '"'.substr($value,0,64).'..."';
  438. else
  439. $args[$key] = '"'.$value.'"';
  440. }
  441. elseif(is_array($value))
  442. $args[$key] = 'array('.$this->argumentsToString($value).')';
  443. elseif($value===null)
  444. $args[$key] = 'null';
  445. elseif(is_resource($value))
  446. $args[$key] = 'resource';
  447. if(is_string($key))
  448. {
  449. $args[$key] = '"'.$key.'" => '.$args[$key];
  450. }
  451. elseif($isAssoc)
  452. {
  453. $args[$key] = $key.' => '.$args[$key];
  454. }
  455. }
  456. $out = implode(", ", $args);
  457. return $out;
  458. }
  459. /**
  460. * Returns a value indicating whether the call stack is from application code.
  461. * @param array $trace the trace data
  462. * @return boolean whether the call stack is from application code.
  463. */
  464. protected function isCoreCode($trace)
  465. {
  466. if(isset($trace['file']))
  467. {
  468. $systemPath=realpath(dirname(__FILE__).'/..');
  469. return $trace['file']==='unknown' || strpos(realpath($trace['file']),$systemPath.DIRECTORY_SEPARATOR)===0;
  470. }
  471. return false;
  472. }
  473. /**
  474. * Renders the source code around the error line.
  475. * @param string $file source file path
  476. * @param integer $errorLine the error line number
  477. * @param integer $maxLines maximum number of lines to display
  478. * @return string the rendering result
  479. */
  480. protected function renderSourceCode($file,$errorLine,$maxLines)
  481. {
  482. $errorLine--; // adjust line number to 0-based from 1-based
  483. if($errorLine<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$errorLine)
  484. return '';
  485. $halfLines=(int)($maxLines/2);
  486. $beginLine=$errorLine-$halfLines>0 ? $errorLine-$halfLines:0;
  487. $endLine=$errorLine+$halfLines<$lineCount?$errorLine+$halfLines:$lineCount-1;
  488. $lineNumberWidth=strlen($endLine+1);
  489. $output='';
  490. for($i=$beginLine;$i<=$endLine;++$i)
  491. {
  492. $isErrorLine = $i===$errorLine;
  493. $code=sprintf("<span class=\"ln".($isErrorLine?' error-ln':'')."\">%0{$lineNumberWidth}d</span> %s",$i+1,CHtml::encode(str_replace("\t",' ',$lines[$i])));
  494. if(!$isErrorLine)
  495. $output.=$code;
  496. else
  497. $output.='<span class="error">'.$code.'</span>';
  498. }
  499. return '<div class="code"><pre>'.$output.'</pre></div>';
  500. }
  501. /**
  502. * Return correct message for each known http error code
  503. * @param integer $httpCode error code to map
  504. * @param string $replacement replacement error string that is returned if code is unknown
  505. * @return string the textual representation of the given error code or the replacement string if the error code is unknown
  506. */
  507. protected function getHttpHeader($httpCode, $replacement='')
  508. {
  509. $httpCodes = array(
  510. 100 => 'Continue',
  511. 101 => 'Switching Protocols',
  512. 102 => 'Processing',
  513. 118 => 'Connection timed out',
  514. 200 => 'OK',
  515. 201 => 'Created',
  516. 202 => 'Accepted',
  517. 203 => 'Non-Authoritative',
  518. 204 => 'No Content',
  519. 205 => 'Reset Content',
  520. 206 => 'Partial Content',
  521. 207 => 'Multi-Status',
  522. 210 => 'Content Different',
  523. 300 => 'Multiple Choices',
  524. 301 => 'Moved Permanently',
  525. 302 => 'Found',
  526. 303 => 'See Other',
  527. 304 => 'Not Modified',
  528. 305 => 'Use Proxy',
  529. 307 => 'Temporary Redirect',
  530. 310 => 'Too many Redirect',
  531. 400 => 'Bad Request',
  532. 401 => 'Unauthorized',
  533. 402 => 'Payment Required',
  534. 403 => 'Forbidden',
  535. 404 => 'Not Found',
  536. 405 => 'Method Not Allowed',
  537. 406 => 'Not Acceptable',
  538. 407 => 'Proxy Authentication Required',
  539. 408 => 'Request Time-out',
  540. 409 => 'Conflict',
  541. 410 => 'Gone',
  542. 411 => 'Length Required',
  543. 412 => 'Precondition Failed',
  544. 413 => 'Request Entity Too Large',
  545. 414 => 'Request-URI Too Long',
  546. 415 => 'Unsupported Media Type',
  547. 416 => 'Requested range unsatisfiable',
  548. 417 => 'Expectation failed',
  549. 418 => 'I’m a teapot',
  550. 422 => 'Unprocessable entity',
  551. 423 => 'Locked',
  552. 424 => 'Method failure',
  553. 425 => 'Unordered Collection',
  554. 426 => 'Upgrade Required',
  555. 449 => 'Retry With',
  556. 450 => 'Blocked by Windows Parental Controls',
  557. 500 => 'Internal Server Error',
  558. 501 => 'Not Implemented',
  559. 502 => 'Bad Gateway ou Proxy Error',
  560. 503 => 'Service Unavailable',
  561. 504 => 'Gateway Time-out',
  562. 505 => 'HTTP Version not supported',
  563. 507 => 'Insufficient storage',
  564. 509 => 'Bandwidth Limit Exceeded',
  565. );
  566. if(isset($httpCodes[$httpCode]))
  567. return $httpCodes[$httpCode];
  568. else
  569. return $replacement;
  570. }
  571. }