Beispiel #1
0
 /**
  * @param int $uploadId
  * @param Package $package
  */
 public function addUploadToPackage($uploadId, Package $package)
 {
     $statementName = __METHOD__;
     $this->dbManager->prepare($statementName, "INSERT INTO upload_packages (package_fk, upload_fk) VALUES(\$1, \$2)");
     $res = $this->dbManager->execute($statementName, array($package->getId(), $uploadId));
     $this->dbManager->freeResult($res);
 }
Beispiel #2
0
 public function rerunBulkAndDeciderOnUpload($uploadId, $groupId, $userId, $jobId)
 {
     $bulkIds = $this->getBulkIds($uploadId, $groupId, $userId);
     if (count($bulkIds) == 0) {
         return 0;
     }
     /* @var $uploadDao UploadDao */
     $uploadDao = $GLOBALS['container']->get('dao.upload');
     $topItem = $uploadDao->getUploadParent($uploadId);
     /* @var $deciderPlugin DeciderJobAgentPlugin */
     $deciderPlugin = plugin_find("agent_deciderjob");
     $dependecies = array();
     $sql = "INSERT INTO license_ref_bulk (user_fk,group_fk,rf_fk,rf_text,removing,upload_fk,uploadtree_fk) " . "SELECT \$1 AS user_fk, \$2 AS group_fk,rf_fk,rf_text,removing,\$3 AS upload_fk, \$4 as uploadtree_fk\n              FROM license_ref_bulk WHERE lrb_pk=\$5 RETURNING lrb_pk";
     $this->dbManager->prepare($stmt = __METHOD__ . 'cloneBulk', $sql);
     foreach ($bulkIds as $bulkId) {
         $res = $this->dbManager->execute($stmt, array($userId, $groupId, $uploadId, $topItem, $bulkId));
         $row = $this->dbManager->fetchArray($res);
         $this->dbManager->freeResult($res);
         $dependecies[] = array('name' => 'agent_monk_bulk', 'args' => $row['lrb_pk'], AgentPlugin::PRE_JOB_QUEUE => array('agent_decider'));
     }
     $errorMsg = '';
     $jqId = $deciderPlugin->AgentAdd($jobId, $uploadId, $errorMsg, $dependecies);
     if (!empty($errorMsg)) {
         throw new Exception($errorMsg);
     }
     return $jqId;
 }
Beispiel #3
0
 /**
  * @brief Update upload properties (name and description)
  *
  * @param $uploadId upload.upload_pk of record to update
  * @param $newName New upload.upload_filename, and uploadtree.ufle_name
  *        If null, old value is not changed.
  * @param $newDesc New upload description (upload.upload_desc)
  *        If null, old value is not changed.
  *
  * @return 1 if the upload record is updated, 0 if not, 2 if no inputs
  **/
 function UpdateUploadProperties($uploadId, $newName, $newDesc)
 {
     if (empty($newName) and empty($newDesc)) {
         return 2;
     }
     if (!empty($newName)) {
         /* Use pfile_fk to select the correct entry in the upload tree, artifacts
          * (e.g. directories of the upload do not have pfiles).
          */
         $row = $this->dbManager->getSingleRow("SELECT pfile_fk FROM upload WHERE upload_pk=\$1", array($uploadId), __METHOD__ . '.getPfileId');
         if (empty($row)) {
             return 0;
         }
         $pfileFk = $row['pfile_fk'];
         $trimNewName = trim($newName);
         /* Always keep uploadtree.ufile_name and upload.upload_filename in sync */
         $this->dbManager->getSingleRow("UPDATE uploadtree SET ufile_name=\$3 WHERE upload_fk=\$1 AND pfile_fk=\$2", array($uploadId, $pfileFk, $trimNewName), __METHOD__ . '.updateItem');
         $this->dbManager->getSingleRow("UPDATE upload SET upload_filename=\$3 WHERE upload_pk=\$1 AND pfile_fk=\$2", array($uploadId, $pfileFk, $trimNewName), __METHOD__ . '.updateUpload.name');
     }
     if (!empty($newDesc)) {
         $trimNewDesc = trim($newDesc);
         $this->dbManager->getSingleRow("UPDATE upload SET upload_desc=\$2 WHERE upload_pk=\$1", array($uploadId, $trimNewDesc), __METHOD__ . '.updateUpload.desc');
     }
     return 1;
 }
