Compare commits

...

3 Commits

Author SHA1 Message Date
Eric Espie
806a5b92df logs & exceptions 2026-06-09 08:56:05 +02:00
Eric Espie
7d0005acf3 Merge branch 'develop' into feature/log-exception 2026-06-08 09:50:00 +02:00
Benjamin DALSASS
9c782c41df log exception 2026-06-05 17:07:02 +02:00
9 changed files with 197 additions and 59 deletions

View File

@@ -5,7 +5,9 @@
* @license http://opensource.org/licenses/AGPL-3.0
*/
class CoreException extends Exception
use Combodo\iTop\Exception\ItopException;
class CoreException extends ItopException
{
protected $m_sIssue;
protected $m_sImpact;

View File

@@ -16,6 +16,7 @@
//
// You should have received a copy of the GNU Affero General Public License
// along with iTop. If not, see <http://www.gnu.org/licenses/>
use Combodo\iTop\Application\Helper\ExceptionHandlerHelper;
use Combodo\iTop\Application\Helper\Session;
require_once(APPROOT.'core/cmdbobject.class.inc.php');
@@ -63,6 +64,9 @@ register_shutdown_function(function () {
}
}
});
set_exception_handler([ExceptionHandlerHelper::class, 'HandleException']);
$oKPI = new ExecutionKPI();
Session::Start();
$oKPI->ComputeAndReport("Session Start");

View File

@@ -614,6 +614,12 @@ class LogChannels
* @since 3.2.0
*/
public const SECURITY = 'Security';
/**
* @var string
* @since 3.3.0
*/
public const EXCEPTION = 'Exception';
}
abstract class LogAPI
@@ -708,8 +714,14 @@ abstract class LogAPI
private static function PrepareErrorLog(string $sMessage, throwable $oException, array $aContext, bool $isPrevious = false): array
{
$aContext['Error Message'] = $oException->getMessage();
$aContext['Stack Trace'] = $oException->getTraceAsString();
$aContext['exception'] = get_class($oException);
$aContext['message'] = $oException->getMessage();
$aContext['stack'] = $oException->getTraceAsString();
if(method_exists($oException, 'GetContext')) {
$aContext = array_merge($aContext, $oException->GetContext());
}
return ['message' => ($isPrevious ? "Previous " : '')."Exception: $sMessage", 'context' => $aContext];
}

View File

