/**
  * \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 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, "", ",") . "&nbsp;";
             //$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 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 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":
             $Filename = GetParm("filename", PARM_STRING);
             $Uri = preg_replace("/&filename=[^&]*/", "", Traceback());
             /* Prompt for the string to search for */
             $V .= "<form action='{$Uri}' method='POST'>\n";
             $V .= "<ul>\n";
             $V .= "<li>Enter the string to search for:<P>";
             $V .= "<INPUT type='text' name='filename' size='40' value='" . htmlentities($Filename) . "'>\n";
             $V .= "</ul>\n";
             $V .= "<input type='submit' value='Search!'>\n";
             $V .= "</form>\n";
             if (!empty($Filename)) {
                 /* 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 '%{$Filename}%';";
                 $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 {$Filename} 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";
                     }
                     pg_free_result($result);
                     $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>";
                 }
             }
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }