/**
  * @param int $uploadTreeId
  * @param string $tableName
  * @param int $agentId
  * @param array $typeToHighlightTypeMap
  * @throws \Exception
  * @return Highlight[]
  */
 public function getHighlights($uploadTreeId, $tableName = "copyright", $agentId = 0, $typeToHighlightTypeMap = array('statement' => Highlight::COPYRIGHT, 'email' => Highlight::EMAIL, 'url' => Highlight::URL, 'author' => Highlight::AUTHOR))
 {
     $pFileId = 0;
     $row = $this->uploadDao->getUploadEntry($uploadTreeId);
     if (!empty($row['pfile_fk'])) {
         $pFileId = $row['pfile_fk'];
     } else {
         $text = _("Could not locate the corresponding pfile.");
         print $text;
     }
     $statementName = __METHOD__ . $tableName;
     $sql = "SELECT * FROM {$tableName} WHERE copy_startbyte IS NOT NULL AND pfile_fk=\$1";
     $params = array($pFileId);
     if ($agentId != 0) {
         $statementName .= '.agentId';
         $sql .= ' AND agent_fk=$2';
         $params[] = $agentId;
     }
     $this->dbManager->prepare($statementName, $sql);
     $result = $this->dbManager->execute($statementName, $params);
     $highlights = array();
     while ($row = $this->dbManager->fetchArray($result)) {
         $type = $row['type'];
         $content = $row['content'];
         $htmlElement = null;
         $highlightType = array_key_exists($type, $typeToHighlightTypeMap) ? $typeToHighlightTypeMap[$type] : Highlight::UNDEFINED;
         $highlights[] = new Highlight($row['copy_startbyte'], $row['copy_endbyte'], $highlightType, -1, -1, $content, $htmlElement);
     }
     $this->dbManager->freeResult($result);
     return $highlights;
 }
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $errorMessage = "";
     $jobqueueId = -1;
     $userId = $_SESSION['UserId'];
     $groupId = $_SESSION['GroupId'];
     $uploadId = intval($_POST['uploadId']);
     $agentName = $_POST['agentName'];
     if ($uploadId > 0) {
         $upload = $this->uploadDao->getUpload($uploadId);
         $uploadName = $upload->getFilename();
         $jobId = JobAddJob($userId, $groupId, $uploadName, $uploadId);
         $ourPlugin = plugin_find($agentName);
         $jobqueueId = $ourPlugin->AgentAdd($jobId, $uploadId, $errorMessage, array());
     } else {
         $errorMessage = "bad request";
     }
     ReportCachePurgeAll();
     $headers = array('Content-type' => 'text/json');
     if (empty($errorMessage) && $jobqueueId > 0) {
         return new Response(json_encode(array("jqid" => $jobqueueId)), Response::HTTP_OK, $headers);
     } else {
         return new Response(json_encode(array("error" => $errorMessage)), Response::HTTP_INTERNAL_SERVER_ERROR, $headers);
     }
 }
 /**
  * 
  * @param int $uploadTreeId
  * @param Request $request
  * @return int $jobQueueId
  */
 private function getJobQueueId($uploadTreeId, Request $request)
 {
     $uploadEntry = $this->uploadDao->getUploadEntry($uploadTreeId);
     $uploadId = intval($uploadEntry['upload_fk']);
     $userId = Auth::getUserId();
     $groupId = Auth::getGroupId();
     if ($uploadId <= 0 || !$this->uploadDao->isAccessible($uploadId, $groupId)) {
         throw new Exception('permission denied');
     }
     $bulkScope = $request->get('bulkScope');
     switch ($bulkScope) {
         case 'u':
             $uploadTreeTable = $this->uploadDao->getUploadtreeTableName($uploadId);
             $topBounds = $this->uploadDao->getParentItemBounds($uploadId, $uploadTreeTable);
             $uploadTreeId = $topBounds->getItemId();
             break;
         case 'f':
             if (!Isdir($uploadEntry['ufile_mode']) && !Iscontainer($uploadEntry['ufile_mode']) && !Isartifact($uploadEntry['ufile_mode'])) {
                 $uploadTreeId = $uploadEntry['parent'] ?: $uploadTreeId;
             }
             break;
         default:
             throw new InvalidArgumentException('bad scope request');
     }
     $refText = $request->get('refText');
     $actions = $request->get('bulkAction');
     $licenseRemovals = array();
     foreach ($actions as $licenseAction) {
         $licenseRemovals[$licenseAction['licenseId']] = $licenseAction['action'] == 'remove';
     }
     $bulkId = $this->licenseDao->insertBulkLicense($userId, $groupId, $uploadTreeId, $licenseRemovals, $refText);
     if ($bulkId <= 0) {
         throw new Exception('cannot insert bulk reference');
     }
     $upload = $this->uploadDao->getUpload($uploadId);
     $uploadName = $upload->getFilename();
     $job_pk = JobAddJob($userId, $groupId, $uploadName, $uploadId);
     /** @var DeciderJobAgentPlugin $deciderPlugin */
     $deciderPlugin = plugin_find("agent_deciderjob");
     $dependecies = array(array('name' => 'agent_monk_bulk', 'args' => $bulkId));
     $conflictStrategyId = intval($request->get('forceDecision'));
     $errorMsg = '';
     $jqId = $deciderPlugin->AgentAdd($job_pk, $uploadId, $errorMsg, $dependecies, $conflictStrategyId);
     if (!empty($errorMsg)) {
         throw new Exception(str_replace('<br>', "\n", $errorMsg));
     }
     return $jqId;
 }
 /**
  * @param string $action
  * @param int $uploadId
  * @param int $uploadTreeId
  * @param int $groupId
  * @return string
  */
 protected function doNextPrev($action, $uploadId, $uploadTreeId, $groupId)
 {
     switch ($action) {
         case "setNextPrev":
             $modName = "view-license";
             $opt = self::OPTION_SKIP_FILE;
             break;
         case "setNextPrevCopyRight":
             $modName = "copyright-view";
             $opt = self::OPTION_SKIP_FILE_COPYRIGHT;
             break;
         case "setNextPrevIp":
             $modName = "ip-view";
             $opt = self::OPTION_SKIP_FILE_IP;
             break;
         case "setNextPrevEcc":
             $modName = "ecc-view";
             $opt = self::OPTION_SKIP_FILE_ECC;
             break;
     }
     $options = array('skipThese' => GetParm($opt, PARM_STRING), 'groupId' => $groupId);
     $prevItem = $this->uploadDao->getPreviousItem($uploadId, $uploadTreeId, $options);
     $prevItemId = $prevItem ? $prevItem->getId() : null;
     $nextItem = $this->uploadDao->getNextItem($uploadId, $uploadTreeId, $options);
     $nextItemId = $nextItem ? $nextItem->getId() : null;
     return array('prev' => $prevItemId, 'next' => $nextItemId, 'uri' => Traceback_uri() . "?mod=" . $modName . Traceback_parm_keep(array('upload', 'folder')));
 }