Beispiel #4
0
 /**
  * @param int $parentFolder  parent folder_pk
  * @return string HTML of the folder tree
  */
 public function showFolderTree($parentFolder)
 {
     $uri = Traceback_uri();
     $sql = $this->folderDao->getFolderTreeCte($parentFolder) . " SELECT folder_pk, folder_name, folder_desc, depth, name_path FROM folder_tree ORDER BY name_path";
     $stmt = __METHOD__;
     $this->dbManager->prepare($stmt, $sql);
     $res = $this->dbManager->execute($stmt, array($parentFolder));
     $out = '';
     $lastDepth = -1;
     while ($row = $this->dbManager->fetchArray($res)) {
         for (; $row['depth'] < $lastDepth; $lastDepth--) {
             $out .= '</li></ul>';
         }
         if ($row['depth'] == $lastDepth) {
             $out .= "</li>\n<li>";
         }
         if ($row['depth'] == 0) {
             $out .= '<ul id="tree"><li>';
             $lastDepth++;
         }
         for (; $row['depth'] > $lastDepth; $lastDepth++) {
             $out .= '<ul><li>';
         }
         $out .= $this->getFormattedItem($row, $uri);
     }
     for (; -1 < $lastDepth; $lastDepth--) {
         $out .= '</li></ul>';
     }
     return $out;
 }
 /**
  * \brief Generate the text for this plugin.
  */
 public function Output()
 {
     /* If this is a POST, then process the request. */
     $folder = GetParm('folder', PARM_INTEGER);
     if (!empty($folder)) {
         $userId = Auth::getUserId();
         $sql = "SELECT folder_name FROM folder join users on (users.user_pk = folder.user_fk or users.user_perm = 10) where folder_pk = \$1 and users.user_pk = \$2;";
         $Folder = $this->dbManager->getSingleRow($sql, array($folder, $userId), __METHOD__ . "GetRowWithFolderName");
         if (!empty($Folder['folder_name'])) {
             $rc = $this->Delete($folder, $userId);
             if (empty($rc)) {
                 /* Need to refresh the screen */
                 $text = _("Deletion of folder ");
                 $text1 = _(" added to job queue");
                 $this->vars['message'] = $text . $Folder['folder_name'] . $text1;
             } else {
                 $text = _("Deletion of ");
                 $text1 = _(" failed: ");
                 $this->vars['message'] = $text . $Folder['folder_name'] . $text1 . $rc;
             }
         } else {
             $text = _("Cannot delete this folder :: Permission denied");
             $this->vars['message'] = $text;
         }
     }
     $V = "<form method='post'>\n";
     // no url = this url
     $text = _("Select the folder to");
     $text1 = _("delete");
     $V .= "{$text} <em>{$text1}</em>.\n";
     $V .= "<ul>\n";
     $text = _("This will");
     $text1 = _("delete");
     $text2 = _("the folder, all subfolders, and all uploaded files stored within the folder!");
     $V .= "<li>{$text} <em>{$text1}</em> {$text2}\n";
     $text = _("Be very careful with your selection since you can delete a lot of work!");
     $V .= "<li>{$text}\n";
     $text = _("All analysis only associated with the deleted uploads will also be deleted.");
     $V .= "<li>{$text}\n";
     $text = _("THERE IS NO UNDELETE. When you select something to delete, it will be removed from the database and file repository.");
     $V .= "<li>{$text}\n";
     $V .= "</ul>\n";
     $text = _("Select the folder to delete:  ");
     $V .= "<P>{$text}\n";
     $V .= "<select name='folder'>\n";
     $text = _("select folder");
     $V .= "<option value=''>[{$text}]</option>\n";
     $V .= FolderListOption(-1, 0);
     $V .= "</select><P />\n";
     $text = _("Delete");
     $V .= "<input type='submit' value='{$text}'>\n";
     $V .= "</form>\n";
     return $V;
 }
Beispiel #6
0
 public function hasActionPermissionsOnJob($jobId, $userId, $groupId)
 {
     $result = array();
     $stmt = __METHOD__;
     $this->dbManager->prepare($stmt, "SELECT *\n       FROM job\n         LEFT JOIN group_user_member gm\n           ON gm.user_fk = job_user_fk\n       WHERE job_pk = \$1\n         AND (job_user_fk = \$2\n              OR gm.group_fk = \$3)");
     $res = $this->dbManager->execute($stmt, array($jobId, $userId, $groupId));
     while ($row = $this->dbManager->fetchArray($res)) {
         $result[$row['jq_pk']] = $row['end_bits'];
     }
     $this->dbManager->freeResult($res);
     return $result;
 }