@@ -132,6 +132,7 @@ return array(
'Combodo\\iTop\\Application\\Branding' => $baseDir . '/sources/Application/Branding.php',
'Combodo\\iTop\\Application\\EventRegister\\ApplicationEvents' => $baseDir . '/sources/Application/EventRegister/ApplicationEvents.php',
'Combodo\\iTop\\Application\\Helper\\CKEditorHelper' => $baseDir . '/sources/Application/Helper/CKEditorHelper.php',
'Combodo\\iTop\\Application\\Helper\\ExceptionHandlerHelper' => $baseDir . '/sources/Application/Helper/ExceptionHandlerHelper.php',
'Combodo\\iTop\\Application\\Helper\\ExportHelper' => $baseDir . '/sources/Application/Helper/ExportHelper.php',
'Combodo\\iTop\\Application\\Helper\\FormHelper' => $baseDir . '/sources/Application/Helper/FormHelper.php',
'Combodo\\iTop\\Application\\Helper\\ImportHelper' => $baseDir . '/sources/Application/Helper/ImportHelper.php',
@@ -444,6 +445,7 @@ return array(
'Combodo\\iTop\\Dependencies\\NPM\\iTopNPM' => $baseDir . '/sources/Dependencies/NPM/iTopNPM.php',
'Combodo\\iTop\\DesignDocument' => $baseDir . '/core/designdocument.class.inc.php',
'Combodo\\iTop\\DesignElement' => $baseDir . '/core/designdocument.class.inc.php',
'Combodo\\iTop\\Exception\\ItopException' => $baseDir . '/sources/Exception/ItopException.php',
'Combodo\\iTop\\Form\\Field\\AbstractSimpleField' => $baseDir . '/sources/Form/Field/AbstractSimpleField.php',
'Combodo\\iTop\\Form\\Field\\BlobField' => $baseDir . '/sources/Form/Field/BlobField.php',
'Combodo\\iTop\\Form\\Field\\CaseLogField' => $baseDir . '/sources/Form/Field/CaseLogField.php',

View File

@@ -533,6 +533,7 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
'Combodo\\iTop\\Application\\Branding' => __DIR__ . '/../..' . '/sources/Application/Branding.php',
'Combodo\\iTop\\Application\\EventRegister\\ApplicationEvents' => __DIR__ . '/../..' . '/sources/Application/EventRegister/ApplicationEvents.php',
'Combodo\\iTop\\Application\\Helper\\CKEditorHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/CKEditorHelper.php',
'Combodo\\iTop\\Application\\Helper\\ExceptionHandlerHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/ExceptionHandlerHelper.php',
'Combodo\\iTop\\Application\\Helper\\ExportHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/ExportHelper.php',
'Combodo\\iTop\\Application\\Helper\\FormHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/FormHelper.php',
'Combodo\\iTop\\Application\\Helper\\ImportHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/ImportHelper.php',
@@ -845,6 +846,7 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
'Combodo\\iTop\\Dependencies\\NPM\\iTopNPM' => __DIR__ . '/../..' . '/sources/Dependencies/NPM/iTopNPM.php',
'Combodo\\iTop\\DesignDocument' => __DIR__ . '/../..' . '/core/designdocument.class.inc.php',
'Combodo\\iTop\\DesignElement' => __DIR__ . '/../..' . '/core/designdocument.class.inc.php',
'Combodo\\iTop\\Exception\\ItopException' => __DIR__ . '/../..' . '/sources/Exception/ItopException.php',
'Combodo\\iTop\\Form\\Field\\AbstractSimpleField' => __DIR__ . '/../..' . '/sources/Form/Field/AbstractSimpleField.php',
'Combodo\\iTop\\Form\\Field\\BlobField' => __DIR__ . '/../..' . '/sources/Form/Field/BlobField.php',
'Combodo\\iTop\\Form\\Field\\CaseLogField' => __DIR__ . '/../..' . '/sources/Form/Field/CaseLogField.php',

View File

@@ -19,12 +19,12 @@ use Combodo\iTop\Application\UI\Base\Component\Toolbar\ToolbarUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Layout\PageContent\PageContentFactory;
use Combodo\iTop\Application\UI\Base\Layout\UIContentBlock;
use Combodo\iTop\Application\UI\Base\Layout\UIContentBlockUIBlockFactory;
use Combodo\iTop\Application\WebPage\ErrorPage;
use Combodo\iTop\Application\WebPage\iTopWebPage;
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Application\WelcomePopup\WelcomePopupService;
use Combodo\iTop\Controller\Base\Layout\ObjectController;
use Combodo\iTop\Controller\WelcomePopupController;
use Combodo\iTop\Exception\ItopException;
use Combodo\iTop\Service\Router\Router;
/**
@@ -1303,39 +1303,9 @@ try {
$oKPI->ComputeAndReport('Compute page');
$oP->output();
} catch (Exception $e) {
$oErrorPage = new ErrorPage(Dict::S('UI:PageTitle:FatalError'));
if ($e instanceof SecurityException) {
$oErrorPage->add("<h1>".Dict::S('UI:SystemIntrusion')."</h1>\n");
} else {
$oErrorPage->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
}
$sErrorDetails = ($e instanceof CoreException) ? $e->getHtmlDesc() : $e->getMessage();
$oErrorPage->error(Dict::Format('UI:Error_Details', utils::EscapeHtml($sErrorDetails)), $e);
$oErrorPage->output();
$sErrorStackTrace = ($e instanceof CoreException) ? $e->getFullStackTraceAsString() : $e->getTraceAsString();
if (MetaModel::IsLogEnabledIssue()) {
if (MetaModel::IsValidClass('EventIssue')) {
try {
$oLog = new EventIssue();
$oLog->Set('message', $e->getMessage());
$oLog->Set('userinfo', '');
$sIssue = ($e instanceof CoreException) ? $e->GetIssue() : 'PHP Exception';
$oLog->Set('issue', $sIssue);
$oLog->Set('impact', 'Page could not be displayed');
$oLog->Set('callstack', $sErrorStackTrace);
$aData = ($e instanceof CoreException) ? $e->getContextData() : [];
$oLog->Set('data', $aData);
$oLog->DBInsertNoReload();
} catch (Exception $e) {
IssueLog::Exception("Failed to log issue into the DB", $e);
}
}
}
$sOperationToLog = $operation ?? 'N/A';
IssueLog::Debug('UI.php operation='.$sOperationToLog.', error='.$e->getMessage()."\n".$sErrorStackTrace, LogChannels::CONSOLE);
throw new ItopException("Unable to handle UI operation", previous: $e, aContext: [
'operation' => ($operation ?? 'N/A'),
]);
}
class UI

View File

@@ -0,0 +1,119 @@
<?php
namespace Combodo\iTop\Application\Helper;
use Combodo\iTop\Application\WebPage\ErrorPage;
use IssueLog;
use SimpleXMLElement;
use Throwable;
class ExceptionHandlerHelper
{
public static array $aSupportedMimeTypes = [
'application/json' => 'json',
'application/xml' => 'xml',
'text/html' => 'html',
'text/plain' => 'text',
];
public static function HandleException(Throwable $oException)
{
$aStatus = ob_get_status();
if (count($aStatus) !== 0) {
ob_end_clean();
}
// Log the exception
IssueLog::Exception('Fatal error', $oException);
$mime = self::NegotiateMimeType();
if ($mime === null) {
http_response_code(406);
header('Content-Type: application/json; charset=utf-8');
header('Vary: Accept');
echo json_encode(['error' => 'Not Acceptable'], JSON_UNESCAPED_UNICODE);
return;
}
http_response_code(500);
header("Content-Type: {$mime}; charset=utf-8");
header('Vary: Accept');
$aData = [
'error' => 'Fatal error',
'message' => 'We are sorry, an unexpected error has occurred. Please try again later.',
];
switch (self::$aSupportedMimeTypes[$mime]) {
case 'json':
echo json_encode($aData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
break;
case 'xml':
$oXml = new SimpleXMLElement('<response/>');
array_walk_recursive($aData, function ($sValue, $sKey) use ($oXml) {
$oXml->addChild((string)$sKey, htmlspecialchars((string)$sValue, ENT_QUOTES | ENT_XML1, 'UTF-8'));
});
echo $oXml->asXML();
break;
case 'html':
// Create error page
$oErrorPage = new ErrorPage('Fatal error');
$oErrorPage->error('We are sorry, an unexpected error has occurred. Please try again later.<br><br>', $oException);
$oErrorPage->output();
break;
case 'text':
echo "Fatal error\n";
echo "We are sorry, an unexpected error has occurred. Please try again later.\n";
break;
}
}
public static function NegotiateMimeType(): ?string
{
$supportedMimes = array_keys(self::$aSupportedMimeTypes);
$acceptHeader = $_SERVER['HTTP_ACCEPT'] ?? '*/*';
if (trim($acceptHeader) === '' || $acceptHeader === '*/*') {
return in_array('application/json', $supportedMimes, true) ? 'application/json' : $supportedMimes[0];
}
$accepted = [];
foreach (explode(',', $acceptHeader) as $part) {
$part = trim($part);
$q = 1.0;
if (str_contains($part, ';')) {
[$type, $params] = array_map('trim', explode(';', $part, 2));
if (preg_match('/q=([0-9.]+)/', $params, $m)) {
$q = (float)$m[1];
}
} else {
$type = $part;
}
$accepted[] = ['type' => $type, 'q' => $q];
}
usort($accepted, fn ($a, $b) => $b['q'] <=> $a['q']);
foreach ($accepted as $a) {
foreach ($supportedMimes as $mime) {
if ($a['type'] === $mime || $a['type'] === '*/*') {
return $mime;
}
// Ex: application/* match application/json
if (str_ends_with($a['type'], '/*')) {
$prefix = explode('/', $a['type'])[0].'/';
if (str_starts_with($mime, $prefix)) {
return $mime;
}
}
}
}
return null;
}
}

