/**
  * \brief Display the loaded menu and plugins.
  */
 function Output()
 {
     global $PG_CONN;
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     if (!$PG_CONN) {
         return "NO DB connection";
     }
     $bucket_pk = GetParm("bucket_pk", PARM_RAW);
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     /* Get the uploadtree table name */
     $uploadtree_rec = GetSingleRec("uploadtree", "where uploadtree_pk='{$uploadtree_pk}'");
     $uploadtree_tablename = GetUploadtreeTableName($uploadtree_rec['upload_fk']);
     /* Get all the non-artifact children */
     $children = GetNonArtifactChildren($uploadtree_pk, $uploadtree_tablename);
     /* Loop through children and create a list of those that contain $bucket_pk */
     $outstr = $bucket_pk;
     foreach ($children as $child) {
         if (BucketInTree($bucket_pk, $child['uploadtree_pk'])) {
             $outstr .= ",{$child['uploadtree_pk']}";
         }
     }
     return $outstr;
 }
 /**
  * \brief Check if the upload has results from this agent.
  *
  * \param $upload_pk
  *
  * \returns:
  * - 0 = no
  * - 1 = yes, from latest agent version
  * - 2 = yes, from older agent version (does not apply to adj2nest)
  **/
 function AgentHasResults($upload_pk)
 {
     /* see if the latest nomos and bucket agents have scaned this upload for this bucketpool */
     $uploadtreeRec = GetSingleRec("uploadtree", "where upload_fk='{$upload_pk}' and lft is not null");
     if (empty($uploadtreeRec)) {
         return 0;
     }
     return 1;
 }
Beispiel #3
0
 /**
  * \brief Find out who I am from my user record.
  * \returns user name
  */
 function WhoAmI()
 {
     $user_pk = $_SESSION['UserId'];
     if (empty($user_pk)) {
         /* Note that this message is localized.  This is a good practice for as
          * much of your UI text as possible.
          */
         return _("You are not logged in");
     }
     /* The user's name is stored in $_SESSION[User] after they login.
      * But to demonstrate a database call, I'll get the name from the
      * user's primary key (in $_SESSION[UserId]).
      */
     $UserRow = GetSingleRec('users', "where user_pk='{$_SESSION['UserId']}'");
     return $UserRow['user_name'];
 }
Beispiel #4
0
 /**
  * \brief Display the loaded menu and plugins.
  */
 function Output()
 {
     $V = "";
     $item = GetParm("uploadtree_pk", PARM_INTEGER);
     /* get uploadtree_tablename from $Item */
     $uploadtreeRec = GetSingleRec("uploadtree", "where uploadtree_pk='{$item}'");
     $uploadRec = GetSingleRec("upload", "where upload_pk='{$uploadtreeRec['upload_fk']}'");
     if (empty($uploadRec['uploadtree_tablename'])) {
         $uploadtree_tablename = "uploadtree";
     } else {
         $uploadtree_tablename = $uploadRec['uploadtree_tablename'];
     }
     $List = GetAllTags($item, true, $uploadtree_tablename);
     foreach ($List as $L) {
         $V .= $L['tag_name'] . ",";
     }
     return new Response($V, Response::HTTP_OK, array('content-type' => 'text/plain'));
 }
 /**
  * \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":
             $Item = GetParm("uploadtree_pk", PARM_INTEGER);
             /* get uploadtree_tablename from $Item */
             $uploadtreeRec = GetSingleRec("uploadtree", "where uploadtree_pk='{$Item}'");
             $uploadRec = GetSingleRec("upload", "where upload_pk='{$uploadtreeRec['upload_fk']}'");
             if (empty($uploadRec['uploadtree_tablename'])) {
                 $uploadtree_tablename = "uploadtree";
             } else {
                 $uploadtree_tablename = $uploadRec['uploadtree_tablename'];
             }
             $List = GetAllTags($Item, true, $uploadtree_tablename);
             foreach ($List as $L) {
                 $V .= $L['tag_name'] . ",";
             }
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print "{$V}";
     return;
 }
Beispiel #6
0
 /**
  * @brief Get uploadtree info for a given uploadtree_pk.
  * @param $Uploadtree_pk
  * @return array with uploadtree record and:\n
  *   agent_pk\n
  *   bucketagent_pk\n
  *   nomosagent_pk\n
  *   bucketpool_pk\n
  */
 function GetTreeInfo($Uploadtree_pk)
 {
     global $PG_CONN;
     $TreeInfo = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$Uploadtree_pk}");
     $TreeInfo['agent_pk'] = LatestAgentpk($TreeInfo['upload_fk'], "nomos_ars");
     /* Get the ars_pk of the scan to display, also the select list  */
     $ars_pk = GetArrayVal("ars", $_GET);
     $BucketSelect = SelectBucketDataset($TreeInfo['upload_fk'], $ars_pk, "selectbdata", "onchange=\"addArsGo('newds','selectbdata');\"");
     $TreeInfo['ars_pk'] = $ars_pk;
     if ($ars_pk == 0) {
         /* No bucket data for this upload */
         return $BucketSelect;
         // $BucketSelect is error message
     }
     /* Get scan keys */
     $where = "where ars_pk={$ars_pk}";
     $row = GetSingleRec("bucket_ars", $where);
     if (empty($row)) {
         Fatal("No bucket data {$where}", __FILE__, __LINE__);
     }
     $TreeInfo['bucketagent_pk'] = $row["agent_fk"];
     $TreeInfo['nomosagent_pk'] = $row["nomosagent_fk"];
     $TreeInfo['bucketpool_pk'] = $row["bucketpool_fk"];
     unset($row);
     return $TreeInfo;
 }
Beispiel #7
0
/**
 * \brief Schedule agent tasks on upload ids
 *
 * \param $upload_pk_list -  upload ids, The string can be a comma-separated list of upload ids.
 * Or, use 'ALL' to specify all upload ids.
 * \param $agent_list - array of agent plugin objects to schedule.
 * \param $Verbose - verbose output, not empty: output, empty: does not output
 */
function QueueUploadsOnAgents($upload_pk_list, $agent_list, $Verbose)
{
    global $Plugins;
    global $PG_CONN;
    /* Get the users.default_bucketpool_fk */
    $user_pk = Auth::getUserId();
    $group_pk = Auth::getGroupId();
    if (empty($upload_pk_list)) {
        return;
    }
    // Schedule them
    $agent_count = count($agent_list);
    foreach (explode(",", $upload_pk_list) as $upload_pk) {
        if (empty($upload_pk)) {
            continue;
        }
        // Create a job for the upload
        $where = "where upload_pk ='{$upload_pk}'";
        $UploadRec = GetSingleRec("upload", $where);
        if (empty($UploadRec)) {
            echo "ERROR: unknown upload_pk: {$upload_pk}\n";
            continue;
        }
        $ShortName = $UploadRec['upload_filename'];
        /* Create Job */
        $job_pk = JobAddJob($user_pk, $group_pk, $ShortName, $upload_pk);
        // don't exit on AgentAdd failure, or all the agents requested will
        // not get scheduled.
        for ($ac = 0; $ac < $agent_count; $ac++) {
            $agentname = $agent_list[$ac]->URI;
            if (!empty($agentname)) {
                $Agent =& $Plugins[plugin_find_id($agentname)];
                $Dependencies = "";
                $ErrorMsg = "already queued!";
                $agent_jq_pk = $Agent->AgentAdd($job_pk, $upload_pk, $ErrorMsg, $Dependencies);
                if ($agent_jq_pk <= 0) {
                    echo "WARNING: Scheduling failed for Agent {$agentname}, upload_pk is: {$upload_pk}, job_pk is:{$job_pk}\n";
                    echo "WARNING message: {$ErrorMsg}\n";
                } else {
                    if ($Verbose) {
                        $SQL = "SELECT upload_filename FROM upload where upload_pk = {$upload_pk}";
                        $result = pg_query($PG_CONN, $SQL);
                        DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        $row = pg_fetch_assoc($result);
                        pg_free_result($result);
                        print "{$agentname} is queued to run on {$upload_pk}:{$row['upload_filename']}.\n";
                    }
                }
            }
        }
        /* for $ac */
    }
    /* for each $upload_pk */
}
Beispiel #8
0
/**
 *  @brief Get the upload permission for a user
 *  @param $upload_pk
 *  @param $user_pk (optional, default is current user_pk)
 *  @return hightest permission level a user has for an upload
 **/