Beispiel #7
0
 public function getRepoPathOfPfile($pfileId, $repo = "files")
 {
     $pfileRow = $this->dbManager->getSingleRow('SELECT * FROM pfile WHERE pfile_pk=$1', array($pfileId));
     global $LIBEXECDIR;
     if (empty($pfileRow['pfile_sha1'])) {
         return null;
     }
     $hash = $pfileRow['pfile_sha1'] . "." . $pfileRow['pfile_md5'] . "." . $pfileRow['pfile_size'];
     $path = '';
     exec("{$LIBEXECDIR}/reppath {$repo} {$hash}", $path);
     return $path[0];
 }
Beispiel #8
0
 public function getAllJobStatus($uploadId, $userId, $groupId)
 {
     $result = array();
     $stmt = __METHOD__;
     $this->dbManager->prepare($stmt, "SELECT jobqueue.jq_pk as jq_pk, jobqueue.jq_end_bits as end_bits\n      FROM jobqueue INNER JOIN job ON jobqueue.jq_job_fk = job.job_pk\n      LEFT JOIN group_user_member gm ON gm.user_fk = job_user_fk\n      WHERE job.job_upload_fk = \$1 AND (job_user_fk = \$2 OR gm.group_fk = \$3)");
     $res = $this->dbManager->execute($stmt, array($uploadId, $userId, $groupId));
     while ($row = $this->dbManager->fetchArray($res)) {
         $result[$row['jq_pk']] = $row['end_bits'];
     }
     $this->dbManager->freeResult($res);
     return $result;
 }
 /**
  * @brief : returns 1 when jobs are running else 0
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $response = '1';
     $jobInfo = $this->dbManager->getSingleRow("SELECT jq_end_bits FROM jobqueue WHERE jq_end_bits ='0' LIMIT 1");
     if (empty($jobInfo)) {
         $response = '0';
     }
     $status = 1;
     ReportCachePurgeAll();
     $status = empty($status) ? Response::HTTP_INTERNAL_SERVER_ERROR : Response::HTTP_OK;
     return new Response(json_encode(array("status" => $response)), $status, array('content-type' => 'text/json'));
 }
Beispiel #10
0
 /**
  * \brief Generate the text for this plugin.
  */
 public function Output()
 {
     /* If this is a POST, then process the request. */
     $FolderSelectId = GetParm('selectfolderid', PARM_INTEGER);
     if (empty($FolderSelectId)) {
         $FolderSelectId = FolderGetTop();
     }
     $FolderId = GetParm('oldfolderid', PARM_INTEGER);
     $NewName = GetParm('newname', PARM_TEXT);
     $NewDesc = GetParm('newdesc', PARM_TEXT);
     if (!empty($FolderId)) {
         $FolderSelectId = $FolderId;
         $rc = $this->Edit($FolderId, $NewName, $NewDesc);
         if ($rc == 1) {
             /* Need to refresh the screen */
             $text = _("Folder Properties changed");
             $this->vars["message"] = $text;
         }
     }
     /* Get the folder info */
     $sql = 'SELECT * FROM folder WHERE folder_pk = $1;';
     $Folder = $this->dbManager->getSingleRow($sql, array($FolderSelectId), __METHOD__ . "getFolderRow");
     /* Display the form */
     $formVars["onchangeURI"] = Traceback_uri() . "?mod=" . $this->Name . "&selectfolderid=";
     $formVars["folderListOption"] = FolderListOption(-1, 0, 1, $FolderSelectId);
     $formVars["folder_name"] = $Folder['folder_name'];
     $formVars["folder_desc"] = $Folder['folder_desc'];
     return $this->renderString("admin-folder-edit-form.html.twig", $formVars);
 }