Exemple #5
0
 /**
  * \brief Display the tagging page.
  * @param string $action
  * @param int $ShowHeader
  */
 function ShowTaggingPage($action, $ShowHeader = 0)
 {
     $V = "";
     $Upload = GetParm("upload", PARM_INTEGER);
     $Item = GetParm("item", PARM_INTEGER);
     if (empty($Item) || empty($Upload)) {
         return;
     }
     /**********************************
        Display micro header
        **********************************/
     if ($ShowHeader) {
         $V .= Dir2Browse("browse", $Item, NULL, 1, "Browse");
     }
     $V .= $this->ShowExistTags($Upload, $Item);
     $V .= $this->ShowAjaxPage();
     if ($action == 'edit') {
         $V .= $this->ShowEditTagPage($Upload, $Item);
     } else {
         /* Show create tag page */
         if ($this->uploadDao->isEditable($Upload, Auth::getGroupId())) {
             $V .= $this->ShowCreateTagPage($Upload, $Item);
         } else {
             $nopermtext = _("You do not have permission to tag this upload.");
             $V .= $nopermtext;
         }
     }
     return $V;
 }
 function processUploadId($uploadId)
 {
     $args = $this->args;
     $this->activeRules = array_key_exists('r', $args) ? intval($args['r']) : self::RULES_ALL;
     $this->licenseMap = new LicenseMap($this->dbManager, $this->groupId, $this->licenseMapUsage);
     $parentBounds = $this->uploadDao->getParentItemBounds($uploadId);
     foreach ($this->uploadDao->getContainedItems($parentBounds) as $item) {
         $process = $this->processItem($item);
         $this->heartbeat($process);
     }
     if (($this->activeRules & self::RULES_BULK_REUSE) == self::RULES_BULK_REUSE) {
         $bulkReuser = new BulkReuser();
         $bulkReuser->rerunBulkAndDeciderOnUpload($uploadId, $this->groupId, $this->userId, $this->jobId);
     }
     return true;
 }
Exemple #7
0
 private function runnerDeciderScanWithNoEventsAndNomosContainedInMonkWithButWithOtherAgentMatchForSameLicenseShouldMakeADecision($runner)
 {
     $this->setUpTables();
     $this->setUpRepo();
     $licenseRef1 = $this->licenseDao->getLicenseByShortName("GPL-3.0")->getRef();
     $licenseRef2 = $this->licenseDao->getLicenseByShortName("GPL-1.0")->getRef();
     $licenseRef3 = $this->licenseDao->getLicenseByShortName("APL-1.0")->getRef();
     $licId1 = $licenseRef1->getId();
     $licId2 = $licenseRef2->getId();
     $licId3 = $licenseRef3->getId();
     $agentNomosId = 6;
     $agentMonkId = 5;
     $agentOther = 8;
     $pfile = 4;
     $this->dbManager->queryOnce("INSERT INTO license_map(rf_fk, rf_parent, usage) VALUES ({$licId2}, {$licId1}, " . LicenseMap::CONCLUSION . ")");
     $this->dbManager->queryOnce("INSERT INTO license_map(rf_fk, rf_parent, usage) VALUES ({$licId3}, {$licId1}, " . LicenseMap::CONCLUSION . ")");
     $this->dbManager->queryOnce("DELETE FROM license_file");
     $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12222,{$licId1},{$pfile},{$agentNomosId})");
     $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12222,10,3)");
     $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12222,18,3)");
     $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12223,{$licId2},{$pfile},{$agentMonkId})");
     $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12223,6,2)");
     $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12223,13,19)");
     $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12224,{$licId3},{$pfile},{$agentOther})");
     $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12224,9,2)");
     $this->dbManager->queryOnce("INSERT INTO highlight (fl_fk,start,len) VALUES(12224,13,19)");
     list($success, $output, $retCode) = $runner->run($uploadId = 2, $userId = 6, $groupId = 4, $jobId = 31, $args = "");
     $this->assertTrue($success, 'cannot run runner');
     $this->assertEquals($retCode, 0, 'decider failed (did you make test?): ' . $output);
     assertThat($this->getHeartCount($output), equalTo(1));
     $uploadBounds = $this->uploadDao->getParentItemBounds($uploadId);
     $decisions = $this->clearingDao->getFileClearingsFolder($uploadBounds, $groupId);
     assertThat($decisions, is(arrayWithSize(1)));
     $this->rmRepo();
 }