function GetUploadPerm($upload_pk, $user_pk = 0)
{
    global $PG_CONN;
    if ($user_pk == 0) {
        $user_pk = Auth::getUserId();
    }
    if ($_SESSION[Auth::USER_LEVEL] == PLUGIN_DB_ADMIN) {
        return Auth::PERM_ADMIN;
    }
    //for the command line didn't have session info
    $UserRow = GetSingleRec("Users", "where user_pk='{$user_pk}'");
    if ($UserRow['user_perm'] == PLUGIN_DB_ADMIN) {
        return Auth::PERM_ADMIN;
    }
    $sql = "select max(perm) as perm from perm_upload, group_user_member where perm_upload.upload_fk={$upload_pk} and user_fk={$user_pk} and group_user_member.group_fk=perm_upload.group_fk";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    if (pg_num_rows($result) < 1) {
        $perm = Auth::PERM_NONE;
    } else {
        $row = pg_fetch_assoc($result);
        $perm = $row['perm'];
    }
    pg_free_result($result);
    /* check the upload public permission */
    $sql = "select public_perm from upload where upload_pk={$upload_pk}";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    if (pg_num_rows($result) < 1) {
        $perm2 = Auth::PERM_NONE;
    } else {
        $row = pg_fetch_assoc($result);
        $perm2 = $row['public_perm'];
    }
    pg_free_result($result);
    return max($perm, $perm2);
}
Beispiel #9
0
 /**
  * \brief Display the loaded menu and plugins.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     global $Plugins;
     global $PG_CONN;
     // make sure there is a db connection
     if (!$PG_CONN) {
         echo _("NO DB connection");
     }
     $OutBuf = "";
     $Time = microtime(true);
     $Max = 50;
     /*  Input parameters */
     $agent_pk = GetParm("agent", PARM_INTEGER);
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     $hash = GetParm("hash", PARM_RAW);
     $type = GetParm("type", PARM_RAW);
     $excl = GetParm("excl", PARM_RAW);
     $filter = GetParm("filter", PARM_RAW);
     if (empty($uploadtree_pk) || empty($hash) || empty($type) || empty($agent_pk)) {
         $text = _("is missing required parameters");
         echo $this->Name . " {$text}.";
         return;
     }
     /* Check item1 and item2 upload permissions */
     $Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$uploadtree_pk}");
     $UploadPerm = GetUploadPerm($Row['upload_fk']);
     if ($UploadPerm < PERM_READ) {
         $text = _("Permission Denied");
         echo "<h2>{$text}<h2>";
         return;
     }
     $Page = GetParm("page", PARM_INTEGER);
     if (empty($Page)) {
         $Page = 0;
     }
     /* get all rows */
     $rows = $this->GetRows($uploadtree_pk, $agent_pk, $upload_pk);
     /* Get uploadtree_tablename */
     $uploadtree_tablename = GetUploadtreeTableName($upload_pk);
     /* slim down to all rows with this hash and type,  and filter */
     $NumInstances = 0;
     $rows = $this->GetRequestedRows($rows, $hash, $type, $excl, $NumInstances, $filter);
     //debugprint($rows, "rows");
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             // micro menus
             $OutBuf .= menu_to_1html(menu_find($this->Name, $MenuDepth), 0);
             $RowCount = count($rows);
             if ($RowCount) {
                 $Content = htmlentities($rows[0]['content']);
                 $Offset = $Page < 0 ? 0 : $Page * $Max;
                 $PkgsOnly = false;
                 $text = _("files");
                 $text1 = _("unique");
                 $text3 = _("copyright");
                 $text4 = _("email");
                 $text5 = _("url");
                 switch ($type) {
                     case "statement":
                         $TypeStr = "{$text3}";
                         break;
                     case "email":
                         $TypeStr = "{$text4}";
                         break;
                     case "url":
                         $TypeStr = "{$text5}";
                         break;
                 }
                 $OutBuf .= "{$NumInstances} {$TypeStr} instances found in {$RowCount}  {$text}";
                 $OutBuf .= ": <b>{$Content}</b>";
                 $text = _("Display excludes files with these extensions");
                 if (!empty($excl)) {
                     $OutBuf .= "<br>{$text}: {$excl}";
                 }
                 /* Get the page menu */
                 if ($RowCount >= $Max && $Page >= 0) {
                     $PagingMenu = "<P />\n" . MenuEndlessPage($Page, intval(($RowCount + $Offset) / $Max)) . "<P />\n";
                     $OutBuf .= $PagingMenu;
                 } else {
                     $PagingMenu = "";
                 }
                 /* Offset is +1 to start numbering from 1 instead of zero */
                 $RowNum = $Offset;
                 $LinkLast = "copyrightview&agent={$agent_pk}";
                 $ShowBox = 1;
                 $ShowMicro = NULL;
                 // base url
                 $ucontent = rawurlencode($Content);
                 $baseURL = "?mod=" . $this->Name . "&agent={$agent_pk}&item={$uploadtree_pk}&hash={$hash}&type={$type}&page=-1";
                 // display rows
                 foreach ($rows as $row) {
                     // Allow user to exclude files with this extension
                     $FileExt = GetFileExt($row['ufile_name']);
                     if (empty($excl)) {
                         $URL = $baseURL . "&excl={$FileExt}";
                     } else {
                         $URL = $baseURL . "&excl={$excl}:{$FileExt}";
                     }
                     $text = _("Exclude this file type");
                     $Header = "<a href={$URL}>{$text}.</a>";
                     $ok = true;
                     if ($excl) {
                         $ExclArray = explode(":", $excl);
                         if (in_array($FileExt, $ExclArray)) {
                             $ok = false;
                         }
                     }
                     if ($ok) {
                         $OutBuf .= Dir2Browse("browse", $row['uploadtree_pk'], $LinkLast, $ShowBox, $ShowMicro, ++$RowNum, $Header, '', $uploadtree_tablename);
                     }
                 }
             } else {
                 $OutBuf .= _("No files found");
             }
             if (!empty($PagingMenu)) {
                 $OutBuf .= $PagingMenu . "\n";
             }
             $OutBuf .= "<hr>\n";
             $Time = microtime(true) - $Time;
             $text = _("Elapsed time");
             $text1 = _("seconds");
             $OutBuf .= sprintf("<small>{$text}: %.2f {$text1}</small>\n", $Time);
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $OutBuf;
     }
     print $OutBuf;
     return;
 }
