CErrorHandler.php 16 KB

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