Exemple #8
0
 /**
  * @param Request $request
  * @return JsonResponse
  */
 protected function respondFolderGetTableData(Request $request)
 {
     /* Get list of uploads in this folder */
     list($result, $iTotalDisplayRecords, $iTotalRecords) = $this->getListOfUploadsOfFolder($request);
     $uri = Traceback_uri() . "?mod=license";
     /* Browse-Pfile menu */
     $menuPfile = menu_find("Browse-Pfile", $menuDepth);
     /* Browse-Pfile menu without the compare menu item */
     $menuPfileNoCompare = menu_remove($menuPfile, "Compare");
     $users = $this->userDao->getUserChoices();
     $statusTypesAvailable = $this->uploadDao->getStatusTypeMap();
     if (!$this->userPerm) {
         unset($statusTypesAvailable[4]);
     }
     $output = array();
     $rowCounter = 0;
     while ($row = $this->dbManager->fetchArray($result)) {
         if (empty($row['upload_pk']) || !$this->uploadDao->isAccessible($row['upload_pk'], Auth::getGroupId())) {
             continue;
         }
         $rowCounter++;
         $output[] = $this->showRow($row, $request, $uri, $menuPfile, $menuPfileNoCompare, $statusTypesAvailable, $users, $rowCounter);
     }
     $this->dbManager->freeResult($result);
     return new JsonResponse(array('sEcho' => intval($request->get('sEcho')), 'aaData' => $output, 'iTotalRecords' => $iTotalRecords, 'iTotalDisplayRecords' => $iTotalDisplayRecords));
 }
 function doEdit($userId, $groupId, $itemId)
 {
     $licenses = GetParm("licenseNumbersToBeSubmitted", PARM_RAW);
     $removed = $_POST['removed'] === 't' || $_POST['removed'] === 'true';
     $itemTreeBounds = $this->uploadDao->getItemTreeBounds($itemId);
     $uploadId = $itemTreeBounds->getUploadId();
     $upload = $this->uploadDao->getUpload($uploadId);
     $uploadName = $upload->getFilename();
     $jobId = JobAddJob($userId, $groupId, $uploadName, $uploadId);
     if (isset($licenses)) {
         if (!is_array($licenses)) {
             return $this->errorJson("bad license array");
         }
         foreach ($licenses as $licenseId) {
             if (intval($licenseId) <= 0) {
                 return $this->errorJson("bad license");
             }
             $this->clearingDao->insertClearingEvent($itemId, $userId, $groupId, $licenseId, $removed, ClearingEventTypes::USER, $reportInfo = '', $comment = '', $jobId);
         }
     }
     /** @var agent_fodecider $deciderPlugin */
     $deciderPlugin = plugin_find("agent_deciderjob");
     $conflictStrategyId = null;
     $errorMsg = "";
     $jq_pk = $deciderPlugin->AgentAdd($jobId, $uploadId, $errorMsg, array(), $conflictStrategyId);
     /** after changing one license, purge all the report cache */
     ReportCachePurgeAll();
     //Todo: Change sql statement of fossology/src/buckets/agent/leaf.c line 124 to take the newest valid license, then uncomment this line
     // $this->ChangeBuckets(); // change bucket accordingly
     if (empty($errorMsg) && $jq_pk > 0) {
         return new JsonResponse(array("jqid" => $jq_pk));
     } else {
         return $this->errorJson($errorMsg, 500);
     }
 }
 /** @group Functional */
 public function testRun()
 {
     $this->setUpTables();
     $this->setUpRepo();
     list($output, $retCode) = $this->runNinka($uploadId = 1);
     $this->rmRepo();
     $this->assertEquals($retCode, 0, 'ninka failed: ' . $output);
     $bounds = $this->uploadDao->getParentItemBounds($uploadId);
     $matches = $this->licenseDao->getAgentFileLicenseMatches($bounds);
     $this->assertEquals($expected = 6, count($matches));
     foreach ($matches as $licenseMatch) {
         /** @var LicenseRef */
         $matchedLicense = $licenseMatch->getLicenseRef();
         switch ($licenseMatch->getFileId()) {
             case 7:
             case 4:
                 $expectedLicense = "GPL-3.0+";
                 break;
             case 3:
                 $expectedLicense = "UnclassifiedLicense";
                 break;
             default:
                 $expectedLicense = "No_license_found";
                 break;
         }
         $this->assertEquals($expectedLicense, $matchedLicense->getShortName(), "unexpected license for fileId " . $licenseMatch->getFileId());
         /** @var AgentRef */
         $agentRef = $licenseMatch->getAgentRef();
         $this->assertEquals($agentRef->getAgentName(), "ninka");
     }
 }