Beispiel #11
0
 public function testGetAgentFileLicenseMatchesWithLicenseMapping()
 {
     $this->testDb->createPlainTables(array('license_ref', 'uploadtree', 'license_file', 'agent', 'license_map'));
     $this->testDb->insertData_license_ref();
     $lic0 = $this->dbManager->getSingleRow("Select * from license_ref limit 1", array(), __METHOD__ . '.anyLicense');
     $licRefId = $lic0['rf_pk'];
     $licenseFileId = 1;
     $pfileId = 42;
     $agentId = 23;
     $matchPercent = 50;
     $uploadtreeId = 512;
     $uploadID = 123;
     $left = 2009;
     $right = 2014;
     $agentName = "fake";
     $agentRev = 1;
     $lic1 = $this->dbManager->getSingleRow("SELECT * FROM license_ref WHERE rf_pk!=\$1 LIMIT 1", array($licRefId), __METHOD__ . '.anyOtherLicense');
     $licVarId = $lic1['rf_pk'];
     $mydate = "'2014-06-04 14:01:30.551093+02'";
     $this->dbManager->insertTableRow('license_map', array('license_map_pk' => 0, 'rf_fk' => $licVarId, 'rf_parent' => $licRefId, 'usage' => LicenseMap::CONCLUSION));
     $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk, rf_fk, agent_fk, rf_match_pct, rf_timestamp, pfile_fk)\n            VALUES ({$licenseFileId}, {$licVarId}, {$agentId}, {$matchPercent}, {$mydate}, {$pfileId})");
     $this->dbManager->queryOnce("INSERT INTO uploadtree (uploadtree_pk, upload_fk, pfile_fk, lft, rgt)\n            VALUES ({$uploadtreeId}, {$uploadID}, {$pfileId}, {$left}, {$right})");
     $stmt = __METHOD__ . '.insert.agent';
     $this->dbManager->prepare($stmt, "INSERT INTO agent (agent_pk, agent_name, agent_rev, agent_enabled) VALUES (\$1,\$2,\$3,\$4)");
     $this->dbManager->execute($stmt, array($agentId, $agentName, $agentRev, 'true'));
     $licDao = new LicenseDao($this->dbManager);
     $itemTreeBounds = new ItemTreeBounds($uploadtreeId, "uploadtree", $uploadID, $left, $right);
     $matches = $licDao->getAgentFileLicenseMatches($itemTreeBounds, LicenseMap::CONCLUSION);
     $licenseRef = new LicenseRef($licRefId, $lic0['rf_shortname'], $lic0['rf_fullname']);
     $agentRef = new AgentRef($agentId, $agentName, $agentRev);
     $expected = array(new LicenseMatch($pfileId, $licenseRef, $agentRef, $licenseFileId, $matchPercent));
     assertThat($matches, equalTo($expected));
     $this->addToAssertionCount(\Hamcrest\MatcherAssert::getCount() - $this->assertCountBefore);
 }
Beispiel #12
0
 /**
  * \brief Database queries
  * \returns html table containing query strings, pid, and start time
  */
 function DatabaseQueries()
 {
     $V = "<table border=1>\n";
     $head1 = _("PID");
     $head2 = _("Query");
     $head3 = _("Started");
     $head4 = _("Elapsed");
     $V .= "<tr><th>{$head1}</th><th>{$head2}</th><th>{$head3}</th><th>{$head4}</th></tr>\n";
     $current_query = strcmp($this->pgVersion['server'], "9.2") >= 0 ? "state" : "current_query";
     $procpid = strcmp($this->pgVersion['server'], "9.2") >= 0 ? "pid" : "procpid";
     $sql = "SELECT {$procpid} processid, {$current_query}, query_start, now()-query_start AS elapsed FROM pg_stat_activity WHERE {$current_query} != '<IDLE>' AND datname = 'fossology' ORDER BY {$procpid}";
     $statementName = __METHOD__ . "queryFor_" . $current_query . "_orderBy_" . $procpid;
     $this->dbManager->prepare($statementName, $sql);
     $result = $this->dbManager->execute($statementName, array());
     if (pg_num_rows($result) > 1) {
         while ($row = pg_fetch_assoc($result)) {
             if ($row[$current_query] == $sql) {
                 continue;
             }
             // Don't display this query
             $V .= "<tr>";
             $V .= "<td>{$row['processid']}</td>";
             $V .= "<td>" . htmlspecialchars($row[$current_query]) . "</td>";
             $StartTime = substr($row['query_start'], 0, 19);
             $V .= "<td>{$StartTime}</td>";
             $V .= "<td>{$row['elapsed']}</td>";
             $V .= "</tr>\n";
         }
     } else {
         $V .= "<tr><td colspan=4>There are no active FOSSology queries</td></tr>";
     }
     pg_free_result($result);
     $V .= "</table>\n";
     return $V;
 }
 /**
  * @param ItemTreeBounds $itemBounds
  * @param int $userId
  * @param int $groupId
  * @param int $type
  * @param boolean $global
  * @param int[] $additionalEventIds additional event ids to include, indexed by licenseId
  */
 public function makeDecisionFromLastEvents(ItemTreeBounds $itemBounds, $userId, $groupId, $type, $global, $additionalEventIds = array())
 {
     if ($type < self::NO_LICENSE_KNOWN_DECISION_TYPE) {
         return;
     }
     $this->dbManager->begin();
     $itemId = $itemBounds->getItemId();
     $previousEvents = $this->clearingDao->getRelevantClearingEvents($itemBounds, $groupId);
     if ($type === self::NO_LICENSE_KNOWN_DECISION_TYPE) {
         $type = DecisionTypes::IDENTIFIED;
         $clearingEventIds = $this->insertClearingEventsForAgentFindings($itemBounds, $userId, $groupId, true, ClearingEventTypes::USER);
         foreach ($previousEvents as $eventId => $clearingEvent) {
             if (!in_array($eventId, $clearingEventIds) && !$clearingEvent->isRemoved()) {
                 $licenseId = $clearingEvent->getLicenseId();
                 $newEventId = $this->clearingDao->insertClearingEvent($itemBounds->getItemId(), $userId, $groupId, $licenseId, true);
                 $clearingEventIds[$licenseId] = $newEventId;
             }
         }
     } else {
         $clearingEventIds = $this->insertClearingEventsForAgentFindings($itemBounds, $userId, $groupId, false, ClearingEventTypes::AGENT, $previousEvents);
         foreach ($previousEvents as $clearingEvent) {
             $clearingEventIds[$clearingEvent->getLicenseId()] = $clearingEvent->getEventId();
         }
     }
     $currentDecision = $this->clearingDao->getRelevantClearingDecision($itemBounds, $groupId);
     $clearingEventIds = array_unique(array_merge($clearingEventIds, $additionalEventIds));
     $scope = $global ? DecisionScopes::REPO : DecisionScopes::ITEM;
     if (null === $currentDecision || $this->clearingDecisionIsDifferentFrom($currentDecision, $type, $scope, $clearingEventIds)) {
         $this->clearingDao->createDecisionFromEvents($itemBounds->getItemId(), $userId, $groupId, $type, $scope, $clearingEventIds);
     } else {
         $this->clearingDao->removeWipClearingDecision($itemId, $groupId);
     }
     $this->dbManager->commit();
 }
