/**
  * \brief testing from GetFileLicenses_tring
  * in this test case, this pfile have only one license
  */
 function testGetFileLicenses_string()
 {
     print "test function GetFileLicenses_tring()\n";
     global $PG_CONN;
     global $uploadtree_pk_parent;
     global $pfile_pk_parent;
     global $agent_pk;
     $license_string = GetFileLicenses_string($agent_pk, '', $uploadtree_pk_parent, $this->uploadtree_tablename);
     /** the expected license value */
     $sql = "SELECT rf_shortname from license_ref where rf_pk = 1;";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $row = pg_fetch_assoc($result);
     $license_value_expected = $row['rf_shortname'];
     pg_free_result($result);
     $this->assertEquals($license_value_expected, $license_string);
 }
 /**
  * \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 Display the loaded menu and plugins.
  */
 function Output()
 {
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     $rf_shortname = GetParm("lic", PARM_RAW);
     $tag_pk = GetParm("tag", PARM_INTEGER);
     $Excl = GetParm("excl", PARM_RAW);
     $Exclic = GetParm("exclic", PARM_RAW);
     if (empty($uploadtree_pk) || empty($rf_shortname)) {
         $text = _("is missing required parameters.");
         return $this->Name . " {$text}";
     }
     $Max = 50;
     $Page = GetParm("page", PARM_INTEGER);
     if (empty($Page)) {
         $Page = 0;
     }
     // Get upload_pk and $uploadtree_tablename
     $UploadtreeRec = GetSingleRec("uploadtree", "where uploadtree_pk={$uploadtree_pk}");
     global $container;
     /** @var UploadDao */
     $uploadDao = $container->get('dao.upload');
     $uploadtree_tablename = $uploadDao->getUploadtreeTableName($UploadtreeRec['upload_fk']);
     // micro menus
     $V = menu_to_1html(menu_find($this->Name, $MenuDepth), 0);
     /* Load licenses */
     $Offset = $Page < 0 ? 0 : $Page * $Max;
     $order = "";
     $PkgsOnly = false;
     // Count is uploadtree recs, not pfiles
     $agentId = GetParm('agentId', PARM_INTEGER);
     if (empty($agentId)) {
         $agentId = "any";
     }
     $CountArray = $this->countFilesWithLicense($agentId, $rf_shortname, $uploadtree_pk, $tag_pk, $uploadtree_tablename);
     if (empty($CountArray)) {
         $V .= _("<b> No files found for license {$rf_shortname} !</b>\n");
     } else {
         $Count = $CountArray['count'];
         $Unique = $CountArray['unique'];
         $text = _("files found");
         $text2 = _("with license");
         $V .= "{$Unique} {$text} {$text2} <b>{$rf_shortname}</b>";
         if ($Count < $Max) {
             $Max = $Count;
         }
         $limit = $Page < 0 ? "ALL" : $Max;
         $order = " order by ufile_name asc";
         /** should delete $filesresult yourself */
         $filesresult = GetFilesWithLicense($agentId, $rf_shortname, $uploadtree_pk, $PkgsOnly, $Offset, $limit, $order, $tag_pk, $uploadtree_tablename);
         $NumFiles = pg_num_rows($filesresult);
         $file_result_temp = pg_fetch_all($filesresult);
         $sorted_file_result = array();
         // the final file list will display
         $max_num = $NumFiles;
         /** sorting by ufile_name from DB, then reorder the duplicates indented */
         for ($i = 0; $i < $max_num; $i++) {
             $row = $file_result_temp[$i];
             if (empty($row)) {
                 continue;
             }
             array_push($sorted_file_result, $row);
             for ($j = $i + 1; $j < $max_num; $j++) {
                 $row_next = $file_result_temp[$j];
                 if (!empty($row_next) && $row['pfile_fk'] == $row_next['pfile_fk']) {
                     array_push($sorted_file_result, $row_next);
                     $file_result_temp[$j] = null;
                 }
             }
         }
         $text = _("Display");
         $text1 = _("excludes");
         $text2 = _("files with these extensions");
         if (!empty($Excl)) {
             $V .= "<br>{$text} <b>{$text1}</b> {$text2}: {$Excl}";
         }
         $text2 = _("files with these licenses");
         if (!empty($Exclic)) {
             $V .= "<br>{$text} <b>{$text1}</b> {$text2}: {$Exclic}";
         }
         /* Get the page menu */
         if ($Max > 0 && $Count >= $Max && $Page >= 0) {
             $VM = "<P />\n" . MenuEndlessPage($Page, intval(($Count + $Offset) / $Max)) . "<P />\n";
             $V .= $VM;
         } else {
             $VM = "";
         }
         /* Offset is +1 to start numbering from 1 instead of zero */
         $RowNum = $Offset;
         $LinkLast = "view-license";
         $ShowBox = 1;
         $ShowMicro = NULL;
         // base url
         $ushortname = rawurlencode($rf_shortname);
         $baseURL = "?mod=" . $this->Name . "&item={$uploadtree_pk}&lic={$ushortname}&page=-1";
         $V .= "<table>";
         $text = _("File");
         $V .= "<tr><th>{$text}</th><th>&nbsp";
         $LastPfilePk = -1;
         $ExclArray = explode(":", $Excl);
         $ExclicArray = explode(":", $Exclic);
         foreach ($sorted_file_result as $row) {
             $pfile_pk = $row['pfile_fk'];
             $licstring = GetFileLicenses_string($row['agent_pk'], $pfile_pk, $row['uploadtree_pk'], $uploadtree_tablename);
             $URLlicstring = urlencode($licstring);
             // Allow user to exclude files with this extension
             $FileExt = GetFileExt($row['ufile_name']);
             $URL = $baseURL;
             if (!empty($Excl)) {
                 $URL .= "&excl={$Excl}:{$FileExt}";
             } else {
                 $URL .= "&excl={$FileExt}";
             }
             if (!empty($Exclic)) {
                 $URL .= "&exclic=" . urlencode($Exclic);
             }
             $text = _("Exclude this file type.");
             $Header = "<a href={$URL}>{$text}</a>";
             /* Allow user to exclude files with this exact license list */
             $URL = $baseURL;
             if (!empty($Exclic)) {
                 $URL .= "&exclic=" . urlencode($Exclic) . ":" . $URLlicstring;
             } else {
                 $URL .= "&exclic={$URLlicstring}";
             }
             if (!empty($Excl)) {
                 $URL .= "&excl={$Excl}";
             }
             $text = _("Exclude files with license");
             $Header .= "<br><a href={$URL}>{$text}: {$licstring}.</a>";
             $excludeByType = $Excl && in_array($FileExt, $ExclArray);
             $excludeByLicense = $Exclic && in_array($licstring, $ExclicArray);
             if (!empty($licstring) && !$excludeByType && !$excludeByLicense) {
                 $V .= "<tr><td>";
                 /* Tack on pfile to url - information only */
                 $LinkLastpfile = $LinkLast . "&pfile={$pfile_pk}";
                 if ($LastPfilePk == $pfile_pk) {
                     $indent = "<div style='margin-left:2em;'>";
                     $outdent = "</div>";
                 } else {
                     $indent = "";
                     $outdent = "";
                 }
                 $V .= $indent;
                 $V .= Dir2Browse("browse", $row['uploadtree_pk'], $LinkLastpfile, $ShowBox, $ShowMicro, ++$RowNum, $Header, '', $uploadtree_tablename);
                 $V .= $outdent;
                 $V .= "</td>";
                 $V .= "<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>";
                 $V .= "<td>{$row['agent_name']}: {$licstring}</td></tr>";
                 $V .= "<tr><td colspan=3><hr></td></tr>";
             }
             $LastPfilePk = $pfile_pk;
         }
         pg_free_result($filesresult);
         $V .= "</table>";
         if (!empty($VM)) {
             $V .= $VM . "\n";
         }
     }
     return $V;
 }