Exemple #11
0
 /**
  * \brief The Picker page
  */
 function Output()
 {
     global $PG_CONN;
     if ($this->State != PLUGIN_STATE_READY) {
         return 0;
     }
     /**
      * create table if it doesn't exist (not assuming Install() was run.
      * eg. source update
      */
     $this->Create_file_picker();
     $RtnMod = GetParm("rtnmod", PARM_TEXT);
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     if (!$uploadtree_pk) {
         return "<h2>Unidentified item 1</h2>";
     }
     $uploadtree_pk2 = GetParm("item2", PARM_INTEGER);
     $folder_pk = GetParm("folder", PARM_INTEGER);
     $user_pk = Auth::getUserId();
     /* Item to start Browse window on */
     $Browseuploadtree_pk = GetParm("bitem", PARM_INTEGER);
     /* Check item1 and item2 upload permissions */
     $Item1Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$uploadtree_pk}");
     if (!$this->uploadDao->isAccessible($Item1Row['upload_fk'], Auth::getGroupId())) {
         $text = _("Permission Denied");
         return "<h2>{$text} item 1</h2>";
     }
     if (!empty($uploadtree_pk2)) {
         $Item2Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$uploadtree_pk2}");
         if (!$this->uploadDao->isAccessible($Item2Row['upload_fk'], Auth::getGroupId())) {
             $text = _("Permission Denied");
             return "<h2>{$text} item 2</h2>";
         }
     }
     /**
      * After picking an item2, this logic will record the pick in
      * the picker history, and then redirect both item1 and item2 to the
      * comparison app.
      */
     if (!empty($user_pk) && !empty($RtnMod) && !empty($uploadtree_pk) && !empty($uploadtree_pk2)) {
         $sql = "insert into file_picker (user_fk, uploadtree_fk1, uploadtree_fk2, last_access_date)\n             values({$user_pk}, {$uploadtree_pk}, {$uploadtree_pk2}, now())";
         // ignore errors (most probably a duplicate key)
         @($result = pg_query($PG_CONN, $sql));
         // Redirect to diff module
         $uri = Traceback_uri() . "?mod={$RtnMod}&item1={$uploadtree_pk}&item2={$uploadtree_pk2}";
         echo "<script type='text/javascript'> window.location.assign('{$uri}');</script>";
         exit;
     }
     $OutBuf = "";
     if ($this->OutputType == 'HTML') {
         if (empty($uploadtree_pk)) {
             $OutBuf = "<h2>Picker URL is missing the first comparison file.</h2>";
         } else {
             $PathArray = Dir2Path($uploadtree_pk, 'uploadtree');
             $OutBuf .= $this->HTMLout($RtnMod, $uploadtree_pk, $Browseuploadtree_pk, $folder_pk, $PathArray);
         }
     }
     return $OutBuf;
 }
 private function getJobQueueId($uploadTreeId)
 {
     $uploadEntry = $this->uploadDao->getUploadEntry($uploadTreeId);
     $uploadId = intval($uploadEntry['upload_fk']);
     if ($uploadId <= 0) {
         throw new Exception('permission denied');
     }
     $bulkScope = filter_input(INPUT_POST, 'bulkScope');
     switch ($bulkScope) {
         case 'u':
             $uploadTreeTable = $this->uploadDao->getUploadtreeTableName($uploadId);
             $row = $this->dbManager->getSingleRow("SELECT uploadtree_pk FROM {$uploadTreeTable} WHERE upload_fk = \$1 ORDER BY uploadtree_pk LIMIT 1", array($uploadId), __METHOD__ . "adam" . $uploadTreeTable);
             $uploadTreeId = $row['uploadtree_pk'];
             break;
         case 'f':
             if (!Isdir($uploadEntry['ufile_mode']) && !Iscontainer($uploadEntry['ufile_mode']) && !Isartifact($uploadEntry['ufile_mode'])) {
                 $uploadTreeId = $uploadEntry['parent'] ?: $uploadTreeId;
             }
             break;
         default:
             throw new InvalidArgumentException('bad scope request');
     }
     $userId = Auth::getUserId();
     $groupId = Auth::getGroupId();
     $refText = filter_input(INPUT_POST, 'refText');
     $action = filter_input(INPUT_POST, 'bulkAction');
     $licenseId = GetParm('licenseId', PARM_INTEGER);
     $removing = $action === 'remove';
     $bulkId = $this->licenseDao->insertBulkLicense($userId, $groupId, $uploadTreeId, $licenseId, $removing, $refText);
     if ($bulkId <= 0) {
         throw new Exception('cannot insert bulk reference');
     }
     $upload = $this->uploadDao->getUpload($uploadId);
     $uploadName = $upload->getFilename();
     $job_pk = JobAddJob($userId, $groupId, $uploadName, $uploadId);
     /** @var DeciderJobAgentPlugin $deciderPlugin */
     $deciderPlugin = plugin_find("agent_deciderjob");
     $dependecies = array(array('name' => 'agent_monk_bulk', 'args' => $bulkId));
     $conflictStrategyId = intval(filter_input(INPUT_POST, 'forceDecision'));
     $errorMsg = '';
     $jqId = $deciderPlugin->AgentAdd($job_pk, $uploadId, $errorMsg, $dependecies, $conflictStrategyId);
     if (!empty($errorMsg)) {
         throw new Exception(str_replace('<br>', "\n", $errorMsg));
     }
     return $jqId;
 }
 /**
  * @param int $userId
  * @param int
  * @param int $lastItem
  * @return array
  */
 protected function updateLastItem($userId, $groupId, $lastItem)
 {
     $type = GetParm("clearingTypes", PARM_INTEGER);
     $global = GetParm("globalDecision", PARM_STRING) === "on";
     $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($lastItem);
     $itemBounds = $this->uploadDao->getItemTreeBounds($lastItem, $uploadTreeTableName);
     $this->clearingDecisionEventProcessor->makeDecisionFromLastEvents($itemBounds, $userId, $groupId, $type, $global);
 }