Beispiel #14
0
 /**
  * \brief Display the user record edit form
  * 
  * \param $UserRec - Database users record for the user to be edited.
  * \param $SessionIsAdmin - Boolean: This session is by an admin
  * \return the text of the display form on success, or error on failure.
  */
 private function DisplayForm($UserRec, $SessionIsAdmin)
 {
     $vars = array('isSessionAdmin' => $SessionIsAdmin, 'userId' => $UserRec['user_pk']);
     /* For Admins, get the list of all users 
      * For non-admins, only show themself
      */
     if ($SessionIsAdmin) {
         $stmt = __METHOD__ . '.asSessionAdmin';
         $sql = "SELECT * FROM users ORDER BY user_name";
         $this->dbManager->prepare($stmt, $sql);
         $res = $this->dbManager->execute($stmt);
         $allUsers = array();
         while ($row = $this->dbManager->fetchArray($res)) {
             $allUsers[$row['user_pk']] = htmlentities($row['user_name']);
         }
         $this->dbManager->freeResult($res);
         $vars['allUsers'] = $allUsers;
     }
     $vars['userName'] = $UserRec['user_name'];
     $vars['userDescription'] = $UserRec['user_desc'];
     $vars['userEMail'] = $UserRec["user_email"];
     $vars['eMailNotification'] = $UserRec['email_notify'] == 'y';
     if ($SessionIsAdmin) {
         $vars['allAccessLevels'] = array(PLUGIN_DB_NONE => _("None (very basic, no database access)"), PLUGIN_DB_READ => _("Read-only (read, but no writes or downloads)"), PLUGIN_DB_WRITE => _("Read-Write (read, download, or edit information)"), PLUGIN_DB_ADMIN => _("Full Administrator (all access including adding and deleting users)"));
         $vars['accessLevel'] = $UserRec['user_perm'];
         $SelectedFolderPk = $UserRec['root_folder_fk'];
         $vars['folderListOption'] = FolderListOption($ParentFolder = -1, $Depth = 0, $IncludeTop = 1, $SelectedFolderPk);
     }
     $vars['isBlankPassword'] = $UserRec['_blank_pass'] == 'on';
     $vars['agentSelector'] = AgentCheckBoxMake(-1, array("agent_unpack", "agent_adj2nest", "wget_agent"), $UserRec['user_name']);
     $vars['bucketPool'] = SelectBucketPool($UserRec["default_bucketpool_fk"]);
     return $vars;
 }
