ExceptionRenderer.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Error;
  16. use Cake\Controller\Controller;
  17. use Cake\Core\App;
  18. use Cake\Core\Configure;
  19. use Cake\Core\Exception\Exception as CakeException;
  20. use Cake\Core\Exception\MissingPluginException;
  21. use Cake\Event\Event;
  22. use Cake\Http\Response;
  23. use Cake\Http\ServerRequest;
  24. use Cake\Network\Exception\HttpException;
  25. use Cake\Routing\DispatcherFactory;
  26. use Cake\Routing\Router;
  27. use Cake\Utility\Inflector;
  28. use Cake\View\Exception\MissingTemplateException;
  29. use Exception;
  30. use PDOException;
  31. /**
  32. * Exception Renderer.
  33. *
  34. * Captures and handles all unhandled exceptions. Displays helpful framework errors when debug is true.
  35. * When debug is false a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
  36. * and it is a type that ExceptionHandler does not know about it will be treated as a 500 error.
  37. *
  38. * ### Implementing application specific exception rendering
  39. *
  40. * You can implement application specific exception handling by creating a subclass of
  41. * ExceptionRenderer and configure it to be the `exceptionRenderer` in config/error.php
  42. *
  43. * #### Using a subclass of ExceptionRenderer
  44. *
  45. * Using a subclass of ExceptionRenderer gives you full control over how Exceptions are rendered, you
  46. * can configure your class in your config/app.php.
  47. */
  48. class ExceptionRenderer implements ExceptionRendererInterface
  49. {
  50. /**
  51. * The exception being handled.
  52. *
  53. * @var \Exception
  54. */
  55. public $error;
  56. /**
  57. * Controller instance.
  58. *
  59. * @var \Cake\Controller\Controller
  60. */
  61. public $controller;
  62. /**
  63. * Template to render for Cake\Core\Exception\Exception
  64. *
  65. * @var string
  66. */
  67. public $template = '';
  68. /**
  69. * The method corresponding to the Exception this object is for.
  70. *
  71. * @var string
  72. */
  73. public $method = '';
  74. /**
  75. * Creates the controller to perform rendering on the error response.
  76. * If the error is a Cake\Core\Exception\Exception it will be converted to either a 400 or a 500
  77. * code error depending on the code used to construct the error.
  78. *
  79. * @param \Exception $exception Exception.
  80. */
  81. public function __construct(Exception $exception)
  82. {
  83. $this->error = $exception;
  84. $this->controller = $this->_getController();
  85. }
  86. /**
  87. * Returns the unwrapped exception object in case we are dealing with
  88. * a PHP 7 Error object
  89. *
  90. * @param \Exception $exception The object to unwrap
  91. * @return \Exception|\Error
  92. */
  93. protected function _unwrap($exception)
  94. {
  95. return $exception instanceof PHP7ErrorException ? $exception->getError() : $exception;
  96. }
  97. /**
  98. * Get the controller instance to handle the exception.
  99. * Override this method in subclasses to customize the controller used.
  100. * This method returns the built in `ErrorController` normally, or if an error is repeated
  101. * a bare controller will be used.
  102. *
  103. * @return \Cake\Controller\Controller
  104. * @triggers Controller.startup $controller
  105. */
  106. protected function _getController()
  107. {
  108. if (!$request = Router::getRequest(true)) {
  109. $request = ServerRequest::createFromGlobals();
  110. }
  111. $response = new Response();
  112. $controller = null;
  113. try {
  114. $class = App::className('Error', 'Controller', 'Controller');
  115. /* @var \Cake\Controller\Controller $controller */
  116. $controller = new $class($request, $response);
  117. $controller->startupProcess();
  118. $startup = true;
  119. } catch (Exception $e) {
  120. $startup = false;
  121. }
  122. // Retry RequestHandler, as another aspect of startupProcess()
  123. // could have failed. Ignore any exceptions out of startup, as
  124. // there could be userland input data parsers.
  125. if ($startup === false && !empty($controller) && isset($controller->RequestHandler)) {
  126. try {
  127. $event = new Event('Controller.startup', $controller);
  128. $controller->RequestHandler->startup($event);
  129. } catch (Exception $e) {
  130. }
  131. }
  132. if (empty($controller)) {
  133. $controller = new Controller($request, $response);
  134. }
  135. return $controller;
  136. }
  137. /**
  138. * Renders the response for the exception.
  139. *
  140. * @return \Cake\Http\Response The response to be sent.
  141. */
  142. public function render()
  143. {
  144. $exception = $this->error;
  145. $code = $this->_code($exception);
  146. $method = $this->_method($exception);
  147. $template = $this->_template($exception, $method, $code);
  148. $unwrapped = $this->_unwrap($exception);
  149. $isDebug = Configure::read('debug');
  150. if (($isDebug || $exception instanceof HttpException) &&
  151. method_exists($this, $method)
  152. ) {
  153. return $this->_customMethod($method, $unwrapped);
  154. }
  155. $message = $this->_message($exception, $code);
  156. $url = $this->controller->request->getRequestTarget();
  157. if (method_exists($exception, 'responseHeader')) {
  158. $this->controller->response->header($exception->responseHeader());
  159. }
  160. $this->controller->response->statusCode($code);
  161. $viewVars = [
  162. 'message' => $message,
  163. 'url' => h($url),
  164. 'error' => $unwrapped,
  165. 'code' => $code,
  166. '_serialize' => ['message', 'url', 'code']
  167. ];
  168. if ($isDebug) {
  169. $viewVars['trace'] = Debugger::formatTrace($unwrapped->getTrace(), [
  170. 'format' => 'array',
  171. 'args' => false
  172. ]);
  173. }
  174. $this->controller->set($viewVars);
  175. if ($unwrapped instanceof CakeException && $isDebug) {
  176. $this->controller->set($unwrapped->getAttributes());
  177. }
  178. return $this->_outputMessage($template);
  179. }
  180. /**
  181. * Render a custom error method/template.
  182. *
  183. * @param string $method The method name to invoke.
  184. * @param \Exception $exception The exception to render.
  185. * @return \Cake\Http\Response The response to send.
  186. */
  187. protected function _customMethod($method, $exception)
  188. {
  189. $result = call_user_func([$this, $method], $exception);
  190. $this->_shutdown();
  191. if (is_string($result)) {
  192. $this->controller->response->body($result);
  193. $result = $this->controller->response;
  194. }
  195. return $result;
  196. }
  197. /**
  198. * Get method name
  199. *
  200. * @param \Exception $exception Exception instance.
  201. * @return string
  202. */
  203. protected function _method(Exception $exception)
  204. {
  205. $exception = $this->_unwrap($exception);
  206. list(, $baseClass) = namespaceSplit(get_class($exception));
  207. if (substr($baseClass, -9) === 'Exception') {
  208. $baseClass = substr($baseClass, 0, -9);
  209. }
  210. $method = Inflector::variable($baseClass) ?: 'error500';
  211. return $this->method = $method;
  212. }
  213. /**
  214. * Get error message.
  215. *
  216. * @param \Exception $exception Exception.
  217. * @param int $code Error code.
  218. * @return string Error message
  219. */
  220. protected function _message(Exception $exception, $code)
  221. {
  222. $exception = $this->_unwrap($exception);
  223. $message = $exception->getMessage();
  224. if (!Configure::read('debug') &&
  225. !($exception instanceof HttpException)
  226. ) {
  227. if ($code < 500) {
  228. $message = __d('cake', 'Not Found');
  229. } else {
  230. $message = __d('cake', 'An Internal Error Has Occurred.');
  231. }
  232. }
  233. return $message;
  234. }
  235. /**
  236. * Get template for rendering exception info.
  237. *
  238. * @param \Exception $exception Exception instance.
  239. * @param string $method Method name.
  240. * @param int $code Error code.
  241. * @return string Template name
  242. */
  243. protected function _template(Exception $exception, $method, $code)
  244. {
  245. $exception = $this->_unwrap($exception);
  246. $isHttpException = $exception instanceof HttpException;
  247. if (!Configure::read('debug') && !$isHttpException || $isHttpException) {
  248. $template = 'error500';
  249. if ($code < 500) {
  250. $template = 'error400';
  251. }
  252. return $this->template = $template;
  253. }
  254. $template = $method ?: 'error500';
  255. if ($exception instanceof PDOException) {
  256. $template = 'pdo_error';
  257. }
  258. return $this->template = $template;
  259. }
  260. /**
  261. * Get an error code value within range 400 to 506
  262. *
  263. * @param \Exception $exception Exception.
  264. * @return int Error code value within range 400 to 506
  265. */
  266. protected function _code(Exception $exception)
  267. {
  268. $code = 500;
  269. $exception = $this->_unwrap($exception);
  270. $errorCode = $exception->getCode();
  271. if ($errorCode >= 400 && $errorCode < 506) {
  272. $code = $errorCode;
  273. }
  274. return $code;
  275. }
  276. /**
  277. * Generate the response using the controller object.
  278. *
  279. * @param string $template The template to render.
  280. * @return \Cake\Http\Response A response object that can be sent.
  281. */
  282. protected function _outputMessage($template)
  283. {
  284. try {
  285. $this->controller->render($template);
  286. return $this->_shutdown();
  287. } catch (MissingTemplateException $e) {
  288. $attributes = $e->getAttributes();
  289. if (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false) {
  290. return $this->_outputMessageSafe('error500');
  291. }
  292. return $this->_outputMessage('error500');
  293. } catch (MissingPluginException $e) {
  294. $attributes = $e->getAttributes();
  295. if (isset($attributes['plugin']) && $attributes['plugin'] === $this->controller->plugin) {
  296. $this->controller->plugin = null;
  297. }
  298. return $this->_outputMessageSafe('error500');
  299. } catch (Exception $e) {
  300. return $this->_outputMessageSafe('error500');
  301. }
  302. }
  303. /**
  304. * A safer way to render error messages, replaces all helpers, with basics
  305. * and doesn't call component methods.
  306. *
  307. * @param string $template The template to render.
  308. * @return \Cake\Http\Response A response object that can be sent.
  309. */
  310. protected function _outputMessageSafe($template)
  311. {
  312. $helpers = ['Form', 'Html'];
  313. $this->controller->helpers = $helpers;
  314. $builder = $this->controller->viewBuilder();
  315. $builder->setHelpers($helpers, false)
  316. ->setLayoutPath('')
  317. ->setTemplatePath('Error');
  318. $view = $this->controller->createView('View');
  319. $this->controller->response->body($view->render($template, 'error'));
  320. $this->controller->response->type('html');
  321. return $this->controller->response;
  322. }
  323. /**
  324. * Run the shutdown events.
  325. *
  326. * Triggers the afterFilter and afterDispatch events.
  327. *
  328. * @return \Cake\Http\Response The response to serve.
  329. */
  330. protected function _shutdown()
  331. {
  332. $this->controller->dispatchEvent('Controller.shutdown');
  333. $dispatcher = DispatcherFactory::create();
  334. $eventManager = $dispatcher->eventManager();
  335. foreach ($dispatcher->filters() as $filter) {
  336. $eventManager->on($filter);
  337. }
  338. $args = [
  339. 'request' => $this->controller->request,
  340. 'response' => $this->controller->response
  341. ];
  342. $result = $dispatcher->dispatchEvent('Dispatcher.afterDispatch', $args);
  343. return $result->getData('response');
  344. }
  345. }