Exemple #14
0
 private function writeReport($contents, $uploadId)
 {
     global $SysConf;
     $packageName = $this->uploadDao->getUpload($uploadId)->getFilename();
     $fileBase = $SysConf['FOSSOLOGY']['path'] . "/report/";
     $fileName = $fileBase . "ReadMe_OSS_" . $packageName . '_' . time() . ".txt";
     foreach ($this->additionalUploadIds as $addUploadId) {
         $packageName .= ', ' . $this->uploadDao->getUpload($addUploadId)->getFilename();
     }
     if (!is_dir($fileBase)) {
         mkdir($fileBase, 0777, true);
     }
     umask(0133);
     $message = $this->generateReport($contents, $packageName);
     file_put_contents($fileName, $message);
     $this->updateReportTable($uploadId, $this->jobId, $fileName);
 }
Exemple #15
0
 /**
  * @param int $uploadId
  */
 protected function computeUri($uploadId)
 {
     global $SysConf;
     $upload = $this->uploadDao->getUpload($uploadId);
     $packageName = $upload->getFilename();
     $fileBase = $SysConf['FOSSOLOGY']['path'] . "/report/";
     $this->uri = $this->getUri($fileBase, $packageName);
 }
 public function getCleared($uploadId, $groupId = null)
 {
     $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId);
     $ungrupedStatements = $this->getStatements($uploadId, $uploadTreeTableName, $groupId);
     $this->changeTreeIdsToPaths($ungrupedStatements, $uploadTreeTableName, $uploadId);
     $statements = $this->groupStatements($ungrupedStatements);
     return array("statements" => array_values($statements));
 }
 /**
  * @param ItemTreeBounds $itemTreeBounds
  * @return array with keys 'isFlat','iTotalRecords','fileSwitch'
  */
 private function countFileListing(ItemTreeBounds $itemTreeBounds)
 {
     $isFlat = isset($_GET['flatten']);
     $vars['isFlat'] = $isFlat;
     $vars['iTotalRecords'] = $this->uploadDao->countNonArtifactDescendants($itemTreeBounds, $isFlat);
     $uri = Traceback_uri() . '?mod=' . $this->Name . Traceback_parm_keep(array('upload', 'folder', 'show', 'item'));
     $vars['fileSwitch'] = $isFlat ? $uri : $uri . "&flatten=yes";
     return $vars;
 }