/**
 * \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);
}
 /**
  * \brief This function is called when user output is
  * requested.  This function is responsible for assigning headers. \n 
  * If $Type is "HTML" then generate an HTTP header. \n
  * If $Type is "XML" then begin an XML header. \n
  * If $Type is "Text" then generate a text header as needed. \n
  * The $ToStdout flag is "1" if output should go to stdout
  * 
  * \return 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;
     }
     if (GetParm("output", PARM_STRING) == 'dltext') {
         $Type = 'dltext';
     }
     $this->OutputType = $Type;
     $this->OutputToStdout = $ToStdout;
     $Item = GetParm("item", PARM_INTEGER);
     if (empty($Item)) {
         return;
     }
     // Get the upload for this uploadtree_pk
     $uploadtreeRec = GetSingleRec("uploadtree", "where uploadtree_pk='{$Item}'");
     $uploadtree_tablename = GetUploadtreeTableName($uploadtreeRec['upload_fk']);
     switch ($this->OutputType) {
         case "dltext":
             $this->NoHeader = 1;
             $Path = Dir2Path($Item, $uploadtree_tablename);
             $Name = $Path[count($Path) - 1]['ufile_name'] . ".txt";
             header("Content-Type: text");
             header('Content-Disposition: attachment; filename="' . $Name . '"');
             $V = "";
             break;
         case "XML":
             $V = "<xml>\n";
             break;
         case "HTML":
             header('Content-type: text/html');
             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";
             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='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 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 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;
 }
Beispiel #14
0
/**
 * \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 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 The Picker page
  */
 function Output()
 {
     global $PG_CONN;
     if ($this->State != PLUGIN_STATE_READY) {
         return 0;
     }
     /**
      * create table if it doesn't exist (not assuming Install() was run.
      * eg. source update
      */
     $this->Create_file_picker();
     $RtnMod = GetParm("rtnmod", PARM_TEXT);
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     $uploadtree_pk2 = GetParm("item2", PARM_INTEGER);
     $folder_pk = GetParm("folder", PARM_INTEGER);
     $user_pk = $_SESSION['UserId'];
     /* Item to start Browse window on */
     $Browseuploadtree_pk = GetParm("bitem", PARM_INTEGER);
     /* Check item1 and item2 upload permissions */
     $Item1Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$uploadtree_pk}");
     $UploadPerm = GetUploadPerm($Item1Row['upload_fk']);
     if ($UploadPerm < PERM_READ) {
         $text = _("Permission Denied");
         echo "<h2>{$text} item 1<h2>";
         return;
     }
     if (!empty($uploadtree_pk2)) {
         $Item2Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$uploadtree_pk2}");
         $UploadPerm = GetUploadPerm($Item2Row['upload_fk']);
         if ($UploadPerm < PERM_READ) {
             $text = _("Permission Denied");
             echo "<h2>{$text} item 2<h2>";
             return;
         }
     }
     /**
      * After picking an item2, this logic will record the pick in
      * the picker history, and then redirect both item1 and item2 to the
      * comparison app.
      */
     if (!empty($user_pk) && !empty($RtnMod) && !empty($uploadtree_pk) && !empty($uploadtree_pk2)) {
         // Record pick
         $sql = "insert into file_picker (user_fk, uploadtree_fk1, uploadtree_fk2, last_access_date)\n             values({$user_pk}, {$uploadtree_pk}, {$uploadtree_pk2}, now())";
         // ignore errors (most probably a duplicate key)
         @($result = pg_query($PG_CONN, $sql));
         // Redirect to diff module
         $uri = Traceback_uri() . "?mod={$RtnMod}&item1={$uploadtree_pk}&item2={$uploadtree_pk2}";
         echo "<script type='text/javascript'> window.location.assign('{$uri}');</script>";
         exit;
     }
     $OutBuf = "";
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             if (empty($uploadtree_pk)) {
                 $OutBuf = "<h2>Picker URL is missing the first comparison file.</h2>";
             } else {
                 $PathArray = Dir2Path($uploadtree_pk, 'uploadtree');
                 $OutBuf .= $this->HTMLout($RtnMod, $uploadtree_pk, $Browseuploadtree_pk, $folder_pk, $PathArray);
             }
             break;
         case "Text":
             break;
         default:
     }
     if (!$this->OutputToStdout) {
         return $OutBuf;
     }
     print "{$OutBuf}";
     return;
 }
 /**
  * \brief Given an uploadpk, add a job.
  * \param $Depends - specifying other dependencies.
  * $Depends can be a jq_pk, or an array of jq_pks, or NULL.
  *
  * \return NULL on success, string on failure.
  */
 function AgentAdd($uploadpk, $Depends = NULL, $priority = 0)
 {
     global $PG_CONN;
     $Job_name = str_replace("'", "''", "reunpack");
     //get userpk from uploadpk
     $UploadRec = GetSingleRec("upload", "where upload_pk='{$uploadpk}'");
     //updated ununpack_ars table to let reunpack run
     $SQLARS = "UPDATE ununpack_ars SET ars_success = FALSE WHERE upload_fk = '{$uploadpk}';";
     $result = pg_query($PG_CONN, $SQLARS);
     DBCheckResult($result, $SQLARS, __FILE__, __LINE__);
     pg_free_result($result);
     if (empty($uploadpk)) {
         $SQLInsert = "INSERT INTO job\n        (job_queued,job_priority,job_name,job_user_fk) VALUES\n        (now(),'{$priority}','{$Job_name}',{$UploadRec['user_fk']});";
     } else {
         $SQLInsert = "INSERT INTO job\n        (job_queued,job_priority,job_name,job_upload_fk,job_user_fk) VALUES\n        (now(),'{$priority}','{$Job_name}','{$uploadpk}',{$UploadRec['user_fk']});";
     }
     $SQLcheck = "SELECT job_pk FROM job WHERE job_upload_fk = '{$uploadpk}' AND job_name = '{$Job_name}' AND job_user_fk = {$UploadRec['user_fk']} ORDER BY job_pk DESC LIMIT 1;";
     $result = pg_query($PG_CONN, $SQLcheck);
     DBCheckResult($result, $SQLcheck, __FILE__, __LINE__);
     $row = pg_fetch_assoc($result);
     pg_free_result($result);
     if (!empty($row)) {
         $jobpk = $row['job_pk'];
     } else {
         $result = pg_query($PG_CONN, $SQLInsert);
         DBCheckResult($result, $SQLInsert, __FILE__, __LINE__);
         $row = pg_fetch_assoc($result);
         pg_free_result($result);
         $SQLcheck = "SELECT job_pk FROM job WHERE job_upload_fk = '{$uploadpk}' AND job_name = '{$Job_name}' AND job_user_fk = {$UploadRec['user_fk']};";
         $result = pg_query($PG_CONN, $SQLcheck);
         DBCheckResult($result, $SQLcheck, __FILE__, __LINE__);
         $row = pg_fetch_assoc($result);
         pg_free_result($result);
         $jobpk = $row['job_pk'];
     }
     if (empty($jobpk) || $jobpk < 0) {
         return "Failed to insert job record! {$SQLInsert}";
     }
     if (!empty($Depends) && !is_array($Depends)) {
         $Depends = array($Depends);
     }
     /* job "unpack" has jobqueue item "unpack" */
     $jqargs = "SELECT pfile.pfile_sha1 || '.' || pfile.pfile_md5 || '.' || pfile.pfile_size AS pfile,\n      upload_pk, pfile_fk\n        FROM upload\n        INNER JOIN pfile ON upload.pfile_fk = pfile.pfile_pk\n        WHERE upload.upload_pk = '{$uploadpk}';";
     echo "JobQueueAdd used to do a reschedule here<br>";
     $jobqueuepk = JobQueueAdd($jobpk, "ununpack", $uploadpk, NULL, $Depends);
     if (empty($jobqueuepk)) {
         return "Failed to insert item into job queue";
     }
     return NULL;
 }
/**
 * \brief get upload id through uploadtreeid
 *
 * \param $uploadtreeid - uploadtree id
 *
 * \return return upload id
 */