Beispiel #15
0
 private function runnerDeciderRealShouldMakeNoDecisionForIrrelevantFiles($runner)
 {
     $this->setUpTables();
     $this->setUpRepo();
     $monkAgentId = 5;
     $licenseRef1 = $this->licenseDao->getLicenseByShortName("GPL-3.0")->getRef();
     $licId1 = $licenseRef1->getId();
     $pfile = 4;
     $jobId = 16;
     $groupId = 2;
     $userId = 2;
     $itemId = 7;
     $itemTreeBounds = new ItemTreeBounds($itemId, 'uploadtree_a', $uploadId = 1, 15, 16);
     $this->dbManager->queryOnce("DELETE FROM license_file");
     /* insert NoLicenseKnown decisions */
     $this->dbManager->queryOnce("INSERT INTO clearing_decision (clearing_decision_pk, uploadtree_fk, pfile_fk, user_fk, group_fk, decision_type, scope, date_added)" . " VALUES (2, {$itemId}, {$pfile}, {$userId}, {$groupId}, " . DecisionTypes::IRRELEVANT . ", " . DecisionScopes::ITEM . ", '2015-05-04 11:43:18.276425+02')");
     $lastDecision = $this->clearingDao->getRelevantClearingDecision($itemTreeBounds, $groupId);
     $lastClearingId = $lastDecision->getClearingId();
     $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12222,{$licId1},{$pfile},{$monkAgentId})");
     $this->dbManager->queryOnce("INSERT INTO jobqueue (jq_pk, jq_job_fk, jq_type, jq_args, jq_starttime, jq_endtime, jq_endtext, jq_end_bits, jq_schedinfo, jq_itemsprocessed, jq_log, jq_runonpfile, jq_host, jq_cmd_args)" . " VALUES ({$jobId}, 2, 'decider', '2', '2015-06-07 09:57:27.718312+00', NULL, '', 0, NULL, 6, NULL, NULL, NULL, '-r8')");
     list($success, $output, $retCode) = $runner->run($uploadId, $userId, $groupId, $jobId, '');
     $this->assertTrue($success, 'cannot run runner');
     $this->assertEquals($retCode, 0, 'decider failed (did you make test?): ' . $output);
     $newDecision = $this->clearingDao->getRelevantClearingDecision($itemTreeBounds, $groupId);
     assertThat($newDecision->getClearingId(), equalTo($lastClearingId));
     $this->rmRepo();
 }
 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 $uploadId
  * @return int
  * @throws \Exception
  */
 public function getStatus($uploadId)
 {
     $row = $this->dbManager->getSingleRow("SELECT status_fk FROM upload_clearing WHERE upload_fk=\$1 AND group_fk=\$2", array($uploadId, $this->groupId));
     if (false === $row) {
         throw new \Exception("cannot find uploadId={$uploadId}");
     }
     return $row['status_fk'];
 }
Beispiel #18
0
 /**
  * @param int $folderId
  * @return Folder|null
  */
 public function getFolder($folderId)
 {
     $folderRow = $this->dbManager->getSingleRow('SELECT * FROM folder WHERE folder_pk = $1', array($folderId));
     if (!$folderRow) {
         return null;
     }
     return new Folder($folderRow['folder_pk'], $folderRow['folder_name'], $folderRow['folder_desc'], $folderRow['folder_perm']);
 }
 protected function setUp()
 {
     $this->dbViewDao = new DbViewProxy($this->dbViewQuery, $this->dbViewName);
     global $container;
     $container = M::mock('ContainerBuilder');
     $this->dbManagerMock = M::mock(DbManager::classname());
     $container->shouldReceive('get')->withArgs(array('db.manager'))->andReturn($this->dbManagerMock);
 }
 protected function setUp()
 {
     global $container;
     $container = M::mock('ContainerBuilder');
     $this->dbManagerMock = M::mock(DbManager::classname());
     $container->shouldReceive('get')->withArgs(array('db.manager'))->andReturn($this->dbManagerMock);
     $this->almostAllColumns = 'rf_pk,rf_shortname,rf_text,rf_url,rf_add_date,rf_copyleft,rf_fullname,rf_notes,marydone,rf_active,rf_text_updatable,rf_md5,rf_detector_type,rf_source';
 }
Beispiel #21
0
 function testInsertTableRowReturning()
 {
     $this->driver->shouldReceive('insertPreparedAndReturn')->withArgs(array(anything(), '/insert into europe \\(animal\\) values \\(\\$1\\)/i', array('mouse'), 'id'))->andReturnUsing(function ($stmt, $sql, $params, $colName) {
         return $colName == 'id' ? 23 : -1;
     });
     $returnId = $this->dbManager->insertInto('europe', 'animal', array('mouse'), $log = 'logging', 'id');
     assertThat($returnId, equalTo(23));
 }
