Exceptions.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Exceptions Class
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Exceptions
  45. * @author EllisLab Dev Team
  46. * @link https://codeigniter.com/user_guide/libraries/exceptions.html
  47. */
  48. class CI_Exceptions {
  49. /**
  50. * Nesting level of the output buffering mechanism
  51. *
  52. * @var int
  53. */
  54. public $ob_level;
  55. /**
  56. * List of available error levels
  57. *
  58. * @var array
  59. */
  60. public $levels = array(
  61. E_ERROR => 'Error',
  62. E_WARNING => 'Warning',
  63. E_PARSE => 'Parsing Error',
  64. E_NOTICE => 'Notice',
  65. E_CORE_ERROR => 'Core Error',
  66. E_CORE_WARNING => 'Core Warning',
  67. E_COMPILE_ERROR => 'Compile Error',
  68. E_COMPILE_WARNING => 'Compile Warning',
  69. E_USER_ERROR => 'User Error',
  70. E_USER_WARNING => 'User Warning',
  71. E_USER_NOTICE => 'User Notice',
  72. E_STRICT => 'Runtime Notice'
  73. );
  74. /**
  75. * Class constructor
  76. *
  77. * @return void
  78. */
  79. public function __construct()
  80. {
  81. $this->ob_level = ob_get_level();
  82. // Note: Do not log messages from this constructor.
  83. }
  84. // --------------------------------------------------------------------
  85. /**
  86. * Exception Logger
  87. *
  88. * Logs PHP generated error messages
  89. *
  90. * @param int $severity Log level
  91. * @param string $message Error message
  92. * @param string $filepath File path
  93. * @param int $line Line number
  94. * @return void
  95. */
  96. public function log_exception($severity, $message, $filepath, $line)
  97. {
  98. $severity = isset($this->levels[$severity]) ? $this->levels[$severity] : $severity;
  99. log_message('error', 'Severity: '.$severity.' --> '.$message.' '.$filepath.' '.$line);
  100. }
  101. // --------------------------------------------------------------------
  102. /**
  103. * 404 Error Handler
  104. *
  105. * @uses CI_Exceptions::show_error()
  106. *
  107. * @param string $page Page URI
  108. * @param bool $log_error Whether to log the error
  109. * @return void
  110. */
  111. public function show_404($page = '', $log_error = TRUE)
  112. {
  113. if (is_cli())
  114. {
  115. $heading = 'Not Found';
  116. $message = 'The controller/method pair you requested was not found.';
  117. }
  118. else
  119. {
  120. $heading = '404 Page Not Found';
  121. $message = 'The page you requested was not found.';
  122. }
  123. // By default we log this, but allow a dev to skip it
  124. if ($log_error)
  125. {
  126. log_message('error', $heading.': '.$page);
  127. }
  128. echo $this->show_error($heading, $message, 'error_404', 404);
  129. exit(4); // EXIT_UNKNOWN_FILE
  130. }
  131. // --------------------------------------------------------------------
  132. /**
  133. * General Error Page
  134. *
  135. * Takes an error message as input (either as a string or an array)
  136. * and displays it using the specified template.
  137. *
  138. * @param string $heading Page heading
  139. * @param string|string[] $message Error message
  140. * @param string $template Template name
  141. * @param int $status_code (default: 500)
  142. *
  143. * @return string Error page output
  144. */
  145. public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
  146. {
  147. $templates_path = config_item('error_views_path');
  148. if (empty($templates_path))
  149. {
  150. $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
  151. }
  152. if (is_cli())
  153. {
  154. $message = "\t".(is_array($message) ? implode("\n\t", $message) : $message);
  155. $template = 'cli'.DIRECTORY_SEPARATOR.$template;
  156. }
  157. else
  158. {
  159. set_status_header($status_code);
  160. $message = '<p>'.(is_array($message) ? implode('</p><p>', $message) : $message).'</p>';
  161. $template = 'html'.DIRECTORY_SEPARATOR.$template;
  162. }
  163. if (ob_get_level() > $this->ob_level + 1)
  164. {
  165. ob_end_flush();
  166. }
  167. ob_start();
  168. include($templates_path.$template.'.php');
  169. $buffer = ob_get_contents();
  170. ob_end_clean();
  171. return $buffer;
  172. }
  173. // --------------------------------------------------------------------
  174. public function show_exception($exception)
  175. {
  176. $templates_path = config_item('error_views_path');
  177. if (empty($templates_path))
  178. {
  179. $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
  180. }
  181. $message = $exception->getMessage();
  182. if (empty($message))
  183. {
  184. $message = '(null)';
  185. }
  186. if (is_cli())
  187. {
  188. $templates_path .= 'cli'.DIRECTORY_SEPARATOR;
  189. }
  190. else
  191. {
  192. $templates_path .= 'html'.DIRECTORY_SEPARATOR;
  193. }
  194. if (ob_get_level() > $this->ob_level + 1)
  195. {
  196. ob_end_flush();
  197. }
  198. ob_start();
  199. include($templates_path.'error_exception.php');
  200. $buffer = ob_get_contents();
  201. ob_end_clean();
  202. echo $buffer;
  203. }
  204. // --------------------------------------------------------------------
  205. /**
  206. * Native PHP error handler
  207. *
  208. * @param int $severity Error level
  209. * @param string $message Error message
  210. * @param string $filepath File path
  211. * @param int $line Line number
  212. * @return string Error page output
  213. */
  214. public function show_php_error($severity, $message, $filepath, $line)
  215. {
  216. $templates_path = config_item('error_views_path');
  217. if (empty($templates_path))
  218. {
  219. $templates_path = VIEWPATH.'errors'.DIRECTORY_SEPARATOR;
  220. }
  221. $severity = isset($this->levels[$severity]) ? $this->levels[$severity] : $severity;
  222. // For safety reasons we don't show the full file path in non-CLI requests
  223. if ( ! is_cli())
  224. {
  225. $filepath = str_replace('\\', '/', $filepath);
  226. if (FALSE !== strpos($filepath, '/'))
  227. {
  228. $x = explode('/', $filepath);
  229. $filepath = $x[count($x)-2].'/'.end($x);
  230. }
  231. $template = 'html'.DIRECTORY_SEPARATOR.'error_php';
  232. }
  233. else
  234. {
  235. $template = 'cli'.DIRECTORY_SEPARATOR.'error_php';
  236. }
  237. if (ob_get_level() > $this->ob_level + 1)
  238. {
  239. ob_end_flush();
  240. }
  241. ob_start();
  242. include($templates_path.$template.'.php');
  243. $buffer = ob_get_contents();
  244. ob_end_clean();
  245. echo $buffer;
  246. }
  247. public function error_log_php($severity, $message, $filepath, $line)
  248. {
  249. $this->myErrorHandler($severity, $message, $filepath, $line);
  250. $severity = $this->levels[$severity] ?? $severity;
  251. $uri = "\033[32m".$_SERVER['REQUEST_URI']."\033[0m";
  252. $backtraceInfo = "ErrorInfo:\tUri: $uri\n\t\033[0;33mSeverity: $severity\n\tMessage: $message\n\tFilename: $filepath\n\tLine Number: $line:\033[0m\n\n\t\033[32mBacktrace:\033[0m\n";
  253. foreach (debug_backtrace() as $error) {
  254. if (isset($error['file']) && strpos($error['file'], realpath(BASEPATH)) !== 0) {
  255. $backtraceInfo .= "\tFile: {$error['file']} :{$error['line']}\n\tFunction: {$error['function']}\n\n";
  256. }
  257. }
  258. error_log($backtraceInfo);
  259. }
  260. function myErrorHandler($errno, $errstr, $errfile, $errline)
  261. {
  262. if ($errno != E_NOTICE) {
  263. $date = date('Ymd');
  264. $dir = PATH_DAT . '/phperror';
  265. $file = $dir . '/' . $date . '.log';
  266. if (!is_dir($dir)) {
  267. mkdir($dir, 0775);
  268. chgrp_chown($dir);
  269. }
  270. $error = '';
  271. if (!file_exists($file)) {
  272. touch($file) && chmod($file, 0775);
  273. chgrp_chown($file);
  274. $error = "<?php\nexit();\n";
  275. }
  276. $error .= date('Y-m-d H:m:s', time()) . '---';
  277. $error .= 'Error:' . $errstr . '--';
  278. $error .= 'File:' . $errfile . '--';
  279. $error .= 'Line:' . $errline;
  280. $error .= "\n";
  281. $backtrace = array();
  282. $straces = debug_backtrace();
  283. foreach ((array)$straces as $k => $v) {
  284. if ($k == 0) continue;
  285. if (isset($v['file'])) {
  286. $error .= sprintf("#%s %s:%s@%s Args:%s\n", $k, $v['file'], $v['line'], $v['function'], json_encode($v));
  287. } else {
  288. $file = PATH_DAT . 'phperror/' . $date . '.log';
  289. @file_put_contents($file, is_array($error)?json_encode($error):$error . "--myErrorHandler \n ", FILE_APPEND | LOCK_EX);
  290. return true;
  291. }
  292. }
  293. $file = PATH_DAT . 'phperror/' . $date . '.log';
  294. $error .= "--myErrorHandlerEnd";
  295. $data = ['log_level' => 'error', 'log_module' => 'custom_error', 'time' => date('Y-m-d H:i:s'), 'content' => $error];
  296. @file_put_contents($file, json_encode($data) . "\n", FILE_APPEND | LOCK_EX);
  297. }
  298. }
  299. }