Exemple #18
0
 function processUploadId($uploadId)
 {
     $itemTreeBounds = $this->uploadDao->getParentItemBounds($uploadId);
     foreach ($this->uploadDao->getReusedUpload($uploadId, $this->groupId) as $reuseTriple) {
         $reusedUploadId = $reuseTriple['reused_upload_fk'];
         $reusedGroupId = $reuseTriple['reused_group_fk'];
         $reuseMode = $reuseTriple['reuse_mode'];
         $itemTreeBoundsReused = $this->uploadDao->getParentItemBounds($reusedUploadId);
         if (false === $itemTreeBoundsReused) {
             continue;
         }
         if (empty($reuseMode)) {
             $this->processUploadReuse($itemTreeBounds, $itemTreeBoundsReused, $reusedGroupId);
         } else {
             $this->processEnhancedUploadReuse($itemTreeBounds, $itemTreeBoundsReused, $reusedGroupId);
         }
     }
     return true;
 }
 protected function doUndo($itemId, $hash, $type)
 {
     $item = $this->uploadDao->getItemTreeBounds($itemId, $this->uploadtree_tablename);
     $cpTable = $this->getTableName($type);
     if ($cpTable != 'copyright') {
         return new Response('There is not undo for ' . $cpTable, Response::HTTP_NOT_IMPLEMENTED, array('Content-type' => 'text/plain'));
     }
     $this->copyrightDao->rollbackTable($item, $hash, Auth::getUserId(), $cpTable);
     return new Response('Successfully restored', Response::HTTP_OK, array('Content-type' => 'text/plain'));
 }
 public function testRun()
 {
     $this->setUpTables();
     $this->setUpRepo();
     $output = $this->runCopyright($uploadId = 1);
     $this->rmRepo();
     $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId);
     $matches = $this->copyrightDao->getAllEntries("copyright", $uploadId, $uploadTreeTableName);
     $this->assertGreaterThan($expected = 5, count($matches), $output);
 }
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $uploadId = intval($request->get('upload'));
     if (empty($uploadId)) {
         return;
     }
     $uploadTreeId = intval($request->get('item'));
     if (empty($uploadTreeId)) {
         return;
     }
     $onlyTried = !$request->get('all');
     $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId);
     /** @var ItemTreeBounds */
     $itemTreeBounds = $this->uploadDao->getItemTreeBounds($uploadTreeId, $uploadTreeTableName);
     /** @var Session */
     $session = $this->getObject('session');
     $groupId = $session->get(Auth::GROUP_ID);
     $bulkHistory = $this->clearingDao->getBulkHistory($itemTreeBounds, $groupId, $onlyTried);
     return $this->render("bulk-history.html.twig", $this->mergeWithDefault(array('bulkHistory' => $bulkHistory)));
 }
 protected function setUp()
 {
     global $container;
     $this->highlightDao = M::mock(HighlightDao::classname());
     $container->shouldReceive('get')->withArgs(array('dao.highlight'))->andReturn($this->highlightDao);
     $container->shouldReceive('get')->withArgs(array('dao.upload'))->andReturn(M::mock(UploadDao::classname()));
     $container->shouldReceive('get')->withArgs(array('dao.clearing'))->andReturn(M::mock(ClearingDao::classname()));
     $container->shouldReceive('get')->withArgs(array('decision.types'))->andReturn(M::mock(DecisionTypes::classname()));
     $container->shouldReceive('get')->withArgs(array('businessrules.clearing_decision_processor'))->andReturn(M::mock(ClearingDecisionProcessor::classname()));
     $container->shouldReceive('get')->withArgs(array('businessrules.agent_license_event_processor'))->andReturn(M::mock(AgentLicenseEventProcessor::classname()));
     $this->assertCountBefore = \Hamcrest\MatcherAssert::getCount();
 }
 private function loopContainedItems($itemTreeBounds)
 {
     if (!$itemTreeBounds->containsFiles()) {
         return array($itemTreeBounds);
     }
     $result = array();
     $condition = "(ut.lft BETWEEN \$1 AND \$2) AND ((ut.ufile_mode & (3<<28)) = 0)";
     $params = array($itemTreeBounds->getLeft(), $itemTreeBounds->getRight());
     foreach ($this->uploadDao->getContainedItems($itemTreeBounds, $condition, $params) as $item) {
         $result[] = $item->getItemTreeBounds();
     }
     return $result;
 }
 /**
  * @param $itemId - uploadtree id
  * @param $uploadId - upload id
  */
 public function getCopyrightList($itemId, $uploadId)
 {
     if (empty($itemId)) {
         $itemId = $this->uploadDao->getUploadParent($uploadId);
     }
     if (!$this->selectAgentId($uploadId)) {
         echo 'no valid copyright agent found';
         return;
     }
     $uploadtree_tablename = $this->uploadDao->getUploadtreeTableName($uploadId);
     $toprow = $this->uploadDao->getItemTreeBounds($itemId, $uploadtree_tablename);
     $extraWhere = 'agent_fk=' . $this->agentId . ' AND lft>' . $toprow->getLeft() . ' AND rgt<' . $toprow->getRight();
     $allCopyrightEntries = $this->copyrightDao->getAllEntries('copyright', $uploadId, $uploadtree_tablename, empty($this->type) || $this->type == 'all' ? null : $this->type, false, null, $extraWhere);
     $modeMask = empty($this->includeContainer) ? 3 << 28 : 1 << 28;
     $sql = "SELECT uploadtree_pk, ufile_name, lft, rgt FROM {$uploadtree_tablename} \n              WHERE upload_fk=\$1 AND lft>\$2 AND rgt<\$3 AND (ufile_mode & \$4) = 0\n              ORDER BY uploadtree_pk";
     $this->dbManager->prepare($outerStmt = __METHOD__ . '.loopThroughAllRecordsInTree', $sql);
     $outerresult = $this->dbManager->execute($outerStmt, array($toprow->getUploadId(), $toprow->getLeft(), $toprow->getRight(), $modeMask));
     while ($row = $this->dbManager->fetchArray($outerresult)) {
         $this->printRow($row, $uploadtree_tablename, $allCopyrightEntries);
         //$this->uploadDao->getParentItemBounds($uploadId)->getItemId());
     }
     $this->dbManager->freeResult($outerresult);
 }
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $upload = intval($request->get("upload"));
     $groupId = Auth::getGroupId();
     if (!$this->uploadDao->isAccessible($upload, $groupId)) {
         throw new \Exception("Permission Denied");
     }
     $item = intval($request->get("item"));
     $this->uploadtree_tablename = $this->uploadDao->getUploadtreeTableName($upload);
     $itemTreeBounds = $this->uploadDao->getItemTreeBounds($item, $this->uploadtree_tablename);
     $left = $itemTreeBounds->getLeft();
     if (empty($left)) {
         throw new \Exception("Job unpack/adj2nest hasn't completed.");
     }
     $scannerAgents = array_keys($this->agentNames);
     $scanJobProxy = new ScanJobProxy($this->agentDao, $upload);
     $scanJobProxy->createAgentStatus($scannerAgents);
     $selectedAgentId = intval($request->get('agentId'));
     $tag_pk = intval($request->get('tag'));
     $UniqueTagArray = array();
     $this->licenseProjector = new LicenseMap($this->getObject('db.manager'), $groupId, LicenseMap::CONCLUSION, true);
     $vars = $this->createFileListing($tag_pk, $itemTreeBounds, $UniqueTagArray, $selectedAgentId, $groupId, $scanJobProxy);
     return new JsonResponse(array('sEcho' => intval($request->get('sEcho')), 'aaData' => $vars['fileData'], 'iTotalRecords' => intval($request->get('totalRecords')), 'iTotalDisplayRecords' => $vars['iTotalDisplayRecords']));
 }
 /**
  * @param int $uploadId
  * @param int $reuseUploadId
  * @param int $groupId
  * @param int $reuseGroupId
  * @param int $reuseMode
  */
 protected function createPackageLink($uploadId, $reuseUploadId, $groupId, $reuseGroupId, $reuseMode = 0)
 {
     /* @var $packageDao PackageDao */
     $packageDao = $GLOBALS['container']->get('dao.package');
     $newUpload = $this->uploadDao->getUpload($uploadId);
     $uploadForReuse = $this->uploadDao->getUpload($reuseUploadId);
     $package = $packageDao->findPackageForUpload($reuseUploadId);
     if ($package === null) {
         $packageName = StringOperation::getCommonHead($uploadForReuse->getFilename(), $newUpload->getFilename());
         $package = $packageDao->createPackage($packageName ?: $uploadForReuse->getFilename());
         $packageDao->addUploadToPackage($reuseUploadId, $package);
     }
     $packageDao->addUploadToPackage($uploadId, $package);
     $this->uploadDao->addReusedUpload($uploadId, $reuseUploadId, $groupId, $reuseGroupId, $reuseMode);
 }