/**
 * \brief get nomos license list of one specified uploadtree_id
 *
 * \param $uploadtree_pk - uploadtree id
 * \param $upload_pk - upload id
 * \param $container - include container or not, 1: yes, 0: no (default)
 */
function GetLicenseList($uploadtree_pk, $upload_pk, $container = 0)
{
    global $PG_CONN;
    if (empty($uploadtree_pk)) {
        /* Find the uploadtree_pk for this upload so that it can be used in the browse link */
        $uploadtreeRec = GetSingleRec("uploadtree", "where parent is NULL and upload_fk='{$upload_pk}'");
        $uploadtree_pk = $uploadtreeRec['uploadtree_pk'];
    }
    //  print "Upload ID:$upload_pk; Uploadtree ID:$uploadtree_pk\n";
    /* get last nomos agent_pk that has data for this upload */
    $Agent_name = "nomos";
    $AgentRec = AgentARSList("nomos_ars", $upload_pk, 1);
    $agent_pk = $AgentRec[0]["agent_fk"];
    if ($AgentRec === false) {
        echo _("No data available");
        return;
    }
    /* get the top of tree */
    $sql = "SELECT upload_fk, lft, rgt from uploadtree where uploadtree_pk='{$uploadtree_pk}';";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    $toprow = pg_fetch_assoc($result);
    pg_free_result($result);
    $uploadtree_tablename = GetUploadtreeTableName($toprow['upload_fk']);
    /* loop through all the records in this tree */
    $sql = "select uploadtree_pk, ufile_name, lft, rgt from {$uploadtree_tablename} \n              where upload_fk='{$toprow['upload_fk']}' \n                    and lft>'{$toprow['lft']}'  and rgt<'{$toprow['rgt']}'\n                    and ((ufile_mode & (1<<28)) = 0)";
    $container_sql = " and ((ufile_mode & (1<<29)) = 0)";
    /* include container or not */
    if (empty($container)) {
        $sql .= $container_sql;
        // do not include container
    }
    $sql .= "order by uploadtree_pk";
    $outerresult = pg_query($PG_CONN, $sql);
    DBCheckResult($outerresult, $sql, __FILE__, __LINE__);
    /* Select each uploadtree row in this tree, write out text:
     * filepath : license list
     * e.g. Pound-2.4.tgz/Pound-2.4/svc.c: GPL_v3+, Indemnity
     */
    while ($row = pg_fetch_assoc($outerresult)) {
        $filepatharray = Dir2Path($row['uploadtree_pk'], $uploadtree_tablename);
        $filepath = "";
        foreach ($filepatharray as $uploadtreeRow) {
            if (!empty($filepath)) {
                $filepath .= "/";
            }
            $filepath .= $uploadtreeRow['ufile_name'];
        }
        $V = $filepath . ": " . GetFileLicenses_string($agent_pk, 0, $row['uploadtree_pk'], $uploadtree_tablename);
        #$V = $filepath;
        print "{$V}";
        print "\n";
    }
    pg_free_result($outerresult);
}
示例#5
0
 /**
  * \brief This function returns the scheduler status.
  */
 function Output()
 {
     global $SysConf;
     global $PG_CONN;
     if (!$PG_CONN) {
         echo _("NO DB connection");
     }
     if ($this->State != PLUGIN_STATE_READY) {
         return 0;
     }
     $V = "";
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     if (empty($uploadtree_pk)) {
         return;
     }
     $upload_pk = GetParm("upload", PARM_INTEGER);
     if (empty($upload_pk)) {
         return;
     }
     if (!$this->uploadDao->isAccessible($upload_pk, Auth::getGroupId())) {
         $text = _("Permission Denied");
         return "<h2>{$text}</h2>";
     }
     $dltext = GetParm("output", PARM_STRING) == 'dltext';
     /* get last nomos agent_pk that has data for this upload */
     $AgentRec = AgentARSList("nomos_ars", $upload_pk, 1);
     $agent_pk = $AgentRec[0]["agent_fk"];
     if ($AgentRec === false) {
         return _("No data available");
     }
     /* how many lines of data do you want to display */
     $NomostListNum = @$SysConf['SYSCONFIG']['NomostListNum'];
     /* get the top of tree */
     $toprow = $this->uploadDao->getUploadEntry($uploadtree_pk);
     /* loop through all the records in this tree */
     $sql = "select uploadtree_pk, ufile_name, lft, rgt from uploadtree\n              where upload_fk='{$toprow['upload_fk']}' \n                    and lft>'{$toprow['lft']}'  and rgt<'{$toprow['rgt']}'\n                    and (ufile_mode & (3<<28)) = 0 limit {$NomostListNum}";
     $outerresult = pg_query($PG_CONN, $sql);
     DBCheckResult($outerresult, $sql, __FILE__, __LINE__);
     /* Select each uploadtree row in this tree, write out text:
      * filepath : license list
      * e.g. Pound-2.4.tgz/Pound-2.4/svc.c: GPL_v3+, Indemnity
      */
     $uploadtreeTablename = $this->uploadDao->getUploadtreeTableName($toprow['upload_fk']);
     $lines = array();
     while ($row = pg_fetch_assoc($outerresult)) {
         $filepatharray = Dir2Path($row['uploadtree_pk'], $uploadtreeTablename);
         $filepath = "";
         foreach ($filepatharray as $uploadtreeRow) {
             if (!empty($filepath)) {
                 $filepath .= "/";
             }
             $filepath .= $uploadtreeRow['ufile_name'];
         }
         $lines[] = $filepath . ": " . GetFileLicenses_string($agent_pk, 0, $row['uploadtree_pk'], $uploadtreeTablename);
     }
     $RealNumber = pg_num_rows($outerresult);
     pg_free_result($outerresult);
     if ($RealNumber == $NomostListNum) {
         $V .= _("<br><b>Warning: Only the last {$NomostListNum} lines are displayed.  To see the whole list, run fo_nomos_license_list from the command line.</b><br>");
     }
     if ($dltext) {
         $request = $this->getRequest();
         $itemId = intval($request->get('item'));
         $path = Dir2Path($itemId, $uploadtreeTablename);
         $fileName = $path[count($path) - 1]['ufile_name'] . ".txt";
         $headers = array("Content-Type" => "text", "Content-Disposition" => "attachment; filename=\"{$fileName}\"");
         $response = new Response(implode("\n", $lines), Response::HTTP_OK, $headers);
         return $response;
     } else {
         return $V . '<pre>' . implode("\n", $lines) . '</pre>';
     }
 }
 /**
  * \brief Display the loaded menu and plugins.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     global $Plugins;
     $V = "";
     $Time = time();
     $Max = 50;
     /*  Input parameters */
     $nomosagent_pk = GetParm("napk", PARM_INTEGER);
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     $rf_shortname = GetParm("lic", PARM_RAW);
     $tag_pk = GetParm("tag", PARM_INTEGER);
     $Excl = GetParm("excl", PARM_RAW);
     $Exclic = GetParm("exclic", PARM_RAW);
     $rf_shortname = rawurldecode($rf_shortname);
     if (empty($uploadtree_pk) || empty($rf_shortname)) {
         $text = _("is missing required parameters.");
         echo $this->Name . " {$text}";
         return;
     }
     $Page = GetParm("page", PARM_INTEGER);
     if (empty($Page)) {
         $Page = 0;
     }
     // Get upload_pk and $uploadtree_tablename
     $UploadtreeRec = GetSingleRec("uploadtree", "where uploadtree_pk={$uploadtree_pk}");
     $UploadRec = GetSingleRec("upload", "where upload_pk={$UploadtreeRec['upload_fk']}");
     $uploadtree_tablename = $UploadRec['uploadtree_tablename'];
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             // micro menus
             $V .= menu_to_1html(menu_find($this->Name, $MenuDepth), 0);
             /* Load licenses */
             $Offset = $Page < 0 ? 0 : $Page * $Max;
             $order = "";
             $PkgsOnly = false;
             $CheckOnly = false;
             // Count is uploadtree recs, not pfiles
             $CountArray = CountFilesWithLicense($nomosagent_pk, $rf_shortname, $uploadtree_pk, $PkgsOnly, $CheckOnly, $tag_pk, $uploadtree_tablename);
             $Count = $CountArray['count'];
             $Unique = $CountArray['unique'];
             $text = _("files found");
             $text1 = _("unique");
             $text2 = _("with license");
             $V .= "{$Count} {$text} ({$Unique} {$text1}) {$text2} <b>{$rf_shortname}</b>";
             if ($Count < $Max) {
                 $Max = $Count;
             }
             $limit = $Page < 0 ? "ALL" : $Max;
             $order = " order by ufile_name asc";
             /** should delete $filesresult yourself */
             $filesresult = GetFilesWithLicense($nomosagent_pk, $rf_shortname, $uploadtree_pk, $PkgsOnly, $Offset, $limit, $order, $tag_pk, $uploadtree_tablename);
             $NumFiles = pg_num_rows($filesresult);
             $file_result_temp = pg_fetch_all($filesresult);
             $sorted_file_result = array();
             // the final file list will display
             $max_num = $NumFiles;
             /** sorting by ufile_name from DB, then reorder the duplicates indented */
             for ($i = 0; $i < $max_num; $i++) {
                 $row = $file_result_temp[$i];
                 if (empty($row)) {
                     continue;
                 }
                 array_push($sorted_file_result, $row);
                 for ($j = $i + 1; $j < $max_num; $j++) {
                     $row_next = $file_result_temp[$j];
                     if (!empty($row_next) && $row['pfile_fk'] == $row_next['pfile_fk']) {
                         array_push($sorted_file_result, $row_next);
                         $file_result_temp[$j] = null;
                     }
                 }
             }
             $text = _("Display");
             $text1 = _("excludes");
             $text2 = _("files with these extensions");
             if (!empty($Excl)) {
                 $V .= "<br>{$text} <b>{$text1}</b> {$text2}: {$Excl}";
             }
             $text2 = _("files with these licenses");
             if (!empty($Exclic)) {
                 $V .= "<br>{$text} <b>{$text1}</b> {$text2}: {$Exclic}";
             }
             /* Get the page menu */
             if ($Max > 0 && $Count >= $Max && $Page >= 0) {
                 $VM = "<P />\n" . MenuEndlessPage($Page, intval(($Count + $Offset) / $Max)) . "<P />\n";
                 $V .= $VM;
             } else {
                 $VM = "";
             }
             /* Offset is +1 to start numbering from 1 instead of zero */
             $RowNum = $Offset;
             $LinkLast = "view-license&napk={$nomosagent_pk}";
             $ShowBox = 1;
             $ShowMicro = NULL;
             // base url
             $ushortname = rawurlencode($rf_shortname);
             $baseURL = "?mod=" . $this->Name . "&napk={$nomosagent_pk}&item={$uploadtree_pk}&lic={$ushortname}&page=-1";
             $V .= "<table>";
             $text = _("File");
             $V .= "<tr><th>{$text}</th><th>&nbsp";
             $LastPfilePk = -1;
             $ExclArray = explode(":", $Excl);
             $ExclicArray = explode(":", $Exclic);
             foreach ($sorted_file_result as $row) {
                 $pfile_pk = $row['pfile_fk'];
                 $licstring = GetFileLicenses_string($nomosagent_pk, $pfile_pk, $row['uploadtree_pk'], $uploadtree_tablename);
                 $URLlicstring = urlencode($licstring);
                 // Allow user to exclude files with this extension
                 $FileExt = GetFileExt($row['ufile_name']);
                 $URL = $baseURL;
                 if (!empty($Excl)) {
                     $URL .= "&excl={$Excl}:{$FileExt}";
                 } else {
                     $URL .= "&excl={$FileExt}";
                 }
                 if (!empty($Exclic)) {
                     $URL .= "&exclic=" . urlencode($Exclic);
                 }
                 $text = _("Exclude this file type.");
                 $Header = "<a href={$URL}>{$text}</a>";
                 /* Allow user to exclude files with this exact license list */
                 $URL = $baseURL;
                 if (!empty($Exclic)) {
                     $URL .= "&exclic=" . urlencode($Exclic) . ":" . $URLlicstring;
                 } else {
                     $URL .= "&exclic={$URLlicstring}";
                 }
                 if (!empty($Excl)) {
                     $URL .= "&excl={$Excl}";
                 }
                 $text = _("Exclude files with license");
                 $Header .= "<br><a href={$URL}>{$text}: {$licstring}.</a>";
                 $ok = true;
                 /* exclude by type */
                 if ($Excl) {
                     if (in_array($FileExt, $ExclArray)) {
                         $ok = false;
                     }
                 }
                 /* exclude by license */
                 if ($Exclic) {
                     if (in_array($licstring, $ExclicArray)) {
                         $ok = false;
                     }
                 }
                 if (empty($licstring)) {
                     $ok = false;
                 }
                 if ($ok) {
                     $V .= "<tr><td>";
                     /* Tack on pfile to url - information only */
                     $LinkLastpfile = $LinkLast . "&pfile={$pfile_pk}";
                     if ($LastPfilePk == $pfile_pk) {
                         $indent = "<div style='margin-left:2em;'>";
                         $outdent = "</div>";
                     } else {
                         $indent = "";
                         $outdent = "";
                     }
                     $V .= $indent;
                     $V .= Dir2Browse("browse", $row['uploadtree_pk'], $LinkLastpfile, $ShowBox, $ShowMicro, ++$RowNum, $Header, '', $uploadtree_tablename);
                     $V .= $outdent;
                     $V .= "</td>";
                     $V .= "<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>";
                     // spaces to seperate licenses
                     // show the entire license list as a single string with links to the files
                     // in this container with that license.
                     $V .= "<td>{$licstring}</td></tr>";
                     $V .= "<tr><td colspan=3><hr></td></tr>";
                     // separate files
                 }
                 $LastPfilePk = $pfile_pk;
             }
             pg_free_result($filesresult);
             $V .= "</table>";
             if (!empty($VM)) {
                 $V .= $VM . "\n";
             }
             $V .= "<hr>\n";
             $Time = time() - $Time;
             $text = _("Elapsed time");
             $text1 = _("seconds");
             $V .= "<small>{$text}: {$Time} {$text1}</small>\n";
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }
 /**
  * \brief This function returns the scheduler status.
  */
 function Output()
 {
     global $SysConf;
     global $PG_CONN;
     if (!$PG_CONN) {
         echo _("NO DB connection");
     }
     if ($this->State != PLUGIN_STATE_READY) {
         return 0;
     }
     $V = "";
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     if (empty($uploadtree_pk)) {
         return;
     }
     $upload_pk = GetParm("upload", PARM_INTEGER);
     if (empty($upload_pk)) {
         return;
     }
     $UploadPerm = GetUploadPerm($upload_pk);
     if ($UploadPerm < PERM_READ) {
         $text = _("Permission Denied");
         echo "<h2>{$text}<h2>";
         return;
     }
     if (GetParm("output", PARM_STRING) == 'dltext') {
         $dltext = true;
     } else {
         $dltext = false;
     }
     /* get last nomos agent_pk that has data for this upload */
     $Agent_name = "nomos";
     $AgentRec = AgentARSList("nomos_ars", $upload_pk, 1);
     $agent_pk = $AgentRec[0]["agent_fk"];
     if ($AgentRec === false) {
         echo _("No data available");
         return;
     }
     /* how many lines of data do you want to display */
     $NomostListNum = @$SysConf['SYSCONFIG']['NomostListNum'];
     /* get the top of tree */
     $sql = "SELECT upload_fk, lft, rgt from uploadtree where uploadtree_pk='{$uploadtree_pk}'";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $toprow = pg_fetch_assoc($result);
     pg_free_result($result);
     /* loop through all the records in this tree */
     $sql = "select uploadtree_pk, ufile_name, lft, rgt from uploadtree\n              where upload_fk='{$toprow['upload_fk']}' \n                    and lft>'{$toprow['lft']}'  and rgt<'{$toprow['rgt']}'\n                    and ((ufile_mode & (1<<28)) = 0) and ((ufile_mode & (1<<29)) = 0) limit {$NomostListNum}";
     $outerresult = pg_query($PG_CONN, $sql);
     DBCheckResult($outerresult, $sql, __FILE__, __LINE__);
     /* Select each uploadtree row in this tree, write out text:
      * filepath : license list
      * e.g. Pound-2.4.tgz/Pound-2.4/svc.c: GPL_v3+, Indemnity
      */
     $uploadtree_tablename = GetUploadtreeTableName($toprow['upload_fk']);
     while ($row = pg_fetch_assoc($outerresult)) {
         $filepatharray = Dir2Path($row['uploadtree_pk'], $uploadtree_tablename);
         $filepath = "";
         foreach ($filepatharray as $uploadtreeRow) {
             if (!empty($filepath)) {
                 $filepath .= "/";
             }
             $filepath .= $uploadtreeRow['ufile_name'];
         }
         $V .= $filepath . ": " . GetFileLicenses_string($agent_pk, 0, $row['uploadtree_pk'], $uploadtree_tablename);
         if ($dltext) {
             $V .= "\n";
         } else {
             $V .= "<br>";
         }
     }
     $RealNumber = pg_num_rows($outerresult);
     pg_free_result($outerresult);
     if ($RealNumber == $NomostListNum) {
         $V .= _("<br><B>Warning: Only the last {$NomostListNum} lines are displayed.  To see the whole list, run fo_nomos_license_list from the command line.</B><br>");
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print "{$V}";
     return;
 }
 /**
  * \brief Display all the files for a bucket in this subtree.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     global $Plugins;
     global $PG_CONN;
     /*  Input parameters */
     $bucketagent_pk = GetParm("bapk", PARM_INTEGER);
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     $bucket_pk = GetParm("bpk", PARM_INTEGER);
     $bucketpool_pk = GetParm("bp", PARM_INTEGER);
     $nomosagent_pk = GetParm("napk", PARM_INTEGER);
     $BinNoSrc = GetParm("bns", PARM_INTEGER);
     // 1 if requesting binary with no src
     $Excl = GetParm("excl", PARM_RAW);
     if (empty($uploadtree_pk) || empty($bucket_pk) || empty($bucketpool_pk)) {
         $text = _("is missing required parameters.");
         echo $this->Name . " {$text}";
         return;
     }
     /* Check upload permission */
     $Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$uploadtree_pk}");
     $UploadPerm = GetUploadPerm($Row['upload_fk']);
     if ($UploadPerm < PERM_READ) {
         $text = _("Permission Denied");
         echo "<h2>{$text} item 1<h2>";
         return;
     }
     $Page = GetParm("page", PARM_INTEGER);
     if (empty($Page)) {
         $Page = 0;
     }
     $V = "";
     $Time = time();
     $Max = 200;
     // Create cache of bucket_pk => bucket_name
     // Since we are going to do a lot of lookups
     $sql = "select bucket_pk, bucket_name from bucket_def where bucketpool_fk={$bucketpool_pk}";
     $result_name = pg_query($PG_CONN, $sql);
     DBCheckResult($result_name, $sql, __FILE__, __LINE__);
     $bucketNameCache = array();
     while ($name_row = pg_fetch_assoc($result_name)) {
         $bucketNameCache[$name_row['bucket_pk']] = $name_row['bucket_name'];
     }
     pg_free_result($result_name);
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             // micro menus
             $V .= menu_to_1html(menu_find($this->Name, $MenuDepth), 0);
             /* Get all the files under this uploadtree_pk with this bucket */
             $V .= _("The following files are in bucket: '<b>");
             $V .= $bucketNameCache[$bucket_pk];
             $V .= "</b>'.\n";
             $text = _("Display");
             $text1 = _("excludes");
             $text2 = _("files with these licenses");
             if (!empty($Excl)) {
                 $V .= "<br>{$text} <b>{$text1}</b> {$text2}: {$Excl}";
             }
             $Offset = $Page <= 0 ? 0 : $Page * $Max;
             $PkgsOnly = false;
             // Get bounds of subtree (lft, rgt) for this uploadtree_pk
             $sql = "SELECT lft,rgt,upload_fk FROM uploadtree\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);
             /* Get uploadtree table */
             $uploadtree_tablename = GetUploadtreeTableName($upload_pk);
             /* If $BinNoSrc, then only list binary packages in this subtree
              * that do not have Source packages.
              * Else list files in the asked for bucket.
              */
             if ($BinNoSrc) {
             } else {
                 $Offset = $Page < 0 ? 0 : $Page * $Max;
                 $limit = $Page < 0 ? "ALL" : $Max;
                 // Get all the uploadtree_pk's with this bucket (for this agent and bucketpool)
                 // in this subtree.
                 // It would be best to sort by pfile_pk, so that the duplicate pfiles are
                 // correctly indented, but pfile_pk has no meaning to the user.  So a compromise,
                 // sorting by ufile_name is used.
                 $sql = "select uploadtree.*, bucket_file.nomosagent_fk as nomosagent_fk\n               from uploadtree, bucket_file, bucket_def\n               where upload_fk={$upload_pk} and uploadtree.lft between {$lft} and {$rgt}\n                 and ((ufile_mode & (1<<28)) = 0)\n                 and ((ufile_mode & (1<<29))=0)\n                 and uploadtree.pfile_fk=bucket_file.pfile_fk\n                 and agent_fk={$bucketagent_pk}\n                 and bucket_fk={$bucket_pk}\n                 and bucketpool_fk={$bucketpool_pk}\n                 and bucket_pk=bucket_fk \n                 order by uploadtree.ufile_name\n                 limit {$limit} offset {$Offset}";
                 $fileresult = pg_query($PG_CONN, $sql);
                 DBCheckResult($fileresult, $sql, __FILE__, __LINE__);
                 $Count = pg_num_rows($fileresult);
             }
             $file_result_temp = pg_fetch_all($fileresult);
             $sourted_file_result = array();
             // the final file list will display
             $max_num = $Count;
             /** sorting by ufile_name from DB, then reorder the duplicates indented */
             for ($i = 0; $i < $max_num; $i++) {
                 $row = $file_result_temp[$i];
                 if (empty($row)) {
                     continue;
                 }
                 array_push($sourted_file_result, $row);
                 for ($j = $i + 1; $j < $max_num; $j++) {
                     $row_next = $file_result_temp[$j];
                     if (!empty($row_next) && $row['pfile_fk'] == $row_next['pfile_fk']) {
                         array_push($sourted_file_result, $row_next);
                         $file_result_temp[$j] = null;
                     }
                 }
             }
             if ($Count < 1.25 * $Max) {
                 $Max = $Count;
             }
             if ($Max < 1) {
                 $Max = 1;
             }
             // prevent div by zero in corner case of no files
             /* Get the page menu */
             if ($Count >= $Max && $Page >= 0) {
                 $VM = "<P />\n" . MenuEndlessPage($Page, intval(($Count + $Offset) / $Max)) . "<P />\n";
                 $V .= $VM;
             } else {
                 $VM = "";
             }
             // base url
             $baseURL = "?mod=" . $this->Name . "&bapk={$bucketagent_pk}&item={$uploadtree_pk}&bpk={$bucket_pk}&bp={$bucketpool_pk}&napk={$nomosagent_pk}&page=-1";
             // for each uploadtree rec ($fileresult), find all the licenses in it and it's children
             $ShowBox = 1;
             $ShowMicro = NULL;
             $RowNum = $Offset;
             $Header = "";
             $LinkLast = "list_bucket_files&bapk={$bucketagent_pk}";
             /* file display loop/table */
             $V .= "<table>";
             $text = _("File");
             $V .= "<tr><th>{$text}</th><th>&nbsp";
             $ExclArray = explode(":", $Excl);
             $ItemNumb = 0;
             $PrevPfile_pk = 0;
             if ($Count > 0) {
                 foreach ($sourted_file_result as $row) {
                     // get all the licenses in this subtree (bucket uploadtree_pk)
                     $pfile_pk = $row['pfile_fk'];
                     $licstring = GetFileLicenses_string($nomosagent_pk, $row['pfile_fk'], $row['uploadtree_pk'], $uploadtree_tablename);
                     if (empty($licstring)) {
                         $licstring = '-';
                     }
                     $URLlicstring = urlencode($licstring);
                     /* Allow user to exclude files with this exact license list */
                     if (!empty($Excl)) {
                         $URL = $baseURL . "&excl=" . urlencode($Excl) . ":" . $URLlicstring;
                     } else {
                         $URL = $baseURL . "&excl={$URLlicstring}";
                     }
                     $text = _("Exclude files with license");
                     $Header = "<a href={$URL}>{$text}: {$licstring}.</a>";
                     $ok = true;
                     if ($Excl) {
                         if (in_array($licstring, $ExclArray)) {
                             $ok = false;
                         }
                     }
                     if ($ok) {
                         $nomosagent_pk = $row['nomosagent_fk'];
                         $LinkLast = "view-license&bapk={$bucketagent_pk}&napk={$nomosagent_pk}";
                         $V .= "<tr><td>";
                         if ($PrevPfile_pk == $pfile_pk) {
                             $V .= "<div style='margin-left:2em;'>";
                         } else {
                             $V .= "<div>";
                         }
                         $V .= Dir2Browse("browse", $row['uploadtree_pk'], $LinkLast, $ShowBox, $ShowMicro, ++$RowNum, $Header, '', $uploadtree_tablename);
                         $V .= "</div>";
                         $V .= "</td>";
                         $V .= "<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>";
                         // spaces to seperate licenses
                         // show the entire license list as a single string with links to the files
                         // in this container with that license.
                         $V .= "<td>{$licstring}</td></tr>";
                         $V .= "<tr><td colspan=3><hr></td></tr>";
                         // separate files
                     }
                     $PrevPfile_pk = $pfile_pk;
                 }
             }
             pg_free_result($fileresult);
             $V .= "</table>";
             if (!empty($VM)) {
                 $V .= $VM . "\n";
             }
             $V .= "<hr>\n";
             $Time = time() - $Time;
             $text = _("Elapsed time");
             $text1 = _("seconds");
             $V .= "<small>{$text}: {$Time} {$text1}</small>\n";
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }
/**
 * @brief get nomos license list of one specified uploadtree_id
 *
 * @param int $uploadtree_pk - uploadtree id
 * @param int $upload_pk - upload id
 * @param int $showContainer - include container or not, 1: yes, 0: no 
 * @param string $excluding
 * @param bool $ignore ignore files without license
 */