View File

@@ -23,7 +23,6 @@ namespace Combodo\iTop\Application\TwigBase\Controller;
use ApplicationMenu;
use Combodo\iTop\Application\TwigBase\Twig\TwigHelper;
use Combodo\iTop\Application\WebPage\AjaxPage;
use Combodo\iTop\Application\WebPage\ErrorPage;
use Combodo\iTop\Application\WebPage\iTopWebPage;
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Controller\AbstractController;
@@ -261,29 +260,29 @@ abstract class Controller extends AbstractController
*/
public function HandleOperation(): void
{
try {
$this->CheckAccess();
$this->m_sOperation = utils::ReadParam('operation', $this->sDefaultOperation);
// try {
$this->CheckAccess();
$this->m_sOperation = utils::ReadParam('operation', $this->sDefaultOperation);
if ($this->CallOperation(utils::ToCamelCase($this->m_sOperation))) {
return;
}
// Fallback to unchanged names for compatibility
if ($this->CallOperation($this->m_sOperation)) {
return;
}
$this->DisplayBadRequest();
} catch (Exception $e) {
http_response_code(500);
$oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError'));
$oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
$oP->add(get_class($e).' : '.utils::EscapeHtml($e->GetMessage()));
$oP->output();
IssueLog::Exception('HandleOperation failed for '.json_encode($this->m_sOperation), $e);
if ($this->CallOperation(utils::ToCamelCase($this->m_sOperation))) {
return;
}
// Fallback to unchanged names for compatibility
if ($this->CallOperation($this->m_sOperation)) {
return;
}
$this->DisplayBadRequest();
// } catch (Exception $e) {
// http_response_code(500);
// $oP = new ErrorPage(Dict::S('UI:PageTitle:FatalError'));
// $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
// $oP->add(get_class($e).' : '.utils::EscapeHtml($e->GetMessage()));
// $oP->output();
//
// IssueLog::Exception('HandleOperation failed for '.json_encode($this->m_sOperation), $e);
// }
}
/**

View File

@@ -0,0 +1,28 @@
<?php
namespace Combodo\iTop\Exception;
use Exception;
use IssueLog;
use LogChannels;
use Throwable;
class ItopException extends Exception
{
private array $aContext;
public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null, array $aContext = [])
{
$aContext['code'] = $code;
IssueLog::Debug($message, LogChannels::EXCEPTION, $aContext);
parent::__construct($message, $code, $previous);
$this->aContext = $aContext;
}
public function getContext(): array
{
return $this->aContext;
}
}