function GetUploadID($uploadtreeid)
{
    if (empty($uploadtreeid)) {
        return "";
    }
    $upload_rec = GetSingleRec("uploadtree", "where uploadtree_pk={$uploadtreeid}");
    $uploadid = $upload_rec['upload_fk'];
    if (empty($uploadid)) {
        return "";
    } else {
        return $uploadid;
    }
}
 /**
  * \brief Queue the bucket agent.
  *
  * \param $job_pk
  * \param $upload_pk - upload_pk
  * \param $ErrorMsg - error message on failure
  * \param $Dependencies - array of plugin names representing dependencies.
  *        This is for dependencies that this plugin cannot know about ahead of time.
  *
  * \returns
  * - jq_pk Successfully queued
  * -   0   Not queued, latest version of agent has previously run successfully
  * -  -1   Not queued, error, error string in $ErrorMsg
  */
 function AgentAdd($job_pk, $upload_pk, &$ErrorMsg, $Dependencies)
 {
     global $Plugins;
     global $SysConf;
     $Dep = array();
     $jqDeps = array();
     $EmptyDeps = array();
     /* Is the user authenticated?  If not, then fail
      * because we won't know which bucketpool to use.
      */
     $user_pk = $SysConf['auth']['UserId'];
     if (empty($user_pk)) {
         $ErrorMsg = _("Session is unauthenticated, bucket agent cannot run without knowing who the user is.");
         return -1;
     }
     /* get the default_bucketpool_fk from the users record */
     $usersRec = GetSingleRec("users", "where user_pk='{$user_pk}'");
     $default_bucketpool_fk = $usersRec['default_bucketpool_fk'];
     if (!$default_bucketpool_fk) {
         $ErrorMsg = _("User does not have a default bucketpool.  Bucket agent cannot be scheduled without this.");
         return -1;
     }
     /* schedule buckets */
     /* queue up dependencies */
     $Dependencies[] = "agent_nomos";
     $Dependencies[] = "agent_pkgagent";
     $jqargs = "bppk={$default_bucketpool_fk}, upk={$upload_pk}";
     return CommonAgentAdd($this, $job_pk, $upload_pk, $ErrorMsg, $Dependencies, $jqargs);
 }
Beispiel #20
0
 /**
  * \brief Display the loaded menu and plugins.
  */
 function Output()
 {
     global $Plugins;
     global $PG_CONN;
     //phpinfo();
     $CriteriaCount = 0;
     $V = "";
     $GETvars = "";
     $upload_pk = GetParm("upload", PARM_INTEGER);
     $detail = GetParm("detail", PARM_INTEGER);
     $detail = empty($detail) ? 0 : 1;
     $folic = GetParm("folic", PARM_INTEGER);
     $savebtn = GetParm("savebtn", PARM_RAW);
     $spdxbtn = GetParm("spdxbtn", PARM_RAW);
     $agent_pk = LatestAgentpk($upload_pk, "nomos_ars");
     if (empty($agent_pk)) {
         echo "Missing fossology license data.  Run a license scan on this upload.<br>";
         exit;
     }
     $uploadtree_tablename = GetUploadtreeTableName($upload_pk);
     // Check if we have data in the acme_upload table, if not then load it
     $acme_uploadRec = GetSingleRec("acme_upload", "where upload_fk={$upload_pk} ");
     if (empty($acme_uploadRec)) {
         // populate acme_upload
         $MinCount = 1;
         $nomosAgentpk = LatestAgentpk($upload_pk, "nomos_ars");
         $acme_project_array = $this->GetProjectArray1($upload_pk, $nomosAgentpk, $MinCount);
         // low level
         $this->Populate_acme_upload($acme_project_array, $upload_pk, 1);
         $acme_project_array = $this->GetProjectArray0($upload_pk, $nomosAgentpk, $MinCount);
         // high level
         $this->Populate_acme_upload($acme_project_array, $upload_pk, 0);
     }
     $sql = "select * from acme_upload, acme_project where acme_project_pk=acme_project_fk and detail={$detail} and upload_fk={$upload_pk}";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $acme_project_array = pg_fetch_all($result);
     $acme_project_array_orig = $acme_project_array;
     // save the original state so we know which records to update
     /* If the save or spdx buttons were clicked, update $acme_project_array and save the data in the acme_upload table */
     if (!empty($savebtn) or !empty($spdxbtn)) {
         /* First set all projects include to false */
         foreach ($acme_project_array as &$project) {
             $project['include'] = 'f';
         }
         /* Now turn on projects include to match form */
         if (array_key_exists('includeproj', $_POST)) {
             $includeArray = $_POST['includeproj'];
             foreach ($acme_project_array as &$project) {
                 if (array_key_exists($project['acme_project_fk'], $includeArray)) {
                     $project['include'] = "t";
                 }
             }
         }
         /* Finally, update the db with any changed include states */
         $NumRecs = count($acme_project_array);
         for ($i = 0; $i < $NumRecs; $i++) {
             $project = $acme_project_array[$i];
             $project_orig = $acme_project_array_orig[$i];
             if ($project['include'] != $project_orig['include']) {
                 $include = $project['include'] ? "true" : "false";
                 $sql = "update acme_upload set include='{$include}' where acme_upload_pk='{$project['acme_upload_pk']}'";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 pg_free_result($result);
             }
         }
     }
     /* aggregate the fossology licenses for each pfile and each acme_project */
     if ($folic) {
         foreach ($acme_project_array as &$project) {
             $sql = "select uploadtree_pk from acme_pfile, uploadtree where acme_project_fk={$project['acme_project_fk']} \n                and acme_pfile.pfile_fk=uploadtree.pfile_fk and uploadtree.upload_fk={$upload_pk}";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             $LicArray = array();
             $ItemLicArray = array();
             while ($acme_pfileRow = pg_fetch_assoc($result)) {
                 $LicArray = GetFileLicenses($agent_pk, '', $acme_pfileRow['uploadtree_pk'], $uploadtree_tablename);
                 foreach ($LicArray as $key => $license) {
                     $ItemLicArray[$key] = $license;
                 }
             }
             $project['licenses'] = '';
             foreach ($ItemLicArray as $license) {
                 if ($license == "No_license_found") {
                     continue;
                 }
                 if (!empty($project['licenses'])) {
                     $project['licenses'] .= ", ";
                 }
                 $project['licenses'] .= $license;
             }
         }
     }
     /* sort $acme_project_array by count desc */
     usort($acme_project_array, 'proj_cmp');
     /* generate and download spdx file */
     if (!empty($spdxbtn)) {
         $spdxfile = $this->GenerateSPDX($acme_project_array);
         $rv = DownloadString2File($spdxfile, "SPDX.rdf file", "xml");
         if ($rv !== true) {
             echo $rv;
         }
     }
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             $this->NoHeader = 0;
             $this->OutputOpen("HTML", 1);
             $V .= $this->HTMLForm($acme_project_array, $upload_pk);
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }
 /**
  * \brief Set $_SESSION and $SysConf user variables
  * \param $UserRow users table row, if empty, use Default User
  * \return void, updates globals $_SESSION and $SysConf[auth][UserId] variables
  */
 function UpdateSess($UserRow)
 {
     global $SysConf;
     if (empty($UserRow)) {
         $UserRow = GetSingleRec("Users", "where user_name='Default User'");
     }
     $_SESSION['UserId'] = $UserRow['user_pk'];
     $SysConf['auth']['UserId'] = $UserRow['user_pk'];
     $_SESSION['User'] = $UserRow['user_name'];
     $_SESSION['Folder'] = $UserRow['root_folder_fk'];
     $_SESSION['UserLevel'] = $UserRow['user_perm'];
     $_SESSION['UserEmail'] = $UserRow['user_email'];
     $_SESSION['UserEnote'] = $UserRow['email_notify'];
 }
 function Output()
 {
     global $PG_CONN;
     global $PERM_NAMES;
     global $SysConf;
     $user_pk = $SysConf['auth']['UserId'];
     /* GET parameters */
     $group_pk = GetParm('group', PARM_INTEGER);
     /* group_pk to manage */
     $gum_pk = GetParm('gum_pk', PARM_INTEGER);
     /* group_user_member_pk */
     $perm = GetParm('perm', PARM_INTEGER);
     /* Updated permission for gum_pk */
     $newuser = GetParm('newuser', PARM_INTEGER);
     /* New group      */
     $newperm = GetParm('newperm', PARM_INTEGER);
     /* New permission */
     if (empty($newperm)) {
         $newperm = 0;
     }
     /* If gum_pk is passed in, update either the group_perm or user_pk */
     $sql = "";
     if (!empty($gum_pk)) {
         /* Verify user has access */
         if (empty($group_pk)) {
             $gum_rec = GetSingleRec("group_user_member", "where group_user_member_pk='{$gum_pk}'");
             $group_pk = $gum_rec['group_fk'];
         }
         $this->VerifyAccess($user_pk, $group_pk);
         if ($perm === 0 or $perm === 1) {
             $sql = "update group_user_member set group_perm='{$perm}' where group_user_member_pk='{$gum_pk}'";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             pg_free_result($result);
         } else {
             if ($perm === -1) {
                 $sql = "delete from group_user_member where group_user_member_pk='{$gum_pk}'";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 pg_free_result($result);
             }
         }
     } else {
         if (!empty($newuser) && !empty($group_pk)) {
             // before inserting this new record, delete any record for the same upload and group since
             // that would be a duplicate
             $sql = "delete from group_user_member where group_fk='{$group_pk}' and user_fk='{$newuser}'";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             pg_free_result($result);
             if ($newperm >= 0) {
                 $sql = "insert into group_user_member (group_fk, user_fk, group_perm) values ({$group_pk}, {$newuser}, {$newperm})";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 pg_free_result($result);
             }
             $newperm = $newuser = 0;
         }
     }
     // start building the output buffer
     $V = "";
     /* define js_url */
     $V .= js_url();
     /* Get array of groups that this user is an admin of */
     $GroupArray = GetGroupArray($user_pk);
     if (empty($GroupArray)) {
         $text = _("You have no permission to manage any group.");
         echo "<p>{$text}<p>";
         return;
     }
     reset($GroupArray);
     if (empty($group_pk)) {
         $group_pk = key($GroupArray);
     }
     $text = _("Select the group to manage:  \n");
     $V .= "{$text}";
     /*** Display group select list, on change request new page with group= in url ***/
     $url = Traceback_uri() . "?mod=group_manage_users&group=";
     $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
     $V .= Array2SingleSelect($GroupArray, "groupselect", $group_pk, false, false, $onchange);
     /* Create array of group_user_member group_perm possible values for use in a select list */
     $group_permArray = array(-1 => "None", 0 => "User", 1 => "Admin");
     /* Select all the user members of this group */
     $sql = "select group_user_member_pk, user_fk, group_perm, user_name from group_user_member, users\n              where group_fk='{$group_pk}' and user_fk=user_pk order by user_name";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $GroupMembersArray = pg_fetch_all($result);
     pg_free_result($result);
     /* Permissions Table */
     $V .= "<p><table border=1>";
     $UserText = _("User");
     $PermText = _("Permission");
     $V .= "<tr><th>{$UserText}</th><th>{$PermText}</th></tr>";
     if (!empty($GroupMembersArray)) {
         // does this group have childen ?
         foreach ($GroupMembersArray as $GroupMember) {
             $V .= "<tr>";
             $V .= "<td>";
             // user
             $V .= $GroupMember['user_name'];
             $V .= "</td>";
             $V .= "<td>";
             // permission
             $url = Traceback_uri() . "?mod=group_manage_users&gum_pk={$GroupMember['group_user_member_pk']}&perm=";
             $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
             $V .= Array2SingleSelect($group_permArray, "permselect", $GroupMember['group_perm'], false, false, $onchange);
             $V .= "</td>";
             $V .= "</tr>";
         }
     }
     /* Print one extra row for adding perms */
     $V .= "<tr>";
     $V .= "<td>";
     // user
     $url = Traceback_uri() . "?mod=group_manage_users&newperm={$newperm}&group={$group_pk}&newuser="******"onchange=\"js_url(this.value, '{$url}')\"";
     $Selected = empty($newuser) ? "" : $newuser;
     $UserArray = Table2Array("user_pk", "user_name", "users", " ", "order by user_name");
     $V .= Array2SingleSelect($UserArray, "userselectnew", $Selected, true, false, $onchange);
     $V .= "</td>";
     $V .= "<td>";
     // permission
     $url = Traceback_uri() . "?mod=group_manage_users&newuser={$newuser}&group={$group_pk}&newperm=";
     $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
     $Selected = $newperm;
     $V .= Array2SingleSelect($group_permArray, "permselectnew", $Selected, false, false, $onchange);
     $V .= "</td>";
     $V .= "</tr>";
     $V .= "</table>";
     $text = _("All user permissions take place immediately when a value is changed.  There is no submit button.");
     $V .= "<p>" . $text;
     $text = _("Add new users on the last line.");
     $V .= "<br>" . $text;
     if (!$this->OutputToStdout) {
         return $V;
     }
     print "{$V}";
     return;
 }
