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  return $response->withJson($info->getArray(), $info->getCode());
527  }
528 
538  public function getUploadLicenses($request, $response, $args)
539  {
540  $id = intval($args['id']);
541  $query = $request->getQueryParams();
542  $apiVersion = ApiVersion::getVersion($request);
543  if ($apiVersion == ApiVersion::V2) {
544  $page = $query['page'] ?? "";
545  $limit = $query['limit'] ?? "";
546  } else {
547  $page = $request->getHeaderLine("page");
548  $limit = $request->getHeaderLine("limit");
549  }
550  if (! array_key_exists(self::AGENT_PARAM, $query)) {
551  throw new HttpBadRequestException("agent parameter missing from query.");
552  }
553  $agents = explode(",", $query[self::AGENT_PARAM]);
554  $containers = true;
555  if (array_key_exists(self::CONTAINER_PARAM, $query)) {
556  $containers = (strcasecmp($query[self::CONTAINER_PARAM], "true") === 0);
557  }
558 
559  $license = true;
560  if (array_key_exists('license', $query)) {
561  $license = (strcasecmp($query['license'], "true") === 0);
562  }
563 
564  $copyright = false;
565  if (array_key_exists('copyright', $query)) {
566  $copyright = (strcasecmp($query['copyright'], "true") === 0);
567  }
568 
569  if (!$license && !$copyright) {
570  throw new HttpBadRequestException(
571  "'license' and 'copyright' atleast one should be true.");
572  }
573 
574  $this->uploadAccessible($id);
575  $this->isAdj2nestDone($id);
576 
577  $this->areAgentsScheduled($id, $agents, $response);
578 
579  /*
580  * check if page && limit are numeric, if existing
581  */
582  if ((! ($page==='') && (! is_numeric($page) || $page < 1)) ||
583  (! ($limit==='') && (! is_numeric($limit) || $limit < 1))) {
584  throw new HttpBadRequestException(
585  "page and limit need to be positive integers!");
586  }
587 
588  // set page to 1 by default
589  if (empty($page)) {
590  $page = 1;
591  }
592 
593  // set limit to 50 by default and max as 1000
594  if (empty($limit)) {
595  $limit = 50;
596  } else if ($limit > 1000) {
597  $limit = 1000;
598  }
599 
600  $uploadHelper = new UploadHelper();
601  list($licenseList, $count) = $uploadHelper->getUploadLicenseList($id, $agents, $containers, $license, $copyright, $page-1, $limit, $apiVersion);
602  $totalPages = intval(ceil($count / $limit));
603  return $response->withHeader("X-Total-Pages", $totalPages)->withJson($licenseList, 200);
604  }
605 
615  public function getUploadCopyrights($request, $response, $args)
616  {
617  $id = intval($args['id']);
618  $this->uploadAccessible($id);
619  $this->isAdj2nestDone($id);
620  $uploadHelper = new UploadHelper();
621  $licenseList = $uploadHelper->getUploadCopyrightList($id);
622  return $response->withJson($licenseList, 200);
623  }
624 
634  public function updateUpload($request, $response, $args)
635  {
636  $id = intval($args['id']);
637  $query = $request->getQueryParams();
638  $userDao = $this->restHelper->getUserDao();
639  $userId = $this->restHelper->getUserId();
640  $groupId = $this->restHelper->getGroupId();
641 
642  $perm = $userDao->isAdvisorOrAdmin($userId, $groupId);
643  if (!$perm) {
644  throw new HttpForbiddenException("Not advisor or admin of current group. " .
645  "Can not update upload.");
646  }
647  $uploadBrowseProxy = new UploadBrowseProxy(
648  $groupId,
649  $perm,
650  $this->dbHelper->getDbManager()
651  );
652 
653  $assignee = null;
654  $status = null;
655  $comment = null;
656 
657  // Handle assignee info
658  if (array_key_exists(self::FILTER_ASSIGNEE, $query)) {
659  $assignee = filter_var($query[self::FILTER_ASSIGNEE], FILTER_VALIDATE_INT);
660  $userList = $userDao->getUserChoices($groupId);
661  if (!array_key_exists($assignee, $userList)) {
662  throw new HttpNotFoundException(
663  "New assignee does not have permisison on upload.");
664  }
665  $uploadBrowseProxy->updateTable("assignee", $id, $assignee);
666  }
667  // Handle new status
668  if (
669  array_key_exists(self::FILTER_STATUS, $query) &&
670  in_array(strtolower($query[self::FILTER_STATUS]), self::VALID_STATUS)
671  ) {
672  $newStatus = strtolower($query[self::FILTER_STATUS]);
673  $comment = '';
674  if (in_array($newStatus, ["closed", "rejected"])) {
675  $body = $request->getBody();
676  $comment = $body->getContents();
677  $body->close();
678  }
679  $status = 0;
680  if ($newStatus == self::VALID_STATUS[1]) {
681  $status = UploadStatus::IN_PROGRESS;
682  } elseif ($newStatus == self::VALID_STATUS[2]) {
683  $status = UploadStatus::CLOSED;
684  } elseif ($newStatus == self::VALID_STATUS[3]) {
685  $status = UploadStatus::REJECTED;
686  } else {
687  $status = UploadStatus::OPEN;
688  }
689  $uploadBrowseProxy->setStatusAndComment($id, $status, $comment);
690  }
691 
692  $returnVal = new Info(202, "Upload updated successfully.", InfoType::INFO);
693  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
694  }
695 
701  private function isAdj2nestDone($id): void
702  {
703  $itemTreeBounds = $this->restHelper->getUploadDao()->getParentItemBounds(
704  $id);
705  if ($itemTreeBounds === false || empty($itemTreeBounds->getLeft())) {
707  "Ununpack job not started. Please check job status at " .
708  "/api/v1/jobs?upload=" . $id))
709  ->setHeaders(['Retry-After' => '60',
710  'Look-at' => "/api/v1/jobs?upload=" . $id]);
711  }
712  }
713 
723  private function areAgentsScheduled($uploadId, $agents, $response): void
724  {
725  global $container;
726  $agentDao = $container->get('dao.agent');
727 
728  $agentList = array_keys(AgentRef::AGENT_LIST);
729  $intersectArray = array_intersect($agents, $agentList);
730 
731  if (count($agents) != count($intersectArray)) {
732  throw new HttpBadRequestException("Agent should be any of " .
733  implode(", ", $agentList) . ". " . implode(",", $agents) . " passed.");
734  } else {
735  // Agent is valid, check if they have ars tables.
736  foreach ($agents as $agent) {
737  if (! $agentDao->arsTableExists($agent)) {
739  "Agent $agent not scheduled for the upload. " .
740  "Please POST to /jobs");
741  }
742  }
743  }
744 
745  $scanProxy = new ScanJobProxy($agentDao, $uploadId);
746  $agentList = $scanProxy->createAgentStatus($agents);
747 
748  foreach ($agentList as $agent) {
749  if (! array_key_exists('currentAgentId', $agent)) {
751  "Agent " . $agent["agentName"] .
752  " not scheduled for the upload. Please POST to /jobs");
753  }
754  if (array_key_exists('isAgentRunning', $agent) &&
755  $agent['isAgentRunning']) {
757  "Agent " . $agent["agentName"] . " is running. " .
758  "Please check job status at /api/v1/jobs?upload=" . $uploadId))
759  ->setHeaders(['Retry-After' => '60',
760  'Look-at' => "/api/v1/jobs?upload=" . $uploadId]);
761  }
762  }
763  }
764 
774  public function setUploadPermissions($request, $response, $args)
775  {
776  $returnVal = null;
777  // checking if the scheduler is running or not
778  $commu_status = fo_communicate_with_scheduler('status', $response_from_scheduler, $error_info);
779  if (!$commu_status) {
780  throw new HttpServiceUnavailableException("Scheduler is not running!");
781  }
782  // Initialising upload-permissions plugin
783  global $container;
784  $restHelper = $container->get('helper.restHelper');
785  $uploadPermissionObj = $restHelper->getPlugin('upload_permissions');
786 
787  $dbManager = $this->dbHelper->getDbManager();
788  // parsing the request body
789  $reqBody = $this->getParsedBody($request);
790 
791  $folder_pk = intval($reqBody['folderId']);
792  $upload_pk = intval($args['id']);
793  $this->uploadAccessible($upload_pk);
794  $allUploadsPerm = $reqBody['allUploadsPermission'] ? 1 : 0;
795  $newgroup = intval($reqBody['groupId']);
796  $newperm = $this->getEquivalentValueForPermission($reqBody['newPermission']);
797  $public_perm = isset($reqBody['publicPermission']) ? $this->getEquivalentValueForPermission($reqBody['publicPermission']) : -1;
798 
799  $query = "SELECT perm, perm_upload_pk FROM perm_upload WHERE upload_fk=$1 and group_fk=$2;";
800  $result = $dbManager->getSingleRow($query, [$upload_pk, $newgroup], __METHOD__.".getOldPerm");
801  $perm_upload_pk = 0;
802  $perm = 0;
803  if (!empty($result)) {
804  $perm_upload_pk = intVal($result['perm_upload_pk']);
805  $perm = $newperm;
806  }
807 
808  $uploadPermissionObj->editPermissionsForUpload($commu_status, $folder_pk, $upload_pk, $allUploadsPerm, $perm_upload_pk, $perm, $newgroup, $newperm, $public_perm);
809 
810  $returnVal = new Info(202, "Permissions updated successfully!", InfoType::INFO);
811  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
812  }
813 
814  public function getEquivalentValueForPermission($perm)
815  {
816  switch ($perm) {
817  case 'read_only':
818  return Auth::PERM_READ;
819  case 'read_write':
820  return Auth::PERM_WRITE;
821  case 'clearing_admin':
822  return Auth::PERM_CADMIN;
823  case 'admin':
824  return Auth::PERM_ADMIN;
825  default:
826  return Auth::PERM_NONE;
827  }
828  }
829 
839  public function getGroupsWithPermissions($request, $response, $args)
840  {
841  $apiVersion = ApiVersion::getVersion($request);
842  $upload_pk = intval($args['id']);
843  $this->uploadAccessible($upload_pk);
844  $publicPerm = $this->restHelper->getUploadPermissionDao()->getPublicPermission($upload_pk);
845  $permGroups = $this->restHelper->getUploadPermissionDao()->getPermissionGroups($upload_pk);
846 
847  // Removing the perm_upload_pk parameter in response
848  $finalPermGroups = [];
849  foreach ($permGroups as $value) {
850  $groupPerm = new GroupPermission($value['perm'], $value['group_pk'], $value['group_name']);
851  $finalPermGroups[] = $groupPerm->getArray($apiVersion);
852  }
853  $res = new Permissions($publicPerm, $finalPermGroups);
854  return $response->withJson($res->getArray($apiVersion), 200);
855  }
856 
866  public function getMainLicenses($request, $response, $args)
867  {
868  $uploadId = intval($args['id']);
869  $this->uploadAccessible($uploadId);
870 
872  $clearingDao = $this->container->get('dao.clearing');
873  $licenseIds = $clearingDao->getMainLicenseIds($uploadId, $this->restHelper->getGroupId());
874  $licenseDao = $this->container->get('dao.license');
875  $licenses = array();
876 
877  foreach ($licenseIds as $value) {
878  $licenseId = intval($value);
879  $obligations = $licenseDao->getLicenseObligations([$licenseId],
880  false);
881  $obligations = array_merge($obligations,
882  $licenseDao->getLicenseObligations([$licenseId], true));
883  $obligationList = [];
884  foreach ($obligations as $obligation) {
885  $obligationList[] = new Obligation(
886  $obligation['ob_pk'],
887  $obligation['ob_topic'],
888  $obligation['ob_type'],
889  $obligation['ob_text'],
890  $obligation['ob_classification'],
891  $obligation['ob_comment']
892  );
893  }
894  $license = $licenseDao->getLicenseById($licenseId);
895  $licenseObj = new License(
896  $license->getId(),
897  $license->getShortName(),
898  $license->getFullName(),
899  $license->getText(),
900  $license->getUrl(),
901  $obligationList,
902  $license->getRisk()
903  );
904  $licenses[] = $licenseObj->getArray();
905  }
906  return $response->withJson($licenses, 200);
907  }
908 
918  public function setMainLicense($request, $response, $args)
919  {
920  $uploadId = intval($args['id']);
921  $body = $this->getParsedBody($request);
922  $shortName = $body['shortName'];
923  $licenseDao = $this->container->get('dao.license');
924  $clearingDao = $this->container->get('dao.clearing');
925 
926  $this->uploadAccessible($uploadId);
927 
928  if (empty($shortName)) {
929  throw new HttpBadRequestException("Short name missing from request.");
930  }
931  $license = $licenseDao->getLicenseByShortName($shortName,
932  $this->restHelper->getGroupId());
933 
934  if ($license === null) {
935  throw new HttpNotFoundException(
936  "No license with shortname '$shortName' found.");
937  }
938 
939  $licenseIds = $clearingDao->getMainLicenseIds($uploadId, $this->restHelper->getGroupId());
940  if (in_array($license->getId(), $licenseIds)) {
941  throw new HttpBadRequestException(
942  "License already exists for this upload.");
943  }
944 
946  $clearingDao = $this->container->get('dao.clearing');
947  $clearingDao->makeMainLicense($uploadId, $this->restHelper->getGroupId(), $license->getId());
948  $returnVal = new Info(200, "Successfully added new main license", InfoType::INFO);
949  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
950  }
951 
952  /***
953  * Remove the main license from the upload
954  *
955  * @param ServerRequestInterface $request
956  * @param ResponseHelper $response
957  * @param array $args
958  * @return ResponseHelper
959  * @throws HttpErrorException
960  */
961  public function removeMainLicense($request, $response, $args)
962  {
963  $uploadId = intval($args['id']);
964  $shortName = $args['shortName'];
965  $licenseDao = $this->container->get('dao.license');
966  $clearingDao = $this->container->get('dao.clearing');
967  $license = $licenseDao->getLicenseByShortName($shortName, $this->restHelper->getGroupId());
968 
969  $this->uploadAccessible($uploadId);
970 
971  if ($license === null) {
972  throw new HttpNotFoundException(
973  "No license with shortname '$shortName' found.");
974  }
975  $licenseIds = $clearingDao->getMainLicenseIds($uploadId, $this->restHelper->getGroupId());
976  if (!in_array($license->getId(), $licenseIds)) {
977  throw new HttpBadRequestException(
978  "License '$shortName' is not a main license for this upload.");
979  }
980 
981  $clearingDao = $this->container->get('dao.clearing');
982  $clearingDao->removeMainLicense($uploadId, $this->restHelper->getGroupId(), $license->getId());
983  $returnVal = new Info(200, "Main license removed successfully.", InfoType::INFO);
984 
985  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
986  }
987 
997  public function getClearingProgressInfo($request, $response, $args)
998  {
999  $uploadId = intval($args['id']);
1000  $uploadDao = $this->restHelper->getUploadDao();
1001 
1002  $this->uploadAccessible($uploadId);
1003 
1004  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1005 
1006  $noLicenseUploadTreeView = new UploadTreeProxy($uploadId,
1007  array(UploadTreeProxy::OPT_SKIP_THESE => "noLicense",
1008  UploadTreeProxy::OPT_GROUP_ID => $this->restHelper->getGroupId()),
1009  $uploadTreeTableName,
1010  'no_license_uploadtree' . $uploadId);
1011 
1012  $filesOfInterest = $noLicenseUploadTreeView->count();
1013 
1014  $nonClearedUploadTreeView = new UploadTreeProxy($uploadId,
1015  array(UploadTreeProxy::OPT_SKIP_THESE => "alreadyCleared",
1016  UploadTreeProxy::OPT_GROUP_ID => $this->restHelper->getGroupId()),
1017  $uploadTreeTableName,
1018  'already_cleared_uploadtree' . $uploadId);
1019  $filesToBeCleared = $nonClearedUploadTreeView->count();
1020 
1021  $filesAlreadyCleared = $filesOfInterest - $filesToBeCleared;
1022 
1023  $res = [
1024  "totalFilesOfInterest" => intval($filesOfInterest),
1025  "totalFilesCleared" => intval($filesAlreadyCleared),
1026  ];
1027  return $response->withJson($res, 200);
1028  }
1029 
1039  public function getLicensesHistogram($request, $response, $args)
1040  {
1041  $agentDao = $this->container->get('dao.agent');
1042  $clearingDao = $this->container->get('dao.clearing');
1043  $licenseDao = $this->container->get('dao.license');
1044 
1045  $uploadId = intval($args['id']);
1046  $uploadDao = $this->restHelper->getUploadDao();
1047  $query = $request->getQueryParams();
1048  $selectedAgentId = $query['agentId'] ?? null;
1049 
1050  $this->uploadAccessible($uploadId);
1051 
1052  if ($selectedAgentId !== null && !$this->dbHelper->doesIdExist("agent", "agent_pk", $selectedAgentId)) {
1053  throw new HttpNotFoundException("Agent does not exist.");
1054  }
1055 
1056  $scannerAgents = array_keys($this->agentNames);
1057  $scanJobProxy = new ScanJobProxy($agentDao, $uploadId);
1058  $scanJobProxy->createAgentStatus($scannerAgents);
1059  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1060  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
1061  $editedLicenses = $clearingDao->getClearedLicenseIdAndMultiplicities($itemTreeBounds, $this->restHelper->getGroupId());
1062  $selectedAgentIds = empty($selectedAgentId) ? $scanJobProxy->getLatestSuccessfulAgentIds() : $selectedAgentId;
1063  $scannedLicenses = $licenseDao->getLicenseHistogram($itemTreeBounds, $selectedAgentIds);
1064  $allScannerLicenseNames = array_keys($scannedLicenses);
1065  $allEditedLicenseNames = array_keys($editedLicenses);
1066  $allLicNames = array_unique(array_merge($allScannerLicenseNames, $allEditedLicenseNames));
1067  $realLicNames = array_diff($allLicNames, array(LicenseDao::NO_LICENSE_FOUND));
1068  $totalScannerLicenseCount = 0;
1069  $editedTotalLicenseCount = 0;
1070 
1071  $res = array();
1072  foreach ($realLicNames as $licenseShortName) {
1073  $count = 0;
1074  if (array_key_exists($licenseShortName, $scannedLicenses)) {
1075  $count = $scannedLicenses[$licenseShortName]['unique'];
1076  $rfId = $scannedLicenses[$licenseShortName]['rf_pk'];
1077  } else {
1078  $rfId = $editedLicenses[$licenseShortName]['rf_pk'];
1079  }
1080  $editedCount = array_key_exists($licenseShortName, $editedLicenses) ? $editedLicenses[$licenseShortName]['count'] : 0;
1081  $totalScannerLicenseCount += $count;
1082  $editedTotalLicenseCount += $editedCount;
1083  $scannerCountLink = $count;
1084  $editedLink = $editedCount;
1085 
1086  $res[] = array($scannerCountLink, $editedLink, array($licenseShortName, $rfId));
1087  }
1088 
1089  $outputArray = [];
1090 
1091  foreach ($res as $item) {
1092  $outputArray[] = [
1093  "id" => intval($item[2][1]),
1094  "name" => $item[2][0],
1095  "scannerCount" => intval($item[0]),
1096  "concludedCount" => intval($item[1]),
1097  ];
1098  }
1099  return $response->withJson($outputArray, 200);
1100  }
1101 
1111  public function getAllAgents($request, $response, $args)
1112  {
1113  $uploadId = intval($args['id']);
1114 
1115  $this->uploadAccessible($uploadId);
1116 
1117  $scannerAgents = array_keys($this->agentNames);
1118  $agentDao = $this->container->get('dao.agent');
1119  $scanJobProxy = new ScanJobProxy($agentDao, $uploadId);
1120  $res = $scanJobProxy->createAgentStatus($scannerAgents);
1121 
1122  $outputArray = [];
1123  foreach ($res as &$item) {
1124  $successfulAgents = [];
1125  if (count($item['successfulAgents']) > 0) {
1126  $item['isAgentRunning'] = false;
1127  } else {
1128  $item['currentAgentId'] = $agentDao->getCurrentAgentRef($item["agentName"])->getAgentId();
1129  $item['currentAgentRev'] = "";
1130  }
1131  foreach ($item['successfulAgents'] as &$agent) {
1132  $successfulAgent = new SuccessfulAgent(intval($agent['agent_id']), $agent['agent_rev'], $agent['agent_name']);
1133  $successfulAgents[] = $successfulAgent->getArray(ApiVersion::getVersion($request));
1134  }
1135  $agent = new Agent($successfulAgents, $item['uploadId'], $item['agentName'], $item['currentAgentId'], $item['currentAgentRev'], $item['isAgentRunning']);
1136  $outputArray[] = $agent->getArray(ApiVersion::getVersion($request));
1137  }
1138  return $response->withJson($outputArray, 200);
1139  }
1140 
1150  public function getEditedLicenses($request, $response, $args)
1151  {
1152  $uploadId = intval($args['id']);
1153 
1154  $this->uploadAccessible($uploadId);
1155 
1156  $clearingDao = $this->container->get('dao.clearing');
1157  $uploadDao = $this->restHelper->getUploadDao();
1158  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1159  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
1160  $res = $clearingDao->getClearedLicenseIdAndMultiplicities($itemTreeBounds, $this->restHelper->getGroupId());
1161  $outputArray = [];
1162 
1163  foreach ($res as $key => $value) {
1164  $editedLicense = new EditedLicense(intval($value["rf_pk"]), $key, intval($value["count"]), $value["spdx_id"]);
1165  $outputArray[] = $editedLicense->getArray(ApiVersion::getVersion($request));
1166  }
1167  return $response->withJson($outputArray, 200);
1168  }
1169 
1179  public function getReuseReportSummary($request, $response, $args)
1180  {
1181  $uploadId = intval($args['id']);
1182  $this->uploadAccessible($uploadId);
1183 
1185  $reuseReportProcess = $this->container->get('businessrules.reusereportprocessor');
1186  $res = $reuseReportProcess->getReuseSummary($uploadId);
1187  return $response->withJson($res, 200);
1188  }
1189 
1199  public function getScannedLicenses($request, $response, $args)
1200  {
1201  $uploadId = intval($args['id']);
1202  $query = $request->getQueryParams();
1203  $selectedAgentId = $query['agentId'] ?? null;
1204  $licenseDao = $this->container->get('dao.license');
1205 
1206  $this->uploadAccessible($uploadId);
1207  if ($selectedAgentId !== null && !$this->dbHelper->doesIdExist("agent", "agent_pk", $selectedAgentId)) {
1208  throw new HttpNotFoundException("Agent does not exist.");
1209  }
1210  $scannerAgents = array_keys(AgentRef::AGENT_LIST);
1211  $scanJobProxy = new ScanJobProxy($this->agentDao, $uploadId);
1212  $scanJobProxy->createAgentStatus($scannerAgents);
1213  $uploadDao = $this->restHelper->getUploadDao();
1214  $uploadTreeTableName = $uploadDao->getUploadtreeTableName($uploadId);
1215  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
1216  $selectedAgentIds = empty($selectedAgentId) ? $scanJobProxy->getLatestSuccessfulAgentIds() : $selectedAgentId;
1217  $res = $licenseDao->getLicenseHistogram($itemTreeBounds, $selectedAgentIds);
1218  $outputArray = [];
1219 
1220  foreach ($res as $key => $value) {
1221  $scannedLicense = new ScannedLicense($licenseDao->getLicenseByShortName($key)->getId(), $key, $value['count'], $value['unique'], $value['spdx_id']);
1222  $outputArray[] = $scannedLicense->getArray(ApiVersion::getVersion($request));
1223  }
1224  return $response->withJson($outputArray, 200);
1225  }
1235  public function getAgentsRevision($request, $response, $args)
1236  {
1237  $agentDao = $this->container->get('dao.agent');
1238  $uploadId = intval($args['id']);
1239 
1240  $this->uploadAccessible($uploadId);
1241 
1242  $scannerAgents = array_keys($this->agentNames);
1243  $scanJobProxy = new ScanJobProxy($agentDao, $uploadId);
1244  $scanJobProxy->createAgentStatus($scannerAgents);
1245 
1246  $res = array();
1247  foreach ($scanJobProxy->getSuccessfulAgents() as $agent) {
1248  $res[] = array(
1249  "id" => $agent->getAgentId(),
1250  "name" => $agent->getAgentName(),
1251  "revision" => $agent->getAgentRevision(),
1252  );
1253  }
1254  return $response->withJson($res, 200);
1255  }
1256 
1266  public function getTopItem($request, $response, $args)
1267  {
1268  $uploadId = intval($args['id']);
1269  if (!$this->dbHelper->doesIdExist("upload", "upload_pk", $uploadId)) {
1270  $returnVal = new Info(404, "Upload does not exist", InfoType::ERROR);
1271  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
1272  }
1273  $uploadDao = $this->restHelper->getUploadDao();
1274  $itemTreeBounds = $uploadDao->getParentItemBounds($uploadId,
1275  $uploadDao->getUploadtreeTableName($uploadId));
1276  if ($itemTreeBounds === false) {
1277  $error = new Info(500, "Unable to get top item.", InfoType::ERROR);
1278  return $response->withJson($error->getArray(), $error->getCode());
1279  }
1280  $info = new Info(200, $itemTreeBounds->getItemId(), InfoType::INFO);
1281  return $response->withJson($info->getArray(), $info->getCode());
1282  }
1283 }
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