FOSSology  4.4.0
Open Source License Compliance by Open Source Software
UploadController.php
Go to the documentation of this file.
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2018, 2020 Siemens AG
4  SPDX-FileContributor: Gaurav Mishra <mishra.gaurav@siemens.com>
5  SPDX-FileCopyrightText: © 2022 Soham Banerjee <sohambanerjee4abc@hotmail.com>
6  SPDX-FileCopyrightText: © 2022, 2023 Samuel Dushimimana <dushsam100@gmail.com>
7 
8  SPDX-License-Identifier: GPL-2.0-only
9 */
10 
16 namespace Fossology\UI\Api\Controllers;
17 
50 use Psr\Http\Message\ServerRequestInterface;
51 use Slim\Psr7\Factory\StreamFactory;
52 
58 {
59 
63  const AGENT_PARAM = "agent";
64 
68  const FOLDER_PARAM = "folderId";
69 
73  const RECURSIVE_PARAM = "recursive";
74 
78  const FILTER_NAME = "name";
79 
83  const FILTER_STATUS = "status";
84 
88  const FILTER_ASSIGNEE = "assignee";
89 
93  const FILTER_DATE = "since";
94 
98  const PAGE_PARAM = "page";
99 
103  const LIMIT_PARAM = "limit";
104 
108  const UPLOAD_FETCH_LIMIT = 100;
109 
113  const CONTAINER_PARAM = "containers";
114 
118  const VALID_STATUS = ["open", "inprogress", "closed", "rejected"];
119 
123  private $agentNames = AgentRef::AGENT_LIST;
124 
129  private $agentDao;
130 
131  public function __construct($container)
132  {
133  parent::__construct($container);
134  $groupId = $this->restHelper->getGroupId();
135  $dbManager = $this->dbHelper->getDbManager();
136  $this->agentDao = $this->container->get('dao.agent');
137  $uploadBrowseProxy = new UploadBrowseProxy($groupId, 0, $dbManager, false);
138  $uploadBrowseProxy->sanity();
139  }
140 
150  public function getUploads($request, $response, $args)
151  {
152  $id = null;
153  $folderId = null;
154  $recursive = true;
155  $query = $request->getQueryParams();
156  $name = null;
157  $status = null;
158  $assignee = null;
159  $since = null;
160  $apiVersion = ApiVersion::getVersion($request);
161 
162  if (array_key_exists(self::FOLDER_PARAM, $query)) {
163  $folderId = filter_var($query[self::FOLDER_PARAM], FILTER_VALIDATE_INT);
164  if (! $this->restHelper->getFolderDao()->isFolderAccessible($folderId,
165  $this->restHelper->getUserId())) {
166  throw new HttpNotFoundException("Folder does not exist");
167  }
168  }
169 
170  if (array_key_exists(self::RECURSIVE_PARAM, $query)) {
171  $recursive = filter_var($query[self::RECURSIVE_PARAM],
172  FILTER_VALIDATE_BOOLEAN);
173  }
174  if (array_key_exists(self::FILTER_NAME, $query)) {
175  $name = $query[self::FILTER_NAME];
176  }
177  if (array_key_exists(self::FILTER_STATUS, $query)) {
178  switch (strtolower($query[self::FILTER_STATUS])) {
179  case "open":
180  $status = UploadStatus::OPEN;
181  break;
182  case "inprogress":
183  $status = UploadStatus::IN_PROGRESS;
184  break;
185  case "closed":
186  $status = UploadStatus::CLOSED;
187  break;
188  case "rejected":
189  $status = UploadStatus::REJECTED;
190  break;
191  default:
192  $status = null;
193  }
194  }
195  if (array_key_exists(self::FILTER_ASSIGNEE, $query)) {
196  $username = $query[self::FILTER_ASSIGNEE];
197  if (strcasecmp($username, "-me-") === 0) {
198  $assignee = $this->restHelper->getUserId();
199  } elseif (strcasecmp($username, "-unassigned-") === 0) {
200  $assignee = 1;
201  } else {
202  $assignee = $this->restHelper->getUserDao()->getUserByName($username);
203  if (empty($assignee)) {
204  throw new HttpNotFoundException("No user with user name '$username'");
205  }
206  $assignee = $assignee['user_pk'];
207  }
208  }
209  if (array_key_exists(self::FILTER_DATE, $query)) {
210  $date = filter_var($query[self::FILTER_DATE], FILTER_VALIDATE_REGEXP,
211  ["options" => [
212  "regexp" => "/^\d{4}\-\d{2}\-\d{2}$/",
213  "flags" => FILTER_NULL_ON_FAILURE
214  ]]);
215  $since = strtotime($date);
216  }
217  if ($apiVersion == ApiVersion::V2) {
218  $page = $query[self::PAGE_PARAM] ?? "";
219  $limit = $query[self::LIMIT_PARAM] ?? "";
220  } else {
221  $page = $request->getHeaderLine(self::PAGE_PARAM);
222  $limit = $request->getHeaderLine(self::LIMIT_PARAM);
223  }
224  if (! empty($page) || $page == "0") {
225  $page = filter_var($page, FILTER_VALIDATE_INT);
226  if ($page <= 0) {
227  throw new HttpBadRequestException(
228  "page should be positive integer > 0");
229  }
230  } else {
231  $page = 1;
232  }
233  if (! empty($limit)) {
234  $limit = filter_var($limit, FILTER_VALIDATE_INT);
235  if ($limit < 1) {
236  throw new HttpBadRequestException(
237  "limit should be positive integer > 1");
238  }
239  } else {
240  $limit = self::UPLOAD_FETCH_LIMIT;
241  }
242 
243  if (isset($args['id'])) {
244  $id = intval($args['id']);
245  $this->uploadAccessible($id);
246  $this->isAdj2nestDone($id);
247  }
248  $options = [
249  "folderId" => $folderId,
250  "name" => $name,
251  "status" => $status,
252  "assignee" => $assignee,
253  "since" => $since
254  ];
255  list($pages, $uploads) = $this->dbHelper->getUploads(
256  $this->restHelper->getUserId(), $this->restHelper->getGroupId(), $limit,
257  $page, $id, $options, $recursive, $apiVersion);
258  if ($id !== null && ! empty($uploads)) {
259  $uploads = $uploads[0];
260  $pages = 1;
261  }
262  return $response->withHeader("X-Total-Pages", $pages)->withJson($uploads,
263  200);
264  }
265 
275  public function uploadDownload($request, $response, $args)
276  {
278  $ui_download = $this->restHelper->getPlugin('download');
279  $id = null;
280 
281  if (isset($args['id'])) {
282  $id = intval($args['id']);
283  $this->uploadAccessible($id);
284  }
285  $dbManager = $this->restHelper->getDbHelper()->getDbManager();
286  $uploadDao = $this->restHelper->getUploadDao();
287  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($id);
288  $itemTreeBounds = $uploadDao->getParentItemBounds($id,$uploadTreeTableName);
289  $sql = "SELECT pfile_fk , ufile_name FROM uploadtree_a WHERE uploadtree_pk=$1";
290  $params = array($itemTreeBounds->getItemId());
291  $descendants = $dbManager->getSingleRow($sql,$params);
292  $path= RepPath(($descendants['pfile_fk']));
293  $responseFile = $ui_download->getDownload($path, $descendants['ufile_name']);
294  $responseContent = $responseFile->getFile();
295  $newResponse = $response->withHeader('Content-Description',
296  'File Transfer')
297  ->withHeader('Content-Type',
298  $responseContent->getMimeType())
299  ->withHeader('Content-Disposition',
300  $responseFile->headers->get('Content-Disposition'))
301  ->withHeader('Cache-Control', 'must-revalidate')
302  ->withHeader('Pragma', 'private')
303  ->withHeader('Content-Length', filesize($responseContent->getPathname()));
304  $sf = new StreamFactory();
305  return $newResponse->withBody(
306  $sf->createStreamFromFile($responseContent->getPathname())
307  );
308  }
309 
319  public function getUploadSummary($request, $response, $args)
320  {
321  $id = intval($args['id']);
322  $query = $request->getQueryParams();
323  $selectedAgentId = $query['agentId'] ?? null;
324  $agentDao = $this->container->get('dao.agent');
325  $this->uploadAccessible($id);
326  if ($selectedAgentId !== null && !$this->dbHelper->doesIdExist("agent", "agent_pk", $selectedAgentId)) {
327  throw new HttpNotFoundException("Agent does not exist");
328  }
329  $this->isAdj2nestDone($id);
330  $uploadHelper = new UploadHelper();
331  $uploadSummary = $uploadHelper->generateUploadSummary($id, $this->restHelper->getGroupId());
332  $browseLicense = $this->restHelper->getPlugin('license');
333  $uploadDao = $this->restHelper->getUploadDao();
334  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($id);
335  $itemTreeBounds = $uploadDao->getParentItemBounds($id, $uploadTreeTableName);
336  $scanJobProxy = new ScanJobProxy($agentDao, $id);
337  $scannerAgents = array_keys(AgentRef::AGENT_LIST);
338  $scanJobProxy->createAgentStatus($scannerAgents);
339  $selectedAgentIds = empty($selectedAgentId) ? $scanJobProxy->getLatestSuccessfulAgentIds() : $selectedAgentId;
340  $res = $browseLicense->createLicenseHistogram("", "", $itemTreeBounds, $selectedAgentIds, $this->restHelper->getGroupId());
341  $uploadSummary->setUniqueConcludedLicenses($res['editedUniqueLicenseCount']);
342  $uploadSummary->setTotalConcludedLicenses($res['editedLicenseCount']);
343  $uploadSummary->setTotalLicenses($res['scannerLicenseCount']);
344  $uploadSummary->setUniqueLicenses($res['uniqueLicenseCount']);
345  $uploadSummary->setConcludedNoLicenseFoundCount($res['editedNoLicenseFoundCount']);
346  $uploadSummary->setFileCount($res['fileCount']);
347  $uploadSummary->setNoScannerLicenseFoundCount($res['noScannerLicenseFoundCount']);
348  $uploadSummary->setScannerUniqueLicenseCount($res['scannerUniqueLicenseCount']);
349 
350  return $response->withJson($uploadSummary->getArray(), 200);
351  }
352 
362  public function deleteUpload($request, $response, $args)
363  {
364  require_once dirname(__DIR__, 4) . "/delagent/ui/delete-helper.php";
365  $id = intval($args['id']);
366 
367  $this->uploadAccessible($id);
368  $result = TryToDelete($id, $this->restHelper->getUserId(),
369  $this->restHelper->getGroupId(), $this->restHelper->getUploadDao());
370  if ($result->getDeleteMessageCode() !== DeleteMessages::SUCCESS) {
372  $result->getDeleteMessageString());
373  }
374  $returnVal = new Info(202, "Delete Job for file with id " . $id,
375  InfoType::INFO);
376  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
377  }
378 
387  public function moveUpload($request, $response, $args)
388  {
389  if (ApiVersion::getVersion($request) == ApiVersion::V2) {
390  $queryParams = $request->getQueryParams();
391  $action = $queryParams['action'] ?? "";
392  } else {
393  $action = $request->getHeaderLine('action');
394  }
395  if (strtolower($action) == "move") {
396  $copy = false;
397  } else {
398  $copy = true;
399  }
400  return $this->changeUpload($request, $response, $args, $copy);
401  }
402 
413  private function changeUpload($request, $response, $args, $isCopy)
414  {
415  $queryParams = $request->getQueryParams();
416  $isApiVersionV2 = (ApiVersion::getVersion($request) == ApiVersion::V2);
417  $paramType = ($isApiVersionV2) ? 'parameter' : 'header';
418 
419  if ((!$isApiVersionV2 && !$request->hasHeader('folderId') || $isApiVersionV2 && !isset($queryParams['folderId']))
420  || !is_numeric($newFolderID = ($isApiVersionV2 ? $queryParams['folderId'] : $request->getHeaderLine('folderId')))) {
421  throw new HttpBadRequestException("For API version " . ($isApiVersionV2 ? 'V2' : 'V1') . ", 'folderId' $paramType should be present and an integer.");
422  }
423 
424  $id = intval($args['id']);
425  $returnVal = $this->restHelper->copyUpload($id, $newFolderID, $isCopy);
426  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
427  }
428 
438  public function postUpload($request, $response, $args)
439  {
440  $reqBody = $this->getParsedBody($request);
441  if (ApiVersion::getVersion($request) == ApiVersion::V2) {
442  $uploadType = $reqBody['uploadType'] ?? null;
443  $folderId = $reqBody['folderId'] ?? null;
444  $description = $reqBody['uploadDescription'] ?? "";
445  $public = $reqBody['public'] ?? null;
446  $applyGlobal = filter_var($reqBody['applyGlobal'] ?? null,
447  FILTER_VALIDATE_BOOLEAN);
448  $ignoreScm = $reqBody['ignoreScm'] ?? null;
449  } else {
450  $uploadType = $request->getHeaderLine('uploadType');
451  $folderId = $request->getHeaderLine('folderId');
452  $description = $request->getHeaderLine('uploadDescription');
453  $public = $request->getHeaderLine('public');
454  $applyGlobal = filter_var($request->getHeaderLine('applyGlobal'),
455  FILTER_VALIDATE_BOOLEAN);
456  $ignoreScm = $request->getHeaderLine('ignoreScm');
457  }
458 
459  $public = empty($public) ? 'protected' : $public;
460 
461  if (empty($uploadType)) {
462  throw new HttpBadRequestException("Require uploadType");
463  }
464  $scanOptions = [];
465  if (array_key_exists('scanOptions', $reqBody)) {
466  if ($uploadType == 'file') {
467  $scanOptions = json_decode($reqBody['scanOptions'], true);
468  } else {
469  $scanOptions = $reqBody['scanOptions'];
470  }
471  }
472 
473  if (! is_array($scanOptions)) {
474  $scanOptions = [];
475  }
476 
477  $uploadHelper = new UploadHelper();
478 
479  if ($uploadType != "file" && (empty($reqBody) ||
480  ! array_key_exists("location", $reqBody))) {
481  throw new HttpBadRequestException(
482  "Require location object if uploadType != file");
483  }
484  if (empty($folderId) ||
485  !is_numeric($folderId) && $folderId > 0) {
486  throw new HttpBadRequestException("folderId must be a positive integer!");
487  }
488 
489  $allFolderIds = $this->restHelper->getFolderDao()->getAllFolderIds();
490  if (!in_array($folderId, $allFolderIds)) {
491  throw new HttpNotFoundException("folderId $folderId does not exists!");
492  }
493  if (!$this->restHelper->getFolderDao()->isFolderAccessible($folderId)) {
494  throw new HttpForbiddenException("folderId $folderId is not accessible!");
495  }
496 
497  $locationObject = [];
498  if (array_key_exists("location", $reqBody)) {
499  $locationObject = $reqBody["location"];
500  } elseif ($uploadType != 'file') {
501  throw new HttpBadRequestException(
502  "Require location object if uploadType != file");
503  }
504 
505  $uploadResponse = $uploadHelper->createNewUpload($locationObject,
506  $folderId, $description, $public, $ignoreScm, $uploadType,
507  $applyGlobal);
508  $status = $uploadResponse[0];
509  $message = $uploadResponse[1];
510  $statusDescription = $uploadResponse[2];
511  if (! $status) {
512  throw new HttpInternalServerErrorException($message . "\n" .
513  $statusDescription);
514  }
515 
516  $uploadId = $uploadResponse[3];
517  if (! empty($scanOptions)) {
518  $info = $uploadHelper->handleScheduleAnalysis(intval($uploadId),
519  intval($folderId), $scanOptions, true);
520  if ($info->getCode() == 201) {
521  $info = new Info($info->getCode(), intval($uploadId), $info->getType());
522  }
523  } else {
524  $info = new Info(201, intval($uploadId), InfoType::INFO);
525  }
526  if (array_key_exists("mainLicense", $reqBody) &&
527  ! empty($reqBody["mainLicense"])) {
528  global $container;
530  $licenseDao = $container->get('dao.license');
531  $mainLicense = $licenseDao
532  ->getLicenseByShortName($reqBody["mainLicense"]);
533  if ($mainLicense !== null) {
535  $clearingDao = $container->get('dao.clearing');
536  $clearingDao->makeMainLicense($uploadId,
537  $this->restHelper->getGroupId(), $mainLicense->getId());
538  }
539  }
540  return $response->withJson($info->getArray(), $info->getCode());
541  }
542 
552  public function getUploadLicenses($request, $response, $args)
553  {
554  $id = intval($args['id']);
555  $query = $request->getQueryParams();
556  $apiVersion = ApiVersion::getVersion($request);
557  if ($apiVersion == ApiVersion::V2) {
558  $page = $query['page'] ?? "";
559  $limit = $query['limit'] ?? "";
560  } else {
561  $page = $request->getHeaderLine("page");
562  $limit = $request->getHeaderLine("limit");
563  }
564  if (! array_key_exists(self::AGENT_PARAM, $query)) {
565  throw new HttpBadRequestException("agent parameter missing from query.");
566  }
567  $agents = explode(",", $query[self::AGENT_PARAM]);
568  $containers = true;
569  if (array_key_exists(self::CONTAINER_PARAM, $query)) {
570  $containers = (strcasecmp($query[self::CONTAINER_PARAM], "true") === 0);
571  }
572 
573  $license = true;
574  if (array_key_exists('license', $query)) {
575  $license = (strcasecmp($query['license'], "true") === 0);
576  }
577 
578  $copyright = false;
579  if (array_key_exists('copyright', $query)) {
580  $copyright = (strcasecmp($query['copyright'], "true") === 0);
581  }
582 
583  if (!$license && !$copyright) {
584  throw new HttpBadRequestException(
585  "'license' and 'copyright' atleast one should be true.");
586  }
587 
588  $this->uploadAccessible($id);
589  $this->isAdj2nestDone($id);
590 
591  $this->areAgentsScheduled($id, $agents, $response);
592 
593  /*
594  * check if page && limit are numeric, if existing
595  */
596  if ((! ($page==='') && (! is_numeric($page) || $page < 1)) ||
597  (! ($limit==='') && (! is_numeric($limit) || $limit < 1))) {
598  throw new HttpBadRequestException(
599  "page and limit need to be positive integers!");
600  }
601 
602  // set page to 1 by default
603  if (empty($page)) {
604  $page = 1;
605  }
606 
607  // set limit to 50 by default and max as 1000
608  if (empty($limit)) {
609  $limit = 50;
610  } else if ($limit > 1000) {
611  $limit = 1000;
612  }
613 
614  $uploadHelper = new UploadHelper();
615  list($licenseList, $count) = $uploadHelper->getUploadLicenseList($id, $agents, $containers, $license, $copyright, $page-1, $limit, $apiVersion);
616  $totalPages = intval(ceil($count / $limit));
617  return $response->withHeader("X-Total-Pages", $totalPages)->withJson($licenseList, 200);
618  }
619 
629  public function getUploadCopyrights($request, $response, $args)
630  {
631  $id = intval($args['id']);
632  $this->uploadAccessible($id);
633  $this->isAdj2nestDone($id);
634  $uploadHelper = new UploadHelper();
635  $licenseList = $uploadHelper->getUploadCopyrightList($id);
636  return $response->withJson($licenseList, 200);
637  }
638 
648  public function updateUpload($request, $response, $args)
649  {
650  $id = intval($args['id']);
651  $query = $request->getQueryParams();
652  $userDao = $this->restHelper->getUserDao();
653  $userId = $this->restHelper->getUserId();
654  $groupId = $this->restHelper->getGroupId();
655 
656  $perm = $userDao->isAdvisorOrAdmin($userId, $groupId);
657  if (!$perm) {
658  throw new HttpForbiddenException("Not advisor or admin of current group. " .
659  "Can not update upload.");
660  }
661  $uploadBrowseProxy = new UploadBrowseProxy(
662  $groupId,
663  $perm,
664  $this->dbHelper->getDbManager()
665  );
666 
667  $assignee = null;
668  $status = null;
669  $comment = null;
670 
671  // Handle assignee info
672  if (array_key_exists(self::FILTER_ASSIGNEE, $query)) {
673  $assignee = filter_var($query[self::FILTER_ASSIGNEE], FILTER_VALIDATE_INT);
674  $userList = $userDao->getUserChoices($groupId);
675  if (!array_key_exists($assignee, $userList)) {
676  throw new HttpNotFoundException(
677  "New assignee does not have permisison on upload.");
678  }
679  $uploadBrowseProxy->updateTable("assignee", $id, $assignee);
680  }
681  // Handle new status
682  if (
683  array_key_exists(self::FILTER_STATUS, $query) &&
684  in_array(strtolower($query[self::FILTER_STATUS]), self::VALID_STATUS)
685  ) {
686  $newStatus = strtolower($query[self::FILTER_STATUS]);
687  $comment = '';
688  if (in_array($newStatus, ["closed", "rejected"])) {
689  $body = $request->getBody();
690  $comment = $body->getContents();
691  $body->close();
692  }
693  $status = 0;
694  if ($newStatus == self::VALID_STATUS[1]) {
695  $status = UploadStatus::IN_PROGRESS;
696  } elseif ($newStatus == self::VALID_STATUS[2]) {
697  $status = UploadStatus::CLOSED;
698  } elseif ($newStatus == self::VALID_STATUS[3]) {
699  $status = UploadStatus::REJECTED;
700  } else {
701  $status = UploadStatus::OPEN;
702  }
703  $uploadBrowseProxy->setStatusAndComment($id, $status, $comment);
704  }
705 
706  $returnVal = new Info(202, "Upload updated successfully.", InfoType::INFO);
707  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
708  }
709 
715  private function isAdj2nestDone($id): void
716  {
717  $itemTreeBounds = $this->restHelper->getUploadDao()->getParentItemBounds(
718  $id);
719  if ($itemTreeBounds === false || empty($itemTreeBounds->getLeft())) {
721  "Ununpack job not started. Please check job status at " .
722  "/api/v1/jobs?upload=" . $id))
723  ->setHeaders(['Retry-After' => '60',
724  'Look-at' => "/api/v1/jobs?upload=" . $id]);
725  }
726  }
727 
737  private function areAgentsScheduled($uploadId, $agents, $response): void
738  {
739  global $container;
740  $agentDao = $container->get('dao.agent');
741 
742  $agentList = array_keys(AgentRef::AGENT_LIST);
743  $intersectArray = array_intersect($agents, $agentList);
744 
745  if (count($agents) != count($intersectArray)) {
746  throw new HttpBadRequestException("Agent should be any of " .
747  implode(", ", $agentList) . ". " . implode(",", $agents) . " passed.");
748  } else {
749  // Agent is valid, check if they have ars tables.
750  foreach ($agents as $agent) {
751  if (! $agentDao->arsTableExists($agent)) {
753  "Agent $agent not scheduled for the upload. " .
754  "Please POST to /jobs");
755  }
756  }
757  }
758 
759  $scanProxy = new ScanJobProxy($agentDao, $uploadId);
760  $agentList = $scanProxy->createAgentStatus($agents);
761 
762  foreach ($agentList as $agent) {
763  if (! array_key_exists('currentAgentId', $agent)) {
765  "Agent " . $agent["agentName"] .
766  " not scheduled for the upload. Please POST to /jobs");
767  }
768  if (array_key_exists('isAgentRunning', $agent) &&
769  $agent['isAgentRunning']) {
771  "Agent " . $agent["agentName"] . " is running. " .
772  "Please check job status at /api/v1/jobs?upload=" . $uploadId))
773  ->setHeaders(['Retry-After' => '60',
774  'Look-at' => "/api/v1/jobs?upload=" . $uploadId]);
775  }
776  }
777  }
778 
788  public function setUploadPermissions($request, $response, $args)
789  {
790  $returnVal = null;
791  // checking if the scheduler is running or not
792  $commu_status = fo_communicate_with_scheduler('status', $response_from_scheduler, $error_info);
793  if (!$commu_status) {
794  throw new HttpServiceUnavailableException("Scheduler is not running!");
795  }
796  // Initialising upload-permissions plugin
797  global $container;
798  $restHelper = $container->get('helper.restHelper');
799  $uploadPermissionObj = $restHelper->getPlugin('upload_permissions');
800 
801  $dbManager = $this->dbHelper->getDbManager();
802  // parsing the request body
803  $reqBody = $this->getParsedBody($request);
804 
805  $folder_pk = intval($reqBody['folderId']);
806  $upload_pk = intval($args['id']);
807  $this->uploadAccessible($upload_pk);
808  $allUploadsPerm = $reqBody['allUploadsPermission'] ? 1 : 0;
809  $newgroup = intval($reqBody['groupId']);
810  $newperm = $this->getEquivalentValueForPermission($reqBody['newPermission']);
811  $public_perm = isset($reqBody['publicPermission']) ? $this->getEquivalentValueForPermission($reqBody['publicPermission']) : -1;
812 
813  $query = "SELECT perm, perm_upload_pk FROM perm_upload WHERE upload_fk=$1 and group_fk=$2;";
814  $result = $dbManager->getSingleRow($query, [$upload_pk, $newgroup], __METHOD__.".getOldPerm");
815  $perm_upload_pk = 0;
816  $perm = 0;
817  if (!empty($result)) {
818  $perm_upload_pk = intVal($result['perm_upload_pk']);
819  $perm = $newperm;
820  }
821 
822  $uploadPermissionObj->editPermissionsForUpload($commu_status, $folder_pk, $upload_pk, $allUploadsPerm, $perm_upload_pk, $perm, $newgroup, $newperm, $public_perm);
823 
824  $returnVal = new Info(202, "Permissions updated successfully!", InfoType::INFO);
825  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
826  }
827 
828  public function getEquivalentValueForPermission($perm)
829  {
830  switch ($perm) {
831  case 'read_only':
832  return Auth::PERM_READ;
833  case 'read_write':
834  return Auth::PERM_WRITE;
835  case 'clearing_admin':
836  return Auth::PERM_CADMIN;
837  case 'admin':
838  return Auth::PERM_ADMIN;
839  default:
840  return Auth::PERM_NONE;
841  }
842  }
843 
853  public function getGroupsWithPermissions($request, $response, $args)
854  {
855  $apiVersion = ApiVersion::getVersion($request);
856  $upload_pk = intval($args['id']);
857  $this->uploadAccessible($upload_pk);
858  $publicPerm = $this->restHelper->getUploadPermissionDao()->getPublicPermission($upload_pk);
859  $permGroups = $this->restHelper->getUploadPermissionDao()->getPermissionGroups($upload_pk);
860 
861  // Removing the perm_upload_pk parameter in response
862  $finalPermGroups = [];
863  foreach ($permGroups as $value) {
864  $groupPerm = new GroupPermission($value['perm'], $value['group_pk'], $value['group_name']);
865  $finalPermGroups[] = $groupPerm->getArray($apiVersion);
866  }
867  $res = new Permissions($publicPerm, $finalPermGroups);
868  return $response->withJson($res->getArray($apiVersion), 200);
869  }
870 
880  public function getMainLicenses($request, $response, $args)
881  {
882  $uploadId = intval($args['id']);
883  $this->uploadAccessible($uploadId);
884 
886  $clearingDao = $this->container->get('dao.clearing');
887  $licenseIds = $clearingDao->getMainLicenseIds($uploadId, $this->restHelper->getGroupId());
888  $licenseDao = $this->container->get('dao.license');
889  $licenses = array();
890 
891  foreach ($licenseIds as $value) {
892  $licenseId = intval($value);
893  $obligations = $licenseDao->getLicenseObligations([$licenseId],
894  false);
895  $obligations = array_merge($obligations,
896  $licenseDao->getLicenseObligations([$licenseId], true));
897  $obligationList = [];
898  foreach ($obligations as $obligation) {
899  $obligationList[] = new Obligation(
900  $obligation['ob_pk'],
901  $obligation['ob_topic'],
902  $obligation['ob_type'],
903  $obligation['ob_text'],
904  $obligation['ob_classification'],
905  $obligation['ob_comment']
906  );
907  }
908  $license = $licenseDao->getLicenseById($licenseId);
909  $licenseObj = new License(
910  $license->getId(),
911  $license->getShortName(),
912  $license->getFullName(),
913  $license->getText(),
914  $license->getUrl(),
915  $obligationList,
916  $license->getRisk()
917  );
918  $licenses[] = $licenseObj->getArray();
919  }
920  return $response->withJson($licenses, 200);
921  }
922 
932  public function setMainLicense($request, $response, $args)
933  {
934  $uploadId = intval($args['id']);
935  $body = $this->getParsedBody($request);
936  $shortName = $body['shortName'];
937  $licenseDao = $this->container->get('dao.license');
938  $clearingDao = $this->container->get('dao.clearing');
939 
940  $this->uploadAccessible($uploadId);
941 
942  if (empty($shortName)) {
943  throw new HttpBadRequestException("Short name missing from request.");
944  }
945  $license = $licenseDao->getLicenseByShortName($shortName,
946  $this->restHelper->getGroupId());
947 
948  if ($license === null) {
949  throw new HttpNotFoundException(
950  "No license with shortname '$shortName' found.");
951  }
952 
953  $licenseIds = $clearingDao->getMainLicenseIds($uploadId, $this->restHelper->getGroupId());
954  if (in_array($license->getId(), $licenseIds)) {
955  throw new HttpBadRequestException(
956  "License already exists for this upload.");
957  }
958 
960  $clearingDao = $this->container->get('dao.clearing');
961  $clearingDao->makeMainLicense($uploadId, $this->restHelper->getGroupId(), $license->getId());
962  $returnVal = new Info(200, "Successfully added new main license", InfoType::INFO);
963  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
964  }
965 
966  /***
967  * Remove the main license from the upload
968  *
969  * @param ServerRequestInterface $request
970  * @param ResponseHelper $response
971  * @param array $args
972  * @return ResponseHelper
973  * @throws HttpErrorException
974  */
975  public function removeMainLicense($request, $response, $args)
976  {
977  $uploadId = intval($args['id']);
978  $shortName = $args['shortName'];
979  $licenseDao = $this->container->get('dao.license');
980  $clearingDao = $this->container->get('dao.clearing');
981  $license = $licenseDao->getLicenseByShortName($shortName, $this->restHelper->getGroupId());
982 
983  $this->uploadAccessible($uploadId);
984 
985  if ($license === null) {
986  throw new HttpNotFoundException(
987  "No license with shortname '$shortName' found.");
988  }
989  $licenseIds = $clearingDao->getMainLicenseIds($uploadId, $this->restHelper->getGroupId());
990  if (!in_array($license->getId(), $licenseIds)) {
991  throw new HttpBadRequestException(
992  "License '$shortName' is not a main license for this upload.");
993  }
994 
995  $clearingDao = $this->container->get('dao.clearing');
996  $clearingDao->removeMainLicense($uploadId, $this->restHelper->getGroupId(), $license->getId());
997  $returnVal = new Info(200, "Main license removed successfully.", InfoType::INFO);
998 
999  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
1000  }
1001 
1011  public function getClearingProgressInfo($request, $response, $args)
1012  {
1013  $uploadId = intval($args['id']);
1014  $uploadDao = $this->restHelper->getUploadDao();
1015 
1016  $this->uploadAccessible($uploadId);
1017 
1018  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1019 
1020  $noLicenseUploadTreeView = new UploadTreeProxy($uploadId,
1021  array(UploadTreeProxy::OPT_SKIP_THESE => "noLicense",
1022  UploadTreeProxy::OPT_GROUP_ID => $this->restHelper->getGroupId()),
1023  $uploadTreeTableName,
1024  'no_license_uploadtree' . $uploadId);
1025 
1026  $filesOfInterest = $noLicenseUploadTreeView->count();
1027 
1028  $nonClearedUploadTreeView = new UploadTreeProxy($uploadId,
1029  array(UploadTreeProxy::OPT_SKIP_THESE => "alreadyCleared",
1030  UploadTreeProxy::OPT_GROUP_ID => $this->restHelper->getGroupId()),
1031  $uploadTreeTableName,
1032  'already_cleared_uploadtree' . $uploadId);
1033  $filesToBeCleared = $nonClearedUploadTreeView->count();
1034 
1035  $filesAlreadyCleared = $filesOfInterest - $filesToBeCleared;
1036 
1037  $res = [
1038  "totalFilesOfInterest" => intval($filesOfInterest),
1039  "totalFilesCleared" => intval($filesAlreadyCleared),
1040  ];
1041  return $response->withJson($res, 200);
1042  }
1043 
1053  public function getLicensesHistogram($request, $response, $args)
1054  {
1055  $agentDao = $this->container->get('dao.agent');
1056  $clearingDao = $this->container->get('dao.clearing');
1057  $licenseDao = $this->container->get('dao.license');
1058 
1059  $uploadId = intval($args['id']);
1060  $uploadDao = $this->restHelper->getUploadDao();
1061  $query = $request->getQueryParams();
1062  $selectedAgentId = $query['agentId'] ?? null;
1063 
1064  $this->uploadAccessible($uploadId);
1065 
1066  if ($selectedAgentId !== null && !$this->dbHelper->doesIdExist("agent", "agent_pk", $selectedAgentId)) {
1067  throw new HttpNotFoundException("Agent does not exist.");
1068  }
1069 
1070  $scannerAgents = array_keys($this->agentNames);
1071  $scanJobProxy = new ScanJobProxy($agentDao, $uploadId);
1072  $scanJobProxy->createAgentStatus($scannerAgents);
1073  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1074  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
1075  $editedLicenses = $clearingDao->getClearedLicenseIdAndMultiplicities($itemTreeBounds, $this->restHelper->getGroupId());
1076  $selectedAgentIds = empty($selectedAgentId) ? $scanJobProxy->getLatestSuccessfulAgentIds() : $selectedAgentId;
1077  $scannedLicenses = $licenseDao->getLicenseHistogram($itemTreeBounds, $selectedAgentIds);
1078  $allScannerLicenseNames = array_keys($scannedLicenses);
1079  $allEditedLicenseNames = array_keys($editedLicenses);
1080  $allLicNames = array_unique(array_merge($allScannerLicenseNames, $allEditedLicenseNames));
1081  $realLicNames = array_diff($allLicNames, array(LicenseDao::NO_LICENSE_FOUND));
1082  $totalScannerLicenseCount = 0;
1083  $editedTotalLicenseCount = 0;
1084 
1085  $res = array();
1086  foreach ($realLicNames as $licenseShortName) {
1087  $count = 0;
1088  if (array_key_exists($licenseShortName, $scannedLicenses)) {
1089  $count = $scannedLicenses[$licenseShortName]['unique'];
1090  $rfId = $scannedLicenses[$licenseShortName]['rf_pk'];
1091  } else {
1092  $rfId = $editedLicenses[$licenseShortName]['rf_pk'];
1093  }
1094  $editedCount = array_key_exists($licenseShortName, $editedLicenses) ? $editedLicenses[$licenseShortName]['count'] : 0;
1095  $totalScannerLicenseCount += $count;
1096  $editedTotalLicenseCount += $editedCount;
1097  $scannerCountLink = $count;
1098  $editedLink = $editedCount;
1099 
1100  $res[] = array($scannerCountLink, $editedLink, array($licenseShortName, $rfId));
1101  }
1102 
1103  $outputArray = [];
1104 
1105  foreach ($res as $item) {
1106  $outputArray[] = [
1107  "id" => intval($item[2][1]),
1108  "name" => $item[2][0],
1109  "scannerCount" => intval($item[0]),
1110  "concludedCount" => intval($item[1]),
1111  ];
1112  }
1113  return $response->withJson($outputArray, 200);
1114  }
1115 
1125  public function getAllAgents($request, $response, $args)
1126  {
1127  $uploadId = intval($args['id']);
1128 
1129  $this->uploadAccessible($uploadId);
1130 
1131  $scannerAgents = array_keys($this->agentNames);
1132  $agentDao = $this->container->get('dao.agent');
1133  $scanJobProxy = new ScanJobProxy($agentDao, $uploadId);
1134  $res = $scanJobProxy->createAgentStatus($scannerAgents);
1135 
1136  $outputArray = [];
1137  foreach ($res as &$item) {
1138  $successfulAgents = [];
1139  if (count($item['successfulAgents']) > 0) {
1140  $item['isAgentRunning'] = false;
1141  } else {
1142  $item['currentAgentId'] = $agentDao->getCurrentAgentRef($item["agentName"])->getAgentId();
1143  $item['currentAgentRev'] = "";
1144  }
1145  foreach ($item['successfulAgents'] as &$agent) {
1146  $successfulAgent = new SuccessfulAgent(intval($agent['agent_id']), $agent['agent_rev'], $agent['agent_name']);
1147  $successfulAgents[] = $successfulAgent->getArray(ApiVersion::getVersion($request));
1148  }
1149  $agent = new Agent($successfulAgents, $item['uploadId'], $item['agentName'], $item['currentAgentId'], $item['currentAgentRev'], $item['isAgentRunning']);
1150  $outputArray[] = $agent->getArray(ApiVersion::getVersion($request));
1151  }
1152  return $response->withJson($outputArray, 200);
1153  }
1154 
1164  public function getEditedLicenses($request, $response, $args)
1165  {
1166  $uploadId = intval($args['id']);
1167 
1168  $this->uploadAccessible($uploadId);
1169 
1170  $clearingDao = $this->container->get('dao.clearing');
1171  $uploadDao = $this->restHelper->getUploadDao();
1172  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1173  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
1174  $res = $clearingDao->getClearedLicenseIdAndMultiplicities($itemTreeBounds, $this->restHelper->getGroupId());
1175  $outputArray = [];
1176 
1177  foreach ($res as $key => $value) {
1178  $editedLicense = new EditedLicense(intval($value["rf_pk"]), $key, intval($value["count"]), $value["spdx_id"]);
1179  $outputArray[] = $editedLicense->getArray(ApiVersion::getVersion($request));
1180  }
1181  return $response->withJson($outputArray, 200);
1182  }
1183 
1193  public function getReuseReportSummary($request, $response, $args)
1194  {
1195  $uploadId = intval($args['id']);
1196  $this->uploadAccessible($uploadId);
1197 
1199  $reuseReportProcess = $this->container->get('businessrules.reusereportprocessor');
1200  $res = $reuseReportProcess->getReuseSummary($uploadId);
1201  return $response->withJson($res, 200);
1202  }
1203 
1213  public function getScannedLicenses($request, $response, $args)
1214  {
1215  $uploadId = intval($args['id']);
1216  $query = $request->getQueryParams();
1217  $selectedAgentId = $query['agentId'] ?? null;
1218  $licenseDao = $this->container->get('dao.license');
1219 
1220  $this->uploadAccessible($uploadId);
1221  if ($selectedAgentId !== null && !$this->dbHelper->doesIdExist("agent", "agent_pk", $selectedAgentId)) {
1222  throw new HttpNotFoundException("Agent does not exist.");
1223  }
1224  $scannerAgents = array_keys(AgentRef::AGENT_LIST);
1225  $scanJobProxy = new ScanJobProxy($this->agentDao, $uploadId);
1226  $scanJobProxy->createAgentStatus($scannerAgents);
1227  $uploadDao = $this->restHelper->getUploadDao();
1228  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1229  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
1230  $selectedAgentIds = empty($selectedAgentId) ? $scanJobProxy->getLatestSuccessfulAgentIds() : $selectedAgentId;
1231  $res = $licenseDao->getLicenseHistogram($itemTreeBounds, $selectedAgentIds);
1232  $outputArray = [];
1233 
1234  foreach ($res as $key => $value) {
1235  $scannedLicense = new ScannedLicense($licenseDao->getLicenseByShortName($key)->getId(), $key, $value['count'], $value['unique'], $value['spdx_id']);
1236  $outputArray[] = $scannedLicense->getArray(ApiVersion::getVersion($request));
1237  }
1238  return $response->withJson($outputArray, 200);
1239  }
1249  public function getAgentsRevision($request, $response, $args)
1250  {
1251  $agentDao = $this->container->get('dao.agent');
1252  $uploadId = intval($args['id']);
1253 
1254  $this->uploadAccessible($uploadId);
1255 
1256  $scannerAgents = array_keys($this->agentNames);
1257  $scanJobProxy = new ScanJobProxy($agentDao, $uploadId);
1258  $scanJobProxy->createAgentStatus($scannerAgents);
1259 
1260  $res = array();
1261  foreach ($scanJobProxy->getSuccessfulAgents() as $agent) {
1262  $res[] = array(
1263  "id" => $agent->getAgentId(),
1264  "name" => $agent->getAgentName(),
1265  "revision" => $agent->getAgentRevision(),
1266  );
1267  }
1268  return $response->withJson($res, 200);
1269  }
1270 
1280  public function getTopItem($request, $response, $args)
1281  {
1282  $uploadId = intval($args['id']);
1283  if (!$this->dbHelper->doesIdExist("upload", "upload_pk", $uploadId)) {
1284  $returnVal = new Info(404, "Upload does not exist", InfoType::ERROR);
1285  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
1286  }
1287  $uploadDao = $this->restHelper->getUploadDao();
1288  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId,
1289  $uploadDao->getUploadtreeTableName($uploadId));
1290  if ($itemTreeBounds === false) {
1291  $error = new Info(500, "Unable to get top item.", InfoType::ERROR);
1292  return $response->withJson($error->getArray(), $error->getCode());
1293  }
1294  $info = new Info(200, $itemTreeBounds->getItemId(), InfoType::INFO);
1295  return $response->withJson($info->getArray(), $info->getCode());
1296  }
1297 }
Messages which can be generated by delagent.
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
Fossology exception.
Definition: Exception.php:15
Base controller for REST calls.
getParsedBody(ServerRequestInterface $request)
Parse request body as JSON and return associative PHP array.
areAgentsScheduled($uploadId, $agents, $response)
getClearingProgressInfo($request, $response, $args)
setUploadPermissions($request, $response, $args)
getGroupsWithPermissions($request, $response, $args)
changeUpload($request, $response, $args, $isCopy)
Override Slim response for withJson function.
Handle new file uploads from Slim framework and move to FOSSology.
static getVersion(ServerRequestInterface $request)
Definition: ApiVersion.php:29
Different type of infos provided by REST.
Definition: InfoType.php:16
Info model to contain general error and return values.
Definition: Info.php:19
RepPath($PfilePk, $Repo="files")
Given a pfile id, retrieve the pfile path.
Definition: common-repo.php:58
fo_communicate_with_scheduler($input, &$output, &$error_msg)
Communicate with scheduler, send commands to the scheduler, then get the output.
Definition: monk.h:55