Beispiel #23
0
 /**
  * \brief Get a user record
  * \param $user_pk  fetch this users db record
  * 
  * \return users db record
  */
 function GetUserRec($user_pk)
 {
     if (empty($user_pk)) {
         throw new Exception("Invalid access.  Your session has expired.", 1);
     }
     $UserRec = GetSingleRec("users", "WHERE user_pk={$user_pk}");
     if (empty($UserRec)) {
         throw new Exception("Invalid user. ", 1);
     }
     return $UserRec;
 }
    /**
    * @brief Output(): 
    * Requires:\n
           filter: optional filter to apply\n
           item1:  uploadtree_pk of the column 1 tree\n
           item2:  uploadtree_pk of the column 2 tree\n
           freeze: column number (1 or 2) to freeze
    */
    function Output()
    {
        if ($this->State != PLUGIN_STATE_READY) {
            return 0;
        }
        $uTime = microtime(true);
        $V = "";
        /**/
        $UpdCache = GetParm("updcache", PARM_INTEGER);
        /* Remove "updcache" from the GET args and set $this->UpdCache
         * This way all the url's based on the input args won't be
         * polluted with updcache
         * Use Traceback_parm_keep to ensure that all parameters are in order
         */
        $CacheKey = "?mod=" . $this->Name . Traceback_parm_keep(array("item1", "item2", "filter", "col", "freeze", "itemf"));
        if ($UpdCache) {
            $UpdCache = $_GET['updcache'];
            $_SERVER['REQUEST_URI'] = preg_replace("/&updcache=[0-9]*/", "", $_SERVER['REQUEST_URI']);
            unset($_GET['updcache']);
            $V = ReportCachePurgeByKey($CacheKey);
        } else {
            $V = ReportCacheGet($CacheKey);
        }
        /**/
        if (empty($V)) {
            $filter = GetParm("filter", PARM_STRING);
            if (empty($filter)) {
                $filter = "none";
            }
            $FreezeCol = GetParm("freeze", PARM_INTEGER);
            // which column to freeze?  1 or 2 or null
            $ClickedCol = GetParm("col", PARM_INTEGER);
            // which column was clicked on?  1 or 2 or null
            $ItemFrozen = GetParm("itemf", PARM_INTEGER);
            // frozen item or null
            $in_uploadtree_pk1 = GetParm("item1", PARM_INTEGER);
            $in_uploadtree_pk2 = GetParm("item2", PARM_INTEGER);
            if (empty($in_uploadtree_pk1) || empty($in_uploadtree_pk2)) {
                Fatal("Bad input parameters.  Both item1 and item2 must be specified.", __FILE__, __LINE__);
            }
            /* If you click on a item in a frozen column, then you are a dope so ignore $ItemFrozen */
            if ($FreezeCol == $ClickedCol) {
                $ItemFrozen = 0;
                $FreezeCol = 0;
            }
            /* Check item1 upload permission */
            $Item1Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$in_uploadtree_pk1}");
            $UploadPerm = GetUploadPerm($Item1Row['upload_fk']);
            if ($UploadPerm < PERM_READ) {
                $text = _("Permission Denied");
                echo "<h2>{$text} item 1<h2>";
                return;
            }
            /* Check item2 upload permission */
            $Item2Row = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$in_uploadtree_pk2}");
            $UploadPerm = GetUploadPerm($Item2Row['upload_fk']);
            if ($UploadPerm < PERM_READ) {
                $text = _("Permission Denied");
                echo "<h2>{$text} item 2<h2>";
                return;
            }
            $uploadtree_pk1 = $in_uploadtree_pk1;
            $uploadtree_pk2 = $in_uploadtree_pk2;
            if ($FreezeCol == 1) {
                $uploadtree_pk1 = $ItemFrozen;
            } else {
                if ($FreezeCol == 2) {
                    $uploadtree_pk2 = $ItemFrozen;
                }
            }
            $newURL = Traceback_dir() . "?mod=" . $this->Name . "&item1={$uploadtree_pk1}&item2={$uploadtree_pk2}";
            if (!empty($filter)) {
                $newURL .= "&filter={$filter}";
            }
            // rewrite page with new uploadtree_pks */
            if ($uploadtree_pk1 != $in_uploadtree_pk1 || $uploadtree_pk2 != $in_uploadtree_pk2) {
                print <<<JSOUT
<script type="text/javascript">
  window.location.assign('{$newURL}');
</script>
JSOUT;
            }
            $TreeInfo1 = $this->GetTreeInfo($uploadtree_pk1);
            $TreeInfo2 = $this->GetTreeInfo($uploadtree_pk2);
            $ErrText = _("No license data for tree %d.  Use Jobs > Agents to schedule a license scan.");
            $ErrMsg = '';
            if ($TreeInfo1['agent_pk'] == 0) {
                $ErrMsg = sprintf($ErrText, 1);
            } else {
                if ($TreeInfo2['agent_pk'] == 0) {
                    $ErrMsg = sprintf($ErrText, 2);
                } else {
                    $BucketDefArray = initBucketDefArray($TreeInfo1['bucketpool_pk']);
                    /* Get list of children */
                    $Children1 = GetNonArtifactChildren($uploadtree_pk1);
                    $Children2 = GetNonArtifactChildren($uploadtree_pk2);
                    /* Add fuzzyname to children */
                    FuzzyName($Children1);
                    // add fuzzyname to children
                    FuzzyName($Children2);
                    // add fuzzyname to children
                    /* add element licstr to children */
                    $this->AddBucketStr($TreeInfo1, $Children1, $BucketDefArray);
                    $this->AddBucketStr($TreeInfo2, $Children2, $BucketDefArray);
                    /* Master array of children, aligned.   */
                    $Master = MakeMaster($Children1, $Children2);
                    /* add linkurl to children */
                    FileList($Master, $TreeInfo1['agent_pk'], $TreeInfo2['agent_pk'], $filter, $this, $uploadtree_pk1, $uploadtree_pk2);
                    /* Apply filter */
                    $this->FilterChildren($filter, $Master, $BucketDefArray);
                }
            }
            switch ($this->OutputType) {
                case "XML":
                    break;
                case "HTML":
                    if ($ErrMsg) {
                        $V .= $ErrMsg;
                    } else {
                        $V .= $this->HTMLout($Master, $uploadtree_pk1, $uploadtree_pk2, $in_uploadtree_pk1, $in_uploadtree_pk2, $filter, $TreeInfo1, $TreeInfo2, $BucketDefArray);
                    }
                    break;
                case "Text":
                    break;
                default:
            }
            $Cached = false;
        } else {
            $Cached = true;
        }
        if (!$this->OutputToStdout) {
            return $V;
        }
        print "{$V}";
        $Time = microtime(true) - $uTime;
        // convert usecs to secs
        $text = _("Elapsed time: %.2f seconds");
        printf("<small>{$text}</small>", $Time);
        /**/
        if ($Cached) {
            $text = _("cached");
            $text1 = _("Update");
            echo " <i>{$text}</i>   <a href=\"{$_SERVER['REQUEST_URI']}&updcache=1\"> {$text1} </a>";
        } else {
            //  Cache Report if this took longer than 1/2 second
            if ($Time > 0.5) {
                ReportCachePut($CacheKey, $V);
            }
        }
        /**/
        return;
    }
