1<?php 2/** 3 * PHPTAL templating engine 4 * 5 * PHP Version 5 6 * 7 * @category HTML 8 * @package PHPTAL 9 * @author Kornel Lesiński <kornel@aardvarkmedia.co.uk> 10 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License 11 * @version SVN: $Id: $ 12 * @link http://phptal.org/ 13 */ 14 15class PHPTAL_ExceptionHandler 16{ 17 private $encoding; 18 function __construct($encoding) 19 { 20 $this->encoding = $encoding; 21 } 22 23 /** 24 * PHP's default exception handler allows error pages to be indexed and can reveal too much information, 25 * so if possible PHPTAL sets up its own handler to fix this. 26 * 27 * Doesn't change exception handler if non-default one is set. 28 * 29 * @param Exception e exception to re-throw and display 30 * 31 * @return void 32 * @throws Exception 33 */ 34 public static function handleException(Exception $e, $encoding) 35 { 36 // PHPTAL's handler is only useful on fresh HTTP response 37 if (PHP_SAPI !== 'cli' && !headers_sent()) { 38 $old_exception_handler = set_exception_handler(array(new PHPTAL_ExceptionHandler($encoding), '_defaultExceptionHandler')); 39 40 if ($old_exception_handler !== NULL) { 41 restore_exception_handler(); // if there's user's exception handler, let it work 42 } 43 } 44 throw $e; // throws instead of outputting immediately to support user's try/catch 45 } 46 47 48 /** 49 * Generates simple error page. Sets appropriate HTTP status to prevent page being indexed. 50 * 51 * @param Exception e exception to display 52 */ 53 public function _defaultExceptionHandler($e) 54 { 55 if (!headers_sent()) { 56 header('HTTP/1.1 500 PHPTAL Exception'); 57 header('Content-Type:text/html;charset='.$this->encoding); 58 } 59 60 $line = $e->getFile(); 61 if ($e->getLine()) { 62 $line .= ' line '.$e->getLine(); 63 } 64 65 if (ini_get('display_errors')) { 66 $title = get_class($e).': '.htmlspecialchars($e->getMessage()); 67 $body = "<p><strong>\n".htmlspecialchars($e->getMessage()).'</strong></p>' . 68 '<p>In '.htmlspecialchars($line)."</p><pre>\n".htmlspecialchars($e->getTraceAsString()).'</pre>'; 69 } else { 70 $title = "PHPTAL Exception"; 71 $body = "<p>This page cannot be displayed.</p><hr/>" . 72 "<p><small>Enable <code>display_errors</code> to see detailed message.</small></p>"; 73 } 74 75 echo "<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head><style>body{font-family:sans-serif}</style><title>\n"; 76 echo $title.'</title></head><body><h1>PHPTAL Exception</h1>'.$body; 77 error_log($e->getMessage().' in '.$line); 78 echo '</body></html>'.str_repeat(' ', 100)."\n"; // IE won't display error pages < 512b 79 exit(1); 80 } 81} 82