Beispiel #22
0
 protected function setUp()
 {
     $this->folderDao = M::mock(FolderDao::classname());
     $this->dbManager = M::mock(DbManager::classname());
     $this->folderNav = new FolderNav($this->dbManager, $this->folderDao);
     $this->uri = Traceback_uri();
     $this->assertCountBefore = \Hamcrest\MatcherAssert::getCount();
 }
Beispiel #23
0
 public function testGetUploadHashes()
 {
     $this->testDb->createPlainTables(array('pfile'));
     $this->dbManager->queryOnce('ALTER TABLE uploadtree RENAME TO uploadtree_a');
     $this->testDb->insertData(array('uploadtree_a', 'pfile'));
     // (pfile_pk, pfile_md5, pfile_sha1, pfile_size) := (4, '59CACDFCE5051CD8A1D8A1F2DCCE40A5', '04621571BCBABCE75C4DD1C6445B87DEC0995734', 12320);
     $hashes = $this->treeDao->getItemHashes(7, 'uploadtree_a');
     assertThat($hashes, equalTo(array('md5' => '59CACDFCE5051CD8A1D8A1F2DCCE40A5', 'sha1' => '04621571BCBABCE75C4DD1C6445B87DEC0995734')));
 }
 private function getKeyFromShortname($shortname)
 {
     if (array_key_exists($shortname, $this->nkMap)) {
         return $this->nkMap[$shortname];
     }
     $row = $this->dbManager->getSingleRow('SELECT rf_pk FROM license_ref WHERE rf_shortname=$1', array($shortname));
     $this->nkMap[$shortname] = $row === false ? false : $row['rf_pk'];
     return $this->nkMap[$shortname];
 }
Beispiel #25
0
 public function testGetUserName()
 {
     $username = '******';
     $userId = 101;
     $this->testDb->createPlainTables(array('users'));
     $this->dbManager->insertTableRow('users', array('user_pk' => $userId, 'user_name' => $username));
     $uName = $this->userDao->getUserName($userId);
     assertThat($uName, equalTo($username));
 }
Beispiel #26
0
 /** 
  * @brief Return total Job data with time elapsed
  * @param $job_pk
  * @return $row
  */
 public function getDataForASingleJob($job_pk)
 {
     $statementName = __METHOD__ . "getDataForASingleJob";
     $this->dbManager->prepare($statementName, "SELECT *, jq_endtime-jq_starttime as elapsed FROM jobqueue LEFT JOIN job ON job.job_pk = jobqueue.jq_job_fk WHERE jobqueue.jq_pk =\$1");
     $result = $this->dbManager->execute($statementName, array($job_pk));
     $row = $this->dbManager->fetchArray($result);
     $this->dbManager->freeResult($result);
     return $row;
 }