Beispiel #25
0
 /**
  * \brief get an array with uploadtree record and agent_pk
  */
 function GetTreeInfo($Uploadtree_pk)
 {
     $TreeInfo = GetSingleRec("uploadtree", "WHERE uploadtree_pk = {$Uploadtree_pk}");
     $TreeInfo['agent_pk'] = LatestAgentpk($TreeInfo['upload_fk'], "nomos_ars");
     // Get the uploadtree table
     $UploadRec = GetSingleRec("upload", "where upload_pk={$TreeInfo['upload_fk']}");
     $TreeInfo['uploadtree_tablename'] = $UploadRec['uploadtree_tablename'];
     return $TreeInfo;
 }
Beispiel #26
0
 /**
  * @brief Returns an upload job status in html
  * @param $JobData
  * @return Returns an upload job status in html
  **/
 function Show($JobData, $Page)
 {
     global $PG_CONN;
     $OutBuf = '';
     $NumJobs = count($JobData);
     if ($NumJobs == 0) {
         return _("There are no jobs to display");
     }
     /* Next/Prev menu */
     $Next = $NumJobs > $this->MaxUploadsPerPage;
     if ($NumJobs > $this->MaxUploadsPerPage) {
         $OutBuf .= MenuEndlessPage($Page, $Next);
     }
     /*****************************************************************/
     /* Now display the summary */
     /*****************************************************************/
     $Job = -1;
     $Blocked = array();
     $First = 1;
     $Upload = "-1";
     $Uri = Traceback_uri() . "?mod=" . $this->Name;
     $UriFull = $Uri . Traceback_parm_keep(array("upload"));
     $uploadStyle = "style='font:bold 10pt verdana, arial, helvetica; background:gold; color:white;'";
     $jobStyle = "style='font:bold 8pt verdana, arial, helvetica; background:lavender; color:black;'";
     $prevupload_pk = "";
     $OutBuf .= "<table class='text' border=1 width='100%' name='jobtable'>\n";
     $FirstJob = $Page * $this->MaxUploadsPerPage;
     $LastJob = $Page * $this->MaxUploadsPerPage + $this->MaxUploadsPerPage;
     $JobNumber = -1;
     /** if $single_browse is 1, represent alread has an upload browse link, if single_browse is 0, no upload browse link */
     $single_browse = 0;
     foreach ($JobData as $job_pk => $Job) {
         /* Upload  */
         if (!empty($Job["upload"])) {
             $UploadName = GetArrayVal("upload_filename", $Job["upload"]);
             $UploadDesc = GetArrayVal("upload_desc", $Job["upload"]);
             $upload_pk = GetArrayVal("upload_pk", $Job["upload"]);
             /** the column pfile_fk of the record in the table(upload) is NULL when this record is inserted */
             if (!empty($upload_pk) && $prevupload_pk != $upload_pk || empty($upload_pk) && 0 == $single_browse) {
                 $prevupload_pk = $upload_pk;
                 $JobNumber++;
                 /* Only display the jobs for this page */
                 if ($JobNumber >= $LastJob) {
                     break;
                 }
                 if ($JobNumber < $FirstJob) {
                     continue;
                 }
                 /* blank line separator between pfiles */
                 $OutBuf .= "<tr><td colspan=7> <hr> </td></tr>";
                 $OutBuf .= "<tr>";
                 $OutBuf .= "<th {$uploadStyle}></th>";
                 $OutBuf .= "<th colspan=4 {$uploadStyle}>";
                 if (!empty($Job['uploadtree'])) {
                     $uploadtree_pk = $Job['uploadtree']['uploadtree_pk'];
                     $OutBuf .= "<a title='Click to browse' href='" . Traceback_uri() . "?mod=browse&upload=" . $Job['job']['job_upload_fk'] . "&item=" . $uploadtree_pk . "'>";
                 } else {
                     $OutBuf .= "<a title='Click to browse' href='" . Traceback_uri() . "?mod=browse'>";
                 }
                 /* get $UserName if all jobs are shown */
                 $UserName = "";
                 $allusers = GetParm("allusers", PARM_INTEGER);
                 if ($allusers > 0) {
                     $UploadRec = GetSingleRec("upload", "where upload_pk={$Job['job']['job_upload_fk']}");
                     if (!empty($UploadRec)) {
                         $UserRec = GetSingleRec("users", "where user_pk={$UploadRec['user_fk']}");
                         $UserName = "******";
                     } else {
                         $UserRec = GetSingleRec("users", "where user_pk={$Job['job']['job_user_fk']}");
                         $UserName = "******";
                     }
                 }
                 $OutBuf .= $UploadName . $UserName;
                 if (!empty($UploadDesc)) {
                     $OutBuf .= " (" . $UploadDesc . ")";
                 }
                 $OutBuf .= "</a>";
                 $OutBuf .= "</th>";
                 $OutBuf .= "<th {$uploadStyle}></th>";
                 $OutBuf .= "</tr>";
                 $single_browse = 1;
             } else {
                 if ($JobNumber < $FirstJob) {
                     continue;
                 }
             }
         } else {
             /* blank line separator between pfiles */
             $NoUploadStyle = "style='font:bold 10pt verdana, arial, helvetica; background:gold; color:black;'";
             $OutBuf .= "<tr><td colspan=7> <hr> </td></tr>";
             $OutBuf .= "<tr>";
             $OutBuf .= "<th {$NoUploadStyle}></th>";
             $OutBuf .= "<th colspan=4 {$NoUploadStyle}>";
             $OutBuf .= $Job["job"]["job_name"];
             $OutBuf .= "</th>";
             $OutBuf .= "<th {$NoUploadStyle}></th>";
             $OutBuf .= "</tr>";
         }
         /* Job data */
         $OutBuf .= "<tr>";
         $OutBuf .= "<th {$jobStyle}>";
         $OutBuf .= _("Job/Dependency");
         $OutBuf .= "</th>";
         $OutBuf .= "<th {$jobStyle}>";
         $OutBuf .= _("Status");
         $OutBuf .= "</th>";
         $OutBuf .= "<th colspan=3 {$jobStyle}>";
         $OutBuf .= $Job["job"]["job_name"];
         $OutBuf .= "</th>";
         $OutBuf .= "<th {$jobStyle}>";
         $OutBuf .= "</th></tr>";
         /* Job queue */
         foreach ($Job['jobqueue'] as $jq_pk => $jobqueueRec) {
             $RowColor = $this->GetColor($jobqueueRec);
             $jobqueueStyle = $this->jobqueueStyle($RowColor);
             $OutBuf .= "<tr {$jobqueueStyle}>";
             /* Job/Dependency */
             $OutBuf .= "<td {$jobqueueStyle}>";
             $OutBuf .= "<a href='{$UriFull}&show=job&job=" . $jq_pk . "'>";
             $OutBuf .= $jq_pk;
             $OutBuf .= "</a>";
             $count = 0;
             if (!empty($jobqueueRec["depends"])) {
                 foreach ($jobqueueRec["depends"] as $depend_jq_pk) {
                     $OutBuf .= $count++ == 0 ? " / " : ", ";
                     $OutBuf .= "<a href='{$UriFull}&show=job&job=" . $depend_jq_pk . "'>";
                     $OutBuf .= $depend_jq_pk;
                     $OutBuf .= "</a>";
                 }
             }
             $OutBuf .= "</td>";
             /* status */
             $Status = $jobqueueRec["jq_endtext"];
             $OutBuf .= "<td style='text-align:center'>{$Status}</td>";
             $isPaused = $Status == "Paused" ? true : false;
             /* agent name */
             $OutBuf .= "<td>{$jobqueueRec['jq_type']}</td>";
             /* items processed */
             if ($jobqueueRec["jq_itemsprocessed"] > 0) {
                 $items = number_format($jobqueueRec['jq_itemsprocessed']);
                 $OutBuf .= "<td style='text-align:right'>{$items} items</td>";
             } else {
                 $OutBuf .= "<td></td>";
             }
             /* dates */
             $OutBuf .= "<td>";
             $OutBuf .= substr($jobqueueRec['jq_starttime'], 0, 16);
             if (!empty($jobqueueRec["jq_endtime"])) {
                 $OutBuf .= " - " . substr($jobqueueRec['jq_endtime'], 0, 16);
                 $NumSecs = strtotime($jobqueueRec['jq_endtime']) - strtotime($jobqueueRec['jq_starttime']);
             } else {
                 $NumSecs = time() - strtotime($jobqueueRec['jq_starttime']);
             }
             /* Don't display items/sec unless the job has started */
             if ($jobqueueRec['jq_starttime']) {
                 if ($NumSecs > 0) {
                     $ItemsPerSec = round($jobqueueRec['jq_itemsprocessed'] / $NumSecs);
                     if ($ItemsPerSec < 1) {
                         $OutBuf .= sprintf(" : (%01.2f items/sec)", $jobqueueRec['jq_itemsprocessed'] / $NumSecs);
                     } else {
                         $OutBuf .= sprintf(" : (%d items/sec)", $ItemsPerSec);
                     }
                 }
             }
             $OutBuf .= "</td>";
             /* actions, must be admin or own the upload  */
             if ($jobqueueRec['jq_end_bits'] == 0 && ($_SESSION["UserLevel"] == PLUGIN_DB_ADMIN || $_SESSION["UserId"] == $Job['job']['job_user_fk'])) {
                 $OutBuf .= "<th {$jobStyle}>";
                 if ($isPaused) {
                     $text = _("Unpause");
                     $OutBuf .= "<a href='{$UriFull}&action=restart&jobid={$jq_pk}' title='Un-Pause this job'>{$text}</a>";
                 } else {
                     $text = _("Pause");
                     $OutBuf .= "<a href='{$UriFull}&action=pause&jobid={$jq_pk}' title='Pause this job'>{$text}</a>";
                 }
                 $OutBuf .= " | ";
                 $text = _("Cancel");
                 $OutBuf .= "<a href='{$UriFull}&action=cancel&jobid={$jq_pk}' title='Cancel this job'>{$text}</a>";
             } else {
                 $OutBuf .= "<th>";
             }
             $OutBuf .= "</th></tr>";
         }
     }
     $OutBuf .= "</table>\n";
     if ($NumJobs > $this->MaxUploadsPerPage) {
         $OutBuf .= "<p>" . MenuEndlessPage($Page, $Next);
     }
     return $OutBuf;
 }
