/** * \brief test for Isdir Isartifact Iscontainer */ function test_Is() { print "Starting unit test for common-dir.php\n"; print "test function Isdir()\n"; $mode = 536888320; $result = Isdir($mode); $this->assertEquals(true, $result); $mode = 33188; $result = Isdir($mode); $this->assertEquals(false, $result); print "test function Isartifact()\n"; $mode = 536888320; $result = Isartifact($mode); $this->assertEquals(false, $result); $mode = 805323776; $result = Isartifact($mode); $this->assertEquals(true, $result); print "test function Iscontainer()\n"; $mode = 536888320; $result = Iscontainer($mode); $this->assertEquals(true, $result); $mode = 805323776; $result = Iscontainer($mode); $this->assertEquals(true, $result); print "test function DirMode2String()\n"; $result = DirMode2String($mode); $this->assertEquals("a-d-----S---", $result); //print "Ending unit test for common-dir.php\n"; }
/** * * @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; }
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; }
/** * \brief Given an $Uploadtree_pk, display: \n * (1) The histogram for the directory BY LICENSE. \n * (2) The file listing for the directory. * * \param $Uploadtree_pk * \param $Uri * \param $filter * \param $uploadtree_tablename * \param $Agent_pk - agent id */ function ShowUploadHist($Uploadtree_pk, $Uri, $filter, $uploadtree_tablename, $Agent_pk) { global $PG_CONN; $VF = ""; // return values for file listing $VLic = ""; // return values for license histogram $V = ""; // total return value $upload_pk = ""; $VCopyright = ''; global $Plugins; $ModLicView =& $Plugins[plugin_find_id("copyrightview")]; $rows = $this->GetRows($Uploadtree_pk, $Agent_pk, $upload_pk, 0, $filter); if (!is_array($rows)) { return $rows; } $orderBy = array('count', 'copyright'); static $ordercount = 1; static $ordercopyright = 1; $order = ""; /** sorting by count/copyright statement */ if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) { $order = $_GET['orderBy']; if (isset($_GET['orderc'])) { $ordercount = $_GET['orderc']; } if (isset($_GET['ordercp'])) { $ordercopyright = $_GET['ordercp']; } if ('count' == $order && 1 == $ordercount) { $ordercount = 0; } else { if ('count' == $order && 0 == $ordercount) { $ordercount = 1; } else { if ('copyright' == $order && 1 == $ordercopyright) { $ordercopyright = 0; } else { if ('copyright' == $order && 0 == $ordercopyright) { $ordercopyright = 1; } } } } } /* Write license histogram to $VLic */ $CopyrightCount = 0; $UniqueCopyrightCount = 0; $NoCopyrightFound = 0; $VCopyright = ""; $VCopyright .= "<table border=1 width='100%' id='copyright'>\n"; $text = _("Count"); $text1 = _("Files"); $text2 = _("Copyright Statements"); $text3 = _("Email"); $text4 = _("URL"); $VCopyright .= "<tr><th>"; $VCopyright .= "<a href=?mod=" . "{$this->Name}" . Traceback_parm_keep(array("upload", "item", "filter", "agent")) . "&orderBy=count&orderc={$ordercount}>{$text}</a>"; $VCopyright .= "</th>"; $VCopyright .= "<th width='10%'>{$text1}</th>"; $VCopyright .= "<th>"; $VCopyright .= "<a href=?mod=" . "{$this->Name}" . Traceback_parm_keep(array("upload", "item", "filter", "agent")) . "&orderBy=copyright&ordercp={$ordercopyright}>{$text2}</a>"; $VCopyright .= "</th>"; $VCopyright .= "</th></tr>\n"; $EmailCount = 0; $UniqueEmailCount = 0; $NoEmailFound = 0; $VEmail = "<table border=1 width='100%'id='copyrightemail'>\n"; $VEmail .= "<tr><th width='10%'>{$text}</th>"; $VEmail .= "<th width='10%'>{$text1}</th>"; $VEmail .= "<th>{$text3}</th></tr>\n"; $UrlCount = 0; $UniqueUrlCount = 0; $NoUrlFound = 0; $VUrl = "<table border=1 width='100%' id='copyrighturl'>\n"; $VUrl .= "<tr><th width='10%'>{$text}</th>"; $VUrl .= "<th width='10%'>{$text1}</th>"; $VUrl .= "<th>{$text4}</th></tr>\n"; if (!is_array($rows)) { $VCopyright .= "<tr><td colspan=3>{$rows}</td></tr>"; } else { foreach ($rows as $row) { $hash = $row['hash']; if ($row['type'] == 'statement') { $UniqueCopyrightCount++; $CopyrightCount += $row['copyright_count']; $VCopyright .= "<tr><td align='right'>{$row['copyright_count']}</td>"; $VCopyright .= "<td align='center'><a href='"; $VCopyright .= Traceback_uri(); $URLargs = "?mod=copyrightlist&agent={$Agent_pk}&item={$Uploadtree_pk}&hash=" . $hash . "&type=" . $row['type']; if (!empty($filter)) { $URLargs .= "&filter={$filter}"; } $VCopyright .= $URLargs . "'>Show</a></td>"; $VCopyright .= "<td align='left'>"; /* strip out characters we don't want to see This is a hack until the agent stops writing these chars to the db. */ $S = $row['content']; $S = htmlentities($S); $S = str_replace("Â", "", $S); // comes from utf-8 copyright symbol $VCopyright .= $S; /* Debugging $hex = bin2hex($S); $VCopyright .= "<br>$hex" ; End Debugging */ $VCopyright .= "</td>"; $VCopyright .= "</tr>\n"; } else { if ($row['type'] == 'email') { $UniqueEmailCount++; $EmailCount += $row['copyright_count']; $VEmail .= "<tr><td align='right'>{$row['copyright_count']}</td>"; $VEmail .= "<td align='center'><a href='"; $VEmail .= Traceback_uri(); $VEmail .= "?mod=copyrightlist&agent={$Agent_pk}&item={$Uploadtree_pk}&hash=" . $hash . "&type=" . $row['type'] . "'>Show</a></td>"; $VEmail .= "<td align='left'>"; $VEmail .= htmlentities($row['content']); $VEmail .= "</td>"; $VEmail .= "</tr>\n"; } else { if ($row['type'] == 'url') { $UniqueUrlCount++; $UrlCount += $row['copyright_count']; $VUrl .= "<tr><td align='right'>{$row['copyright_count']}</td>"; $VUrl .= "<td align='center'><a href='"; $VUrl .= Traceback_uri(); $VUrl .= "?mod=copyrightlist&agent={$Agent_pk}&item={$Uploadtree_pk}&hash=" . $hash . "&type=" . $row['type'] . "'>Show</a></td>"; $VUrl .= "<td align='left'>"; $VUrl .= htmlentities($row['content']); $VUrl .= "</td>"; $VUrl .= "</tr>\n"; } } } } } $VCopyright .= "</table>\n"; $VCopyright .= "<p>\n"; $text = _("Unique Copyrights"); $text1 = _("Total Copyrights"); $VCopyright .= "{$text}: {$UniqueCopyrightCount}<br>\n"; $NetCopyright = $CopyrightCount; $VCopyright .= "{$text1}: {$NetCopyright}"; $VEmail .= "</table>\n"; $VEmail .= "<p>\n"; $text = _("Unique Emails"); $text1 = _("Total Emails"); $VEmail .= "{$text}: {$UniqueEmailCount}<br>\n"; $NetEmail = $EmailCount; $VEmail .= "{$text1}: {$NetEmail}"; $VUrl .= "</table>\n"; $VUrl .= "<p>\n"; $text = _("Unique URLs"); $text1 = _("Total URLs"); $VUrl .= "{$text}: {$UniqueUrlCount}<br>\n"; $NetUrl = $UrlCount; $VUrl .= "{$text1}: {$NetUrl}"; /******* File Listing ************/ /* Get ALL the items under this Uploadtree_pk */ $Children = GetNonArtifactChildren($Uploadtree_pk, $uploadtree_tablename); $ChildCount = 0; $ChildLicCount = 0; $ChildDirCount = 0; /* total number of directory or containers */ foreach ($Children as $C) { if (Iscontainer($C['ufile_mode'])) { $ChildDirCount++; } } $VF .= "<table border=0>"; foreach ($Children as $C) { if (empty($C)) { continue; } $IsDir = Isdir($C['ufile_mode']); $IsContainer = Iscontainer($C['ufile_mode']); /* Determine the hyperlink for non-containers to view-license */ if (!empty($C['pfile_fk']) && !empty($ModLicView)) { $LinkUri = Traceback_uri(); $LinkUri .= "?mod=view-license&agent={$Agent_pk}&upload={$upload_pk}&item={$C['uploadtree_pk']}"; } else { $LinkUri = NULL; } /* Determine link for containers */ if (Iscontainer($C['ufile_mode'])) { $uploadtree_pk = DirGetNonArtifact($C['uploadtree_pk'], $uploadtree_tablename); $LicUri = "{$Uri}&item=" . $uploadtree_pk; } else { $LicUri = NULL; } /* Populate the output ($VF) - file list */ /* id of each element is its uploadtree_pk */ $LicCount = 0; $VF .= "<tr><td id='{$C['uploadtree_pk']}' align='left'>"; $HasHref = 0; $HasBold = 0; if ($IsContainer) { $VF .= "<a href='{$LicUri}'>"; $HasHref = 1; $VF .= "<b>"; $HasBold = 1; } else { if (!empty($LinkUri)) { $VF .= "<a href='{$LinkUri}'>"; $HasHref = 1; } } $VF .= $C['ufile_name']; if ($IsDir) { $VF .= "/"; } if ($HasBold) { $VF .= "</b>"; } if ($HasHref) { $VF .= "</a>"; } $VF .= "</td><td>"; if ($LicCount) { $VF .= "[" . number_format($LicCount, 0, "", ",") . " "; $VF .= "license" . ($LicCount == 1 ? "" : "s"); $VF .= "</a>"; $VF .= "]"; $ChildLicCount += $LicCount; } $VF .= "</td>"; $VF .= "</tr>\n"; $ChildCount++; } $VF .= "</table>\n"; /*************************************** Problem: $ChildCount can be zero! This happens if you have a container that does not unpack to a directory. For example: file.gz extracts to archive.txt that contains a license. Same problem seen with .pdf and .Z files. Solution: if $ChildCount == 0, then just view the license! $ChildCount can also be zero if the directory is empty. ***************************************/ if ($ChildCount == 0) { $sql = "SELECT * FROM {$this->uploadtree_tablename} WHERE uploadtree_pk = '{$Uploadtree_pk}';"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); pg_free_result($result); if (IsDir($row['ufile_mode'])) { return; } $ModLicView =& $Plugins[plugin_find_id("copyrightview")]; return $ModLicView->Output(); } /* Combine VF and VLic */ $text = _("Jump to"); $text1 = _("Emails"); $text2 = _("Copyright Statements"); $text3 = _("URLs"); $V .= "<table border=0 width='100%'>\n"; $V .= "<tr><td><a name=\"statements\"></a>{$text}: <a href=\"#emails\">{$text1}</a> | <a href=\"#urls\">{$text3}</a></td><td></td></tr>\n"; $V .= "<tr><td valign='top' width='50%'>{$VCopyright}</td><td valign='top'>{$VF}</td></tr>\n"; $V .= "<tr><td><a name=\"emails\"></a>Jump to: <a href=\"#statements\">{$text2}</a> | <a href=\"#urls\">{$text3}</a></td><td></td></tr>\n"; $V .= "<tr><td valign='top' width='50%'>{$VEmail}</td><td valign='top'></td></tr>\n"; $V .= "<tr><td><a name=\"urls\"></a>Jump To: <a href=\"#statements\">{$text2}</a> | <a href=\"#emails\">{$text1}</a></td><td></td></tr>\n"; $V .= "<tr><td valign='top' width='50%'>{$VUrl}</td><td valign='top'></td></tr>\n"; $V .= "</table>\n"; $V .= "<hr />\n"; return $V; }
/** * \brief Display the delete tag page. */ function ShowDeleteTagPage($Upload, $Item) { global $PG_CONN; $VD = ""; $VD .= _("<h3>Delete Tag:</h3>\n"); /* Get ufile_name from uploadtree_pk */ $sql = "SELECT ufile_name, ufile_mode FROM uploadtree\n WHERE uploadtree_pk = {$Item}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); $ufile_name = $row["ufile_name"]; $ufile_mode = $row["ufile_mode"]; pg_free_result($result); $sql = "SELECT tag_pk, tag, tag_file_pk, tag_file_date, tag_file_text FROM tag, tag_file, uploadtree WHERE tag.tag_pk = tag_file.tag_fk AND tag_file.pfile_fk = uploadtree.pfile_fk AND uploadtree.uploadtree_pk = {$Item};"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) > 0) { $VD .= "<form name='form' method='POST' action='" . Traceback_uri() . "?mod=tag&upload={$Upload}&item={$Item}'>\n"; $VD .= "<select multiple size='10' name='tag_file_pk[]'>\n"; while ($row = pg_fetch_assoc($result)) { $VD .= "<option value='" . $row['tag_file_pk'] . "'>" . "-" . $row['tag'] . "</option>\n"; } $VD .= "</select>\n"; if (Iscontainer($ufile_mode)) { $text = _("Delete Tag only for this file."); $VD .= "<p><input type='checkbox' name='tag_file' value='1' checked/>{$text}</p>"; $text = _("Delete Tag for all packages (source and binary) in this container tree."); $VD .= "<p><input type='checkbox' name='tag_package' value='1'/>{$text}</p>"; //$text = _("Delete Tag for every file in this container tree."); //$VD .= "<p><input type='checkbox' name='tag_container' value='1'/> $text</p>"; } else { $VD .= "<p><input type='hidden' name='tag_file' value='1'/></p>"; } $text = _("Delete"); $VD .= "<input type='hidden' name='action' value='delete'/>\n"; $VD .= "<input type='submit' value='{$text}'>\n"; $VD .= "</form>\n"; } pg_free_result($result); return $VD; }
function OutputOpen() { if ($this->State != PLUGIN_STATE_READY) { return 0; } $uploadId = GetParm("upload", PARM_INTEGER); if (empty($uploadId)) { return; } $uploadTreeId = GetParm("item", PARM_INTEGER); if (empty($uploadTreeId)) { $parent = $this->uploadDao->getUploadParent($uploadId); if (!isset($parent)) { $this->invalidParm = true; return; } $item = $this->uploadDao->getNextItem($uploadId, $parent); if ($item === UploadDao::NOT_FOUND) { $this->invalidParm = true; return; } $uploadTreeId = $item->getId(); return new RedirectResponse(Traceback_uri() . '?mod=' . $this->Name . Traceback_parm_keep(array("upload", "show")) . "&item={$uploadTreeId}"); } $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId); $uploadEntry = $this->uploadDao->getUploadEntry($uploadTreeId, $uploadTreeTableName); if (Isdir($uploadEntry['ufile_mode']) || Iscontainer($uploadEntry['ufile_mode'])) { $parent = $this->uploadDao->getUploadParent($uploadId); if (!isset($parent)) { $this->invalidParm = true; return; } $item = $this->uploadDao->getNextItem($uploadId, $parent); if ($item === UploadDao::NOT_FOUND) { $this->invalidParm = true; return; } $uploadTreeId = $item->getId(); return new RedirectResponse(Traceback_uri() . '?mod=' . $this->Name . Traceback_parm_keep(array("upload", "show")) . "&item={$uploadTreeId}"); } return parent::OutputOpen(); }
/** * \brief Find the non artifact children of an uploadtree pk. * If any children are artifacts, resolve them until you get * to a non-artifact. * * \param $uploadtree_pk * \param $uploadtree_tablename * * \return list of child uploadtree recs + pfile_size + pfile_mimetypefk on success. * list may be empty if there are no children. * Child list is sorted by ufile_name. */ function GetNonArtifactChildren($uploadtree_pk, $uploadtree_tablename = 'uploadtree') { global $container; /** @var DbManager */ $dbManager = $container->get('db.manager'); /* Find all the children */ $sql = "select {$uploadtree_tablename}.*, pfile_size, pfile_mimetypefk from {$uploadtree_tablename}\n left outer join pfile on (pfile_pk=pfile_fk)\n where parent=\$1 ORDER BY lft"; $dbManager->prepare($stmt = __METHOD__ . "{$uploadtree_tablename}", $sql); $result = $dbManager->execute($stmt, array($uploadtree_pk)); $children = $dbManager->fetchAll($result); $dbManager->freeResult($result); if (count($children) == 0) { return $children; } /* Loop through each child and replace any artifacts with their non artifact child. Or skip them if they are not containers. */ $foundChildren = array(); foreach ($children as $key => $child) { if (Isartifact($child['ufile_mode'])) { if (Iscontainer($child['ufile_mode'])) { unset($children[$key]); $NonAChildren = GetNonArtifactChildren($child['uploadtree_pk'], $uploadtree_tablename); if ($NonAChildren) { $foundChildren = array_merge($foundChildren, $NonAChildren); } } else { unset($children[$key]); } } else { $foundChildren[$key] = $child; } } // uasort($foundChildren, '_DirCmp'); return $foundChildren; }
/** * @param $Uploadtree_pk * @param $Uri * @param $uploadtree_tablename * @param $Agent_pk * @param $upload_pk * @return array */ protected function getFileListing($Uploadtree_pk, $Uri, $uploadtree_tablename, $Agent_pk, $upload_pk) { $VF = ""; // return values for file listing /******* File Listing ************/ /* Get ALL the items under this Uploadtree_pk */ $Children = GetNonArtifactChildren($Uploadtree_pk, $uploadtree_tablename); $ChildCount = 0; $ChildLicCount = 0; $ChildDirCount = 0; /* total number of directory or containers */ foreach ($Children as $c) { if (Iscontainer($c['ufile_mode'])) { $ChildDirCount++; } } $VF .= "<table border=0>"; foreach ($Children as $child) { if (empty($child)) { continue; } $ChildCount++; global $Plugins; $ModLicView =& $Plugins[plugin_find_id($this->viewName)]; /* Determine the hyperlink for non-containers to view-license */ if (!empty($child['pfile_fk']) && !empty($ModLicView)) { $LinkUri = Traceback_uri(); $LinkUri .= "?mod=" . $this->viewName . "&agent={$Agent_pk}&upload={$upload_pk}&item={$child['uploadtree_pk']}"; } else { $LinkUri = NULL; } /* Determine link for containers */ if (Iscontainer($child['ufile_mode'])) { $uploadtree_pk = DirGetNonArtifact($child['uploadtree_pk'], $uploadtree_tablename); $LicUri = "{$Uri}&item=" . $uploadtree_pk; } else { $LicUri = NULL; } /* Populate the output ($VF) - file list */ /* id of each element is its uploadtree_pk */ $LicCount = 0; $cellContent = Isdir($child['ufile_mode']) ? $child['ufile_name'] . '/' : $child['ufile_name']; if (Iscontainer($child['ufile_mode'])) { $cellContent = "<a href='{$LicUri}'><b>{$cellContent}</b></a>"; } else { if (!empty($LinkUri)) { $cellContent = "<a href='{$LinkUri}'>{$cellContent}</a>"; } } $VF .= "<tr><td id='{$child['uploadtree_pk']}' align='left'>{$cellContent}</td><td>"; if ($LicCount) { $VF .= "[" . number_format($LicCount, 0, "", ",") . " "; $VF .= "license" . ($LicCount == 1 ? "" : "s"); $VF .= "</a>"; $VF .= "]"; $ChildLicCount += $LicCount; } $VF .= "</td></tr>\n"; } $VF .= "</table>\n"; return array($ChildCount, $VF); }
/** * @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'); }
/** * \brief This function returns the output html */ function Output() { global $PG_CONN; global $Plugins; if ($this->State != PLUGIN_STATE_READY) { return 0; } $V = ""; $folder_pk = GetParm("folder", PARM_INTEGER); $Upload = GetParm("upload", PARM_INTEGER); // upload_pk to browse $Item = GetParm("item", PARM_INTEGER); // uploadtree_pk to browse /* check permission if $Upload is given */ if (!empty($Upload)) { $UploadPerm = GetUploadPerm($Upload); if ($UploadPerm < PERM_READ) { $text = _("Permission Denied"); echo "<h2>{$text}<h2>"; return; } } /* kludge for plugins not supplying a folder parameter. * Find what folder this upload is in. Error if in multiple folders. */ if (empty($folder_pk)) { if (empty($Upload)) { $folder_pk = GetUserRootFolder(); } else { /* Make sure the upload record exists */ $sql = "select upload_pk from upload where upload_pk={$Upload}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { echo "This upload no longer exists on this system."; return; } $sql = "select parent_fk from foldercontents where child_id={$Upload} and foldercontents_mode=2"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) > 1) { Fatal("Upload {$Upload} found in multiple folders.", __FILE__, __LINE__); } if (pg_num_rows($result) < 1) { Fatal("Upload {$Upload} missing from foldercontents.", __FILE__, __LINE__); } $row = pg_fetch_assoc($result); $folder_pk = $row['parent_fk']; pg_free_result($result); } } $Folder = $folder_pk; $Show = 'detail'; // always use detail switch ($this->OutputType) { case "XML": break; case "HTML": /************************/ /* Show the folder path */ /************************/ $uploadtree_tablename = ""; if (!empty($Item)) { /* Make sure the item is not a file */ $sql = "SELECT ufile_mode, upload_fk FROM uploadtree WHERE uploadtree_pk = '{$Item}';"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); pg_free_result($result); $Upload = $row['upload_fk']; $UploadPerm = GetUploadPerm($Upload); if ($UploadPerm < PERM_READ) { $text = _("Permission Denied"); echo "<h2>{$text}<h2>"; return; } if (!Iscontainer($row['ufile_mode'])) { /* Not a container! */ $View =& $Plugins[plugin_find_id("view")]; if (!empty($View)) { return $View->ShowView(NULL, "browse"); } } $V .= "<font class='text'>\n"; $uploadtree_tablename = GetUploadtreeTableName($row['upload_fk']); $V .= Dir2Browse($this->Name, $Item, NULL, 1, "Browse", -1, '', '', $uploadtree_tablename) . "\n"; } else { if (!empty($Upload)) { $V .= "<font class='text'>\n"; $uploadtree_tablename = GetUploadtreeTableName($Upload); $V .= Dir2BrowseUpload($this->Name, $Upload, NULL, 1, "Browse", $uploadtree_tablename) . "\n"; } else { $V .= "<font class='text'>\n"; } } /******************************/ /* Get the folder description */ /******************************/ if (!empty($Upload)) { if (empty($Item)) { $sql = "select uploadtree_pk from uploadtree\n where parent is NULL and upload_fk={$Upload} "; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result)) { $row = pg_fetch_assoc($result); $Item = $row['uploadtree_pk']; } else { $text = _("Missing upload tree parent for upload"); $V .= "<hr><h2>{$text} {$Upload}</h2><hr>"; break; } pg_free_result($result); } $V .= $this->ShowItem($Upload, $Item, $Show, $Folder, $uploadtree_tablename); } else { $V .= $this->ShowFolder($Folder, $Show); } $V .= "</font>\n"; break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print "{$V}"; return; }
/** * \brief generate the link for one side of a diff element. * * \param $MasterRow - Master row * \param $side * \param $agent_pk - agent id * \param $filter - filter * \param $plugin * \param $ModLicView * \param $uploadtree_pk1 - uploadtree pk1 * \param $uploadtree_pk2 - uploadtree pk2 * * \return the link for one side of a diff element */ function GetDiffLink($MasterRow, $side, $agent_pk, $filter, $plugin, $ModLicView, $uploadtree_pk1, $uploadtree_pk2) { /* calculate opposite side number */ if ($side == 1) { $OppositeSide = 2; $OppositeItem = $uploadtree_pk2; } else { $OppositeSide = 1; $OppositeItem = $uploadtree_pk1; } $OppositeChild = $MasterRow[$OppositeSide]; $Child = $MasterRow[$side]; /* if the opposite column element is empty, then use the original uploadtree_pk */ if (empty($OppositeChild)) { $OppositeParm = "&item{$OppositeSide}={$OppositeItem}"; } else { $OppositeParm = "&item{$OppositeSide}={$OppositeChild['uploadtree_pk']}"; } $IsDir = Isdir($Child['ufile_mode']); $IsContainer = Iscontainer($Child['ufile_mode']); /* Determine the hyperlink for non-containers to view-license */ if (!empty($Child['pfile_fk']) && !empty($ModLicView)) { $LinkUri = Traceback_uri(); $LinkUri .= "?mod=view-license&napk={$agent_pk}&upload={$Child['upload_fk']}&item={$Child['uploadtree_pk']}"; } else { $LinkUri = NULL; } /* Determine link for containers */ if (Iscontainer($Child['ufile_mode'])) { $Container_uploadtree_pk = $Child['uploadtree_pk']; $LicUri = "?mod={$plugin->Name}&item{$side}={$Child['uploadtree_pk']}{$OppositeParm}&col={$side}"; if (!empty($filter)) { $LicUri .= "&filter={$filter}"; } } else { $LicUri = NULL; } $HasHref = 0; $HasBold = 0; $Flink = ""; if ($IsContainer) { $Flink = "<a href='{$LicUri}'>"; $HasHref = 1; $Flink .= "<b>"; $HasBold = 1; } else { if (!empty($LinkUri)) { $Flink .= "<a href='{$LinkUri}'>"; $HasHref = 1; } } $Flink .= $Child['ufile_name']; if ($IsDir) { $Flink .= "/"; } if ($HasBold) { $Flink .= "</b>"; } if ($HasHref) { $Flink .= "</a>"; } return $Flink; }
/** * @param array $child * @param int $uploadId * @param int $selectedAgentId * @param array $pfileLicenses * @param int $groupId * @param string $uri * @param array $UniqueTagArray * @param boolean $isFlat * @param int[] $latestSuccessfulAgentIds * @return array */ private function createFileDataRow($child, $uploadId, $selectedAgentId, $pfileLicenses, $groupId, $uri, &$UniqueTagArray, $isFlat, $latestSuccessfulAgentIds) { $fileId = $child['pfile_fk']; $childUploadTreeId = $child['uploadtree_pk']; $linkUri = ''; if (!empty($fileId)) { $linkUri = Traceback_uri(); $linkUri .= "?mod=view-license&upload={$uploadId}&item={$childUploadTreeId}"; if ($selectedAgentId) { $linkUri .= "&agentId={$selectedAgentId}"; } } /* Determine link for containers */ $isContainer = Iscontainer($child['ufile_mode']); if ($isContainer && !$isFlat) { $uploadtree_pk = $child['uploadtree_pk']; $linkUri = "{$uri}&item=" . $uploadtree_pk; if ($selectedAgentId) { $linkUri .= "&agentId={$selectedAgentId}"; } } else { if ($isContainer) { $uploadtree_pk = Isartifact($child['ufile_mode']) ? DirGetNonArtifact($childUploadTreeId, $this->uploadtree_tablename) : $childUploadTreeId; $linkUri = "{$uri}&item=" . $uploadtree_pk; if ($selectedAgentId) { $linkUri .= "&agentId={$selectedAgentId}"; } } } /* Populate the output ($VF) - file list */ /* id of each element is its uploadtree_pk */ $fileName = $child['ufile_name']; if ($isContainer) { $fileName = "<a href='{$linkUri}'><span style='color: darkblue'> <b>{$fileName}</b> </span></a>"; } else { if (!empty($linkUri)) { $fileName = "<a href='{$linkUri}'>{$fileName}</a>"; } } /* show licenses under file name */ $childItemTreeBounds = new ItemTreeBounds($childUploadTreeId, $this->uploadtree_tablename, $child['upload_fk'], $child['lft'], $child['rgt']); $licenseEntries = array(); if ($isContainer) { $agentFilter = $selectedAgentId ? array($selectedAgentId) : $latestSuccessfulAgentIds; $licenseEntries = $this->licenseDao->getLicenseShortnamesContained($childItemTreeBounds, $agentFilter, array()); } else { if (array_key_exists($fileId, $pfileLicenses)) { foreach ($pfileLicenses[$fileId] as $shortName => $rfInfo) { $agentEntries = array(); foreach ($rfInfo as $agent => $match) { $agentName = $this->agentNames[$agent]; $agentEntry = "<a href='?mod=view-license&upload={$child['upload_fk']}&item={$childUploadTreeId}&format=text&agentId={$match['agent_id']}&licenseId={$match['license_id']}#highlight'>" . $agentName . "</a>"; if ($match['match_percentage'] > 0) { $agentEntry .= ": {$match['match_percentage']}%"; } $agentEntries[] = $agentEntry; } $licenseEntries[] = $shortName . " [" . implode("][", $agentEntries) . "]"; } } } $licenseList = implode(', ', $licenseEntries); $fileListLinks = FileListLinks($uploadId, $childUploadTreeId, 0, $fileId, true, $UniqueTagArray, $this->uploadtree_tablename, !$isFlat); if (!$isContainer) { $text = _("Copyright/Email/Url"); $fileListLinks .= "[<a href='" . Traceback_uri() . "?mod=copyright-view&upload={$uploadId}&item={$childUploadTreeId}' >{$text}</a>]"; $text = _("ReadMe_OSS"); $fileListLinks .= "[<a href='" . Traceback_uri() . "?mod=ui_readmeoss&upload={$uploadId}&item={$childUploadTreeId}' >{$text}</a>]"; $text = _("SPDX"); $fileListLinks .= "[<a href='" . Traceback_uri() . "?mod=ui_spdx2&upload={$uploadId}&item={$childUploadTreeId}' >{$text}</a>]"; } return array($fileName, $licenseList, $fileListLinks); }
/** * @return bool */ public function isContainer() { return Iscontainer($this->fileMode); }
/** * @param array $row fetched row * @param Request $request * @param $uri * @param $menuPfile * @param $menuPfileNoCompare * @param array $statusTypesAvailable * @param array $users * @param string (unique) * @return array */ private function showRow($row, Request $request, $uri, $menuPfile, $menuPfileNoCompare, $statusTypesAvailable, $users, $rowCounter) { $show = $request->get('show'); $folder = $request->get('folder'); $uploadId = intval($row['upload_pk']); $description = htmlentities($row['upload_desc']); $fileName = $row['ufile_name']; if (empty($fileName)) { $fileName = $row['upload_filename']; } $itemId = Isartifact($row['ufile_mode']) ? DirGetNonArtifact($row['uploadtree_pk']) : $row['uploadtree_pk']; $nameColumn = "<b>{$fileName}</b>"; if (IsContainer($row['ufile_mode'])) { $nameColumn = "<a href='{$uri}&upload={$uploadId}&folder={$folder}&item={$itemId}&show={$show}'>{$nameColumn}</a>"; } $nameColumn .= "<br>"; if (!empty($description)) { $nameColumn .= "<i>{$description}</i><br>"; } $Parm = "upload={$uploadId}&show={$show}&item=" . $row['uploadtree_pk']; if (Iscontainer($row['ufile_mode'])) { $nameColumn .= MenuRenderer::menuToActiveSelect($menuPfile, $Parm, $uploadId); } else { $nameColumn .= MenuRenderer::menuToActiveSelect($menuPfileNoCompare, $Parm, $uploadId); } $modsUploadMulti = MenuHook::getAgentPluginNames('UploadMulti'); if (!empty($modsUploadMulti)) { $nameColumn = '<input type="checkbox" name="uploads[]" class="browse-upload-checkbox" value="' . $uploadId . '"/>' . $nameColumn; } $dateCol = substr($row['upload_ts'], 0, 19); $pairIdPrio = array($uploadId, floatval($row[UploadBrowseProxy::PRIO_COLUMN])); if (!$this->userPerm && 4 == $row['status_fk']) { $currentStatus = $this->statusTypes[4]; } else { $statusAction = " onchange =\"changeTableEntry(this, {$uploadId},'status_fk' )\" "; $currentStatus = $this->createSelect("Status" . $this->userPerm . "Of_{$rowCounter}", $statusTypesAvailable, $row['status_fk'], $statusAction); } if ($this->userPerm) { $action = " onchange =\"changeTableEntry(this, {$uploadId}, 'assignee')\""; $currentAssignee = $this->createSelectUsers("AssignedTo_{$rowCounter}", $users, $row['assignee'], $action); } else { $currentAssignee = array_key_exists($row['assignee'], $users) ? $users[$row['assignee']] : _('Unassigned'); } $rejectableUploadId = $this->userPerm || $row['status_fk'] < 4 ? $uploadId : 0; $tripleComment = array($rejectableUploadId, $row['status_fk'], htmlspecialchars($row['status_comment'])); $sql = "SELECT rf_pk, rf_shortname FROM upload_clearing_license ucl, license_ref" . " WHERE ucl.group_fk=\$1 AND upload_fk=\$2 AND ucl.rf_fk=rf_pk"; $stmt = __METHOD__ . '.collectMainLicenses'; $this->dbManager->prepare($stmt, $sql); $res = $this->dbManager->execute($stmt, array(Auth::getGroupId(), $uploadId)); $mainLicenses = array(); while ($lic = $this->dbManager->fetchArray($res)) { $mainLicenses[] = '<a onclick="javascript:window.open(\'' . Traceback_uri() . "?mod=popup-license&rf={$lic['rf_pk']}','License text','width=600,height=400,toolbar=no,scrollbars=yes,resizable=yes');" . '" href="javascript:;">' . $lic['rf_shortname'] . '</a>' . "<img onclick=\"removeMainLicense({$uploadId},{$lic['rf_pk']});\" class=\"delete\" src=\"images/space_16.png\" alt=\"\"/></img>"; } $this->dbManager->freeResult($res); $output = array($nameColumn, $currentStatus, $tripleComment, implode(', ', $mainLicenses), $currentAssignee, $dateCol, $pairIdPrio); return $output; }
/** * @param array $child * @param int $uploadId * @param int $selectedAgentId * @param array $pfileLicenses * @param int $groupId * @param ClearingDecision[][] $editedMappedLicenses * @param string $uri * @param null|ClearingView $ModLicView * @param array $UniqueTagArray * @param boolean $isFlat * @param int[] $latestSuccessfulAgentIds * @return array */ private function createFileDataRow($child, $uploadId, $selectedAgentId, $pfileLicenses, $groupId, $editedMappedLicenses, $uri, $ModLicView, &$UniqueTagArray, $isFlat, $latestSuccessfulAgentIds) { $fileId = $child['pfile_fk']; $childUploadTreeId = $child['uploadtree_pk']; $linkUri = ''; if (!empty($fileId) && !empty($ModLicView)) { $linkUri = Traceback_uri(); $linkUri .= "?mod=view-license&upload={$uploadId}&item={$childUploadTreeId}"; if ($selectedAgentId) { $linkUri .= "&agentId={$selectedAgentId}"; } } /* Determine link for containers */ $isContainer = Iscontainer($child['ufile_mode']); if ($isContainer && !$isFlat) { $fatChild = $this->uploadDao->getFatItemArray($child['uploadtree_pk'], $uploadId, $this->uploadtree_tablename); $uploadtree_pk = $fatChild['item_id']; $linkUri = "{$uri}&item=" . $uploadtree_pk; if ($selectedAgentId) { $linkUri .= "&agentId={$selectedAgentId}"; } $child['ufile_name'] = $fatChild['ufile_name']; if (!Iscontainer($fatChild['ufile_mode'])) { $isContainer = false; } } else { if ($isContainer) { $uploadtree_pk = Isartifact($child['ufile_mode']) ? DirGetNonArtifact($childUploadTreeId, $this->uploadtree_tablename) : $childUploadTreeId; $linkUri = "{$uri}&item=" . $uploadtree_pk; if ($selectedAgentId) { $linkUri .= "&agentId={$selectedAgentId}"; } } } /* Populate the output ($VF) - file list */ /* id of each element is its uploadtree_pk */ $fileName = $child['ufile_name']; if ($isContainer) { $fileName = "<a href='{$linkUri}'><span style='color: darkblue'> <b>{$fileName}</b> </span></a>"; } else { if (!empty($linkUri)) { $fileName = "<a href='{$linkUri}'>{$fileName}</a>"; } } /* show licenses under file name */ $childItemTreeBounds = new ItemTreeBounds($childUploadTreeId, $this->uploadtree_tablename, $child['upload_fk'], $child['lft'], $child['rgt']); if ($isContainer) { $agentFilter = $selectedAgentId ? array($selectedAgentId) : $latestSuccessfulAgentIds; $licenseEntries = $this->licenseDao->getLicenseShortnamesContained($childItemTreeBounds, $agentFilter, array()); $editedLicenses = $this->clearingDao->getClearedLicenses($childItemTreeBounds, $groupId); } else { $licenseEntries = array(); if (array_key_exists($fileId, $pfileLicenses)) { foreach ($pfileLicenses[$fileId] as $shortName => $rfInfo) { $agentEntries = array(); foreach ($rfInfo as $agent => $match) { $agentName = $this->agentNames[$agent]; $agentEntry = "<a href='?mod=view-license&upload={$child['upload_fk']}&item={$childUploadTreeId}&format=text&agentId={$match['agent_id']}&licenseId={$match['license_id']}#highlight'>" . $agentName . "</a>"; if ($match['match_percentage'] > 0) { $agentEntry .= ": {$match['match_percentage']}%"; } $agentEntries[] = $agentEntry; } $licenseEntries[] = $shortName . " [" . implode("][", $agentEntries) . "]"; } } /* @var $decision ClearingDecision */ if (false !== ($decision = $this->clearingFilter->getDecisionOf($editedMappedLicenses, $childUploadTreeId, $fileId))) { $editedLicenses = $decision->getPositiveLicenses(); } else { $editedLicenses = array(); } } $concludedLicenses = array(); /** @var LicenseRef $licenseRef */ foreach ($editedLicenses as $licenseRef) { $projectedId = $this->licenseProjector->getProjectedId($licenseRef->getId()); $projectedName = $this->licenseProjector->getProjectedShortname($licenseRef->getId(), $licenseRef->getShortName()); $concludedLicenses[$projectedId] = $projectedName; } $editedLicenseList = implode(', ', $concludedLicenses); $licenseList = implode(', ', $licenseEntries); $fileListLinks = FileListLinks($uploadId, $childUploadTreeId, 0, $fileId, true, $UniqueTagArray, $this->uploadtree_tablename, !$isFlat); $getTextEditUser = _("Edit"); $fileListLinks .= "[<a href='#' onclick='openUserModal({$childUploadTreeId})' >{$getTextEditUser}</a>]"; if ($isContainer) { $getTextEditBulk = _("Bulk"); $fileListLinks .= "[<a href='#' onclick='openBulkModal({$childUploadTreeId})' >{$getTextEditBulk}</a>]"; } $filesThatShouldStillBeCleared = array_key_exists($childItemTreeBounds->getItemId(), $this->filesThatShouldStillBeCleared) ? $this->filesThatShouldStillBeCleared[$childItemTreeBounds->getItemId()] : 0; $filesToBeCleared = array_key_exists($childItemTreeBounds->getItemId(), $this->filesToBeCleared) ? $this->filesToBeCleared[$childItemTreeBounds->getItemId()] : 0; $filesCleared = $filesToBeCleared - $filesThatShouldStillBeCleared; $img = $filesCleared == $filesToBeCleared ? 'green' : 'red'; return array($fileName, $licenseList, $editedLicenseList, $img, "{$filesCleared}/{$filesToBeCleared}", $fileListLinks); }
/** * \brief get a a path to a file * * \param $File1uploadtree_pk - pk of file1 * \param $FolderList - folder path for the file (or folder). * \param $DirectoryList - directory path to the file. May be empty. \n * * \example * $FolderList array example: \n * [0] => Array \n * [folder_pk] => 1 \n * [folder_name] => Software Repository \n * [1] => Array \n * [folder_pk] => 5 \n * [folder_name] => cpio \n * \n * $DirectoryList array example: \n * [0] => Array \n * [uploadtree_pk] => 897121 \n * [parent] => \n * [upload_fk] => 11 \n * [pfile_fk] => 691036 \n * [ufile_mode] => 536904704 \n * [lft] => 1 \n * [rgt] => 1048 \n * [ufile_name] => cpio-2.10-9.el6.src.rpm \n * * \return string which is a linked path to a file. * The path includes folders and files. * This is the stuff in the yellow box */ function HTMLPath($File1uploadtree_pk, $FolderList, $DirectoryList) { if (empty($FolderList)) { return "__FILE__ __LINE__ No folder list specified"; } $OutBuf = ""; $Uri2 = Traceback_uri() . "?mod={$this->Name}"; /* Box decorations */ $OutBuf .= "<div style='border: thin dotted gray; background-color:lightyellow'>\n"; /* write the FolderList */ $text = _("Folder"); $OutBuf .= "<b>{$text}</b>: "; foreach ($FolderList as $Folder) { $folder_pk = $Folder['folder_pk']; $folder_name = htmlentities($Folder['folder_name']); $OutBuf .= "<a href='{$Uri2}&folder={$folder_pk}&item={$File1uploadtree_pk}'><b>{$folder_name}</b></a>/"; } /* write the DirectoryList */ if (!empty($DirectoryList)) { $OutBuf .= "<br>"; $First = true; /* If $First is true, directory path starts a new line */ /* Show the path within the upload */ foreach ($DirectoryList as $uploadtree_rec) { if (!$First) { $OutBuf .= "/ "; } $href = "{$Uri2}&bitem={$uploadtree_rec['uploadtree_pk']}&item={$File1uploadtree_pk}"; $OutBuf .= "<a href='{$href}'>"; if (!$First && Iscontainer($uploadtree_rec['ufile_mode'])) { $OutBuf .= "<br> "; } $OutBuf .= "<b>" . $uploadtree_rec['ufile_name'] . "</b>"; $OutBuf .= "</a>"; $First = false; } } $OutBuf .= "</div>\n"; // box return $OutBuf; }
/** * \brief Given an $Uploadtree_pk, display: * - The histogram for the directory BY LICENSE. * - The file listing for the directory. */ function ShowUploadHist($Uploadtree_pk, $Uri, $tag_pk) { global $PG_CONN; $VF = ""; // return values for file listing $VLic = ""; // return values for license histogram $V = ""; // total return value $UniqueTagArray = array(); global $Plugins; $ModLicView =& $Plugins[plugin_find_id("view-license")]; /******* Get license names and counts ******/ /* Find lft and rgt bounds for this $Uploadtree_pk */ $sql = "SELECT lft,rgt,upload_fk FROM {$this->uploadtree_tablename}\n WHERE uploadtree_pk = {$Uploadtree_pk}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); $lft = $row["lft"]; $rgt = $row["rgt"]; $upload_pk = $row["upload_fk"]; pg_free_result($result); if (empty($lft)) { $text = _("Job unpack/adj2nest hasn't completed."); $VLic = "<b>{$text}</b><p>"; return $VLic; } /* Find total number of files for this $Uploadtree_pk * Exclude artifacts and directories. */ $sql = "SELECT count(*) as count FROM {$this->uploadtree_tablename}\n WHERE upload_fk = {$upload_pk} \n and {$this->uploadtree_tablename}.lft BETWEEN {$lft} and {$rgt}\n and ((ufile_mode & (1<<28))=0) \n and ((ufile_mode & (1<<29))=0) and pfile_fk!=0"; //$uTime = microtime(true); $result = pg_query($PG_CONN, $sql); //printf( "<small>count files Elapsed time: %.2f seconds</small>", microtime(true) - $uTime); // convert usecs to secs DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); $FileCount = $row["count"]; pg_free_result($result); /* Get the counts for each license under this UploadtreePk*/ if (empty($tag_pk)) { $TagTable = ""; $TagClause = ""; } else { $TagTable = " right join tag_file on tag_file.pfile_fk=license_file_ref.pfile_fk "; $TagClause = " and tag_fk={$tag_pk}"; } /** advanced interface allowing user to select dataset (agent version) */ $Agent_name = 'nomos'; $dataset = "nomos_dataset"; $Agent_pk = GetParm("agent", PARM_STRING); /** if do not specify agent, get the latest agent result for this upload */ if (empty($Agent_pk)) { $Agent_pk = LatestAgentpk($upload_pk, "nomos_ars"); } if ($Agent_pk == 0) { $text = _("No data available. Use Jobs > Agents to schedule a license scan."); $VLic = "<b>{$text}</b><p>"; return $VLic; } /** get nomos select dataset */ $AgentSelect = AgentSelect($Agent_name, $upload_pk, true, $dataset, $dataset, $Agent_pk, "onchange=\"addArsGo('newds', 'nomos_dataset');\""); /** change the nomos license result when selecting one version of nomos */ if (!empty($AgentSelect)) { $action = Traceback_uri() . "?mod=nomoslicense&upload={$upload_pk}&item={$Uploadtree_pk}"; $VLic .= "<script type='text/javascript'>\n function addArsGo(formid, selectid)\n {\n var selectobj = document.getElementById(selectid);\n var Agent_pk = selectobj.options[selectobj.selectedIndex].value;\n document.getElementById(formid).action='{$action}'+'&agent='+Agent_pk;\n document.getElementById(formid).submit();\n return;\n }\n </script>"; /* form to select new dataset, show dataset */ $VLic .= "<form action='{$action}' id='newds' method='POST'>\n"; $VLic .= $AgentSelect; $VLic .= "</form>"; } $orderBy = array('count', 'license_name'); $ordersql = "liccount desc"; static $ordercount = 1; static $orderlic = 1; /** sorting by count/licnese name */ if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) { $order = $_GET['orderBy']; if (isset($_GET['orderc'])) { $ordercount = $_GET['orderc']; } if (isset($_GET['orderl'])) { $orderlic = $_GET['orderl']; } if ('count' == $order && 1 == $ordercount) { $ordersql = "liccount desc"; $ordercount = 0; } else { if ('count' == $order && 0 == $ordercount) { $ordersql = "liccount "; $ordercount = 1; } else { if ('license_name' == $order && 1 == $orderlic) { $ordersql = "rf_shortname "; $orderlic = 0; } else { if ('license_name' == $order && 0 == $orderlic) { $ordersql = "rf_shortname desc"; $orderlic = 1; } } } } } // Void ARE EXCLUDED FROM LICENSE COUNT $sql = "SELECT distinct(SS.rf_shortname) as licname, count(SS.rf_shortname) as liccount, SS.rf_shortname from \n (SELECT distinct(license_file_ref.pfile_fk), rf_shortname\n from license_file_ref {$TagTable}\n right join {$this->uploadtree_tablename} on license_file_ref.pfile_fk={$this->uploadtree_tablename}.pfile_fk \n where rf_shortname <> 'Void' and upload_fk='{$upload_pk}' and {$this->uploadtree_tablename}.lft BETWEEN {$lft} and {$rgt} \n and agent_fk={$Agent_pk} {$TagClause} group by license_file_ref.pfile_fk, rf_shortname\n ) as SS\n group by rf_shortname order by {$ordersql}"; //$uTime = microtime(true); $result = pg_query($PG_CONN, $sql); //$Time = microtime(true) - $uTime; // convert usecs to secs //$text = _("histogram Elapsed time: %.2f seconds"); //printf( "<small>$text</small>", $Time); DBCheckResult($result, $sql, __FILE__, __LINE__); /* Write license histogram to $VLic */ $LicCount = 0; $UniqueLicCount = 0; $NoLicFound = 0; $VLic .= "<table border=1 width='100%' id='lichistogram'>\n"; $text = _("Count"); $VLic .= "<tr><th>"; $VLic .= "<a href=?mod=" . "{$this->Name}" . Traceback_parm_keep(array("upload", "item", "tag", "agent")) . "&orderBy=count&orderc={$ordercount}>{$text}</a>"; $VLic .= "</th>"; $text = _("Files"); $VLic .= "<th width='10%'>{$text}</th>"; $text = _("License Name"); $VLic .= "<th>"; $VLic .= "<a href=?mod=" . "{$this->Name}" . Traceback_parm_keep(array("upload", "item", "tag", "agent")) . "&orderBy=license_name&orderl={$orderlic}>{$text}</a>"; $VLic .= "</th></tr>\n"; while ($row = pg_fetch_assoc($result)) { $UniqueLicCount++; $LicCount += $row['liccount']; /* Count */ $VLic .= "<tr><td align='right'>{$row['liccount']}</td>"; /* Show */ $VLic .= "<td align='center'><a href='"; $VLic .= Traceback_uri(); $text = _("Show"); $tagClause = $tag_pk ? "&tag={$tag_pk}" : ""; $VLic .= "?mod=list_lic_files&napk={$Agent_pk}&item={$Uploadtree_pk}&lic=" . urlencode($row['rf_shortname']) . $tagClause . "'>{$text}</a></td>"; /* License name */ $VLic .= "<td align='left'>"; $rf_shortname = rawurlencode($row['rf_shortname']); $VLic .= "<a id='{$rf_shortname}' onclick='FileColor_Get(\"" . Traceback_uri() . "?mod=ajax_filelic&napk={$Agent_pk}&item={$Uploadtree_pk}&lic={$rf_shortname}&ut={$this->uploadtree_tablename}\")'"; $VLic .= ">{$row['licname']} </a>"; $VLic .= "</td>"; $VLic .= "</tr>\n"; if ($row['licname'] == "No_license_found") { $NoLicFound = $row['liccount']; } } $VLic .= "</table>\n"; $VLic .= "<p>\n"; $VLic .= _("Hint: Click on the license name to "); $text = _("highlight"); $VLic .= "<span style='background-color:{$this->HighlightColor}'>{$text} </span>"; $VLic .= _("where the license is found in the file listing.<br>\n"); $VLic .= "<table border=0 id='licsummary'>"; $text = _("Unique licenses"); $VLic .= "<tr><td align=right>{$UniqueLicCount}</td><td>{$text}</td></tr>"; $NetLic = $LicCount - $NoLicFound; $text = _("Licenses found"); $VLic .= "<tr><td align=right>{$NetLic}</td><td>{$text}</td></tr>"; $text = _("Files with no licenses"); $VLic .= "<tr><td align=right>{$NoLicFound}</td><td>{$text}</td></tr>"; $text = _("Files"); $VLic .= "<tr><td align=right>{$FileCount}</td><td>{$text}</td></tr>"; $VLic .= "</table>"; pg_free_result($result); /******* File Listing ************/ /* Get ALL the items under this Uploadtree_pk */ $Children = GetNonArtifactChildren($Uploadtree_pk, $this->uploadtree_tablename); /* Filter out Children that don't have tag */ if (!empty($tag_pk)) { TagFilter($Children, $tag_pk, $this->uploadtree_tablename); } $ChildCount = 0; $ChildLicCount = 0; //$uTime = microtime(true); if (!empty($Children)) { /* For alternating row background colors */ $RowStyle1 = "style='background-color:#ecfaff'"; // pale blue $RowStyle2 = "style='background-color:#ffffe3'"; // pale yellow $ColorSpanRows = 1; // Alternate background color every $ColorSpanRows $RowNum = 0; $VF .= "<table border=0 id='dirlist'>"; foreach ($Children as $C) { if (empty($C)) { continue; } $IsDir = Isdir($C['ufile_mode']); $IsContainer = Iscontainer($C['ufile_mode']); /* Determine the hyperlink for non-containers to view-license */ if (!empty($C['pfile_fk']) && !empty($ModLicView)) { $LinkUri = Traceback_uri(); $LinkUri .= "?mod=view-license&napk={$Agent_pk}&upload={$upload_pk}&item={$C['uploadtree_pk']}"; } else { $LinkUri = NULL; } /* Determine link for containers */ if (Iscontainer($C['ufile_mode'])) { $uploadtree_pk = DirGetNonArtifact($C['uploadtree_pk'], $this->uploadtree_tablename); $LicUri = "{$Uri}&item=" . $uploadtree_pk; } else { $LicUri = NULL; } /* Populate the output ($VF) - file list */ /* id of each element is its uploadtree_pk */ /* Set alternating row background color - repeats every $ColorSpanRows rows */ $RowStyle = $RowNum++ % (2 * $ColorSpanRows) < $ColorSpanRows ? $RowStyle1 : $RowStyle2; $VF .= "<tr {$RowStyle}>"; $VF .= "<td id='{$C['uploadtree_pk']}' align='left'>"; $HasHref = 0; $HasBold = 0; if ($IsContainer) { $VF .= "<a href='{$LicUri}'>"; $HasHref = 1; $VF .= "<b>"; $HasBold = 1; } else { if (!empty($LinkUri)) { $VF .= "<a href='{$LinkUri}'>"; $HasHref = 1; } } $VF .= $C['ufile_name']; if ($IsDir) { $VF .= "/"; } if ($HasBold) { $VF .= "</b>"; } if ($HasHref) { $VF .= "</a>"; } /* show licenses under file name */ $VF .= "<br>"; $VF .= GetFileLicenses_string($Agent_pk, $C['pfile_fk'], $C['uploadtree_pk'], $this->uploadtree_tablename); $VF .= "</td><td valign='top'>"; /* display file links */ $VF .= FileListLinks($C['upload_fk'], $C['uploadtree_pk'], $Agent_pk, $C['pfile_fk'], true, $UniqueTagArray, $this->uploadtree_tablename); $VF .= "</td>"; $VF .= "</tr>\n"; $ChildCount++; } $VF .= "</table>\n"; } //$Time = microtime(true) - $uTime; // convert usecs to secs //$text = _("Sum of children Elapsed time: %.2f seconds"); //printf( "<small>$text</small>", $Time); /*************************************** Problem: $ChildCount can be zero! This happens if you have a container that does not unpack to a directory. For example: file.gz extracts to archive.txt that contains a license. Same problem seen with .pdf and .Z files. Solution: if $ChildCount == 0, then just view the license! $ChildCount can also be zero if the directory is empty. ***************************************/ if ($ChildCount == 0) { $sql = "SELECT * FROM {$this->uploadtree_tablename} WHERE uploadtree_pk = '{$Uploadtree_pk}';"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); pg_free_result($result); if (IsDir($row['ufile_mode'])) { return; } $ModLicView =& $Plugins[plugin_find_id("view-license")]; return $ModLicView->Output(); } $V .= ActiveHTTPscript("FileColor"); /* Add javascript for color highlighting This is the response script needed by ActiveHTTPscript responseText is license name',' followed by a comma seperated list of uploadtree_pk's */ $script = "\n <script type=\"text/javascript\" charset=\"utf-8\">\n var Lastutpks=''; /* save last list of uploadtree_pk's */\n var LastLic=''; /* save last License (short) name */\n var color = '{$this->HighlightColor}';\n function FileColor_Reply()\n {\n if ((FileColor.readyState==4) && (FileColor.status==200))\n {\n /* remove previous highlighting */\n var numpks = Lastutpks.length;\n if (numpks > 0) document.getElementById(LastLic).style.backgroundColor='white';\n while (numpks)\n {\n document.getElementById(Lastutpks[--numpks]).style.backgroundColor='white';\n }\n\n utpklist = FileColor.responseText.split(',');\n LastLic = utpklist.shift();\n numpks = utpklist.length;\n Lastutpks = utpklist;\n\n /* apply new highlighting */\n elt = document.getElementById(LastLic);\n if (elt != null) elt.style.backgroundColor=color;\n while (numpks)\n {\n document.getElementById(utpklist[--numpks]).style.backgroundColor=color;\n }\n }\n return;\n }\n </script>\n "; $V .= $script; /****** Filters *******/ /* Only display the filter pulldown if there are filters available * Currently, this is only tags. */ /** @todo qualify with tag namespace to avoid tag name collisions. **/ /* turn $UniqueTagArray into key value pairs ($SelectData) for select list */ $SelectData = array(); if (count($UniqueTagArray)) { foreach ($UniqueTagArray as $UTA_row) { $SelectData[$UTA_row['tag_pk']] = $UTA_row['tag_name']; } $V .= "Tag filter"; $myurl = "?mod=" . $this->Name . Traceback_parm_keep(array("upload", "item")); $Options = " id='filterselect' onchange=\"js_url(this.value, '{$myurl}&tag=')\""; $V .= Array2SingleSelectTag($SelectData, "tag_ns_pk", $tag_pk, true, false, $Options); } /****** Combine VF and VLic ********/ $V .= "<table border=0 width='100%'>\n"; $V .= "<tr><td valign='top' >{$VLic}</td><td valign='top'>{$VF}</td></tr>\n"; $V .= "</table>\n"; $V .= "<hr />\n"; return $V; }
/** * \brief Given an Upload and UploadtreePk item, display: * - The file listing for the directory, with license navigation. * - Recursively traverse the tree. * \note This is recursive! * Output goes to stdout! */ function ShowLicenseTree($Upload, $Item, $Uri, $Path = NULL) { /***** Get all the licenses PER item (file or directory) under this UploadtreePk. Save the data 3 ways: - Number of licenses PER item. - Number of items PER license. - Number of items PER license family. *****/ global $Plugins; $Time = time(); $ModLicView =& $Plugins[plugin_find_id("view-license")]; if ($Path == NULL) { $Path = array(); } /****************************************/ /* Get the items under this UploadtreePk */ $Children = DirGetList($Upload, $Item); $Name = ""; foreach ($Children as $C) { if (empty($C)) { continue; } /* Store the item information */ $IsDir = Isdir($C['ufile_mode']); $IsContainer = Iscontainer($C['ufile_mode']); $IsArtifact = Isartifact($C['ufile_mode']); /* Load licenses for the item */ $Lics = array(); LicenseGetAll($C['uploadtree_pk'], $Lics); /* Determine the hyperlinks */ if (!empty($C['pfile_fk'])) { $LinkUri = "{$Uri}&item=" . $C['uploadtree_pk']; $LinkUri = str_replace("mod=license-tree", "mod=view-license", $LinkUri); } else { $LinkUri = NULL; } if (Iscontainer($C['ufile_mode'])) { $uploadtree_pk = DirGetNonArtifact($C['uploadtree_pk']); $LicUri = "{$Uri}&item=" . $uploadtree_pk; $LicUri = str_replace("mod=license-tree", "mod=license", $LicUri); } else { $LicUri = NULL; } /* Populate the output */ ksort($Lics); $LicCount = $Lics[' Total ']; $LicSum = ""; foreach ($Lics as $Key => $Val) { if ($Key == " Total ") { continue; } if (!empty($LicSum)) { $LicSum .= ","; } $LicSum .= $Key; } /* Display the results */ if ($LicCount > 0) { $LicSum = ""; foreach ($Lics as $Key => $Val) { if ($Key == " Total ") { continue; } if (!empty($LicSum)) { $LicSum .= ","; } $LicSum .= $Key; } $Name = $C['ufile_name']; if ($IsArtifact) { $Name = str_replace("artifact.", "", $Name); } if ($this->OutputType == 'HTML') { $this->ShowOutputHTML($LicCount, $LicSum, $IsContainer, $IsArtifact, $IsDir, $Path, $Name, $LicUri, $LinkUri); } else { if ($this->OutputType == 'CSV') { $this->ShowOutputCSV($LicCount, $LicSum, $IsContainer, $IsArtifact, $IsDir, $Path, $Name, $LicUri, $LinkUri); } } } /* Recurse! */ if (($IsDir || $IsContainer) && $LicCount > 0) { $NewPath = $Path; $NewPath[] = $Name; $this->ShowLicenseTree($Upload, $C['uploadtree_pk'], $Uri, $NewPath); } } /* for each item in the directory */ flush(); }
/** * \brief Given an Upload and UploadtreePk item, display: * - The histogram for the directory BY LICENSE. * - The file listing for the directory, with license navigation. */ function ShowUploadHist($Upload, $Item, $Uri) { /***** Get all the licenses PER item (file or directory) under this UploadtreePk. Save the data 3 ways: - Number of licenses PER item. - Number of items PER license. - Number of items PER license family. *****/ $VF = ""; // return values for file listing $VH = ""; // return values for license histogram $V = ""; // total return value global $Plugins; global $PG_CONN; $Lics = array(); // license summary for an item in the directory $ModLicView =& $Plugins[plugin_find_id("view-license")]; /* Arrays for storying item->license and license->item mappings */ $LicGID2Item = array(); $LicItem2GID = array(); $MapLic2GID = array(); /* every license should have an ID number */ /* Get the counts for each license under this UploadtreePk*/ LicenseGetAll($Item, $Lics); // key is license name, value is count $LicTotal = $Lics[' Total ']; /* Ensure that every license is associated with an ID */ /* MapLic2Gid key is license name, value is a sequence number (GID) */ $MapNext = 0; foreach ($Lics as $Key => $Val) { $MapLic2GID[$Key] = $MapNext++; } /****************************************/ /* Get ALL the items under this UploadtreePk */ $Children = DirGetList($Upload, $Item); $ChildCount = 0; $ChildLicCount = 0; $ChildDirCount = 0; /* total number of directory or containers */ foreach ($Children as $C) { if (Iscontainer($C['ufile_mode'])) { $ChildDirCount++; } } $VF .= "<table border=0>"; foreach ($Children as $C) { if (empty($C)) { continue; } /* Store the item information */ $IsDir = Isdir($C['ufile_mode']); $IsContainer = Iscontainer($C['ufile_mode']); /* Determine the hyperlinks */ if (!empty($C['pfile_fk']) && !empty($ModLicView)) { $LinkUri = "{$Uri}&item=" . $C['uploadtree_pk']; $LinkUri = preg_replace("/mod=license/", "mod=view-license", $LinkUri); } else { $LinkUri = NULL; } if (Iscontainer($C['ufile_mode'])) { $uploadtree_pk = DirGetNonArtifact($C['uploadtree_pk']); $LicUri = "{$Uri}&item=" . $uploadtree_pk; } else { $LicUri = NULL; } /* Populate the output ($VF) - file list */ /* Find number of licenses in child */ // if (($ChildDirCount < 20) || (!$IsContainer)) // { $LicCount = LicenseCount($C['uploadtree_pk']); } // else { $LicCount=0; } $LicCount = 0; $VF .= '<tr><td id="Lic-' . $LicCount . '" align="left">'; $HasHref = 0; $HasBold = 0; if ($IsContainer) { $VF .= "<a href='{$LicUri}'>"; $HasHref = 1; $VF .= "<b>"; $HasBold = 1; } else { if (!empty($LinkUri)) { $VF .= "<a href='{$LinkUri}'>"; $HasHref = 1; } } $VF .= $C['ufile_name']; if ($IsDir) { $VF .= "/"; } if ($HasBold) { $VF .= "</b>"; } if ($HasHref) { $VF .= "</a>"; } $VF .= "</td><td>"; if ($LicCount) { $VF .= "[" . number_format($LicCount, 0, "", ",") . " "; //$VF .= "<a href=\"javascript:LicColor('Lic-$ChildCount','LicGroup-','" . trim($LicItem2GID[$ChildCount]) . "','lightgreen');\">"; $VF .= "license" . ($LicCount == 1 ? "" : "s"); $VF .= "</a>"; $VF .= "]"; $ChildLicCount += $LicCount; } $VF .= "</td>"; $VF .= "</tr>\n"; $ChildCount++; } $VF .= "</table>\n"; // print "ChildCount=$ChildCount ChildLicCount=$ChildLicCount\n"; /*************************************** Problem: $ChildCount can be zero! This happens if you have a container that does not unpack to a directory. For example: file.gz extracts to archive.txt that contains a license. Same problem seen with .pdf and .Z files. Solution: if $ChildCount == 0, then just view the license! $ChildCount can also be zero if the directory is empty. ***************************************/ if ($ChildCount == 0) { $sql = "SELECT * FROM uploadtree WHERE uploadtree_pk = '{$Item}';"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); pg_free_result($result); if (IsDir($row['ufile_mode'])) { return; } $ModLicView =& $Plugins[plugin_find_id("view-license")]; return $ModLicView->Output(); } /****************************************/ /* List the licenses */ $VH .= "<table border=1 width='100%'>\n"; $SFbL = plugin_find_id("search_file_by_license"); $text = _("Count"); $VH .= "<tr><th width='10%'>{$text}</th>"; $text = _("Files"); if ($SFbL >= 0) { $VH .= "<th width='10%'>{$text}</th>"; } $text = _("License"); $VH .= "<th>{$text}</th>\n"; /* krsort + arsort = consistent sorting order */ arsort($Lics); /* Redo the sorting */ $SortOrder = array(); foreach ($Lics as $Key => $Val) { if (empty($Val)) { continue; } $SortOrder[] = $Val . "|" . str_replace("'", "", $Key) . "|" . $Key; } usort($SortOrder, array($this, "SortName")); $LicsTotal = array(); foreach ($SortOrder as $Key => $Val) { if (empty($Val)) { continue; } list($x, $y, $z) = explode("\\|", $Val, 3); $LicsTotal[$z] = $x; } $Total = 0; foreach ($Lics as $Key => $Val) { if ($Key != ' Total ') { $GID = $MapLic2GID[$Key]; $VH .= "<tr><td align='right'>{$Val}</td>"; $Total += $Val; if ($SFbL >= 0) { $VH .= "<td align='center'><a href='"; $VH .= Traceback_uri(); $text = _("Show"); $VH .= "?mod=search_file_by_license&item={$Item}&lic=" . urlencode($Key) . "'>{$text}</a></td>"; } $VH .= "<td id='LicGroup-{$GID}'>"; $Uri = Traceback_uri() . "?mod=license_listing&item={$Item}&lic={$GID}"; // $VH .= "<a href=\"javascript:LicColor('LicGroup-$GID','Lic-','" . trim($LicGID2Item[$GID]) . "','yellow'); "; // $VH .= "\">"; $VH .= htmlentities($Key); $VH .= "</a>"; $VH .= "</td></tr>\n"; } } $VH .= "</table>\n"; $VH .= "<br>\n"; $text = _("Total licenses"); $VH .= "{$text}: {$Total}\n"; /****************************************/ /* Licenses use Javascript to highlight */ $VJ = ""; // return values for the javascript $VJ .= "<script language='javascript'>\n"; $VJ .= "<!--\n"; $VJ .= "var LastSelf='';\n"; $VJ .= "var LastPrefix='';\n"; $VJ .= "var LastListing='';\n"; $VJ .= "function LicColor(Self,Prefix,Listing,color)\n"; $VJ .= "{\n"; $VJ .= "if (LastSelf!='')\n"; $VJ .= " { document.getElementById(LastSelf).style.backgroundColor='white'; }\n"; $VJ .= "LastSelf = Self;\n"; $VJ .= "if (LastPrefix!='')\n"; $VJ .= " {\n"; $VJ .= " List = LastListing.split(' ');\n"; $VJ .= " for(var i in List)\n"; $VJ .= " {\n"; $VJ .= " document.getElementById(LastPrefix + List[i]).style.backgroundColor='white';\n"; $VJ .= " }\n"; $VJ .= " }\n"; $VJ .= "LastPrefix = Prefix;\n"; $VJ .= "LastListing = Listing;\n"; $VJ .= "if (Self!='')\n"; $VJ .= " {\n"; $VJ .= " document.getElementById(Self).style.backgroundColor=color;\n"; $VJ .= " }\n"; $VJ .= "if (Listing!='')\n"; $VJ .= " {\n"; $VJ .= " List = Listing.split(' ');\n"; $VJ .= " for(var i in List)\n"; $VJ .= " {\n"; $VJ .= " document.getElementById(Prefix + List[i]).style.backgroundColor=color;\n"; $VJ .= " }\n"; $VJ .= " }\n"; $VJ .= "}\n"; $VJ .= "// -->\n"; $VJ .= "</script>\n"; /* Combine VF and VH */ $V .= "<table border=0 width='100%'>\n"; $V .= "<tr><td valign='top' width='50%'>{$VH}</td><td valign='top'>{$VF}</td></tr>\n"; $V .= "</table>\n"; $V .= "<hr />\n"; $V .= $VJ; return $V; }
/** * \brief Find the non artifact children of an uploadtree pk. * If any children are artifacts, resolve them until you get * to a non-artifact. * * This function replaces DirGetList() * * \param $uploadtree_pk * \param $uploadtree_tablename * * \return list of child uploadtree recs + pfile_size + pfile_mimetypefk on success. * list may be empty if there are no children. * Child list is sorted by ufile_name. */ function GetNonArtifactChildren($uploadtree_pk, $uploadtree_tablename = 'uploadtree') { global $PG_CONN; $foundChildren = array(); /* Find all the children */ $sql = "select {$uploadtree_tablename}.*, pfile_size, pfile_mimetypefk from {$uploadtree_tablename}\n left outer join pfile on (pfile_pk=pfile_fk)\n where parent={$uploadtree_pk}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) == 0) { pg_free_result($result); return $foundChildren; } $children = pg_fetch_all($result); pg_free_result($result); /* Loop through each child and replace any artifacts with their non artifact child. Or skip them if they are not containers. */ foreach ($children as $key => $child) { if (Isartifact($child['ufile_mode'])) { if (Iscontainer($child['ufile_mode'])) { unset($children[$key]); $NonAChildren = GetNonArtifactChildren($child['uploadtree_pk'], $uploadtree_tablename); if ($NonAChildren) { $foundChildren = array_merge($foundChildren, $NonAChildren); } } else { unset($children[$key]); } } else { $foundChildren[$key] = $child; } } uasort($foundChildren, '_DirCmp'); return $foundChildren; }
/** * \brief Given an $Uploadtree_pk, display: \n * (1) The histogram for the directory BY bucket. \n * (2) The file listing for the directory. */ function ShowUploadHist($Uploadtree_pk, $Uri) { global $PG_CONN; $VF = ""; // return values for file listing $VLic = ""; // return values for output $V = ""; // total return value $UniqueTagArray = array(); global $Plugins; $ModLicView =& $Plugins[plugin_find_id("view-license")]; /******* Get Bucket names and counts ******/ /* Find lft and rgt bounds for this $Uploadtree_pk */ $sql = "SELECT lft,rgt,upload_fk FROM {$this->uploadtree_tablename}\n WHERE uploadtree_pk = {$Uploadtree_pk}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { pg_free_result($result); $text = _("Invalid URL, nonexistant item"); return "<h2>{$text} {$Uploadtree_pk}</h2>"; } $row = pg_fetch_assoc($result); $lft = $row["lft"]; $rgt = $row["rgt"]; $upload_pk = $row["upload_fk"]; pg_free_result($result); /* Get the ars_pk of the scan to display, also the select list */ $ars_pk = GetArrayVal("ars", $_GET); $BucketSelect = SelectBucketDataset($upload_pk, $ars_pk, "selectbdata", "onchange=\"addArsGo('newds','selectbdata');\""); if ($ars_pk == 0) { /* No bucket data for this upload */ return $BucketSelect; } /* Get scan keys */ $sql = "select agent_fk, nomosagent_fk, bucketpool_fk from bucket_ars where ars_pk={$ars_pk}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); $bucketagent_pk = $row["agent_fk"]; $nomosagent_pk = $row["nomosagent_fk"]; $bucketpool_pk = $row["bucketpool_fk"]; pg_free_result($result); /* Create bucketDefArray as individual query this is MUCH faster than incorporating it with a join in the following queries. */ $bucketDefArray = initBucketDefArray($bucketpool_pk); /*select all the buckets for entire tree for this bucketpool */ $sql = "SELECT distinct(bucket_fk) as bucket_pk,\n count(bucket_fk) as bucketcount, bucket_reportorder\n from bucket_file, bucket_def,\n (SELECT distinct(pfile_fk) as PF from {$this->uploadtree_tablename} \n where upload_fk={$upload_pk} \n and ((ufile_mode & (1<<28))=0)\n and ((ufile_mode & (1<<29))=0)\n and {$this->uploadtree_tablename}.lft BETWEEN {$lft} and {$rgt}) as SS\n where PF=pfile_fk and agent_fk={$bucketagent_pk} \n and bucket_file.nomosagent_fk={$nomosagent_pk}\n and bucket_pk=bucket_fk\n and bucketpool_fk={$bucketpool_pk}\n group by bucket_fk,bucket_reportorder\n order by bucket_reportorder asc"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $historows = pg_fetch_all($result); pg_free_result($result); /* Show dataset list */ if (!empty($BucketSelect)) { $action = Traceback_uri() . "?mod=bucketbrowser&upload={$upload_pk}&item={$Uploadtree_pk}"; $VLic .= "<script type='text/javascript'>\nfunction addArsGo(formid, selectid ) \n{\nvar selectobj = document.getElementById(selectid);\nvar ars_pk = selectobj.options[selectobj.selectedIndex].value;\ndocument.getElementById(formid).action='{$action}'+'&ars='+ars_pk;\ndocument.getElementById(formid).submit();\nreturn;\n}\n</script>"; /* form to select new dataset (ars_pk) */ $VLic .= "<form action='{$action}' id='newds' method='POST'>\n"; $VLic .= $BucketSelect; $VLic .= "</form>"; } $sql = "select bucketpool_name, version from bucketpool where bucketpool_pk={$bucketpool_pk}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); $bucketpool_name = $row['bucketpool_name']; $bucketpool_version = $row['version']; pg_free_result($result); /* Write bucket histogram to $VLic */ $bucketcount = 0; $Uniquebucketcount = 0; $NoLicFound = 0; if (is_array($historows)) { $text = _("Bucket Pool"); $VLic .= "{$text}: {$bucketpool_name} v{$bucketpool_version}<br>"; $VLic .= "<table border=1 width='100%'>\n"; $text = _("Count"); $VLic .= "<tr><th width='10%'>{$text}</th>"; $text = _("Files"); $VLic .= "<th width='10%'>{$text}</th>"; $text = _("Bucket"); $VLic .= "<th align='left'>{$text}</th></tr>\n"; foreach ($historows as $bucketrow) { $Uniquebucketcount++; $bucket_pk = $bucketrow['bucket_pk']; $bucketcount = $bucketrow['bucketcount']; $bucket_name = $bucketDefArray[$bucket_pk]['bucket_name']; $bucket_color = $bucketDefArray[$bucket_pk]['bucket_color']; /* Count */ $VLic .= "<tr><td align='right' style='background-color:{$bucket_color}'>{$bucketcount}</td>"; /* Show */ $VLic .= "<td align='center'><a href='"; $VLic .= Traceback_uri(); $text = _("Show"); $VLic .= "?mod=list_bucket_files&bapk={$bucketagent_pk}&item={$Uploadtree_pk}&bpk={$bucket_pk}&bp={$bucketpool_pk}&napk={$nomosagent_pk}" . "'>{$text}</a></td>"; /* Bucket name */ $VLic .= "<td align='left'>"; $VLic .= "<a id='{$bucket_pk}' onclick='FileColor_Get(\"" . Traceback_uri() . "?mod=ajax_filebucket&bapk={$bucketagent_pk}&item={$Uploadtree_pk}&bucket_pk={$bucket_pk}\")'"; $VLic .= ">{$bucket_name} </a>"; /* Allow users to tag an entire bucket */ /* Future, maybe v 2.1 $TagHref = "<a href=" . Traceback_uri() . "?mod=bucketbrowser&upload=$upload_pk&item=$Uploadtree_pk&bapk=$bucketagent_pk&bpk=$bucket_pk&bp=$bucketpool_pk&napk=$nomosagent_pk&tagbucket=1>Tag</a>"; $VLic .= " [$TagHref]"; */ $VLic .= "</td>"; $VLic .= "</tr>\n"; // if ($row['bucket_name'] == "No Buckets Found") $NoLicFound = $row['bucketcount']; } $VLic .= "</table>\n"; $VLic .= "<p>\n"; $text = _("Unique buckets"); $VLic .= "{$text}: {$Uniquebucketcount}<br>\n"; } /******* File Listing ************/ /* Get ALL the items under this Uploadtree_pk */ $Children = GetNonArtifactChildren($Uploadtree_pk, $this->uploadtree_tablename); if (count($Children) == 0) { $sql = "SELECT * FROM {$this->uploadtree_tablename} WHERE uploadtree_pk = '{$Uploadtree_pk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); pg_free_result($result); if (empty($row) || IsDir($row['ufile_mode'])) { return; } // $ModLicView = &$Plugins[plugin_find_id("view-license")]; // return($ModLicView->Output() ); } $ChildCount = 0; $Childbucketcount = 0; /* Countd disabled until we know we need them $NumSrcPackages = 0; $NumBinPackages = 0; $NumBinNoSrcPackages = 0; */ /* get mimetypes for packages */ $MimetypeArray = GetPkgMimetypes(); $VF .= "<table border=0>"; foreach ($Children as $C) { if (empty($C)) { continue; } /* update package counts */ /* This is an expensive count. Comment out until we know we really need it IncrSrcBinCounts($C, $MimetypeArray, $NumSrcPackages, $NumBinPackages, $NumBinNoSrcPackages); */ $IsDir = Isdir($C['ufile_mode']); $IsContainer = Iscontainer($C['ufile_mode']); /* Determine the hyperlink for non-containers to view-license */ if (!empty($C['pfile_fk']) && !empty($ModLicView)) { $LinkUri = Traceback_uri(); $LinkUri .= "?mod=view-license&napk={$nomosagent_pk}&bapk={$bucketagent_pk}&upload={$upload_pk}&item={$C['uploadtree_pk']}"; } else { $LinkUri = NULL; } /* Determine link for containers */ if (Iscontainer($C['ufile_mode'])) { $uploadtree_pk = DirGetNonArtifact($C['uploadtree_pk'], $this->uploadtree_tablename); $tmpuri = "?mod=" . $this->Name . Traceback_parm_keep(array("upload", "folder", "ars")); $LicUri = "{$tmpuri}&item=" . $uploadtree_pk; } else { $LicUri = NULL; } /* Populate the output ($VF) - file list */ /* id of each element is its uploadtree_pk */ $VF .= "<tr><td id='{$C['uploadtree_pk']}' align='left'>"; $HasHref = 0; $HasBold = 0; if ($IsContainer) { $VF .= "<a href='{$LicUri}'>"; $HasHref = 1; $VF .= "<b>"; $HasBold = 1; } else { if (!empty($LinkUri)) { $VF .= "<a href='{$LinkUri}'>"; $HasHref = 1; } } $VF .= $C['ufile_name']; if ($IsDir) { $VF .= "/"; } if ($HasBold) { $VF .= "</b>"; } if ($HasHref) { $VF .= "</a>"; } /* print buckets */ $VF .= "<br>"; $VF .= "<span style='position:relative;left:1em'>"; /* get color coded string of bucket names */ $VF .= GetFileBuckets_string($nomosagent_pk, $bucketagent_pk, $C['uploadtree_pk'], $bucketDefArray, ",", True); $VF .= "</span>"; $VF .= "</td><td valign='top'>"; /* display item links */ $VF .= FileListLinks($C['upload_fk'], $C['uploadtree_pk'], $nomosagent_pk, $C['pfile_fk'], True, $UniqueTagArray, $this->uploadtree_tablename); $VF .= "</td>"; $VF .= "</tr>\n"; $ChildCount++; } $VF .= "</table>\n"; $V .= ActiveHTTPscript("FileColor"); /* Add javascript for color highlighting This is the response script needed by ActiveHTTPscript responseText is bucket_pk',' followed by a comma seperated list of uploadtree_pk's */ $script = "\n <script type=\"text/javascript\" charset=\"utf-8\">\n var Lastutpks=''; /* save last list of uploadtree_pk's */\n var Lastbupk=''; /* save last bucket_pk */\n var color = '#4bfe78';\n function FileColor_Reply()\n {\n if ((FileColor.readyState==4) && (FileColor.status==200))\n {\n /* remove previous highlighting */\n var numpks = Lastutpks.length;\n if (numpks > 0) document.getElementById(Lastbupk).style.backgroundColor='white';\n while (numpks)\n {\n document.getElementById(Lastutpks[--numpks]).style.backgroundColor='white';\n }\n\n utpklist = FileColor.responseText.split(',');\n Lastbupk = utpklist.shift();\n numpks = utpklist.length;\n Lastutpks = utpklist;\n\n /* apply new highlighting */\n elt = document.getElementById(Lastbupk);\n if (elt != null) elt.style.backgroundColor=color;\n while (numpks)\n {\n document.getElementById(utpklist[--numpks]).style.backgroundColor=color;\n }\n }\n return;\n }\n </script>\n "; $V .= $script; /* Display source, binary, and binary missing source package counts */ /* Counts disabled above until we know we need these $VLic .= "<ul>"; $text = _("source packages"); $VLic .= "<li> $NumSrcPackages $text"; $text = _("binary packages"); $VLic .= "<li> $NumBinPackages $text"; $text = _("binary packages with no source package"); $VLic .= "<li> $NumBinNoSrcPackages $text"; $VLic .= "</ul>"; */ /* Combine VF and VLic */ $V .= "<table border=0 width='100%'>\n"; $V .= "<tr><td valign='top' width='50%'>{$VLic}</td><td valign='top'>{$VF}</td></tr>\n"; $V .= "</table>\n"; $V .= "<hr />\n"; return $V; }
protected function handle(Request $request) { $vars = array(); $uploadId = intval($request->get('upload')); $uploadTreeId = intval($request->get('item')); if (empty($uploadTreeId) || empty($uploadId)) { $text = _("Empty Input"); $vars['message'] = "<h2>{$text}</h2>"; return $this->responseBad($vars); } if (!$this->uploadDao->isAccessible($uploadId, Auth::getGroupId())) { $text = _("Permission Denied"); $vars['message'] = "<h2>{$text}</h2>"; return $this->responseBad(); } $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId); $uploadEntry = $this->uploadDao->getUploadEntry($uploadTreeId, $uploadTreeTableName); if (Isdir($uploadEntry['ufile_mode']) || Iscontainer($uploadEntry['ufile_mode'])) { $parent = $this->uploadDao->getUploadParent($uploadEntry['upload_fk']); if (!isset($parent)) { return $this->responseBad(); } $uploadTree = $this->uploadDao->getNextItem($uploadEntry['upload_fk'], $parent); if ($uploadTree === UploadDao::NOT_FOUND) { return $this->responseBad(); } $uploadTreeId = $uploadTree->getId(); return new RedirectResponse(Traceback_uri() . '?mod=' . $this->getName() . Traceback_parm_keep(array('show', 'upload')) . "&item={$uploadTreeId}"); } if (empty($uploadTreeId)) { return $this->responseBad('No item selected.'); } $copyrightDecisionMap = $this->decisionTypes->getMap(); $vars['micromenu'] = Dir2Browse($this->modBack, $uploadTreeId, NULL, $showBox = 0, "View", -1, '', '', $uploadTreeTableName); $lastItem = GetParm("lastItem", PARM_INTEGER); $changed = GetParm("changedSomething", PARM_STRING); $userId = Auth::getUserId(); if (!empty($lastItem) && $changed == "true") { $lastUploadEntry = $this->uploadDao->getUploadEntry($lastItem, $uploadTreeTableName); $clearingType = $_POST['clearingTypes']; $description = $_POST['description']; $textFinding = $_POST['textFinding']; $comment = $_POST['comment']; $this->copyrightDao->saveDecision($this->decisionTableName, $lastUploadEntry['pfile_fk'], $userId, $clearingType, $description, $textFinding, $comment); } $scanJobProxy = new ScanJobProxy($this->agentDao, $uploadId); $scanJobProxy->createAgentStatus(array($this->agentName)); $selectedScanners = $scanJobProxy->getLatestSuccessfulAgentIds(); $highlights = array(); if (array_key_exists($this->agentName, $selectedScanners)) { $latestXpAgentId = $selectedScanners[$this->agentName]; $highlights = $this->copyrightDao->getHighlights($uploadTreeId, $this->tableName, $latestXpAgentId, $this->typeToHighlightTypeMap); } if (count($highlights) < 1) { $vars['message'] = _("No ") . $this->tableName . _(" data is available for this file."); } /* @var $view ui_view */ $view = plugin_find("view"); $theView = $view->getView(null, null, $showHeader = 0, "", $highlights, false, true); list($pageMenu, $textView) = $theView; list($description, $textFinding, $comment, $decisionType) = $this->copyrightDao->getDecision($this->decisionTableName, $uploadEntry['pfile_fk']); $vars['description'] = $description; $vars['textFinding'] = $textFinding; $vars['comment'] = $comment; $vars['itemId'] = $uploadTreeId; $vars['uploadId'] = $uploadId; $vars['pageMenu'] = $pageMenu; $vars['textView'] = $textView; $vars['legendBox'] = $this->legendBox(); $vars['uri'] = Traceback_uri() . "?mod=" . $this->Name; $vars['optionName'] = $this->optionName; $vars['formName'] = "CopyRightForm"; $vars['ajaxAction'] = $this->ajaxAction; $vars['skipOption'] = $this->skipOption; $vars['selectedClearingType'] = $decisionType; $vars['clearingTypes'] = $copyrightDecisionMap; $vars['xptext'] = $this->xptext; $agentId = intval($request->get("agent")); $vars = array_merge($vars, $this->additionalVars($uploadId, $uploadTreeId, $agentId)); return $this->render('ui-cp-view.html.twig', $this->mergeWithDefault($vars)); }