Beispiel #27
0
 /**
  * \brief Generate output.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     $newarray = GetParm("new", PARM_RAW);
     $oldarray = GetParm("old", PARM_RAW);
     /* Compare new and old array
      * and update DB with new values */
     $UpdateMsg = "";
     if (!empty($newarray)) {
         foreach ($newarray as $VarName => $VarValue) {
             if ($VarValue != $oldarray[$VarName]) {
                 /* get validation_function row from sysconfig table */
                 $sys_array = $this->dbManager->getSingleRow("select validation_function, ui_label from sysconfig where variablename=\$1", array($VarName), __METHOD__ . '.getVarNameData');
                 $validation_function = $sys_array['validation_function'];
                 $ui_label = $sys_array['ui_label'];
                 $is_empty = empty($validation_function);
                 /* 1. the validation_function is empty
                     2. the validation_function is not empty, and after checking, the value is valid
                    update sysconfig table
                    */
                 if ($is_empty || !$is_empty && 1 == $validation_function($VarValue)) {
                     $this->dbManager->getSingleRow("update sysconfig set conf_value=\$1 where variablename=\$2", array($VarValue, $VarName), __METHOD__ . '.setVarNameData');
                     if (!empty($UpdateMsg)) {
                         $UpdateMsg .= ", ";
                     }
                     $UpdateMsg .= $VarName;
                 } else {
                     if (!$is_empty && 0 == $validation_function($VarValue)) {
                         if (!strcmp($validation_function, 'check_boolean')) {
                             $warning_msg = _("Error: You set {$ui_label} to {$VarValue}. Valid  values are 'true' and 'false'.");
                             echo "<script>alert('{$warning_msg}');</script>";
                         } else {
                             if (strpos($validation_function, "url")) {
                                 $warning_msg = _("Error: {$ui_label} {$VarValue}, is not a reachable URL.");
                                 echo "<script>alert('{$warning_msg}');</script>";
                             }
                         }
                     }
                 }
             }
         }
         if (!empty($UpdateMsg)) {
             $UpdateMsg .= _(" updated.");
         }
     }
     $OutBuf = '';
     if ($this->OutputType == 'HTML') {
         if ($UpdateMsg) {
             $OutBuf .= "<span style='background-color:#ff8a8a'>{$UpdateMsg}</style><hr>";
         }
         $OutBuf .= $this->HTMLout();
     }
     $this->vars['content'] = $OutBuf;
 }
 protected function setUp()
 {
     $this->uploadTreeId = 432;
     $this->pfileId = 32;
     $this->userId = 12;
     $this->groupId = 5;
     $this->timestamp = time();
     $this->clearingDao = M::mock(ClearingDao::classname());
     $this->agentLicenseEventProcessor = M::mock(AgentLicenseEventProcessor::classname());
     $this->clearingEventProcessor = new ClearingEventProcessor();
     $this->itemTreeBounds = M::mock(ItemTreeBounds::classname());
     $this->itemTreeBounds->shouldReceive("getItemId")->withNoArgs()->andReturn($this->uploadTreeId);
     $this->itemTreeBounds->shouldReceive("getPfileId")->withNoArgs()->andReturn($this->pfileId);
     $this->dbManager = M::mock(DbManager::classname());
     $this->dbManager->shouldReceive('begin')->withNoArgs();
     $this->dbManager->shouldReceive('commit')->withNoArgs();
     $this->clearingDecisionProcessor = new ClearingDecisionProcessor($this->clearingDao, $this->agentLicenseEventProcessor, $this->clearingEventProcessor, $this->dbManager);
     $this->assertCountBefore = \Hamcrest\MatcherAssert::getCount();
 }
 public function testmakeAccessibleToGroup()
 {
     $this->testDb->createPlainTables(array('perm_upload', 'group_user_member'));
     $userId = 501;
     $groupId = 601;
     $groupIdAlternative = 602;
     $this->dbManager->insertTableRow('group_user_member', array('group_fk' => $groupId, 'user_fk' => $userId, 'group_perm' => Auth::PERM_READ));
     $this->dbManager->insertTableRow('group_user_member', array('group_fk' => $groupIdAlternative, 'user_fk' => $userId, 'group_perm' => Auth::PERM_READ));
     $unaccessibleIsAccessible = $this->uploadPermissionDao->isAccessible($uploadId = 1, $groupId);
     assertThat($unaccessibleIsAccessible, equalTo(false));
     $this->uploadPermissionDao->makeAccessibleToGroup($uploadId, $groupId, Auth::PERM_WRITE);
     $accessibleIsAccessible = $this->uploadPermissionDao->isAccessible($uploadId, $groupId);
     assertThat($accessibleIsAccessible, equalTo(true));
     $stillUnaccessibleIsAccessible = $this->uploadPermissionDao->isAccessible($uploadId, $groupIdAlternative);
     assertThat($stillUnaccessibleIsAccessible, equalTo(false));
     $this->uploadPermissionDao->makeAccessibleToAllGroupsOf($uploadId, $userId);
     $nowAccessibleIsAccessible = $this->uploadPermissionDao->isAccessible($uploadId, $groupIdAlternative);
     assertThat($nowAccessibleIsAccessible, equalTo(true));
 }
Beispiel #30
0
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $userId = $_SESSION['UserId'];
     $jqIds = (array) $request->get('jqIds');
     $result = array();
     foreach ($jqIds as $jq_pk) {
         $jobInfo = $this->dbManager->getSingleRow("SELECT jobqueue.jq_end_bits as end_bits FROM jobqueue INNER JOIN job ON jobqueue.jq_job_fk = job.job_pk\n          WHERE jobqueue.jq_pk = \$1 AND job_user_fk = \$2", array($jq_pk, $userId));
         if ($jobInfo !== false) {
             $result[$jq_pk] = array('end_bits' => $jobInfo['end_bits']);
         }
     }
     ReportCachePurgeAll();
     $status = empty($result) ? Response::HTTP_INTERNAL_SERVER_ERROR : Response::HTTP_OK;
     if (empty($result)) {
         $result = array("error" => "no info");
     }
     $response = new Response(json_encode($result), $status, array('content-type' => 'text/json'));
     return $response;
 }