Beispiel #27
0
/**
 * \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;
    if (empty($UploadName)) {
        $text = "UploadName is empty\n";
        echo $text;
        return 1;
    }
    $user_pk = $SysConf['auth']['UserId'];
    /* 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}, {$UploadName},{$UploadArchive},{$UploadDescription},{$Mode},{$FolderPk}, {$public_flag});\n";
    }
    if (!$Test) {
        $Src = $UploadArchive;
        if (!empty($TarSource)) {
            $Src = $TarSource;
        }
        $UploadPk = JobAddUpload($user_pk, $UploadName, $Src, $UploadDescription, $Mode, $FolderPk, $public_flag);
        print "  UploadPk is: '{$UploadPk}'\n";
    }
    /* Prepare the job: job "wget" */
    if ($Verbose) {
        print "JobAddJob({$user_pk}, wget, {$UploadPk});\n";
    }
    if (!$Test) {
        $jobpk = JobAddJob($user_pk, "wget", $UploadPk);
        if (empty($jobpk) || $jobpk < 0) {
            $text = _("Failed to insert job record");
            echo $text;
            return 1;
        }
    }
    $jq_args = "{$UploadPk} - {$Src}";
    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*/
    }
}
/**
 * \brief Find what folder an item is in.
 *
 * \param $upload_pk (null if $uploadtree_pk is passed in)
 * \param $uploadtree_pk (null if $upload_pk is passed in)
 * If both $upload_pk and $uploadtree_pk is passed in, $upload_pk will be used.
 *
 * \return the folder_pk that the upload_pk (or uploadtree_pk) is in
 */