function GetLicenseList($uploadtree_pk, $upload_pk, $showContainer, $excluding, $ignore)
{
    /* @var $dbManager DbManager */
    $dbManager = $GLOBALS['container']->get('db.manager');
    if (empty($uploadtree_pk)) {
        $uploadtreeRec = $dbManager->getSingleRow('SELECT uploadtree_pk FROM uploadtree WHERE parent IS NULL AND upload_fk=$1', array($upload_pk), __METHOD__ . '.find.uploadtree.to.use.in.browse.link');
        $uploadtree_pk = $uploadtreeRec['uploadtree_pk'];
    }
    /* get last nomos agent_pk that has data for this upload */
    $AgentRec = AgentARSList("nomos_ars", $upload_pk, 1);
    $agent_pk = $AgentRec[0]["agent_fk"];
    if ($AgentRec === false) {
        echo _("No data available \n");
        return;
    }
    $bottomItem = $dbManager->getSingleRow("SELECT upload_fk, ufile_name path, lft, rgt FROM uploadtree WHERE uploadtree_pk=\$1", array($uploadtree_pk), __METHOD__ . '.get.top.of.tree');
    $bottomItem['uploadtree_pk'] = $uploadtree_pk;
    $bottomItem['include'] = empty($excluding) || false === strpos("/{$bottomItem['path']}/", $excluding);
    $pathStack = array();
    $uploadtree_tablename = GetUploadtreeTableName($bottomItem['upload_fk']);
    $sql = "SELECT uploadtree_pk, ufile_name, lft, rgt, ufile_mode FROM {$uploadtree_tablename}\n              WHERE (lft BETWEEN \$1 AND \$2) AND (ufile_mode & (1<<28)) = 0";
    $params = array($bottomItem['lft'] + 1, $bottomItem['rgt']);
    $stmt = __METHOD__ . '.loop.through';
    if ($uploadtree_tablename == 'uploadtree_a') {
        $sql .= ' AND upload_fk=$3';
        $params[] = $bottomItem['upload_fk'];
        $stmt .= '.ut_a';
    }
    $sql .= ' ORDER BY lft';
    $dbManager->prepare($stmt, $sql);
    $res = $dbManager->execute($stmt, $params);
    while ($item = $dbManager->fetchArray($res)) {
        while ($bottomItem['rgt'] <= $item['lft']) {
            $bottomItem = array_pop($pathStack);
        }
        if (!$bottomItem['include']) {
            continue;
        }
        $item['path'] = "{$bottomItem['path']}/{$item['ufile_name']}";
        if (($item['ufile_mode'] & 1 << 29) == 0) {
            $license_name = GetFileLicenses_string($agent_pk, 0, $item['uploadtree_pk'], $uploadtree_tablename);
            if (!$ignore || !empty($license_name) && 'No_license_found' != $license_name) {
                print "{$item['path']}: {$license_name}\n";
            }
            continue;
        }
        $item['include'] = $bottomItem['include'] && (empty($excluding) || false === strpos("/{$item['ufile_name']}/", $excluding));
        if ($item['include'] && $showContainer) {
            print "{$item['path']}\n";
        }
        array_push($pathStack, $bottomItem);
        $bottomItem = $item;
    }
    $dbManager->freeResult($res);
}