FOSSology  4.7.1
Open Source License Compliance by Open Source Software
index.php
Go to the documentation of this file.
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2017-2018,2021 Siemens AG
4  SPDX-FileCopyrightText: © 2021 Orange by Piotr Pszczola <piotr.pszczola@orange.com>
5  SPDX-FileCopyrightText: © 2023 Samuel Dushimimana <dushsam100@gmail.com>
6 
7  SPDX-License-Identifier: GPL-2.0-only
8 */
15 namespace Fossology\UI\Api;
16 
17 $GLOBALS['apiCall'] = true;
18 
19 // setup autoloading
20 require_once dirname(__DIR__, 3) . "/vendor/autoload.php";
21 require_once dirname(__FILE__, 4) . "/lib/php/bootstrap.php";
22 
56 use Psr\Http\Message\ServerRequestInterface;
57 use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
58 use Psr\Log\LoggerInterface;
59 use Slim\Exception\HttpMethodNotAllowedException;
60 use Slim\Exception\HttpNotFoundException;
61 use Slim\Factory\AppFactory;
62 use Slim\Middleware\ContentLengthMiddleware;
63 use Slim\Psr7\Request;
64 use Slim\Psr7\Response;
65 use Throwable;
66 
67 // Extracts the version from the URL
68 function getVersionFromUri ($uri)
69 {
70  $matches = [];
71  preg_match('/\/repo\/api\/v(\d+)/', $uri, $matches);
72  return isset($matches[1]) ? intval($matches[1]) : null;
73 }
74 
75 // Determine the API version based on the URL
76 $requestedVersion = isset($_SERVER['REQUEST_URI']) ? getVersionFromUri($_SERVER['REQUEST_URI']) : null;
77 $apiVersion = in_array($requestedVersion, [ApiVersion::V1, ApiVersion::V2]) ? $requestedVersion : ApiVersion::V1; // Default to "1"
78 
79 // Construct the base path
80 $BASE_PATH = "/repo/api/v" .$apiVersion;
81 
82 const AUTH_METHOD = "JWT_TOKEN";
83 
84 $GLOBALS['apiBasePath'] = $BASE_PATH;
85 
86 $startTime = microtime(true);
87 
88 /* Set SYSCONFDIR and set global (for backward compatibility) */
89 $SysConf = bootstrap();
90 
91 global $container;
93 $timingLogger = $container->get("log.timing");
94 $timingLogger->logWithStartTime("bootstrap", $startTime);
95 
96 /* Load UI templates */
97 $loader = $container->get('twig.loader');
98 $loader->addPath(dirname(__FILE__, 2) .'/template');
99 
100 /* Initialize global system configuration variables $SysConfig[] */
101 $timingLogger->tic();
102 $error = ConfigInit($GLOBALS['SYSCONFDIR'], $SysConf, false);
103 
104 $dbConnected = true;
105 if ($error === -1) {
106  $dbConnected = false;
107 }
108 
109 $timingLogger->toc("setup init");
110 
111 $timingLogger->tic();
112 if ($dbConnected) {
113  plugin_load();
114 }
115 
116 AppFactory::setContainer($container);
117 AppFactory::setResponseFactory(new ResponseFactoryHelper());
118 $app = AppFactory::create();
119 $app->setBasePath($BASE_PATH);
120 
121 // Custom middleware to set the API version as a request attribute
122 $apiVersionMiddleware = function (Request $request, RequestHandler $handler) use ($apiVersion) {
123  $request = $request->withAttribute(ApiVersion::ATTRIBUTE_NAME, $apiVersion);
124  return $handler->handle($request);
125 };
126 
127 /*
128  * To check the order of middlewares, refer
129  * https://www.slimframework.com/docs/v4/concepts/middleware.html
130  *
131  * FOSSology Init is the first middleware and Rest Auth is second.
132  *
133  * 1. The call enters from Rest Auth and initialize session variables.
134  * 2. It then goes to FOSSology Init and initialize all plugins
135  * 3. Added ApiVersion middleware to set 'apiVersion' attribute in request.
136  * 4. The normal flow continues.
137  * 5. The call enters ApiVersion middleware and leaves as is.
138  * 6. The call now enters FOSSology Init again and plugins are unloaded.
139  * 7. The call then enters Rest Auth and leaves as is.
140  */
141 if ($dbConnected) {
142  // Middleware for plugin initialization
143  $app->add(new FossologyInitMiddleware());
144  // Middleware for authentication
145  $app->add(new RestAuthMiddleware());
146  // Content length middleware
147  $app->add(new ContentLengthMiddleware());
148  // Api version middleware
149  $app->add($apiVersionMiddleware);
150 } else {
151  // DB not connected
152  // Respond to health request as expected
153  $app->get('/health', function($req, $res) {
154  $handler = new InfoController($GLOBALS['container']);
155  return $handler->getHealth($req, $res, -1);
156  });
157  // Handle any other request and respond explicitly
158  $app->any('{route:.*}', function(ServerRequestInterface $req, ResponseHelper $res) {
159  $error = new Info(503, "Unable to connect to DB.", InfoType::ERROR);
160  return $res->withJson($error->getArray(), $error->getCode());
161  });
162 
163  // Prevent further actions and exit
164  $app->run();
165  return 0;
166 }
167 
168 // Regex for matching a valid path parameter
169 $pattern = "[\\w\\d\\-\\.@_]+";
170 
171 // Regex for matching group names, which may contain spaces
172 $groupPattern = "[\\w\\d\\-\\.@_ ]+";
173 
175 $app->options('/{routes:.+}', AuthController::class . ':optionsVerification');
176 
178 $app->post('/tokens', AuthController::class . ':createNewJwtToken');
179 
181 $app->group('/osselot',
182  function (\Slim\Routing\RouteCollectorProxy $app) {
183  $app->get('/packages/{package:[\\w\\d\\-\\.@_]+}/versions', OsselotController::class . ':getPackageVersions');
184  $app->any('/{params:.*}', BadRequestController::class);
185  });
186 
188 $app->group('/uploads',
189  function (\Slim\Routing\RouteCollectorProxy $app) {
190  $app->get('[/{id:\\d+}]', UploadController::class . ':getUploads');
191  $app->delete('/{id:\\d+}', UploadController::class . ':deleteUpload');
192  $app->patch('/{id:\\d+}', UploadController::class . ':updateUpload');
193  $app->put('/{id:\\d+}', UploadController::class . ':moveUpload');
194  $app->post('', UploadController::class . ':postUpload');
195  $app->post('/oneshot/nomos', OneShotController::class . ':runOneShotNomos');
196  $app->post('/oneshot/monk', OneShotController::class . ':runOneShotMonk');
197  $app->post('/oneshot/ceu', OneShotController::class . ':runOneShotCEU');
198  $app->put('/{id:\\d+}/permissions', UploadController::class . ':setUploadPermissions');
199  $app->get('/{id:\\d+}/perm-groups', UploadController::class . ':getGroupsWithPermissions');
200  $app->get('/{id:\\d+}/groups/permission', UploadController::class . ':getGroupsWithPermissions');
201  $app->get('/{id:\\d+}/summary', UploadController::class . ':getUploadSummary');
202  $app->get('/{id:\\d+}/agents', UploadController::class . ':getAllAgents');
203  $app->get('/{id:\\d+}/agents/revision', UploadController::class . ':getAgentsRevision');
204  $app->get('/{id:\\d+}/licenses', UploadController::class . ':getUploadLicenses');
205  $app->get('/{id:\\d+}/licenses/histogram', UploadController::class . ':getLicensesHistogram');
206  $app->get('/{id:\\d+}/licenses/edited', UploadController::class . ':getEditedLicenses');
207  $app->get('/{id:\\d+}/licenses/reuse', UploadController::class . ':getReuseReportSummary');
208  $app->get('/{id:\\d+}/licenses/scanned', UploadController::class . ':getScannedLicenses');
209  $app->get('/{id:\\d+}/licenses/main', UploadController::class . ':getMainLicenses');
210  $app->post('/{id:\\d+}/licenses/main', UploadController::class . ':setMainLicense');
211  $app->get('/{id:\\d+}/download', UploadController::class . ':uploadDownload');
212  $app->get('/{id:\\d+}/clearing-progress', UploadController::class . ':getClearingProgressInfo');
213  $app->delete('/{id:\\d+}/licenses/{shortName:[\\w\\- \\.]+}/main', UploadController::class . ':removeMainLicense');
214  $app->get('/{id:\\d+}/topitem', UploadController::class . ':getTopItem');
215  $app->put('/{id:\\d+}/item/{itemId:\\d+}/licenses', UploadTreeController::class . ':handleAddEditAndDeleteLicenseDecision');
216  $app->get('/{id:\\d+}/item/{itemId:\\d+}/view', UploadTreeController::class. ':viewLicenseFile');
217  $app->get('/{id:\\d+}/item/{itemId:\\d+}/prev-next', UploadTreeController::class . ':getNextPreviousItem');
218  $app->get('/{id:\\d+}/item/{itemId:\\d+}/licenses', UploadTreeController::class . ':getLicenseDecisions');
219  $app->put('/{id:\\d+}/item/{itemId:\\d+}/clearing-decision', UploadTreeController::class . ':setClearingDecision');
220  $app->get('/{id:\\d+}/item/{itemId:\\d+}/bulk-history', UploadTreeController::class . ':getBulkHistory');
221  $app->get('/{id:\\d+}/item/{itemId:\\d+}/clearing-history', UploadTreeController::class . ':getClearingHistory');
222  $app->get('/{id:\\d+}/item/{itemId:\\d+}/highlight', UploadTreeController::class . ':getHighlightEntries');
223  $app->get('/{id:\\d+}/item/{itemId:\\d+}/tree/view', UploadTreeController::class . ':getTreeView');
224  $app->get('/{id:\\d+}/item/{itemId:\\d+}/info', FileInfoController::class . ':getItemInfo');
225  $app->post('/{id:\\d+}/item/{itemId:\\d+}/bulk-scan', UploadTreeController::class . ':scheduleBulkScan');
226  $app->get('/{id:\\d+}/conf', ConfController::class . ':getConfInfo');
227  $app->put('/{id:\\d+}/conf', ConfController::class . ':updateConfData');
228  $app->get('/{id:\\d+}/copyrights', UploadController::class . ':getUploadCopyrights');
229  $app->post('/{id:\\d+}/osselot/import', OsselotController::class . ':importOsselotReport');
231  $app->group('/{id:\\d+}/item/{itemId:\\d+}', function (\Slim\Routing\RouteCollectorProxy $app) {
232  $app->get('/copyrights', CopyrightController::class . ':getFileCopyrights');
233  $app->delete('/copyrights/{hash:.*}', CopyrightController::class . ':deleteFileCopyright');
234  $app->patch('/copyrights/{hash:.*}', CopyrightController::class . ':restoreFileCopyright');
235  $app->put('/copyrights/{hash:.*}', CopyrightController::class . ':updateFileCopyright');
236  $app->get('/totalcopyrights', CopyrightController::class . ':getTotalFileCopyrights');
237  $app->get('/scancode-copyrights', CopyrightController::class . ':getFileScanCodeCopyrights');
238  $app->delete('/scancode-copyrights/{hash:.*}', CopyrightController::class . ':deleteFileScanCodeCopyright');
239  $app->patch('/scancode-copyrights/{hash:.*}', CopyrightController::class . ':restoreFileScanCodeCopyright');
240  $app->put('/scancode-copyrights/{hash:.*}', CopyrightController::class . ':updateFileScanCodeCopyright');
241  $app->get('/user-copyrights', CopyrightController::class . ':getFileUserCopyrights');
242  $app->delete('/user-copyrights/{hash:.*}', CopyrightController::class . ':deleteFileUserCopyright');
243  $app->patch('/user-copyrights/{hash:.*}', CopyrightController::class . ':restoreFileUserCopyright');
244  $app->put('/user-copyrights/{hash:.*}', CopyrightController::class . ':updateFileUserCopyright');
245  $app->get('/totalusercopyrights', CopyrightController::class . ':getTotalFileUserCopyrights');
246  $app->get('/emails', CopyrightController::class . ':getFileEmail');
247  $app->delete('/emails/{hash:.*}', CopyrightController::class . ':deleteFileEmail');
248  $app->patch('/emails/{hash:.*}', CopyrightController::class . ':restoreFileEmail');
249  $app->put('/emails/{hash:.*}', CopyrightController::class . ':updateFileEmail');
250  $app->get('/scancode-emails', CopyrightController::class . ':getFileScanCodeEmail');
251  $app->delete('/scancode-emails/{hash:.*}', CopyrightController::class . ':deleteFileScanCodeEmail');
252  $app->patch('/scancode-emails/{hash:.*}', CopyrightController::class . ':restoreFileScanCodeEmail');
253  $app->put('/scancode-emails/{hash:.*}', CopyrightController::class . ':updateFileScanCodeEmail');
254  $app->get('/urls', CopyrightController::class . ':getFileUrl');
255  $app->delete('/urls/{hash:.*}', CopyrightController::class . ':deleteFileUrl');
256  $app->patch('/urls/{hash:.*}', CopyrightController::class . ':restoreFileUrl');
257  $app->put('/urls/{hash:.*}', CopyrightController::class . ':updateFileUrl');
258  $app->get('/scancode-urls', CopyrightController::class . ':getFileScanCodeUrl');
259  $app->delete('/scancode-urls/{hash:.*}', CopyrightController::class . ':deleteFileScanCodeUrl');
260  $app->patch('/scancode-urls/{hash:.*}', CopyrightController::class . ':restoreFileScanCodeUrl');
261  $app->put('/scancode-urls/{hash:.*}', CopyrightController::class . ':updateFileScanCodeUrl');
262  $app->get('/authors', CopyrightController::class . ':getFileAuthor');
263  $app->delete('/authors/{hash:.*}', CopyrightController::class . ':deleteFileAuthor');
264  $app->patch('/authors/{hash:.*}', CopyrightController::class . ':restoreFileAuthor');
265  $app->put('/authors/{hash:.*}', CopyrightController::class . ':updateFileAuthor');
266  $app->get('/scancode-authors', CopyrightController::class . ':getFileScanCodeAuthor');
267  $app->delete('/scancode-authors/{hash:.*}', CopyrightController::class . ':deleteFileScanCodeAuthor');
268  $app->patch('/scancode-authors/{hash:.*}', CopyrightController::class . ':restoreFileScanCodeAuthor');
269  $app->put('/scancode-authors/{hash:.*}', CopyrightController::class . ':updateFileScanCodeAuthor');
270  $app->get('/eccs', CopyrightController::class . ':getFileEcc');
271  $app->delete('/eccs/{hash:.*}', CopyrightController::class . ':deleteFileEcc');
272  $app->patch('/eccs/{hash:.*}', CopyrightController::class . ':restoreFileEcc');
273  $app->put('/eccs/{hash:.*}', CopyrightController::class . ':updateFileEcc');
274  $app->get('/keywords', CopyrightController::class . ':getFileKeyword');
275  $app->delete('/keywords/{hash:.*}', CopyrightController::class . ':deleteFileKeyword');
276  $app->patch('/keywords/{hash:.*}', CopyrightController::class . ':restoreFileKeyword');
277  $app->put('/keywords/{hash:.*}', CopyrightController::class . ':updateFileKeyword');
278  $app->get('/ipras', CopyrightController::class . ':getFileIpra');
279  $app->delete('/ipras/{hash:.*}', CopyrightController::class . ':deleteFileIpra');
280  $app->patch('/ipras/{hash:.*}', CopyrightController::class . ':restoreFileIpra');
281  $app->put('/ipras/{hash:.*}', CopyrightController::class . ':updateFileIpra');
282  });
283  $app->any('/{params:.*}', BadRequestController::class);
284  });
285 
286 
288 $app->group('/users',
289  function (\Slim\Routing\RouteCollectorProxy $app) use ($pattern) {
290  $app->get('/self', UserController::class . ':getCurrentUser');
291  $app->get("[/{pathParam:$pattern}]", UserController::class . ':getUsers');
292  $app->put("/{pathParam:$pattern}", UserController::class . ':updateUser');
293  $app->post('', UserController::class . ':addUser');
294  $app->delete("/{pathParam:$pattern}", UserController::class . ':deleteUser');
295  $app->post('/tokens', UserController::class . ':createRestApiToken');
296  $app->get('/tokens/{type:\\w+}', UserController::class . ':getTokens');
297  $app->any('/{params:.*}', BadRequestController::class);
298  });
299 
301 $app->group('/obligations',
302  function (\Slim\Routing\RouteCollectorProxy $app) {
303  $app->get('/list', ObligationController::class . ':obligationsList');
304  $app->get('/{id:\\d+}', ObligationController::class . ':obligationsDetails');
305  $app->get('', ObligationController::class . ':obligationsAllDetails');
306  $app->delete('/{id:\\d+}', ObligationController::class . ':deleteObligation');
307  $app->get('/export-csv', ObligationController::class . ':exportObligationsToCSV');
308  $app->post('/import-csv', ObligationController::class . ':importObligationsFromCSV');
309  $app->get('/export-json', ObligationController::class . ':exportObligationsToJSON');
310  $app->post('/import-json', ObligationController::class . ':importObligationsFromJSON');
311  $app->any('/{params:.*}', BadRequestController::class);
312  });
313 
315 $app->group('/groups',
316  function (\Slim\Routing\RouteCollectorProxy $app) use ($pattern, $groupPattern) {
317  $app->get('', GroupController::class . ':getGroups');
318  $app->post('', GroupController::class . ':createGroup');
319  $app->post("/{pathParam:$groupPattern}/user/{userPathParam:$pattern}", GroupController::class . ':addMember');
320  $app->put("/{pathParam:$groupPattern}", GroupController::class . ':updateGroup');
321  $app->delete("/{pathParam:$groupPattern}", GroupController::class . ':deleteGroup');
322  $app->delete("/{pathParam:$groupPattern}/user/{userPathParam:$pattern}", GroupController::class . ':deleteGroupMember');
323  $app->get('/deletable', GroupController::class . ':getDeletableGroups');
324  $app->get("/{pathParam:$groupPattern}/members", GroupController::class . ':getGroupMembers');
325  $app->put("/{pathParam:$groupPattern}/user/{userPathParam:$pattern}", GroupController::class . ':changeUserPermission');
326  $app->any('/{params:.*}', BadRequestController::class);
327  });
328 
330 $app->group('/jobs',
331  function (\Slim\Routing\RouteCollectorProxy $app) {
332  $app->get('[/{id:\\d+}]', JobController::class . ':getJobs');
333  $app->get('/all', JobController::class . ':getAllJobs');
334  $app->get('/dashboard/statistics', JobController::class . ':getJobStatistics');
335  $app->get('/scheduler/operation/{operationName:[\\w\\- \\.]+}', JobController::class . ':getSchedulerJobOptionsByOperation');
336  $app->post('/scheduler/operation/run', JobController::class . ':handleRunSchedulerOption');
337  $app->post('', JobController::class . ':createJob');
338  $app->get('/history', JobController::class . ':getJobsHistory');
339  $app->get('/dashboard', JobController::class . ':getAllServerJobsStatus');
340  $app->delete('/{id:\\d+}/{queue:\\d+}', JobController::class . ':deleteJob');
341  $app->any('/{params:.*}', BadRequestController::class);
342  });
343 
345 $app->group('/search',
346  function (\Slim\Routing\RouteCollectorProxy $app) {
347  $app->get('', SearchController::class . ':performSearch');
348  });
349 
351 $app->group('/maintenance',
352  function (\Slim\Routing\RouteCollectorProxy $app) {
353  $app->post('', MaintenanceController::class . ':createMaintenance');
354  $app->get('', MaintenanceController::class . ':getMaintenanceInfo');
355  $app->any('/{params:.*}', BadRequestController::class);
356  });
357 
358 
360 $app->group('/folders',
361  function (\Slim\Routing\RouteCollectorProxy $app) {
362  $app->get('[/{id:\\d+}]', FolderController::class . ':getFolders');
363  $app->post('', FolderController::class . ':createFolder');
364  $app->delete('/{id:\\d+}', FolderController::class . ':deleteFolder');
365  $app->patch('/{id:\\d+}', FolderController::class . ':editFolder');
366  $app->put('/{id:\\d+}', FolderController::class . ':copyFolder');
367  $app->get('/{id:\\d+}/contents/unlinkable', FolderController::class . ':getUnlinkableFolderContents');
368  $app->put('/contents/{contentId:\\d+}/unlink', FolderController::class . ':unlinkFolder');
369  $app->get('/{id:\\d+}/contents', FolderController::class . ':getAllFolderContents');
370  $app->any('/{params:.*}', BadRequestController::class);
371  });
372 
374 $app->group('/report',
375  function (\Slim\Routing\RouteCollectorProxy $app) {
376  $app->get('', ReportController::class . ':getReport');
377  $app->get('/{id:\\d+}', ReportController::class . ':downloadReport');
378  $app->post('/import', ReportController::class . ':importReport');
379  $app->any('/{params:.*}', BadRequestController::class);
380  });
381 
383 $app->group('/customise',
384  function (\Slim\Routing\RouteCollectorProxy $app) {
385  $app->get('', CustomiseController::class . ':getCustomiseData');
386  $app->put('', CustomiseController::class . ':updateCustomiseData');
387  $app->get('/banner', CustomiseController::class . ':getBannerMessage');
388  $app->any('/{params:.*}', BadRequestController::class);
389  });
390 
392 $app->group('/info',
393  function (\Slim\Routing\RouteCollectorProxy $app) {
394  $app->get('', InfoController::class . ':getInfo');
395  });
396 $app->group('/health',
397  function (\Slim\Routing\RouteCollectorProxy $app) {
398  $app->get('', InfoController::class . ':getHealth');
399  });
400 $app->group('/openapi',
401  function (\Slim\Routing\RouteCollectorProxy $app) {
402  $app->get('', InfoController::class . ':getOpenApi');
403  });
404 
406 $app->group('/filesearch',
407  function (\Slim\Routing\RouteCollectorProxy $app) {
408  $app->post('', FileSearchController::class . ':getFiles');
409  $app->any('/{params:.*}', BadRequestController::class);
410  });
411 
413 $app->group('/license',
414  function (\Slim\Routing\RouteCollectorProxy $app) {
415  $app->get('', LicenseController::class . ':getAllLicenses');
416  $app->post('/import-csv', LicenseController::class . ':handleImportLicense');
417  $app->get('/export-csv', LicenseController::class . ':exportAdminLicenseToCSV');
418  $app->post('/import-json', LicenseController::class . ':handleImportLicense');
419  $app->get('/export-json', LicenseController::class . ':exportAdminLicenseToJSON');
420  $app->get('/bulk-text/export', LicenseController::class . ':exportBulkText');
421  $app->post('', LicenseController::class . ':createLicense');
422  $app->put('/verify/{shortname:.+}', LicenseController::class . ':verifyLicense');
423  $app->put('/merge/{shortname:.+}', LicenseController::class . ':mergeLicense');
424  $app->get('/admincandidates', LicenseController::class . ':getCandidates');
425  $app->get('/adminacknowledgements', LicenseController::class . ':getAllAdminAcknowledgements');
426  $app->get('/stdcomments', LicenseController::class . ':getAllLicenseStandardComments');
427  $app->put('/stdcomments', LicenseController::class . ':handleLicenseStandardComment');
428  $app->post('/suggest', LicenseController::class . ':getSuggestedLicense');
429  $app->get('/{shortname:.+}', LicenseController::class . ':getLicense');
430  $app->patch('/{shortname:.+}', LicenseController::class . ':updateLicense');
431  $app->delete('/admincandidates/{id:\\d+}',
432  LicenseController::class . ':deleteAdminLicenseCandidate');
433  $app->put('/adminacknowledgements', LicenseController::class . ':handleAdminLicenseAcknowledgement');
434  $app->any('/{params:.*}', BadRequestController::class);
435  });
436 
438 $app->group('/license-compatibility-rules',
439  function (\Slim\Routing\RouteCollectorProxy $app) {
440  $app->get('', LicenseCompatibilityRuleController::class . ':getRules');
441  $app->post('', LicenseCompatibilityRuleController::class . ':createRule');
442  $app->get('/export', LicenseCompatibilityRuleController::class . ':exportRules');
443  $app->post('/import', LicenseCompatibilityRuleController::class . ':importRules');
444  $app->put('/{id:\\d+}', LicenseCompatibilityRuleController::class . ':updateRule');
445  $app->delete('/{id:\\d+}', LicenseCompatibilityRuleController::class . ':deleteRule');
446  $app->any('/{params:.*}', BadRequestController::class);
447  });
448 
450 $app->group('/overview',
451  function (\Slim\Routing\RouteCollectorProxy $app) {
452  $app->get('/database/contents', OverviewController::class . ':getDatabaseContents');
453  $app->get('/disk/usage', OverviewController::class . ':getDiskSpaceUsage');
454  $app->get('/info/php', OverviewController::class . ':getPhpInfo');
455  $app->get('/database/metrics', OverviewController::class . ':getDatabaseMetrics');
456  $app->get('/queries/active', OverviewController::class . ':getActiveQueries');
457  $app->any('/{params:.*}', BadRequestController::class);
458  });
459 
461 // Define Custom Error Handler
462 $customErrorHandler = function (
463  ServerRequestInterface $request,
464  Throwable $exception,
465  bool $displayErrorDetails,
466  bool $logErrors,
467  bool $logErrorDetails,
468  ?LoggerInterface $logger = null
469 ) use ($app) {
470  if ($logger === null) {
471  $logger = $app->getContainer()->get('logger');
472  }
473  if ($logErrors) {
474  $logger->error($exception->getMessage(), $exception->getTrace());
475  }
476  if ($displayErrorDetails) {
477  $payload = ['error'=> $exception->getMessage(),
478  'trace' => $exception->getTraceAsString()];
479  } else {
480  $error = new Info(500, "Something went wrong! Please try again later.",
481  InfoType::ERROR);
482  $payload = $error->getArray();
483  }
484 
485  $response = $app->getResponseFactory()->createResponse(500)
486  ->withHeader("Content-Type", "application/json");
487  $response->getBody()->write(
488  json_encode($payload, JSON_UNESCAPED_UNICODE)
489  );
490 
491  plugin_unload();
492  return CorsHelper::addCorsHeaders($response);
493 };
494 
495 $errorMiddleware = $app->addErrorMiddleware(false, true, true,
496  $container->get("logger"));
497 
498 // Catch all routes
499 $errorMiddleware->setErrorHandler(
500  HttpNotFoundException::class,
501  function (ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails) {
502  $response = new ResponseHelper();
503  $error = new Info(404, "Resource not found", InfoType::ERROR);
504  $response = $response->withJson($error->getArray(), $error->getCode());
505  plugin_unload();
506  return CorsHelper::addCorsHeaders($response);
507  });
508 
509 // Set the Not Allowed Handler
510 $errorMiddleware->setErrorHandler(
511  HttpMethodNotAllowedException::class,
512  function (ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails) {
513  $response = new ResponseHelper();
514  $error = new Info(405, "Method not allowed", InfoType::ERROR);
515  $response = $response->withJson($error->getArray(), $error->getCode());
516  plugin_unload();
517  return CorsHelper::addCorsHeaders($response);
518  });
519 
520 // Set custom error handler
521 $errorMiddleware->setErrorHandler(
522  HttpErrorException::class,
523  function (ServerRequestInterface $request, HttpErrorException $exception, bool $displayErrorDetails) {
524  $response = new ResponseHelper();
525  $error = new Info($exception->getCode(), $exception->getMessage(),
526  InfoType::ERROR);
527  $response = $response->withJson($error->getArray(), $error->getCode());
528  if (!empty($exception->getHeaders())) {
529  foreach ($exception->getHeaders() as $key => $value) {
530  $response = $response->withHeader($key, $value);
531  }
532  }
533  plugin_unload();
534  return CorsHelper::addCorsHeaders($response);
535  }, true
536 );
537 
538 $errorMiddleware->setDefaultErrorHandler($customErrorHandler);
539 
540 $app->run();
541 
542 $GLOBALS['container']->get("db.manager")->flushStats();
543 return 0;
Controller for REST API version.
Controller for OSSelot REST API endpoints.
Controller for OverviewController model.
static addCorsHeaders(ResponseInterface $response)
Definition: CorsHelper.php:21
Override Slim response factory for custom response.
Override Slim response for withJson function.
Middleware to initialize FOSSology for Slim framework.
Authentication middleware for Slim framework.
Different type of infos provided by REST.
Definition: InfoType.php:16
Info model to contain general error and return values.
Definition: Info.php:19
plugin_load()
Load every module ui found in mods-enabled.
if(!function_exists('resolve_sysconfig_value')) ConfigInit($sysconfdir, &$SysConf, $exitOnDbFail=true)
Initialize the fossology system after bootstrap().
bootstrap($sysconfdir="")
Bootstrap the fossology php library.
Definition: migratetest.php:82