function GetFolderFromItem($upload_pk = "", $uploadtree_pk = "")
{
    global $PG_CONN;
    /* validate inputs */
    if (empty($uploadtree_pk) and empty($upload_pk)) {
        return "__FILE__:__LINE__ GetFolderFromItem(empty)<br>";
    }
    if (empty($upload_pk)) {
        $UTrec = GetSingleRec("uploadtree", "where uploadtree_pk={$uploadtree_pk}");
        $upload_pk = $UTrec['upload_fk'];
    }
    $sql = "select parent_fk from foldercontents where child_id='{$upload_pk}' and foldercontents_mode=" . FolderDao::MODE_UPLOAD;
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    $FolderRow = pg_fetch_assoc($result);
    pg_free_result($result);
    return $FolderRow['parent_fk'];
}
/**
 * \brief Populate the sysconfig table with core variables.
 */
function Populate_sysconfig()
{
    global $PG_CONN;
    $Columns = "variablename, conf_value, ui_label, vartype, group_name, group_order, description, validation_function";
    $ValueArray = array();
    /*  Email */
    $Variable = "SupportEmailLabel";
    $SupportEmailLabelPrompt = _('Support Email Label');
    $SupportEmailLabelDesc = _('e.g. "Support"<br>Text that the user clicks on to create a new support email. This new email will be preaddressed to this support email address and subject.  HTML is ok.');
    $ValueArray[$Variable] = "'{$Variable}', 'Support', '{$SupportEmailLabelPrompt}'," . CONFIG_TYPE_TEXT . ",'Support', 1, '{$SupportEmailLabelDesc}', ''";
    $Variable = "SupportEmailAddr";
    $SupportEmailAddrPrompt = _('Support Email Address');
    $SupportEmailAddrValid = "check_email_address";
    $SupportEmailAddrDesc = _('e.g. "*****@*****.**"<br>Individual or group email address to those providing FOSSology support.');
    $ValueArray[$Variable] = "'{$Variable}', null, '{$SupportEmailAddrPrompt}', " . CONFIG_TYPE_TEXT . ",'Support', 2, '{$SupportEmailAddrDesc}', '{$SupportEmailAddrValid}'";
    $Variable = "SupportEmailSubject";
    $SupportEmailSubjectPrompt = _('Support Email Subject line');
    $SupportEmailSubjectDesc = _('e.g. "fossology support"<br>Subject line to use on support email.');
    $ValueArray[$Variable] = "'{$Variable}', 'FOSSology Support', '{$SupportEmailSubjectPrompt}'," . CONFIG_TYPE_TEXT . ",'Support', 3, '{$SupportEmailSubjectDesc}', ''";
    /*  Banner Message */
    $Variable = "BannerMsg";
    $BannerMsgPrompt = _('Banner message');
    $BannerMsgDesc = _('This is message will be displayed on every page with a banner.  HTML is ok.');
    $ValueArray[$Variable] = "'{$Variable}', null, '{$BannerMsgPrompt}', " . CONFIG_TYPE_TEXTAREA . ",'Banner', 1, '{$BannerMsgDesc}', ''";
    /*  Logo  */
    $Variable = "LogoImage";
    $LogoImagePrompt = _('Logo Image URL');
    $LogoImageValid = "check_logo_image_url";
    $LogoImageDesc = _('e.g. "http://mycompany.com/images/companylogo.png" or "images/mylogo.png"<br>This image replaces the fossology project logo. Image is constrained to 150px wide.  80-100px high is a good target.  If you change this URL, you MUST also enter a logo URL.');
    $ValueArray[$Variable] = "'{$Variable}', null, '{$LogoImagePrompt}', " . CONFIG_TYPE_TEXT . ",'Logo', 1, '{$LogoImageDesc}', '{$LogoImageValid}'";
    $Variable = "LogoLink";
    $LogoLinkPrompt = _('Logo URL');
    $LogoLinkDesc = _('e.g. "http://mycompany.com/fossology"<br>URL a person goes to when they click on the logo.  If you change the Logo URL, you MUST also enter a Logo Image.');
    $LogoLinkValid = "check_logo_url";
    $ValueArray[$Variable] = "'{$Variable}', null, '{$LogoLinkPrompt}', " . CONFIG_TYPE_TEXT . ",'Logo', 2, '{$LogoLinkDesc}', '{$LogoLinkValid}'";
    $Variable = "FOSSologyURL";
    $URLPrompt = _("FOSSology URL");
    $hostname = exec("hostname -f");
    if (empty($hostname)) {
        $hostname = "localhost";
    }
    $FOSSologyURL = $hostname . "/repo/";
    $URLDesc = _("URL of this FOSSology server, e.g. {$FOSSologyURL}");
    $URLValid = "check_fossology_url";
    $ValueArray[$Variable] = "'{$Variable}', '{$FOSSologyURL}', '{$URLPrompt}', " . CONFIG_TYPE_TEXT . ",'URL', 1, '{$URLDesc}', '{$URLValid}'";
    $Variable = "NomostListNum";
    $NomosNumPrompt = _("Maximum licenses to List");
    $NomostListNum = "2200";
    $NomosNumDesc = _("For License List and License List Download, you can set the maximum number of lines to list/download. Default 2200.");
    $ValueArray[$Variable] = "'{$Variable}', '{$NomostListNum}', '{$NomosNumPrompt}', " . CONFIG_TYPE_TEXT . ",'Number', 4, '{$NomosNumDesc}', null";
    $Variable = "ShowJobsAutoRefresh";
    $contextNamePrompt = _("ShowJobs Auto Refresh Time");
    $contextValue = "10";
    $contextDesc = _("No of seconds to refresh ShowJobs");
    $ValueArray[$Variable] = "'{$Variable}', '{$contextValue}', '{$contextNamePrompt}', " . CONFIG_TYPE_TEXT . ",'Number', null, '{$contextDesc}', null";
    $Variable = "BlockSizeHex";
    $hexPrompt = _("Chars per page in hex view");
    $hexDesc = _("Number of characters per page in hex view");
    $ValueArray[$Variable] = "'{$Variable}', '8192', '{$hexPrompt}', " . CONFIG_TYPE_TEXT . ",'Number', 5, '{$hexDesc}', null";
    $Variable = "BlockSizeText";
    $textPrompt = _("Chars per page in text view");
    $textDesc = _("Number of characters per page in text view");
    $ValueArray[$Variable] = "'{$Variable}', '81920', '{$textPrompt}', " . CONFIG_TYPE_TEXT . ",'Number', 5, '{$textDesc}', null";
    /*  "Upload from server"-configuration  */
    $Variable = "UploadFromServerWhitelist";
    $contextNamePrompt = _("Whitelist for serverupload");
    $contextValue = "/tmp";
    $contextDesc = _("List of allowed prefixes for upload, separated by \":\" (colon)");
    $ValueArray[$Variable] = "'{$Variable}', '{$contextValue}', '{$contextNamePrompt}', " . CONFIG_TYPE_TEXT . ",'UploadFromServer', 5, '{$contextDesc}', null";
    $Variable = "UploadFromServerAllowedHosts";
    $contextNamePrompt = _("List of allowed hosts for serverupload");
    $contextValue = "localhost";
    $contextDesc = _("List of allowed hosts for upload, separated by \":\" (colon)");
    $ValueArray[$Variable] = "'{$Variable}', '{$contextValue}', '{$contextNamePrompt}', " . CONFIG_TYPE_TEXT . ",'UploadFromServer', 5, '{$contextDesc}', null";
    /* Doing all the rows as a single insert will fail if any row is a dupe.
       So insert each one individually so that new variables get added.
      */
    foreach ($ValueArray as $Variable => $Values) {
        /* Check if the variable already exists.  Insert it if it does not.
         * This is better than an insert ignoring duplicates, because that
         * generates a postresql log message.
         */
        $VarRec = GetSingleRec("sysconfig", "where variablename='{$Variable}'");
        if (empty($VarRec)) {
            $sql = "insert into sysconfig ({$Columns}) values ({$Values});";
            $result = pg_query($PG_CONN, $sql);
            DBCheckResult($result, $sql, __FILE__, __LINE__);
            pg_free_result($result);
        }
        unset($VarRec);
    }
}