summaryrefslogtreecommitdiff
path: root/include/errorhandler.php
blob: 027cf2a6f3855dc5b10e92c146d8b0c172093fe6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
 * @param array<int, array<string, mixed>> $trace
 */
function format_backtrace(array $trace): string {
	$rv = "";
	$idx = 1;

	foreach ($trace as $e) {
		if (isset($e["file"]) && isset($e["line"])) {
			$fmt_args = [];

			if (is_array($e["args"] ?? false)) {
				foreach ($e["args"] as $a) {
					if (is_object($a)) {
						array_push($fmt_args, "{" . get_class($a) . "}");
					} else if (is_array($a)) {
						array_push($fmt_args, "[" . truncate_string(json_encode($a), 256, "...")) . "]";
					} else if (is_resource($a)) {
						array_push($fmt_args, truncate_string(get_resource_type($a), 256, "..."));
					} else if (is_string($a)) {
						array_push($fmt_args, truncate_string($a, 256, "..."));
					}
				}
			}

			$filename = str_replace(dirname(__DIR__) . "/", "", $e["file"]);

			$rv .= sprintf("%d. %s(%s): %s(%s)\n",
				$idx,
				$filename,
				$e["line"],
				$e["function"],
				implode(", ", $fmt_args));

			$idx++;
		}
	}

	return $rv;
}

function ttrss_error_handler(int $errno, string $errstr, string $file, int $line): bool {
	// return true in order to avoid default error handling by PHP
	if (!(error_reporting() & $errno)) return true;

	$file = substr(str_replace(dirname(__DIR__), "", $file), 1);

	$context = format_backtrace(debug_backtrace());
	$errstr = truncate_middle($errstr, 16384, " (...) ");

	if (php_sapi_name() == 'cli' && class_exists("Debug")) {
		Debug::log("!! Exception: $errstr ($file:$line)");
		Debug::log($context);
	}

	if (class_exists("Logger"))
		return Logger::log_error((int)$errno, $errstr, $file, (int)$line, $context);
	else
		return false;
}

function ttrss_fatal_handler(): bool {
	$error = error_get_last();

	if ($error !== NULL) {
		$errno = $error["type"];
		$file = $error["file"];
		$line = $error["line"];
		$errstr  = $error["message"];

		if (!$errno) return false;

		$context = format_backtrace(debug_backtrace());

		$file = substr(str_replace(dirname(__DIR__), "", $file), 1);

		if (php_sapi_name() == 'cli' && class_exists("Debug")) {
			Debug::log("!! Fatal error: $errstr ($file:$line)");
			Debug::log($context);
		}

		if (class_exists("Logger"))
			return Logger::log_error((int)$errno, $errstr, $file, (int)$line, $context);
	}

	if (php_sapi_name() == 'cli')
		exit(1);

	return false;
}

register_shutdown_function('ttrss_fatal_handler');
set_error_handler('ttrss_error_handler');