FOSSology  4.7.1
Open Source License Compliance by Open Source Software
OsselotController.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2025 Vaibhav Sahu <sahusv4527@gmail.com>
4  SPDX-License-Identifier: GPL-2.0-only
5 */
6 
7 namespace Fossology\UI\Api\Controllers;
8 
17 use Symfony\Component\HttpFoundation\Request;
18 
24 {
33  public function getPackageVersions($request, $response, $args): ResponseHelper
34  {
35  global $SysConf;
36 
37  if (($SysConf['SYSCONFIG']['EnableOsselotReuse'] ?? '') !== 'true') {
38  $error = new Info(501, "OSSelot integration is disabled", InfoType::ERROR);
39  return $response->withJson($error->getArray(), $error->getCode());
40  }
41 
42  $package = $args['package'] ?? "";
43  if (strlen(trim($package)) == 0) {
44  throw new HttpBadRequestException("Missing package name");
45  }
46 
47  try {
48  $helper = new OsselotLookupHelper();
49  $versions = $helper->getVersions($package);
50 
51  if (empty($versions)) {
52  $error = new Info(404, "No curated versions found for '$package'", InfoType::ERROR);
53  return $response->withJson($error->getArray(), $error->getCode());
54  }
55 
56  rsort($versions, SORT_NATURAL);
57 
58  return $response->withJson($versions, 200);
59 
60  } catch (\Exception $e) {
61  $error = new Info(502, "OSSelot unavailable, try later", InfoType::ERROR);
62  return $response->withJson($error->getArray(), $error->getCode());
63  }
64  }
65 
74  public function importOsselotReport($request, $response, $args): ResponseHelper
75  {
76  global $SysConf;
77 
78  if (($SysConf['SYSCONFIG']['EnableOsselotReuse'] ?? '') !== 'true') {
79  $err = new Info(501, "OSSelot integration is disabled", InfoType::ERROR);
80  return $response->withJson($err->getArray(), $err->getCode());
81  }
82 
83  $uploadId = (int)($args['id'] ?? 0);
84  $this->uploadAccessible($uploadId);
85 
86  $body = $this->getParsedBody($request);
87  $pkg = $body['package'] ?? null;
88  $ver = $body['version'] ?? null;
89  $options = $body['options'] ?? null;
90 
91  if (!$pkg || !$ver || !is_array($options)) {
92  throw new HttpBadRequestException("Missing required fields: package, version, options");
93  }
94  $requiredOptions = [
95  'addLicenseInfoFromInfoInFile',
96  'addLicenseInfoFromConcluded',
97  'addConcludedAsDecisions',
98  'addCopyrights'
99  ];
100 
101  foreach ($requiredOptions as $optKey) {
102  if (!array_key_exists($optKey, $options)) {
103  throw new HttpBadRequestException("Option '$optKey' is required");
104  }
105  }
106 
107  $jobDao = $this->restHelper->getJobDao();
108  if (method_exists($jobDao, 'hasPendingReportImport') &&
109  $jobDao->hasPendingReportImport($uploadId)) {
110  $err = new Info(409, "An import job is already in progress for this upload", InfoType::ERROR);
111  return $response->withJson($err->getArray(), $err->getCode());
112  }
113 
114  try {
115  $helper = new OsselotLookupHelper();
116  $cachedPath = $helper->fetchSpdxFile($pkg, $ver);
117 
118  if (!$cachedPath || !is_file($cachedPath) || !is_readable($cachedPath)) {
119  $err = new Info(404, "No curated SPDX report found for '$pkg' version '$ver'", InfoType::ERROR);
120  return $response->withJson($err->getArray(), $err->getCode());
121  }
122 
123  $fileBase = $SysConf['FOSSOLOGY']['path'] . "/ReportImport/";
124  if (!is_dir($fileBase) && !mkdir($fileBase, 0755, true)) {
125  throw new \RuntimeException('Failed to create ReportImport directory');
126  }
127 
128  $originalName = basename($cachedPath);
129  if (!str_ends_with($originalName, '.rdf.xml')) {
130  $baseName = pathinfo($originalName, PATHINFO_FILENAME);
131  $originalName = str_ends_with($originalName, '.rdf') ?
132  $baseName . '.rdf.xml' : $originalName . '.rdf.xml';
133  }
134 
135  $targetFile = time() . '_' . random_int(0, getrandmax()) . '_osselot_' . $originalName;
136  $targetPath = $fileBase . $targetFile;
137 
138  if (!copy($cachedPath, $targetPath)) {
139  throw new \RuntimeException('Failed to copy SPDX file to target location');
140  }
141 
142  $reportImportAgent = plugin_find('agent_reportImport');
143  if (!$reportImportAgent || !method_exists($reportImportAgent, 'addReport') ||
144  !method_exists($reportImportAgent, 'setAdditionalJqCmdArgs') ||
145  !method_exists($reportImportAgent, 'AgentAdd')) {
146  throw new \RuntimeException('ReportImport agent not available or missing required methods');
147  }
148 
149  $importRequest = new Request();
150 
151  $addNewLicensesAs = $options['addNewLicensesAs'] ?? 'candidate';
152  if (!in_array($addNewLicensesAs, ['candidate', 'approved', 'rejected'], true)) {
153  $addNewLicensesAs = 'candidate';
154  }
155  $importRequest->request->set('addNewLicensesAs', $addNewLicensesAs);
156 
157  $booleanOptions = [
158  'addLicenseInfoFromInfoInFile' => $options['addLicenseInfoFromInfoInFile'],
159  'addLicenseInfoFromConcluded' => $options['addLicenseInfoFromConcluded'],
160  'addConcludedAsDecisions' => $options['addConcludedAsDecisions'],
161  'addConcludedAsDecisionsOverwrite' => $options['addConcludedAsDecisionsOverwrite'] ?? false,
162  'addConcludedAsDecisionsTBD' => $options['addConcludedAsDecisionsTBD'] ?? false,
163  'addCopyrights' => $options['addCopyrights']
164  ];
165 
166  foreach ($booleanOptions as $key => $value) {
167  $importRequest->request->set($key, $value ? 'true' : 'false');
168  }
169 
170  $licenseMatch = $options['licenseMatch'] ?? 'spdxid';
171  if (!in_array($licenseMatch, ['spdxid', 'name', 'text'], true)) {
172  $licenseMatch = 'spdxid';
173  }
174  $importRequest->request->set('licenseMatch', $licenseMatch);
175 
176  $jqCmdArgs = $reportImportAgent->addReport($targetFile);
177  $additionalArgs = $reportImportAgent->setAdditionalJqCmdArgs($importRequest);
178  $jqCmdArgs .= $additionalArgs;
179 
180  $userId = Auth::getUserId();
181  $groupId = Auth::getGroupId();
182 
183  $jobId = JobAddJob($userId, $groupId, "OSSelot Import", $uploadId);
184 
185  $error = "";
186  $dependencies = array();
187  $jobQueueId = $reportImportAgent->AgentAdd($jobId, $uploadId, $error, $dependencies, $jqCmdArgs);
188 
189  if ($jobQueueId < 0) {
190  if (file_exists($targetPath)) {
191  unlink($targetPath);
192  }
193  throw new \RuntimeException("Cannot schedule import job: " . $error);
194  }
195 
196  $info = new Info(202, "Import job scheduled successfully", InfoType::INFO);
197  $responseData = $info->getArray();
198  $responseData['jobId'] = intval($jobQueueId);
199 
200  return $response->withJson($responseData, $info->getCode());
201 
202  } catch (\InvalidArgumentException $e) {
203  $err = new Info(400, $e->getMessage(), InfoType::ERROR);
204  return $response->withJson($err->getArray(), $err->getCode());
205  } catch (\RuntimeException $e) {
206  if (isset($targetPath) && file_exists($targetPath)) {
207  unlink($targetPath);
208  }
209 
210  if (strpos($e->getMessage(), 'Could not fetch') !== false ||
211  strpos($e->getMessage(), 'No curated') !== false) {
212  $err = new Info(404, "No curated SPDX report found for '$pkg' version '$ver'", InfoType::ERROR);
213  } else {
214  $err = new Info(502, "OSSelot service unavailable, try later", InfoType::ERROR);
215  }
216  return $response->withJson($err->getArray(), $err->getCode());
217  } catch (\Exception $e) {
218  if (isset($targetPath) && file_exists($targetPath)) {
219  unlink($targetPath);
220  }
221 
222  error_log("OSSelot import error: " . $e->getMessage());
223  $err = new Info(502, "OSSelot service unavailable, try later", InfoType::ERROR);
224  return $response->withJson($err->getArray(), $err->getCode());
225  }
226  }
227 }
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
static getUserId()
Get the current user's id.
Definition: Auth.php:68
static getGroupId()
Get the current user's group id.
Definition: Auth.php:80
Fossology exception.
Definition: Exception.php:15
Controller for OSSelot REST API endpoints.
Base controller for REST calls.
getParsedBody(ServerRequestInterface $request)
Parse request body as JSON and return associative PHP array.
Override Slim response for withJson function.
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_find($pluginName)
Given the official name of a plugin, return the $Plugins object.
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690