FOSSology  4.4.0
Open Source License Compliance by Open Source Software
LicenseController.php
Go to the documentation of this file.
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2021 HH Partners
4  SPDX-FileCopyrightText: © 2023 Samuel Dushimimana <dushsam100@gmail.com>
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
13 namespace Fossology\UI\Api\Controllers;
14 
33 use Psr\Container\ContainerInterface;
34 use Psr\Http\Message\ServerRequestInterface as Request;
35 use Slim\Psr7\Factory\StreamFactory;
36 
42 {
46  const PAGE_PARAM = "page";
50  const LIMIT_PARAM = "limit";
54  const ACTIVE_PARAM = "active";
58  const LICENSE_FETCH_LIMIT = 100;
63  private $licenseDao;
64 
70 
76 
77 
81  public function __construct($container)
82  {
83  parent::__construct($container);
84  $this->licenseDao = $this->container->get('dao.license');
85  $this->adminLicenseAckDao = $this->container->get('dao.license.acknowledgement');
86  $this->licenseStdCommentDao = $this->container->get('dao.license.stdc');
87  }
88 
98  public function getLicense($request, $response, $args)
99  {
100  $shortName = $args["shortname"];
101 
102  if (empty($shortName)) {
103  throw new HttpBadRequestException("Short name missing from request.");
104  }
105 
106  $license = $this->licenseDao->getLicenseByShortName($shortName,
107  $this->restHelper->getGroupId());
108 
109  if ($license === null) {
110  throw new HttpNotFoundException(
111  "No license found with short name '$shortName'.");
112  }
113 
114  $obligations = $this->licenseDao->getLicenseObligations([$license->getId()],
115  false);
116  $obligations = array_merge($obligations,
117  $this->licenseDao->getLicenseObligations([$license->getId()], true));
118  $obligationList = [];
119  foreach ($obligations as $obligation) {
120  $obligationList[] = new Obligation(
121  $obligation['ob_pk'],
122  $obligation['ob_topic'],
123  $obligation['ob_type'],
124  $obligation['ob_text'],
125  $obligation['ob_classification'],
126  $obligation['ob_comment']
127  );
128  }
129 
130  $returnVal = new License(
131  $license->getId(),
132  $license->getShortName(),
133  $license->getFullName(),
134  $license->getText(),
135  $license->getUrl(),
136  $obligationList,
137  $license->getRisk()
138  );
139 
140  return $response->withJson($returnVal->getArray(), 200);
141  }
142 
152  public function getAllLicenses($request, $response, $args)
153  {
154  $query = $request->getQueryParams();
155  $limit = $request->getHeaderLine(self::LIMIT_PARAM);
156  if (! empty($limit)) {
157  $limit = filter_var($limit, FILTER_VALIDATE_INT);
158  if ($limit < 1) {
159  throw new HttpBadRequestException(
160  "limit should be positive integer > 1");
161  }
162  } else {
163  $limit = self::LICENSE_FETCH_LIMIT;
164  }
165 
166  $kind = "all";
167  if (array_key_exists("kind", $query) && !empty($query["kind"]) &&
168  in_array($query["kind"], ["all", "candidate", "main"])) {
169  $kind = $query["kind"];
170  }
171 
172  $totalPages = $this->dbHelper->getLicenseCount($kind,
173  $this->restHelper->getGroupId());
174  $totalPages = intval(ceil($totalPages / $limit));
175 
176  $page = $request->getHeaderLine(self::PAGE_PARAM);
177  if (! empty($page) || $page == "0") {
178  $page = filter_var($page, FILTER_VALIDATE_INT);
179  if ($page <= 0) {
180  throw new HttpBadRequestException(
181  "page should be positive integer > 0");
182  }
183  if ($totalPages != 0 && $page > $totalPages) {
184  throw (new HttpBadRequestException(
185  "Can not exceed total pages: $totalPages"))
186  ->setHeaders(["X-Total-Pages" => $totalPages]);
187  }
188  } else {
189  $page = 1;
190  }
191  $onlyActive = $request->getHeaderLine(self::ACTIVE_PARAM);
192  if (! empty($onlyActive)) {
193  $onlyActive = filter_var($onlyActive, FILTER_VALIDATE_BOOLEAN);
194  } else {
195  $onlyActive = false;
196  }
197 
198  $licenses = $this->dbHelper->getLicensesPaginated($page, $limit,
199  $kind, $this->restHelper->getGroupId(), $onlyActive);
200  $licenseList = [];
201 
202  foreach ($licenses as $license) {
203  $newRow = new License(
204  $license['rf_pk'],
205  $license['rf_shortname'],
206  $license['rf_fullname'],
207  $license['rf_text'],
208  $license['rf_url'],
209  null,
210  $license['rf_risk'],
211  $license['group_fk'] != 0
212  );
213  $licenseList[] = $newRow->getArray();
214  }
215 
216  return $response->withHeader("X-Total-Pages", $totalPages)
217  ->withJson($licenseList, 200);
218  }
219 
229  public function createLicense($request, $response, $args)
230  {
231  $newLicense = $this->getParsedBody($request);
232  $newLicense = License::parseFromArray($newLicense);
233  if ($newLicense === -1) {
234  throw new HttpBadRequestException(
235  "Input contains additional properties.");
236  }
237  if ($newLicense === -2) {
238  throw new HttpBadRequestException("Property 'shortName' is required.");
239  }
240  if (! $newLicense->getIsCandidate() && ! Auth::isAdmin()) {
241  throw new HttpForbiddenException("Need to be admin to create " .
242  "non-candidate license.");
243  }
244  $tableName = "license_ref";
245  $assocData = [
246  "rf_shortname" => $newLicense->getShortName(),
247  "rf_fullname" => $newLicense->getFullName(),
248  "rf_text" => $newLicense->getText(),
249  "rf_md5" => md5($newLicense->getText()),
250  "rf_risk" => $newLicense->getRisk(),
251  "rf_url" => $newLicense->getUrl(),
252  "rf_detector_type" => 1
253  ];
254  $okToAdd = true;
255  if ($newLicense->getIsCandidate()) {
256  $tableName = "license_candidate";
257  $assocData["group_fk"] = $this->restHelper->getGroupId();
258  $assocData["rf_user_fk_created"] = $this->restHelper->getUserId();
259  $assocData["rf_user_fk_modified"] = $this->restHelper->getUserId();
260  $assocData["marydone"] = $newLicense->getMergeRequest();
261  $okToAdd = $this->isNewLicense($newLicense->getShortName(),
262  $this->restHelper->getGroupId());
263  } else {
264  $okToAdd = $this->isNewLicense($newLicense->getShortName());
265  }
266  if (! $okToAdd) {
267  throw new HttpConflictException("License with shortname '" .
268  $newLicense->getShortName() . "' already exists!");
269  }
270  try {
271  $rfPk = $this->dbHelper->getDbManager()->insertTableRow($tableName,
272  $assocData, __METHOD__ . ".newLicense", "rf_pk");
273  $newInfo = new Info(201, $rfPk, InfoType::INFO);
274  } catch (\Exception $e) {
275  throw new HttpConflictException(
276  "License with same text already exists!", $e);
277  }
278  return $response->withJson($newInfo->getArray(), $newInfo->getCode());
279  }
280 
290  public function updateLicense($request, $response, $args)
291  {
292  $newParams = $this->getParsedBody($request);
293  $shortName = $args["shortname"];
294  if (empty($shortName)) {
295  throw new HttpBadRequestException("Short name missing from request.");
296  }
297 
298  $license = $this->licenseDao->getLicenseByShortName($shortName,
299  $this->restHelper->getGroupId());
300 
301  if ($license === null) {
302  throw new HttpNotFoundException(
303  "No license found with short name '$shortName'.");
304  }
305  $isCandidate = $this->restHelper->getDbHelper()->doesIdExist(
306  "license_candidate", "rf_pk", $license->getId());
307  if (!$isCandidate && !Auth::isAdmin()) {
308  throw new HttpForbiddenException(
309  "Need to be admin to edit non-candidate license.");
310  }
311  if ($isCandidate && ! $this->restHelper->getUserDao()->isAdvisorOrAdmin(
312  $this->restHelper->getUserId(), $this->restHelper->getGroupId())) {
313  throw new HttpForbiddenException(
314  "Operation not permitted for this group.");
315  }
316 
317  $assocData = [];
318  if (array_key_exists('fullName', $newParams)) {
319  $assocData['rf_fullname'] = StringOperation::replaceUnicodeControlChar($newParams['fullName']);
320  }
321  if (array_key_exists('text', $newParams)) {
322  $assocData['rf_text'] = StringOperation::replaceUnicodeControlChar($newParams['text']);
323  }
324  if (array_key_exists('url', $newParams)) {
325  $assocData['rf_url'] = StringOperation::replaceUnicodeControlChar($newParams['url']);
326  }
327  if (array_key_exists('risk', $newParams)) {
328  $assocData['rf_risk'] = intval($newParams['risk']);
329  }
330  if (empty($assocData)) {
331  throw new HttpBadRequestException("Empty body sent.");
332  }
333 
334  $tableName = "license_ref";
335  if ($isCandidate) {
336  $tableName = "license_candidate";
337  }
338  $this->dbHelper->getDbManager()->updateTableRow($tableName, $assocData,
339  "rf_pk", $license->getId(), __METHOD__ . ".updateLicense");
340  $newInfo = new Info(200, "License " . $license->getShortName() .
341  " updated.", InfoType::INFO);
342  return $response->withJson($newInfo->getArray(), $newInfo->getCode());
343  }
344 
351  private function isNewLicense($shortName, $groupId = 0)
352  {
353  $tableName = "ONLY license_ref";
354  $where = "";
355  $params = [$shortName];
356  $statement = __METHOD__;
357  if ($groupId != 0) {
358  $tableName = "license_candidate";
359  $where = "AND group_fk = $2";
360  $params[] = $groupId;
361  $statement .= ".candidate";
362  }
363  $sql = "SELECT count(*) cnt FROM " .
364  "$tableName WHERE rf_shortname = $1 $where;";
365  $result = $this->dbHelper->getDbManager()->getSingleRow($sql, $params,
366  $statement);
367  return $result["cnt"] == 0;
368  }
369 
379  public function handleImportLicense($request, $response, $args)
380  {
381  $this->throwNotAdminException();
382  $symReq = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
384  $adminLicenseFromCsv = $this->restHelper->getPlugin('admin_license_from_csv');
385 
386  $uploadedFile = $symReq->files->get($adminLicenseFromCsv->getFileInputName(),
387  null);
388 
389  $requestBody = $this->getParsedBody($request);
390  $delimiter = ',';
391  $enclosure = '"';
392  if (array_key_exists("delimiter", $requestBody) && !empty($requestBody["delimiter"])) {
393  $delimiter = $requestBody["delimiter"];
394  }
395  if (array_key_exists("enclosure", $requestBody) && !empty($requestBody["enclosure"])) {
396  $enclosure = $requestBody["enclosure"];
397  }
398 
399  $res = $adminLicenseFromCsv->handleFileUpload($uploadedFile, $delimiter,
400  $enclosure);
401 
402  if (!$res[0]) {
403  throw new HttpBadRequestException($res[1]);
404  }
405 
406  $newInfo = new Info($res[2], $res[1], InfoType::INFO);
407  return $response->withJson($newInfo->getArray(), $newInfo->getCode());
408  }
409 
419  public function getCandidates($request, $response, $args)
420  {
421  $this->throwNotAdminException();
423  $adminLicenseCandidate = $this->restHelper->getPlugin("admin_license_candidate");
424  $licenses = LicenseCandidate::convertDbArray($adminLicenseCandidate->getCandidateArrayData());
425  return $response->withJson($licenses, 200);
426  }
427 
437  public function deleteAdminLicenseCandidate($request, $response, $args)
438  {
439  $this->throwNotAdminException();
440  $id = intval($args['id']);
442  $adminLicenseCandidate = $this->restHelper->getPlugin('admin_license_candidate');
443 
444  if (!$adminLicenseCandidate->getDataRow($id)) {
445  throw new HttpNotFoundException("License candidate not found.");
446  }
447  $res = $adminLicenseCandidate->doDeleteCandidate($id,false);
448  $message = $res->getContent();
449  if ($res->getContent() !== 'true') {
450  throw new HttpConflictException(
451  "License used at following locations, can not delete: " .
452  $message);
453  }
454  $resInfo = new Info(202, "License candidate will be deleted.",
455  InfoType::INFO);
456  return $response->withJson($resInfo->getArray(), $resInfo->getCode());
457  }
458 
468  public function getAllAdminAcknowledgements($request, $response, $args)
469  {
470  $this->throwNotAdminException();
471  $res = $this->adminLicenseAckDao->getAllAcknowledgements();
472 
473  foreach ($res as $key => $ack) {
474  $res[$key]['id'] = intval($ack['la_pk']);
475  unset($res[$key]['la_pk']);
476  $res[$key]['is_enabled'] = $ack['is_enabled'] == "t";
477  }
478 
479  return $response->withJson($res, 200);
480  }
481 
491  public function handleAdminLicenseAcknowledgement($request, $response, $args)
492  {
493  $body = $this->getParsedBody($request);
494  $errors = [];
495  $success = [];
496 
497  if (empty($body)) {
498  throw new HttpBadRequestException("Request body is missing or empty.");
499  }
500  if (!is_array($body)) {
501  throw new HttpBadRequestException("Request body should be an array.");
502  }
503  foreach (array_keys($body) as $index) {
504  $ackReq = $body[$index];
505  if ((!$ackReq['update'] && empty($ackReq['name'])) || ($ackReq['update'] && empty($ackReq['name']) && !$ackReq['toggle'])) {
506  $error = new Info(400, "Acknowledgement name missing from the request #" . ($index + 1), InfoType::ERROR);
507  $errors[] = $error->getArray();
508  continue;
509  } else if ((!$ackReq['update'] && empty($ackReq['ack'])) || ($ackReq['update'] && empty($ackReq['ack']) && !$ackReq['toggle'])) {
510  $error = new Info(400, "Acknowledgement text missing from the request #" . ($index + 1), InfoType::ERROR);
511  $errors[] = $error->getArray();
512  continue;
513  }
514 
515  if ($ackReq['update']) {
516 
517  if (empty($ackReq['id'])) {
518  $error = new Info(400, "Acknowledgement ID missing from the request #" . ($index + 1), InfoType::ERROR);
519  $errors[] = $error->getArray();
520  continue;
521  }
522 
523  $sql = "SELECT la_pk, name FROM license_std_acknowledgement WHERE la_pk = $1;";
524  $existingAck = $this->dbHelper->getDbManager()->getSingleRow($sql, [$ackReq['id']]);
525 
526  if (empty($existingAck)) {
527  $error = new Info(404, "Acknowledgement not found for the request #" . ($index + 1), InfoType::ERROR);
528  $errors[] = $error->getArray();
529  continue;
530  } else if ($existingAck["name"] != $ackReq["name"] && $this->dbHelper->doesIdExist("license_std_acknowledgement", "name", $ackReq["name"])) {
531  $error = new Info(400, "Name already exists.", InfoType::ERROR);
532  $errors[] = $error->getArray();
533  continue;
534  }
535 
536  if ($ackReq["name"] && $ackReq["ack"]) {
537  $this->adminLicenseAckDao->updateAcknowledgement($ackReq["id"], $ackReq["name"], $ackReq["ack"]);
538  }
539 
540  if ($ackReq["toggle"]) {
541  $this->adminLicenseAckDao->toggleAcknowledgement($ackReq["id"]);
542  }
543 
544  $info = new Info(200, "Successfully updated admin license acknowledgement with name '" . $existingAck["name"] . "'", InfoType::INFO);
545  } else {
546 
547  if ($this->dbHelper->doesIdExist("license_std_acknowledgement", "name", $ackReq["name"])) {
548  $error = new Info(400, "Name already exists for the request #" . ($index + 1), InfoType::ERROR);
549  $errors[] = $error->getArray();
550  continue;
551  }
552  $res = $this->adminLicenseAckDao->insertAcknowledgement($ackReq["name"], $ackReq["ack"]);
553  if ($res == -2) {
554  $error = new Info(500, "Error while inserting new acknowledgement.", InfoType::ERROR);
555  $errors[] = $error->getArray();
556  continue;
557  }
558  $info = new Info(201, "Acknowledgement added successfully.", InfoType::INFO);
559  }
560  $success[] = $info->getArray();
561  }
562  return $response->withJson([
563  'success' => $success,
564  'errors' => $errors
565  ], 200);
566  }
567 
576  public function getAllLicenseStandardComments($request, $response, $args)
577  {
578  $res = $this->licenseStdCommentDao->getAllComments();
579  foreach ($res as $key => $ack) {
580  $res[$key]['id'] = intval($ack['lsc_pk']);
581  $res[$key]['is_enabled'] = $ack['is_enabled'] == "t";
582  unset($res[$key]['lsc_pk']);
583  }
584  return $response->withJson($res, 200);
585  }
586 
596  public function handleLicenseStandardComment($request, $response, $args)
597  {
598  $this->throwNotAdminException();
599 
600  $body = $this->getParsedBody($request);
601  $errors = [];
602  $success = [];
603 
604  if (empty($body)) {
605  throw new HttpBadRequestException("Request body is missing or empty.");
606  }
607  if (!is_array($body)) {
608  throw new HttpBadRequestException("Request body should be an array.");
609  }
610  foreach (array_keys($body) as $index) {
611  $commentReq = $body[$index];
612 
613  // Check if name and comment are present if update is false
614  if ((!$commentReq['update'] && empty($commentReq['name']))) {
615  $error = new Info(400, "Comment name missing from the request #" . ($index + 1), InfoType::ERROR);
616  $errors[] = $error->getArray();
617  continue;
618  } else if ((!$commentReq['update'] && empty($commentReq['comment']))) {
619  $error = new Info(400, "Comment text missing from the request #" . ($index + 1), InfoType::ERROR);
620  $errors[] = $error->getArray();
621  continue;
622  } else if ($commentReq['update'] && empty($commentReq['name']) && empty($commentReq['comment']) && empty($commentReq['toggle'])) {
623  $error = new Info(400, "Comment name, text or toggle missing from the request #" . ($index + 1), InfoType::ERROR);
624  $errors[] = $error->getArray();
625  continue;
626  }
627 
628  if ($commentReq['update']) {
629 
630  if (empty($commentReq['id'])) {
631  $error = new Info(400, "Standard Comment ID missing from the request #" . ($index + 1), InfoType::ERROR);
632  $errors[] = $error->getArray();
633  continue;
634  }
635 
636  $sql = "SELECT lsc_pk, name, comment FROM license_std_comment WHERE lsc_pk = $1;";
637  $existingComment = $this->dbHelper->getDbManager()->getSingleRow($sql, [$commentReq['id']]);
638 
639  if (empty($existingComment)) {
640  $error = new Info(404, "Standard comment not found for the request #" . ($index + 1), InfoType::ERROR);
641  $errors[] = $error->getArray();
642  continue;
643  // check if the new name doesn't already exist
644  } else if ($existingComment["name"] != $commentReq["name"] && $this->dbHelper->doesIdExist("license_std_comment", "name", $commentReq["name"])) {
645  $error = new Info(400, "Name already exists.", InfoType::ERROR);
646  $errors[] = $error->getArray();
647  continue;
648  }
649 
650  // if both fields were specified and are not empty, update the comment
651  if ($commentReq["name"] && $commentReq["comment"]) {
652  $this->licenseStdCommentDao->updateComment($commentReq["id"], $commentReq["name"], $commentReq["comment"]);
653  } else if ($commentReq["name"]) {
654  $this->licenseStdCommentDao->updateComment($commentReq["id"], $commentReq["name"], $existingComment["comment"]);
655  } else if ($commentReq["comment"]) {
656  $this->licenseStdCommentDao->updateComment($commentReq["id"], $existingComment["name"], $commentReq["comment"]);
657  }
658  // toggle the comment if the toggle field is set to true
659  if ($commentReq["toggle"]) {
660  $this->licenseStdCommentDao->toggleComment($commentReq["id"]);
661  }
662 
663  $info = new Info(200, "Successfully updated standard comment", InfoType::INFO);
664  } else {
665 
666  if ($this->dbHelper->doesIdExist("license_std_comment", "name", $commentReq["name"])) {
667  $error = new Info(400, "Name already exists for the request #" . ($index + 1), InfoType::ERROR);
668  $errors[] = $error->getArray();
669  continue;
670  }
671  $res = $this->licenseStdCommentDao->insertComment($commentReq["name"], $commentReq["comment"]);
672  if ($res == -2) {
673  $error = new Info(500, "Error while inserting new comment.", InfoType::ERROR);
674  $errors[] = $error->getArray();
675  continue;
676  }
677  $info = new Info(201, "Comment with name '". $commentReq['name'] ."' added successfully.", InfoType::INFO);
678  }
679  $success[] = $info->getArray();
680  }
681  return $response->withJson([
682  'success' => $success,
683  'errors' => $errors
684  ], 200);
685  }
686 
696  public function verifyLicense($request, $response, $args)
697  {
698  $this->throwNotAdminException();
699  $licenseShortName = $args["shortname"];
700  $body = $this->getParsedBody($request);
701  $parentName = $body["parentShortname"];
702 
703  if (empty($licenseShortName) || empty($parentName)) {
704  throw new HttpBadRequestException(
705  "License ShortName or Parent ShortName is missing.");
706  }
707 
708  $license = $this->licenseDao->getLicenseByShortName($licenseShortName, $this->restHelper->getGroupId());
709  if ($licenseShortName != $parentName) {
710  $parentLicense = $this->licenseDao->getLicenseByShortName($parentName, $this->restHelper->getGroupId());
711  } else {
712  $parentLicense = $license;
713  }
714 
715  if (empty($license) || empty($parentLicense)) {
716  throw new HttpNotFoundException("License not found.");
717  }
718 
719  try {
721  $adminLicenseCandidate = $this->restHelper->getPlugin('admin_license_candidate');
722  $ok = $adminLicenseCandidate->verifyCandidate($license->getId(), $licenseShortName, $parentLicense->getId());
723  } catch (\Throwable $th) {
724  throw new HttpConflictException('The license text already exists.', $th);
725  }
726 
727  if (!$ok) {
728  throw new HttpBadRequestException('Short name must be unique');
729  }
730  $with = $parentLicense->getId() === $license->getId() ? '' : " as variant of ($parentName).";
731  $info = new Info(200, 'Successfully verified candidate ('.$licenseShortName.')'.$with, InfoType::INFO);
732  return $response->withJson($info->getArray(), $info->getCode());
733  }
734 
744  public function mergeLicense($request, $response, $args)
745  {
746  $this->throwNotAdminException();
747  $licenseShortName = $args["shortname"];
748  $body = $this->getParsedBody($request);
749  $parentName = $body["parentShortname"];
750 
751  if (empty($licenseShortName) || empty($parentName)) {
752  throw new HttpBadRequestException(
753  "License ShortName or Parent ShortName is missing.");
754  }
755  if ($licenseShortName == $parentName) {
756  throw new HttpBadRequestException(
757  "License ShortName and Parent ShortName are same.");
758  }
759 
760  $license = $this->licenseDao->getLicenseByShortName($licenseShortName, $this->restHelper->getGroupId());
761  $mergeLicense = $this->licenseDao->getLicenseByShortName($parentName, $this->restHelper->getGroupId());
762 
763  if (empty($license) || empty($mergeLicense)) {
764  throw new HttpNotFoundException("License not found.");
765  }
766 
768  $adminLicenseCandidate = $this->restHelper->getPlugin('admin_license_candidate');
769  $vars = $adminLicenseCandidate->getDataRow($license->getId());
770  if (empty($vars)) {
771  throw new HttpNotFoundException("Candidate license not found.");
772  }
773 
774  try {
775  $vars['shortname'] = $vars['rf_shortname'];
776  $ok = $adminLicenseCandidate->mergeCandidate($license->getId(), $mergeLicense->getId(), $vars);
777  } catch (\Throwable $th) {
778  throw new HttpConflictException('The license text already exists.', $th);
779  }
780 
781  if (!$ok) {
782  throw new HttpInternalServerErrorException("Please try again later.");
783  }
784  $info = new Info(200, "Successfully merged candidate ($parentName) into ($licenseShortName).", InfoType::INFO);
785  return $response->withJson($info->getArray(), $info->getCode());
786  }
787 
797  public function getSuggestedLicense($request, $response, $args)
798  {
799  $this->throwNotAdminException();
800  $body = $this->getParsedBody($request);
801  $rfText = $body["referenceText"];
802  if (empty($rfText)) {
803  throw new HttpBadRequestException("Reference text is missing.");
804  }
806  $adminLicenseCandidate = $this->restHelper->getPlugin('admin_license_candidate');
807  list ($suggestIds, $rendered) = $adminLicenseCandidate->suggestLicenseId($rfText, true);
808  $highlights = [];
809 
810  foreach ($rendered as $value) {
811  $highlights[] = $value->getArray();
812  }
813 
814  if (! empty($suggestIds)) {
815  $suggest = $suggestIds[0];
816  $suggestLicense = $adminLicenseCandidate->getDataRow($suggest, 'ONLY license_ref');
817  $suggestLicense = [
818  'id' => intval($suggestLicense['rf_pk']),
819  'spdxName' => $suggestLicense['rf_spdx_id'],
820  'shortName' => $suggestLicense['rf_shortname'],
821  'fullName' => $suggestLicense['rf_fullname'],
822  'text' => $suggestLicense['rf_text'],
823  'url' => $suggestLicense['rf_url'],
824  'notes' => $suggestLicense['rf_notes'],
825  'risk' => intval($suggestLicense['rf_risk']),
826  'highlights' => $highlights,
827  ];
828  }
829  if (empty($suggestLicense)) {
830  $suggestLicense = [];
831  }
832  return $response->withJson($suggestLicense, 200);
833  }
834 
844  public function exportAdminLicenseToCSV($request, $response, $args)
845  {
846  $this->throwNotAdminException();
847  $query = $request->getQueryParams();
848  $rf = 0;
849  if (array_key_exists('id', $query)) {
850  $rf = intval($query['id']);
851  }
852  if ($rf != 0 &&
853  (! $this->dbHelper->doesIdExist("license_ref", "rf_pk", $rf) &&
854  ! $this->dbHelper->doesIdExist("license_candidate", "rf_pk", $rf))) {
855  throw new HttpNotFoundException("License not found.");
856  }
857  $dbManager = $this->dbHelper->getDbManager();
858  $licenseCsvExport = new LicenseCsvExport($dbManager);
859  $content = $licenseCsvExport->createCsv($rf);
860  $fileName = "fossology-license-export-" . date("YMj-Gis");
861  $newResponse = $response->withHeader('Content-type', 'text/csv, charset=UTF-8')
862  ->withHeader('Content-Disposition', 'attachment; filename=' . $fileName . '.csv')
863  ->withHeader('Pragma', 'no-cache')
864  ->withHeader('Cache-Control', 'no-cache, must-revalidate, maxage=1, post-check=0, pre-check=0')
865  ->withHeader('Expires', 'Expires: Thu, 19 Nov 1981 08:52:00 GMT');
866  $sf = new StreamFactory();
867  return $newResponse->withBody(
868  $content ? $sf->createStream($content) : $sf->createStream('')
869  );
870  }
871 }
Helper class to export license list as a CSV from the DB.
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
static isAdmin()
Check if user is admin.
Definition: Auth.php:92
Fossology exception.
Definition: Exception.php:15
static replaceUnicodeControlChar($input, $replace="")
handleLicenseStandardComment($request, $response, $args)
handleAdminLicenseAcknowledgement($request, $response, $args)
getAllLicenseStandardComments($request, $response, $args)
getAllAdminAcknowledgements($request, $response, $args)
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
static parseFromArray($inputLicense)
Definition: License.php:338