/** * \brief This is where we check for * changes to the full-debug setting. */ function PostInitialize() { if ($this->State != PLUGIN_STATE_VALID) { return 0; } // don't re-run // Make sure dependencies are met foreach ($this->Dependency as $key => $val) { $id = plugin_find_id($val); if ($id < 0) { $this->Destroy(); return 0; } } $FullMenuDebug = GetParm("fullmenu", PARM_INTEGER); if ($FullMenuDebug == 2) { $_SESSION['fullmenudebug'] = 1; } if ($FullMenuDebug == 1) { $_SESSION['fullmenudebug'] = 0; } // It worked, so mark this plugin as ready. $this->State = PLUGIN_STATE_READY; // Add this plugin to the menu if ($this->MenuList !== "") { menu_insert("Main::" . $this->MenuList, $this->MenuOrder, $this->Name, $this->MenuTarget); } return 1; }
/** * \brief Generate output for this plug-in. */ function Output() { if ($this->State != PLUGIN_STATE_READY) { return; } global $SysConf; global $Plugins; $html = "<table width='100%' border=0 cellpadding=0>\n <tr>\n"; $Uri = Traceback_dir(); if (@$SysConf['SYSCONFIG']['LogoImage'] and @$SysConf['SYSCONFIG']['LogoLink']) { $LogoLink = $SysConf['SYSCONFIG']['LogoLink']; $LogoImg = $SysConf['SYSCONFIG']['LogoImage']; } else { $LogoLink = 'http://fossology.org'; $LogoImg = Traceback_uri . 'images/fossology-logo.gif'; } $html .= " <td width='15%'>"; $html .= "<a href='{$LogoLink}' target='_top'><img src='{$LogoImg}' align=absmiddle border=0></a>"; $html .= "</td>\n"; $html .= " <td valign='top'>"; $Menu =& $Plugins[plugin_find_id("menus")]; $Menu->OutputSet($this->OutputType, 0); $html .= $Menu->Output(); $html .= " </td>\n"; $html .= " </tr>\n"; $html .= "</table>\n"; return $html; }
/** * @param $menu menu list need to show as list * @param $parm a list of parameters to add to the URL. * @param $uploadId upload id */ public static function menuToActiveSelect($menu, &$parm, $uploadId = "") { if (empty($menu)) { return ''; } $showFullName = isset($_SESSION) && array_key_exists('fullmenudebug', $_SESSION) && $_SESSION['fullmenudebug'] == 1; $optionsOut = ""; foreach ($menu as $Val) { if (!empty($Val->HTML)) { $entry = $Val->HTML; } else { if (!empty($Val->URI)) { if (!empty($uploadId) && "tag" == $Val->URI) { $tagstatus = TagStatus($uploadId); if (0 == $tagstatus) { // tagging on this upload is disabled break; } } $entry = '<option value="' . Traceback_uri() . '?mod=' . $Val->URI . '&' . $parm . '"'; if (!empty($Val->Title)) { $entry .= ' title="' . htmlentities($Val->Title, ENT_QUOTES) . '"'; } $entry .= '>' . $Val->getName($showFullName) . '</option>'; } else { $entry = "<option>" . $Val->getName($showFullName) . "</option>"; } } $optionsOut .= $entry; } if (plugin_find_id('showjobs') >= 0) { $optionsOut .= '<option value="' . Traceback_uri() . '?mod=showjobs&upload=' . $uploadId . '" title="' . _("Scan History") . '" >' . _("History") . '</option>'; } return '<select class="goto-active-option"><option>-- select action --</option>' . $optionsOut . '</select>'; }
/** * \brief This function is called before the plugin * is used and after all plugins have been initialized. * * \return on success, false on failure. * \note Do not assume that the plugin exists! Actually check it! * Purpose: Only allow people who are logged in to edit their own properties. */ function PostInitialize() { global $Plugins; if ($this->State != PLUGIN_STATE_VALID) { return 0; } // don't run if ($_SESSION['User'] == "Default User") { /* Only valid if the user is logged in. */ $this->State = PLUGIN_STATE_INVALID; return 0; } // Make sure dependencies are met foreach ($this->Dependency as $key => $val) { $id = plugin_find_id($val); if ($id < 0) { $this->Destroy(); return 0; } } // It worked, so mark this plugin as ready. $this->State = PLUGIN_STATE_READY; // Add this plugin to the menu if ($this->MenuList !== "") { menu_insert("Main::" . $this->MenuList, $this->MenuOrder, $this->Name, $this->MenuTarget); } return $this->State == PLUGIN_STATE_READY; }
/** * \brief Generate the text for this plugin. */ function Output() { if ($this->State != PLUGIN_STATE_READY) { return; } global $PG_CONN; $V = ""; switch ($this->OutputType) { case "XML": break; case "HTML": /* Get uploadtree_pk's for all debian uploads */ $sql = "SELECT uploadtree_pk, upload_pk, upload_filename FROM upload INNER JOIN uploadtree ON upload_fk=upload_pk AND parent IS NULL WHERE upload_filename LIKE '%debian%';"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $row = pg_fetch_assoc($result); if (empty($row['upload_pk'])) { $V .= "There are no uploads with 'debian' in the description."; } else { /* Loop thru results to obtain all licenses in their uploadtree recs*/ $Lics = array(); while ($Row = pg_fetch_array($result)) { if (empty($Row['upload_pk'])) { continue; } else { LicenseGetAll($Row[uploadtree_pk], $Lics); } $V .= "<option value='" . $Row['upload_pk'] . "'>{$Name}</option>\n"; } $V .= "</select><P />\n"; arsort($Lics); $V .= "<table border=1>\n"; foreach ($Lics as $key => $value) { if ($key == " Total ") { $V .= "<tr><th>{$key}<th>{$value}\n"; } else { if (plugin_find_id('search_file_by_license') >= 0) { $V .= "<tr><td><a href='/repo/?mod=search_file_by_license&item={$Row['uploadtree_pk']}&lic=" . urlencode($key) . "'>{$key}</a><td align='right'>{$value}\n"; } else { $V .= "<tr><td>{$key}<td align='right'>{$value}\n"; } } } $V .= "</table>\n"; // print "<pre>"; print_r($Lics); print "</pre>"; } pg_free_result($result); break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print $V; return; }
/** * \brief This function is called when user output is * finished. */ function OutputClose() { if ($this->State != PLUGIN_STATE_READY) { return 0; } global $Plugins; $P =& $Plugins[plugin_find_id("Default")]; return $P->OutputClose(); }
/** * \brief This function is called when user output is * requested. This function is responsible for content. */ function Output() { if ($this->State != PLUGIN_STATE_READY) { return; } global $Plugins; $P =& $Plugins[plugin_find_id("Default")]; $GoMod = GetParm("remod", PARM_STRING); $GoOpt = GetParm("reopt", PARM_STRING); $GoOpt = preg_replace("/--/", "&", $GoOpt); return $P->Output($GoMod, $GoOpt); }
/** * @param Request $request * @return Response */ protected function handle(Request $request) { $show = $request->get('show'); if ($show == 'licensebrowser') { return $this->render("getting_started_licensebrowser.html.twig"); } $login = _("Login"); if (empty($_SESSION['User']) && plugin_find_id("auth") >= 0) { $login = "******" . Traceback_uri() . "?mod=auth'>{$login}</a>"; } $vars = array('login' => $login, 'SiteURI' => Traceback_uri()); return $this->render('getting_started.html.twig', $this->mergeWithDefault($vars)); }
/** * \brief Add an upload to multiple agents. * * \param $uploadpk * \param $agentlist - list of agents * \return NULL on success, error message string on failure */ function AgentsAdd($uploadpk, $agentlist) { global $Plugins; global $PG_CONN; global $SysConf; $rc = ""; $Alist = array(); /* Make sure the uploadpk is valid */ if (!$uploadpk) { return "agent-add.php AgentsAdd(): No upload_pk specified"; } $sql = "SELECT upload_pk, upload_filename FROM upload WHERE upload_pk = '{$uploadpk}';"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { $ErrMsg = __FILE__ . ":" . __LINE__ . " " . _("Upload") . " " . $uploadpk . " " . _("not found"); return $ErrMsg; } $UploadRow = pg_fetch_assoc($result); $ShortName = $UploadRow['upload_filename']; pg_free_result($result); /* Create Job */ $user_pk = $SysConf['auth']['UserId']; $job_pk = JobAddJob($user_pk, $ShortName, $uploadpk); /* Validate the agent list and add agents as needed. */ /** Don't worry about order or duplicates -- it will do the right thing. **/ $Depth = 0; $agent_list = menu_find("Agents", $depth); for ($al = 0; !empty($agentlist[$al]); $al++) { /* check if the agent exists in the list of viable agents */ $Found = -1; for ($ac = 0; $Found < 0 && !empty($agent_list[$ac]->URI); $ac++) { if (!strcmp($agent_list[$ac]->URI, $agentlist[$al])) { $Found = $al; break; } } if ($Found >= 0) { //print "Adding to " . $agentlist[$Found] . "<br>\n"; $Dependencies = array(); $P =& $Plugins[plugin_find_id($agentlist[$Found])]; $rv = $P->AgentAdd($job_pk, $uploadpk, $ErrorMsg, $Dependencies); if ($rv == -1) { $rc .= $ErrorMsg; } } else { $rc .= "Agent '" . htmlentities($agentlist[$al]) . "' not found.\n"; } } return $rc; }
/** * \brief This function is called when user output is * requested. This function is responsible for content. \n * The $ToStdout flag is "1" if output should go to stdout, and * 0 if it should be returned as a string. (Strings may be parsed * and used by other plugins.) */ function Output() { global $PG_CONN; if ($this->State != PLUGIN_STATE_READY) { return; } $V = ""; global $Plugins; $View =& $Plugins[plugin_find_id("view")]; $Item = GetParm("item", PARM_INTEGER); $Upload = GetParm("upload", PARM_INTEGER); $ModBack = GetParm("modback", PARM_STRING); if (empty($ModBack)) { $ModBack = 'copyrighthist'; } $pfile = 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 (!empty($row['pfile_fk'])) { $pfile = $row['pfile_fk']; } else { $text = _("Could not locate the corresponding pfile."); print $text; } $sql = "SELECT * FROM copyright WHERE copy_startbyte IS NOT NULL\n and pfile_fk=" . $pfile . ";"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { $text = _("No copyright data is available for this file."); print $text; return; } $row = pg_fetch_assoc($result, 0); $colors = array(); $colors['statement'] = 0; $colors['email'] = 1; $colors['url'] = 2; if (!empty($row['copy_startbyte'])) { while ($row = pg_fetch_assoc($result)) { $View->AddHighlight($row['copy_startbyte'], $row['copy_endbyte'], $colors[$row['type']], '', $row['content'], -1, Traceback_uri() . "?mod=copyrightlist&agent=" . $row['agent_fk'] . "&item={$Item}&hash=" . $row['hash'] . "&type=" . $row['type']); } $View->SortHighlightMenu(); } pg_free_result($result); $View->ShowView(NULL, $ModBack, 1, 1, NULL, True); return; }
/** * @param Request $request * @return Response */ protected function handle(Request $request) { $vars = array('isSecure' => $request->isSecure()); if (array_key_exists('User', $_SESSION) && $_SESSION['User'] == "Default User" && plugin_find_id("auth") >= 0) { if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") { $vars['protocol'] = "HTTPS"; } else { $vars['protocol'] = preg_replace("@/.*@", "", @$_SERVER['SERVER_PROTOCOL']); } $vars['referrer'] = "?mod=browse"; $vars['authUrl'] = "?mod=auth"; } return $this->render("home.html.twig", $this->mergeWithDefault($vars)); }
/** * @param string $hook 'ParmAgents'|'Agents'|'UploadMulti' * @return array */ public static function getAgentPluginNames($hook = 'Agents') { $maxDepth = 0; $agentList = menu_find($hook, $maxDepth) ?: array(); $agentPluginNames = array(); if (is_array($agentList)) { foreach ($agentList as $parmAgent) { $agent = plugin_find_id($parmAgent->URI); if (!empty($agent)) { $agentPluginNames[] = $agent; } } } return $agentPluginNames; }
/** * \brief Generate output for this plug-in. */ function Output() { global $Plugins; global $SysConf; if ($this->State != PLUGIN_STATE_READY) { return; } $V = ""; switch ($this->OutputType) { case "XML": break; case "HTML": $Uri = Traceback_dir(); $V .= "<table width='100%' border=0 cellpadding=0>\n"; $V .= " <tr>\n"; /* custom or default logo? */ if (@$SysConf['SYSCONFIG']['LogoImage'] and @$SysConf['SYSCONFIG']['LogoLink']) { $LogoLink = $SysConf['SYSCONFIG']['LogoLink']; $LogoImg = $SysConf['SYSCONFIG']['LogoImage']; } else { $LogoLink = 'http://fossology.org'; $LogoImg = Traceback_uri . 'images/fossology-logo.gif'; } $V .= " <td width='15%'>"; $V .= "<a href='{$LogoLink}' target='_top'><img src='{$LogoImg}' align=absmiddle border=0></a>"; $V .= "</td>\n"; $V .= " <td valign='top'>"; $Menu =& $Plugins[plugin_find_id("menus")]; $Menu->OutputSet($this->OutputType, 0); $V .= $Menu->Output(); $Menu->OutputUnSet(); $V .= " </td>\n"; $V .= " </tr>\n"; $V .= "</table>\n"; break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print "{$V}"; return; }
/** * \brief Display the loaded menu and plugins. */ public function Output() { global $Plugins; global $PG_CONN; $UploadPk = GetParm("upload", PARM_INTEGER); $Agent = GetParm("agent", PARM_STRING); if (empty($UploadPk) || empty($Agent)) { return new Response('missing parameter', Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain')); } $sql = "SELECT upload_pk, upload_filename FROM upload WHERE upload_pk = '{$UploadPk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { $errMsg = __FILE__ . ":" . __LINE__ . " " . _("Upload") . " " . $UploadPk . " " . _("not found"); return new Response($errMsg, Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain')); } $UploadRow = pg_fetch_assoc($result); $ShortName = $UploadRow['upload_filename']; pg_free_result($result); $user_pk = Auth::getUserId(); $group_pk = Auth::getGroupId(); $job_pk = JobAddJob($user_pk, $group_pk, $ShortName, $UploadPk); $Dependencies = array(); $P =& $Plugins[plugin_find_id($Agent)]; $rv = $P->AgentAdd($job_pk, $UploadPk, $ErrorMsg, $Dependencies); if ($rv <= 0) { $text = _("Scheduling of Agent(s) failed: "); return new Response($text . $rv . $ErrorMsg, Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain')); } /** check if the scheudler is running */ $status = GetRunnableJobList(); $scheduler_msg = ""; if (empty($status)) { $scheduler_msg .= _("Is the scheduler running? "); } $URL = Traceback_uri() . "?mod=showjobs&upload={$UploadPk}"; /* Need to refresh the screen */ $text = _("Your jobs have been added to job queue."); $LinkText = _("View Jobs"); $msg = "{$scheduler_msg}" . "{$text} <a href={$URL}>{$LinkText}</a>"; $this->vars['message'] = $msg; return new Response($msg, Response::HTTP_OK, array('Content-type' => 'text/plain')); }
/** * \brief Generate the text for this plugin. */ function Output() { if ($this->State != PLUGIN_STATE_READY) { return; } global $Plugins; $V = ""; switch ($this->OutputType) { case "XML": break; case "HTML": /* If this is a POST, then process the request. */ $uploadpk = GetParm('uploadunpack', PARM_INTEGER); if (!empty($uploadpk)) { $P =& $Plugins[plugin_find_id("agent_unpack")]; $rc = $P->AgentAdd($uploadpk); if (empty($rc)) { /* Need to refresh the screen */ $text = _("Unpack added to job queue"); $V .= displayMessage($text); } else { $text = _("Unpack of Upload failed"); $V .= displayMessage("{$text}: {$rc}"); } } /* Set default values */ if (empty($GetURL)) { $GetURL = 'http://'; } //$V .= $this->ShowReunpackView($uploadtree_pk); break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print "{$V}"; return; }
/** * \brief Display the loaded menu and plugins. */ function Output() { if ($this->State != PLUGIN_STATE_READY) { return; } $V = ""; global $Plugins; switch ($this->OutputType) { case "XML": break; case "HTML": $UploadPk = GetParm("upload", PARM_INTEGER); if (empty($UploadPk)) { return; } $Depth = 0; $agent_list = menu_find("Agents", $depth); $Skip = array("agent_unpack", "agent_adj2nest", "wget_agent"); for ($ac = 0; !empty($agent_list[$ac]->URI); $ac++) { if (array_search($agent_list[$ac]->URI, $Skip) !== false) { continue; } $P =& $Plugins[plugin_find_id($agent_list[$ac]->URI)]; if ($P->AgentHasResults($UploadPk) != 1) { $V .= "<option value='" . $agent_list[$ac]->URI . "'>"; $V .= htmlentities($agent_list[$ac]->Name); $V .= "</option>\n"; } } break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print $V; return; }
private function checkPrerequisites() { if ($this->requiresLogin && !$this->isLoggedIn()) { throw new \Exception("not allowed without login"); } foreach ($this->dependencies as $dependency) { $id = plugin_find_id($dependency); if ($id < 0) { $this->unInstall(); throw new \Exception("unsatisfied dependency '{$dependency}' in module '" . $this->getName() . "'"); } } }
/** * @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); }
/** * \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 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 Called if there is no file. User is queried if they want * to reunpack. */ function CheckRestore($Item, $Filename) { global $Plugins; $this->NoHeader = 0; header('Content-type: text/html'); header("Pragma: no-cache"); /* for IE cache control */ header('Cache-Control: no-cache, must-revalidate, maxage=1, post-check=0, pre-check=0'); /* prevent HTTP/1.1 caching */ header('Expires: Expires: Thu, 19 Nov 1981 08:52:00 GMT'); /* mark it as expired (value from Apache default) */ $V = ""; if ($this->NoMenu == 0 && $this->Name != "menus") { $Menu =& $Plugins[plugin_find_id("menus")]; } else { $Menu = NULL; } /* DOCTYPE is required for IE to use styles! (else: css menu breaks) */ $V .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "xhtml1-frameset.dtd">' . "\n"; $V .= "<html>\n"; $V .= "<head>\n"; $V .= "<meta name='description' content='The study of Open Source'>\n"; if ($this->NoHeader == 0) { /** Known bug: DOCTYPE "should" be in the HEADER and the HEAD tags should come first. Also, IE will ignore <style>...</style> tags that are NOT in a <head>...</head>block. **/ if (!empty($this->Title)) { $V .= "<title>" . htmlentities($this->Title) . "</title>\n"; } $V .= "<link rel='stylesheet' href='css/fossology.css'>\n"; if (!empty($Menu)) { print $Menu->OutputCSS(); } $V .= "</head>\n"; $V .= "<body class='text'>\n"; print $V; if (!empty($Menu)) { $Menu->Output($this->Title); } } $P =& $Plugins[plugin_find_id("view")]; $P->ShowView(NULL, "browse"); exit; }
protected function outputWhenFileNotInRepo($uploadpk, $item) { global $Plugins; $reunpackPlugin =& $Plugins[plugin_find_id("ui_reunpack")]; $state = $reunpackPlugin->CheckStatus($uploadpk, "reunpack", "ununpack"); /* If this is a POST, then process the request. */ $uploadunpack = GetParm('uploadunpack', PARM_INTEGER); $flag = 0; $output = ''; if ($state != 0 && $state != 2) { $flag = 1; $text = _("Reunpack job is running: you can see it in"); $text1 = _("jobqueue"); $output .= "<p> <font color=red>{$text} <a href='" . Traceback_uri() . "?mod=showjobs'>{$text1}</a></font></p>"; } elseif (!empty($uploadunpack)) { $rc = $reunpackPlugin->AgentAdd($uploadpk); if (empty($rc)) { /* Need to refresh the screen */ $this->vars['message'] = _("Unpack added to job queue"); $flag = 1; $text = _("Reunpack job is running: you can see it in"); $text1 = _("jobqueue"); $output .= "<p> <font color=red>{$text} <a href='" . Traceback_uri() . "?mod=showjobs'>{$text1}</a></font></p>"; } else { $text = _("Unpack of Upload failed"); $this->vars['message'] = "{$text}: {$rc}"; } } $text = _("File contents are not available in the repository."); $output .= "{$text}\n"; $output .= $reunpackPlugin->ShowReunpackView($item, $flag); return $output; }
/** * \brief This function is called when user output is * requested. This function is responsible for assigning headers. * If $Type is "HTML" then generate an HTTP header. * If $Type is "XML" then begin an XML header. * If $Type is "Text" then generate a text header as needed. * The $ToStdout flag is "1" if output should go to stdout, and * 0 if it should be returned as a string. (Strings may be parsed * and used by other plugins.) */ function OutputOpen($Type, $ToStdout) { global $Plugins; if ($this->State != PLUGIN_STATE_READY) { return 0; } $this->OutputType = $Type; $this->OutputToStdout = $ToStdout; // Put your code here switch ($this->OutputType) { case "XML": $V = "<xml>\n"; break; case "HTML": header('Content-type: text/html'); header("Pragma: no-cache"); /* for IE cache control */ header('Cache-Control: no-cache, must-revalidate, maxage=1, post-check=0, pre-check=0'); /* prevent HTTP/1.1 caching */ header('Expires: Expires: Thu, 19 Nov 1981 08:52:00 GMT'); /* mark it as expired (value from Apache default) */ if ($this->NoHTML) { return; } $V = ""; if ($this->NoMenu == 0 && $this->Name != "menus") { $Menu =& $Plugins[plugin_find_id("menus")]; $Menu->OutputSet($Type, $ToStdout); } else { $Menu = NULL; } /* DOCTYPE is required for IE to use styles! (else: css menu breaks) */ $V .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "xhtml1-frameset.dtd">' . "\n"; // $V .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . "\n"; // $V .= '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Loose//EN" "http://www.w3.org/TR/html4/loose.dtd">' . "\n"; // $V .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "xhtml1-strict.dtd">' . "\n"; $V .= "<html>\n"; $V .= "<head>\n"; $V .= "<meta name='description' content='The study of Open Source'>\n"; $V .= "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>\n"; if ($this->NoHeader == 0) { /** Known bug: DOCTYPE "should" be in the HEADER and the HEAD tags should come first. Also, IE will ignore <style>...</style> tags that are NOT in a <head>...</head> block. **/ if (!empty($this->Title)) { $V .= "<title>" . htmlentities($this->Title) . "</title>\n"; } $V .= "<link rel='stylesheet' href='css/fossology.css'>\n"; print $V; $V = ""; if (!empty($Menu)) { print $Menu->OutputCSS(); } $V .= "</head>\n"; $V .= "<body class='text'>\n"; print $V; $V = ""; if (!empty($Menu)) { $Menu->Output($this->Title); } } break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print $V; return; }
/** * \brief Analyze one uploaded file. * \param $Highlight - if copyright info lines would be highlight, now always yes */ function AnalyzeOne() { global $Plugins; global $SYSCONFDIR; $ModBack = GetParm("modback", PARM_STRING); $copyright_array = array(); $V = ""; /** @var ui_view $view */ $view =& $Plugins[plugin_find_id("view")]; $tempFileName = $_FILES['licfile']['tmp_name']; $ui_dir = getcwd(); $copyright_dir = "{$SYSCONFDIR}/mods-enabled/copyright/agent/"; if (!chdir($copyright_dir)) { $errmsg = _("unable to change working directory to {$copyright_dir}\n"); return $errmsg; } //$Sys = "./copyright -C $tempFileName -c $SYSCONFDIR"; $Sys = "./copyright -c {$SYSCONFDIR} {$tempFileName}"; $inputFile = popen($Sys, "r"); $colors = array(); $colors['statement'] = 0; $colors['email'] = 1; $colors['url'] = 2; $stuff = array(); $stuff['statement'] = array(); $stuff['email'] = array(); $stuff['url'] = array(); $realline = ""; $highlights = array(); $typeToHighlightTypeMap = array('statement' => Highlight::COPYRIGHT, 'email' => Highlight::EMAIL, 'url' => Highlight::URL); while (!feof($inputFile)) { $Line = fgets($inputFile); if ($Line[0] == '/') { continue; } $count = strlen($Line); if ($count > 0) { /** $Line is not "'", also $Line is not end with ''', please notice that: usually $Line is end with NL(new line) */ if ($count > 1 && "'" != $Line[$count - 2] || 1 == $count && "'" != $Line[$count - 1]) { $Line = str_replace("\n", ' ', $Line); // in order to preg_match_all correctly, replace NL with white space $realline .= $Line; continue; } $realline .= $Line; //print "<br>realline$realline<br>"; $match = array(); preg_match_all("/\t\\[(?P<start>\\d+)\\:(?P<end>\\d+)\\:(?P<type>[A-Za-z]+)\\] \\'(?P<content>.+)\\'/", $realline, $match); //print_r($match); if (!empty($match['start'])) { $stuff[$match['type'][0]][] = $match['content'][0]; if ($this->NoHTML) { // For REST API array_push($copyright_array, $match['content'][0]); } else { $highlights[] = new Highlight($match['start'][0], $match['end'][0], $typeToHighlightTypeMap[$match['type'][0]], -1, -1, $match['content'][0]); } } } $realline = ""; } pclose($inputFile); if ($this->NoHTML) { return $copyright_array; } $inputFile = fopen($tempFileName, "r"); if ($inputFile) { $V = $view->getView($inputFile, $ModBack, 0, NULL, $highlights); // do not show Header and micro menus fclose($inputFile); } if (!chdir($ui_dir)) { $errmsg = _("unable to change back to working directory {$ui_dir}\n"); return $errmsg; } /* Clean up */ return $V; }
/** * \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; }
/** * \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 Process the upload request. * \param $Folder * \param $GetURL * \param $Desc * \param $Name * \param $Accept * \param $Reject * \param $Level * \param $public_perm public permission on the upload * Returns NULL on success, string on failure. */ function Upload($Folder, $GetURL, $Desc, $Name, $Accept, $Reject, $Level, $public_perm) { global $SysConf; /* See if the URL looks valid */ if (empty($Folder)) { $text = _("Invalid folder"); return $text; } $GetURL = trim($GetURL); if (empty($GetURL)) { $text = _("Invalid URL"); return $text; } if (preg_match("@^((http)|(https)|(ftp))://([[:alnum:]]+)@i", $GetURL) != 1) { $text = _("Invalid URL"); return "{$text}: " . htmlentities($GetURL); } if (preg_match("@[[:space:]]@", $GetURL) != 0) { $text = _("Invalid URL (no spaces permitted)"); return "{$text}: " . htmlentities($GetURL); } if (empty($Name)) { $Name = basename($GetURL); } $ShortName = basename($Name); if (empty($ShortName)) { $ShortName = $Name; } /* Create an upload record. */ $Mode = 1 << 2; // code for "it came from wget" $user_pk = $SysConf['auth']['UserId']; $uploadpk = JobAddUpload($user_pk, $ShortName, $GetURL, $Desc, $Mode, $Folder, $public_perm); if (empty($uploadpk)) { $text = _("Failed to insert upload record"); return $text; } /* Set default values */ if (empty($Level) && !is_numeric($Level) || $Level < 0) { $Level = 1; } /* first trim, then get rid of whitespaces before and after each comma letter */ $Accept = preg_replace('/\\s*,\\s*/', ',', trim($Accept)); $Reject = preg_replace('/\\s*,\\s*/', ',', trim($Reject)); /* Create the job: job "wget" */ $jobpk = JobAddJob($user_pk, "wget", $uploadpk); if (empty($jobpk) || $jobpk < 0) { $text = _("Failed to insert job record"); return $text; } $jq_args = "{$uploadpk} - {$GetURL} -l {$Level} "; if (!empty($Accept)) { $jq_args .= "-A {$Accept} "; } if (!empty($Reject)) { // reject the files index.html* $jq_args .= "-R {$Reject},index.html* "; } else { $jq_args .= "-R index.html* "; } $jobqueuepk = JobQueueAdd($jobpk, "wget_agent", $jq_args, NULL, NULL); if (empty($jobqueuepk)) { $text = _("Failed to insert task 'wget_agent' into job queue"); return $text; } global $Plugins; /* schedule agents */ $unpackplugin =& $Plugins[plugin_find_id("agent_unpack")]; $ununpack_jq_pk = $unpackplugin->AgentAdd($jobpk, $uploadpk, $ErrorMsg, array("wget_agent")); if ($ununpack_jq_pk < 0) { return $ErrorMsg; } $adj2nestplugin =& $Plugins[plugin_find_id("agent_adj2nest")]; $adj2nest_jq_pk = $adj2nestplugin->AgentAdd($jobpk, $uploadpk, $ErrorMsg, array()); if ($adj2nest_jq_pk < 0) { return $ErrorMsg; } AgentCheckBoxDo($jobpk, $uploadpk); $msg = ""; /** check if the scheudler is running */ $status = GetRunnableJobList(); if (empty($status)) { $msg .= _("Is the scheduler running? "); } $Url = Traceback_uri() . "?mod=showjobs&upload={$uploadpk}"; $text = _("The upload"); $text1 = _("has been queued. It is"); $msg .= "{$text} {$Name} {$text1} "; $keep = "<a href='{$Url}'>upload #" . $uploadpk . "</a>.\n"; print displayMessage($msg, $keep); return NULL; }
/** * \brief Generate the text for this plugin. */ function Output() { $SiteURI = Traceback_uri(); if ($this->State != PLUGIN_STATE_READY) { return; } $V = ""; switch ($this->OutputType) { case "XML": break; case "HTML": if (empty($_SESSION['User']) && plugin_find_id("auth") >= 0) { $text = _("Login"); $Login = "******"; } else { $Login = _("Login"); } $text1 = _("The FOSSology Toolset"); $text11 = _("FOSSology is a framework for software analysis tools. The current FOSSology tools can:"); $text12 = _("Find license references in software"); $text13 = _("Browse uploaded file hierarchies"); $text14 = _("Find copyrights, url's and email addresses"); $text15 = _("Classify licenses into user definable categories (aka buckets)"); $text16 = _("Browse package (rpm, apt) metadata"); $text2 = _("FOSSology's Graphical User Interface"); $text21 = _("This website is an interface into the FOSSology project. With it, you can:"); $text22 = _("Upload files to analyze."); $text23 = _("Unpack and store the data within the files for analysis. "); $text24 = _("Invoke specialized agents to scan and analyze the files. "); $text25 = _("Store and display the analyzed results. "); $text3 = _("How to Begin"); $text31 = _("The menu at the top contains all the primary capabilities of FOSSology. Most functions require you to log in before they can be accessed. The following functions are available without logging in:"); $text32 = _("If you don't know where to start, try browsing the currently uploaded projects. "); $text33 = _("Look through the uploaded projects for specific files. "); $text34 = _("If you log in, you can access additional capabilities. Depending on your account's access rights,"); $text35 = _("you may be able to upload files, schedule analysis tasks, or even add new users."); $text4 = _("Inside FOSSology"); $text41 = _("Some parts of FOSSology helpful to know about are:"); $text42 = _("Software Repository"); $text43 = _("- Stores files uploaded for analysis."); $text44 = _("Database"); $text45 = _("- Stores user accounts, file information, and analysis results."); $text46 = _("Agents"); $text47 = _("- Perform analysis of files and data found in the Software Repository and Database."); $text48 = _("Scheduler"); $text49 = _("- Runs the agents, making efficient use of available resources."); $text410 = _("Web GUI"); $text411 = _("- Provides user access to FOSSology."); $text412 = _("Command line utilities"); $text413 = _("- Provides scripting access to FOSSology."); $text5 = _("Need Some Help?"); $text51 = _("Now that you've been introduced to Fossology, try exploring it!"); $text52 = _("The following resources will provide additional help and information:"); $text53 = _("Help tab"); $text54 = _("- Select this website's Help tab for software-related help and tips."); $text55 = _("FOSSology web site"); $text56 = _("- Where you can find more information and get help on FOSSology."); $V .= "\n<table width='100%' border='0'>\n <tr> \n <td valign='top'> <h3><font color='#CC0000' face='Verdana, Arial, Helvetica, sans-serif'>{$text1}</font></h3>\n <blockquote> \n <p><font face='Arial, Helvetica, sans-serif'>{$text11} <br>\n <br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text12}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text13}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text14}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text15}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text16}<br>\n </font>\n <p>\n </blockquote></td>\n <td><img src='{$SiteURI}images/white.png'></td>\n </tr>\n</table>\n\n<table width='100%' border='0'>\n <tr> \n <td><img src='{$SiteURI}images/logo2.png' align='right'></td>\n <td valign='top'>\n <h3><font color='#CC0000' face='Verdana, Arial, Helvetica, sans-serif'>{$text2}</font></h3>\n <blockquote> \n <p> <font face='Arial, Helvetica, sans-serif'>{$text21}<br>\n <br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text22}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text23}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text24}<br>\n <img src='{$SiteURI}images/right-point-bullet.gif'>{$text25}</font><br>\n </p>\n </blockquote></td>\n </tr>\n</table>\n\n<table width='100%' border='0'>\n <tr> \n <td valign='top'> <h3><font color='#CC0000' face='Verdana, Arial, Helvetica, sans-serif'>{$text3}</font></h3>\n <blockquote> \n <p><font face='Arial, Helvetica, sans-serif'> {$text31}<br>\n <br>\n <strong><em>{$Login}:</em></strong> {$text34}<br>\n {$text35}</font></p>\n </blockquote></td>\n </tr>\n</table>\n\n<table width='100%' border='0'>\n <tr> \n <td valign='top'> <h3><font color='#CC0000' face='Verdana, Arial, Helvetica, sans-serif'>{$text4}</font></h3>\n <blockquote> \n <p><font face='Arial, Helvetica, sans-serif'>{$text41}<br>\n <br>\n <em><strong>{$text42}</strong></em> {$text43}<br>\n <em><strong>{$text44}</strong></em> {$text45}<br>\n <em><strong>{$text46}</strong></em> {$text47}<br>\n <em><strong>{$text48}</strong></em> {$text49}<br>\n <em><strong>{$text410}</strong></em> ­ {$text411}<br>\n <em><strong>{$text412}</strong></em> ­ {$text413}<br>\n </p>\n </blockquote></td>\n <td><img src='{$SiteURI}images/fossology-flow4.png'></td>\n </tr>\n</table>\n\n<table width='100%' border='0'>\n <tr> \n <td valign='top'> <h3><font color='#CC0000' face='Verdana, Arial, Helvetica, sans-serif'><img src='{$SiteURI}images/white.png' align='left'>{$text5}</font></h3>\n <blockquote> \n <blockquote> \n <p><font face='Arial, Helvetica, sans-serif'>{$text51}<br>\n {$text52}\n </font></p>\n <blockquote>\n\t\t <!-- <font face='Arial, Helvetica, sans-serif'><em><strong>{$text53}</strong></em>{$text54}\n </font><br>-->\n \n\t\t\t <font face='Arial, Helvetica, sans-serif'><em><strong><a href='http://fossology.org/'>{$text55}</a></strong></em> {$text56}<br>\n </font> \n </blockquote>\n </blockquote>\n </blockquote></td>\n </tr>\n</table>\n"; break; case "Text": break; default: break; } if (!$this->OutputToStdout) { return $V; } print $V; return; }
/** * \brief Given one object (file or URL), upload it. * * \param $FolderPath - folder path * \param $UploadArchive - upload file(absolute path) or url * \param $UploadName - uploaded file/dir name * \param $UploadDescription - upload description * * \return 1: error, 0: success */ function UploadOne($FolderPath, $UploadArchive, $UploadName, $UploadDescription, $TarSource = NULL) { global $Verbose; global $Test; global $QueueList; global $fossjobs_command; global $public_flag; global $SysConf; global $PG_CONN; global $VCS; global $vcsuser; global $vcspass; global $TarExcludeList; $jobqueuepk = 0; if (empty($UploadName)) { $text = "UploadName is empty\n"; echo $text; return 1; } $user_pk = $SysConf['auth']['UserId']; $group_pk = $SysConf['auth']['GroupId']; /* Get the user record and check the PLUGIN_DB_ level to make sure they have at least write access */ $UsersRow = GetSingleRec("users", "where user_pk={$user_pk}"); if ($UsersRow["user_perm"] < PLUGIN_DB_WRITE) { print "You have no permission to upload files into FOSSology\n"; return 1; } /* Get the folder's primary key */ $root_folder_fk = $UsersRow["root_folder_fk"]; global $OptionA; /* Should it use bucket names? */ if ($OptionA) { global $bucket_size; $FolderPath .= "/" . GetBucketFolder($UploadName, $bucket_size); } $FolderPk = GetFolder($FolderPath, $root_folder_fk); if ($FolderPk == 1) { print " Uploading to folder: 'Software Repository'\n"; } else { print " Uploading to folder: '{$FolderPath}'\n"; } print " Uploading as '{$UploadName}'\n"; if (!empty($UploadDescription)) { print " Upload description: '{$UploadDescription}'\n"; } $Mode = 1 << 3; // code for "it came from web upload" /* Create the upload for the file */ if ($Verbose) { print "JobAddUpload({$user_pk}, {$group_pk}, {$UploadName},{$UploadArchive},{$UploadDescription},{$Mode},{$FolderPk}, {$public_flag});\n"; } if (!$Test) { $Src = $UploadArchive; if (!empty($TarSource)) { $Src = $TarSource; } $UploadPk = JobAddUpload($user_pk, $group_pk, $UploadName, $Src, $UploadDescription, $Mode, $FolderPk, $public_flag); print " UploadPk is: '{$UploadPk}'\n"; } /* Prepare the job: job "wget" */ if ($Verbose) { print "JobAddJob({$user_pk}, {$group_pk}, wget, {$UploadPk});\n"; } if (!$Test) { $jobpk = JobAddJob($user_pk, $group_pk, "wget", $UploadPk); if (empty($jobpk) || $jobpk < 0) { $text = _("Failed to insert job record"); echo $text; return 1; } } $jq_args = "{$UploadPk} - {$Src}"; if ($TarExcludeList) { $jq_args .= " " . $TarExcludeList; } if ($VCS) { $jq_args .= " " . $VCS; } // add flags when upload from version control system if ($vcsuser && $vcspass) { $jq_args .= " --username {$vcsuser} --password {$vcspass} "; } if ($Verbose) { print "JobQueueAdd({$jobpk}, wget_agent, {$jq_args}, no, NULL);\n"; } if (!$Test) { $jobqueuepk = JobQueueAdd($jobpk, "wget_agent", $jq_args, "no", NULL); if (empty($jobqueuepk)) { $text = _("Failed to insert task 'wget' into job queue"); echo $text; return 1; } } /* schedule agents */ global $Plugins; if ($Verbose) { print "AgentAdd wget_agent and dj2nest.\n"; } if (!$Test) { $unpackplugin =& $Plugins[plugin_find_id("agent_unpack")]; $ununpack_jq_pk = $unpackplugin->AgentAdd($jobpk, $UploadPk, $ErrorMsg, array("wget_agent")); if ($ununpack_jq_pk < 0) { echo $ErrorMsg; return 1; } $adj2nestplugin =& $Plugins[plugin_find_id("agent_adj2nest")]; $adj2nest_jq_pk = $adj2nestplugin->AgentAdd($jobpk, $UploadPk, $ErrorMsg, array()); if ($adj2nest_jq_pk < 0) { echo $ErrorMsg; return 1; } } if (!empty($QueueList)) { switch ($QueueList) { case 'ALL': case 'all': $Cmd = "{$fossjobs_command} -U '{$UploadPk}'"; break; default: $Cmd = "{$fossjobs_command} -U '{$UploadPk}' -A '{$QueueList}'"; break; } if ($Verbose) { print "CMD={$Cmd}\n"; } if (!$Test) { system($Cmd); } } else { /* No other agents other than unpack scheduled, attach to unpack*/ } global $OptionS; /* Should it run synchronously? */ if ($OptionS) { $working = true; $waitCount = 0; while ($working && $waitCount++ < 30) { sleep(3); $SQL = "select * from jobqueue inner join job on job.job_pk = jobqueue.jq_job_fk where job_upload_fk = '{$UploadPk}' and jq_end_bits = 0 and jq_type = 'wget_agent'"; $result = pg_query($PG_CONN, $SQL); DBCheckResult($result, $SQL, __FILE__, __LINE__); $row_count = pg_num_rows($result); pg_free_result($result); if ($row_count == 0) { $working = false; } } if ($working) { echo "Gave up waiting for copy completion. Is the scheduler running?"; return 1; } } }
/** * @brief extends standard Output to handle empty uploads */ function Output() { if ($this->invalidParm) { $this->vars['content'] = 'This upload contains no files!<br><a href="' . Traceback_uri() . '?mod=browse">Go back to browse view</a>'; return $this->render("include/base.html.twig"); } $uploadId = GetParm("upload", PARM_INTEGER); if (empty($uploadId)) { return new Response("", Response::HTTP_BAD_REQUEST); } $uploadTreeId = GetParm("item", PARM_INTEGER); if (empty($uploadTreeId)) { return new Response("", Response::HTTP_BAD_REQUEST); } $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $lastItem = GetParm("lastItem", PARM_INTEGER); if (!empty($lastItem)) { $this->updateLastItem($userId, $groupId, $lastItem); } $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId); $itemTreeBounds = $this->uploadDao->getItemTreeBounds($uploadTreeId, $uploadTreeTableName); $this->vars['micromenu'] = Dir2Browse('license', $uploadTreeId, NULL, $showBox = 0, "View", -1, '', '', $uploadTreeTableName); global $Plugins; /** @var ui_view $view */ $view =& $Plugins[plugin_find_id("view")]; $licenseId = GetParm("licenseId", PARM_INTEGER); $selectedAgentId = GetParm("agentId", PARM_INTEGER); $highlightId = GetParm("highlightId", PARM_INTEGER); $clearingId = GetParm("clearingId", PARM_INTEGER); if ($clearingId !== null) { $highlightId = -1; } else { if ($highlightId !== null) { $clearingId = -1; } } $baseUri = Traceback_uri(); $this->vars['baseuri'] = $baseUri; $this->vars['uri'] = $baseUri . "?mod=" . $this->Name . Traceback_parm_keep(array('upload', 'folder')); $this->vars['bulkHistoryHighlightUri'] = $this->vars['uri']; $this->vars['optionName'] = "skipFile"; $this->vars['formName'] = "uiClearingForm"; $this->vars['ajaxAction'] = "setNextPrev"; $highlights = $this->getSelectedHighlighting($itemTreeBounds, $licenseId, $selectedAgentId, $highlightId, $clearingId, $uploadId); $isSingleFile = !$itemTreeBounds->containsFiles(); $hasWritePermission = $this->uploadDao->isEditable($uploadId, $groupId); $clearingDecisions = null; if ($isSingleFile || $hasWritePermission) { $clearingDecisions = $this->clearingDao->getFileClearings($itemTreeBounds, $groupId, false); } if ($isSingleFile && $hasWritePermission) { $this->vars['bulkUri'] = Traceback_uri() . "?mod=popup-license"; $licenseArray = $this->licenseDao->getLicenseArray($groupId); // $clearingDecision = $this->clearingDao->getRelevantClearingDecision($itemTreeBounds, $groupId); list($addedResults, $removedResults) = $this->clearingDecisionEventProcessor->getCurrentClearings($itemTreeBounds, $groupId, LicenseMap::CONCLUSION); if (count($addedResults) + count($removedResults) > 0) { array_unshift($licenseArray, array('id' => 0, 'fullname' => '', 'shortname' => '------')); } /** @var ClearingResult $result */ foreach ($removedResults as $result) { array_unshift($licenseArray, array('id' => $result->getLicenseId(), 'fullname' => $result->getLicenseFullName(), 'shortname' => $result->getLicenseShortName())); } /** @var ClearingResult $result */ foreach ($addedResults as $result) { array_unshift($licenseArray, array('id' => $result->getLicenseId(), 'fullname' => $result->getLicenseFullName(), 'shortname' => $result->getLicenseShortName())); } $this->vars['licenseArray'] = $licenseArray; } elseif ($isSingleFile) { $this->vars['auditDenied'] = true; } $clearingHistory = array(); $selectedClearingType = false; if ($hasWritePermission) { $clearingHistory = $this->getClearingHistory($clearingDecisions); } if (count($clearingHistory) > 0) { $selectedClearingType = $this->decisionTypes->getTypeByName($clearingHistory[0]['type']); } $bulkHistory = $this->clearingDao->getBulkHistory($itemTreeBounds, $groupId); $ModBack = GetParm("modback", PARM_STRING) ?: "license"; list($pageMenu, $textView) = $view->getView(NULL, $ModBack, 0, "", $highlights, false, true); $this->vars['uploadId'] = $uploadId; $this->vars['itemId'] = $uploadTreeId; $this->vars['pageMenu'] = $pageMenu; $this->vars['textView'] = $textView; $this->vars['legendData'] = $this->highlightRenderer->getLegendData($selectedAgentId || $clearingId); $this->vars['clearingTypes'] = $this->decisionTypes->getMap(); $this->vars['selectedClearingType'] = $selectedClearingType; $this->vars['tmpClearingType'] = $this->clearingDao->isDecisionWip($uploadTreeId, $groupId); $this->vars['clearingHistory'] = $clearingHistory; $this->vars['bulkHistory'] = $bulkHistory; $noLicenseUploadTreeView = new UploadTreeProxy($uploadId, $options = array(UploadTreeProxy::OPT_SKIP_THESE => "noLicense", UploadTreeProxy::OPT_GROUP_ID => $groupId), $uploadTreeTableName, $viewName = 'no_license_uploadtree' . $uploadId); $filesOfInterest = $noLicenseUploadTreeView->count(); $nonClearedUploadTreeView = new UploadTreeProxy($uploadId, $options = array(UploadTreeProxy::OPT_SKIP_THESE => "alreadyCleared", UploadTreeProxy::OPT_GROUP_ID => $groupId), $uploadTreeTableName, $viewName = 'already_cleared_uploadtree' . $uploadId); $filesToBeCleared = $nonClearedUploadTreeView->count(); $filesAlreadyCleared = $filesOfInterest - $filesToBeCleared; $this->vars['message'] = _("Cleared") . ": {$filesAlreadyCleared}/{$filesOfInterest}"; return $this->render("ui-clearing-view.html.twig"); }