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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik;
use Piwik\Exception\DI\DependencyException;
use Exception;
use Piwik\API\Request;
use Piwik\API\ResponseBuilder;
use Piwik\Container\ContainerDoesNotExistException;
use Piwik\Container\StaticContainer;
use Piwik\Exception\IRedirectException;
use Piwik\Http\HttpCodeException;
use Piwik\Plugins\CoreAdminHome\CustomLogo;
use Piwik\Plugins\Monolog\Processor\ExceptionToTextProcessor;
use Piwik\Log\LoggerInterface;
/**
* Contains Piwik's uncaught exception handler.
*/
class ExceptionHandler
{
public static function setUp()
{
set_exception_handler(['Piwik\ExceptionHandler', 'handleException']);
}
/**
* @param Exception|\Throwable $exception
*/
public static function handleException($exception)
{
if (Common::isPhpCliMode()) {
self::dieWithCliError($exception);
}
self::dieWithHtmlErrorPage($exception);
}
/**
* @param Exception|\Throwable $exception
*/
public static function dieWithCliError($exception)
{
self::logException($exception);
$message = $exception->getMessage();
if (!method_exists($exception, 'isHtmlMessage') || !$exception->isHtmlMessage()) {
$message = strip_tags(str_replace('<br />', PHP_EOL, $message));
}
$message = sprintf(
"Uncaught exception in %s line %d:\n%s\n",
$exception->getFile(),
$exception->getLine(),
ExceptionToTextProcessor::getMessageAndWholeBacktrace($exception)
);
echo $message;
exit(1);
}
/**
* @param Exception|\Throwable $exception
*/
public static function dieWithHtmlErrorPage($exception)
{
// Set an appropriate HTTP response code.
switch (true) {
case ($exception instanceof HttpCodeException && $exception->getCode() > 0):
// For these exception types, use the exception-provided error code.
http_response_code($exception->getCode());
break;
case ($exception instanceof \Piwik\Exception\NotYetInstalledException):
http_response_code(404);
break;
default:
http_response_code(500);
}
// Log the error with an appropriate loglevel.
switch (true) {
case ($exception instanceof HttpCodeException && $exception->getCode() >= 400 && $exception->getCode() < 500):
// Log exceptions, resulting in 4xx HTTP status code, only at debug level
self::logException($exception, Log::DEBUG);
break;
default:
self::logException($exception);
}
Common::sendHeader('Content-Type: text/html; charset=utf-8');
try {
echo self::getErrorResponse($exception);
} catch (Exception $e) {
// When there are failures while generating the HTML error response itself,
// we simply print out the error message instead.
echo $exception->getMessage();
}
exit(1);
}
public static function replaceSensitiveValues(string $message): string
{
$dbConfig = Db::getDatabaseConfig();
$valuesToReplace = [
'tokenauth' => Piwik::getCurrentUserTokenAuth(),
'generalSalt' => SettingsPiwik::getSalt(),
'dbuser' => $dbConfig['username'],
'dbpass' => $dbConfig['password'],
];
$mailConfig = Config::getInstance()->mail;
if (!empty($mailConfig['username'])) {
$valuesToReplace['smtpuser'] = $mailConfig['username'];
}
if (!empty($mailConfig['password'])) {
$valuesToReplace['smtppass'] = $mailConfig['password'];
}
// Remove possible empty entries
$valuesToReplace = array_filter($valuesToReplace);
// replace all sensitive values
$message = str_replace(array_values($valuesToReplace), array_keys($valuesToReplace), $message);
// remove the document root from all messages
return str_replace(PIWIK_DOCUMENT_ROOT, '', $message);
}
/**
* @param Exception|\Throwable $ex
*/
private static function getErrorResponse($ex)
{
$debugTrace = self::replaceSensitiveValues($ex->getTraceAsString());
$message = $ex->getMessage();
$isHtmlMessage = method_exists($ex, 'isHtmlMessage') && $ex->isHtmlMessage();
if (!$isHtmlMessage && Request::isApiRequest($_GET)) {
$outputFormat = strtolower(Common::getRequestVar('format', 'xml', 'string', $_GET + $_POST));
$response = new ResponseBuilder($outputFormat);
return $response->getResponseException($ex);
} elseif (!$isHtmlMessage) {
$message = Common::sanitizeInputValue($message);
}
$logoHeaderUrl = 'plugins/Morpheus/images/logo.svg';
$logoFaviconUrl = 'plugins/CoreHome/images/favicon.png';
try {
$logo = new CustomLogo();
if ($logo->hasSVGLogo()) {
$logoHeaderUrl = $logo->getSVGLogoUrl();
} else {
$logoHeaderUrl = $logo->getHeaderLogoUrl();
}
$logoFaviconUrl = $logo->getPathUserFavicon();
} catch (Exception $ex) {
try {
Log::debug($ex);
} catch (\Exception $otherEx) {
// DI container may not be setup at this point
}
}
// Exceptions that should result in 4xx status code should not be logged
$writeErrorLog = !($ex instanceof HttpCodeException && $ex->getCode() >= 400 && $ex->getCode() < 500);
$redirectUrl = null;
$countdownToRedirect = null;
if ($ex instanceof IRedirectException) {
$redirectUrl = $ex->getRedirectionUrl();
$countdownToRedirect = $ex->getCountdown();
}
$hostname = Url::getRFCValidHostname();
$hostStr = $hostname ? "[$hostname] " : '- ';
$result = Piwik_GetErrorMessagePage(
$message,
$debugTrace,
true,
true,
$logoHeaderUrl,
$logoFaviconUrl,
null,
$hostStr,
$writeErrorLog,
$redirectUrl,
$countdownToRedirect
);
try {
/**
* Triggered before a Piwik error page is displayed to the user.
*
* This event can be used to modify the content of the error page that is displayed when
* an exception is caught.
*
* @param string &$result The HTML of the error page.
* @param Exception $ex The Exception displayed in the error page.
*/
Piwik::postEvent('FrontController.modifyErrorPage', [&$result, $ex]);
} catch (ContainerDoesNotExistException $ex) {
// this can happen when an error occurs before the Piwik environment is created
}
return $result;
}
public static function shouldPrintBackTraceWithMessage(): bool
{
if (
class_exists('\Piwik\SettingsServer')
&& class_exists('\Piwik\Common')
&& \Piwik\SettingsServer::isArchivePhpTriggered()
&& \Piwik\Common::isPhpCliMode()
) {
return true;
}
try {
$isDevelopmentModeEnabled = Development::isEnabled();
} catch (Exception $e) {
$isDevelopmentModeEnabled = false;
}
return $isDevelopmentModeEnabled
|| (defined('PIWIK_PRINT_ERROR_BACKTRACE') && PIWIK_PRINT_ERROR_BACKTRACE)
|| !empty($GLOBALS['PIWIK_PRINT_ERROR_BACKTRACE'])
|| !empty($GLOBALS['PIWIK_TRACKER_DEBUG']);
}
private static function logException($exception, $loglevel = Log::ERROR)
{
try {
switch ($loglevel) {
case (Log::DEBUG):
StaticContainer::get(LoggerInterface::class)->debug('Uncaught exception: {exception}', [
'exception' => $exception,
'ignoreInScreenWriter' => true,
]);
break;
case (Log::ERROR):
default:
StaticContainer::get(LoggerInterface::class)->error('Uncaught exception: {exception}', [
'exception' => $exception,
'ignoreInScreenWriter' => true,
]);
}
} catch (DependencyException $ex) {
// ignore (occurs if exception is thrown when resolving DI entries)
} catch (ContainerDoesNotExistException $ex) {
// ignore
}
}
}
|