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