Exemple #27
0
 /**
  * @param int $uploadTreeId
  * @param int $Folder
  * @param int $Upload
  * @return string
  */
 function outputItemHtml($uploadTreeId, $Folder, $Upload)
 {
     global $container;
     $dbManager = $container->get('db.manager');
     $show = 'quick';
     $html = '';
     $uploadtree_tablename = "";
     if (!empty($uploadTreeId)) {
         $sql = "SELECT ufile_mode, upload_fk FROM uploadtree WHERE uploadtree_pk = \$1";
         $row = $dbManager->getSingleRow($sql, array($uploadTreeId));
         $Upload = $row['upload_fk'];
         if (!$this->uploadDao->isAccessible($Upload, Auth::getGroupId())) {
             $this->vars['message'] = _("Permission Denied");
             return $this->render('include/base.html.twig');
         }
         if (!Iscontainer($row['ufile_mode'])) {
             global $Plugins;
             $View =& $Plugins[plugin_find_id("view")];
             if (!empty($View)) {
                 $this->vars['content'] = $View->ShowView(NULL, "browse");
                 return $this->render('include/base.html.twig');
             }
         }
         $uploadtree_tablename = $this->uploadDao->getUploadtreeTableName($row['upload_fk']);
         $html .= Dir2Browse($this->Name, $uploadTreeId, NULL, 1, "Browse", -1, '', '', $uploadtree_tablename) . "\n";
     } else {
         if (!empty($Upload)) {
             $uploadtree_tablename = $this->uploadDao->getUploadtreeTableName($Upload);
             $html .= Dir2BrowseUpload($this->Name, $Upload, NULL, 1, "Browse", $uploadtree_tablename) . "\n";
         }
     }
     if (empty($Upload)) {
         $this->vars['show'] = $show;
         $this->ShowFolder($Folder);
         return $html;
     }
     if (empty($uploadTreeId)) {
         try {
             $uploadTreeId = $this->uploadDao->getUploadParent($Upload);
         } catch (Exception $e) {
             $this->vars['message'] = $e->getMessage();
             return $this->render('include/base.html.twig');
         }
     }
     $html .= $this->ShowItem($Upload, $uploadTreeId, $show, $Folder, $uploadtree_tablename);
     $this->vars['content'] = $html;
     return $this->render('include/base.html.twig');
 }
 public function Output()
 {
     $uploadId = GetParm("upload", PARM_INTEGER);
     if (!$this->uploadDao->isAccessible($uploadId, Auth::getGroupId())) {
         return;
     }
     $itemId = GetParm("item", PARM_INTEGER);
     $this->vars['micromenu'] = Dir2Browse("browse", $itemId, NULL, $showBox = 0, "View-Meta");
     $V = "";
     $V .= $this->ShowTagInfo($uploadId, $itemId);
     $V .= $this->ShowPackageinfo($uploadId, $itemId, 1);
     $V .= $this->ShowMetaView($uploadId, $itemId);
     $V .= $this->ShowSightings($uploadId, $itemId);
     $V .= $this->ShowView($uploadId, $itemId);
     return $V;
 }
 public function testGetFileNamesGroupByText()
 {
     $this->clearedGetterTest = new TestClearedGetter();
     $uploadId = 1;
     $parentId = 112;
     $uploadTreeTableName = "ut";
     $this->uploadDao->shouldReceive('getUploadtreeTableName')->with($uploadId)->andReturn($uploadTreeTableName);
     $this->treeDao->shouldReceive('getMinimalCoveringItem')->with($uploadId, $uploadTreeTableName)->andReturn($parentId);
     $this->treeDao->shouldReceive('getFullPath')->with(1, $uploadTreeTableName, $parentId)->andReturn("a/1");
     $this->treeDao->shouldReceive('getFullPath')->with(2, $uploadTreeTableName, $parentId)->andReturn("a/2");
     $this->treeDao->shouldReceive('getFullPath')->with(3, $uploadTreeTableName, $parentId)->andReturn("a/b/1");
     $tester = new TestClearedGetter("text");
     $statements = $tester->getCleared($uploadId);
     $expected = array("statements" => array(array("content" => "1", "text" => "t1", "comments" => "c1", "files" => array("a/1")), array("content" => "1", "text" => "t2", "comments" => "c1", "files" => array("a/2")), array("content" => "2", "text" => "t3", "comments" => "c3", "files" => array("a/b/1"))));
     $expected = arsort($expected);
     assertThat($expected, equalTo($statements));
 }
Exemple #30
0
 protected function setUp()
 {
     $this->uploadDao = M::mock(UploadDao::classname());
     $logger = new Logger('default');
     $logger->pushHandler(new ErrorLogHandler());
     $this->testDb = new TestPgDb();
     $this->dbManager =& $this->testDb->getDbManager();
     $this->clearingDao = new ClearingDao($this->dbManager, $this->uploadDao);
     $this->testDb->createPlainTables(array('clearing_decision', 'clearing_decision_event', 'clearing_decision_type', 'clearing_event', 'clearing_licenses', 'highlight_bulk', 'license_ref', 'license_ref_bulk', 'license_set_bulk', 'users', 'uploadtree'));
     $this->testDb->createInheritedTables();
     $userArray = array(array('myself', 1), array('in_same_group', 2), array('in_trusted_group', 3));
     foreach ($userArray as $ur) {
         $this->dbManager->insertInto('users', 'user_name, root_folder_fk', $ur);
     }
     $refArray = array(array(401, 'FOO', 'foo full', 'foo text'), array(402, 'BAR', 'bar full', 'bar text'), array(403, 'BAZ', 'baz full', 'baz text'), array(404, 'QUX', 'qux full', 'qux text'));
     foreach ($refArray as $params) {
         $this->dbManager->insertInto('license_ref', 'rf_pk, rf_shortname, rf_fullname, rf_text', $params, $logStmt = 'insert.ref');
     }
     $modd = 536888320;
     $modf = 33188;
     /*                          (pfile,item,lft,rgt)
           upload101:   upload101/    (  0, 299,  1,  4)
                        Afile         (201, 301,  1,  2)
                        Bfile         (202, 302,  3,  4)
           upload102:   upload102/    (  0, 300,  1,  8)
                        Afile         (201, 303,  1,  2)
                        A-dir/        (  0, 304,  3,  6)
                        A-dir/Afile   (201, 305,  4,  5)
                        Bfile         (202, 306,  7,  8)
         */
     $this->items = array(299 => array(101, 299, 0, $modd, 1, 4, "upload101"), 300 => array(102, 300, 0, $modd, 1, 8, "upload102"), 301 => array(101, 301, 201, $modf, 1, 2, "Afile"), 302 => array(101, 302, 202, $modf, 3, 4, "Bfile"), 303 => array(102, 303, 201, $modf, 1, 2, "Afile"), 304 => array(102, 304, 0, $modd, 3, 6, "A-dir"), 305 => array(102, 305, 201, $modf, 4, 5, "Afile"), 306 => array(102, 306, 202, $modf, 7, 8, "Bfile"));
     foreach ($this->items as $ur) {
         $this->dbManager->insertInto('uploadtree', 'upload_fk,uploadtree_pk,pfile_fk,ufile_mode,lft,rgt,ufile_name', $ur);
     }
     $this->now = time();
     $bulkLicArray = array(array(1, 401, 'TextFOO', false, 101, 299, $this->groupId), array(2, 402, 'TextBAR', false, 101, 299, $this->groupId), array(3, 403, 'TextBAZ', true, 101, 301, $this->groupId), array(4, 403, 'TextBAZ', false, 101, 299, $this->groupId), array(5, 404, 'TextQUX', true, 101, 299, $this->groupId), array(6, 401, 'TexxFOO', true, 101, 302, $this->groupId), array(7, 403, 'TextBAZ', false, 102, 300, $this->groupId), array(8, 403, 'TextBAZ', true, 102, 306, $this->groupId));
     foreach ($bulkLicArray as $params) {
         $paramsRef = array($params[0], $params[2], $params[4], $params[5], $params[6]);
         $paramsSet = array($params[0], $params[1], $params[3]);
         $this->dbManager->insertInto('license_ref_bulk', 'lrb_pk, rf_text, upload_fk, uploadtree_fk, group_fk', $paramsRef, 'insert.bulkref');
         $this->dbManager->insertInto('license_set_bulk', 'lrb_fk, rf_fk, removing', $paramsSet, 'insert.bulkset');
     }
     $this->assertCountBefore = \Hamcrest\MatcherAssert::getCount();
 }