Esempio n. 1
0
 /**
  * \brief test for GetPkgMimetypes()
  */
 function test_GetPkgMimetypes()
 {
     print "test function GetPkgMimetypes()\n";
     global $PG_CONN;
     #prepare database testdata
     $mimeType = "application/x-rpm";
     /** delete test data pre testing */
     $sql = "DELETE FROM mimetype where mimetype_name in ('{$mimeType}');";
     $result = pg_query($PG_CONN, $sql);
     pg_free_result($result);
     /** insert on record */
     $sql = "INSERT INTO mimetype(mimetype_pk, mimetype_name) VALUES(10000, '{$mimeType}');";
     $result = pg_query($PG_CONN, $sql);
     pg_free_result($result);
     #begin test GetPkgMimetypes()
     $sql = "select * from mimetype where\n             mimetype_name='application/x-rpm'";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $row = pg_fetch_assoc($result);
     $expected = $row['mimetype_pk'];
     pg_free_result($result);
     $result = GetPkgMimetypes();
     $this->assertContains($expected, $result);
     /** delete test data post testing */
     $sql = "DELETE FROM mimetype where mimetype_name in ('{$mimeType}');";
     $result = pg_query($PG_CONN, $sql);
     pg_free_result($result);
 }
/**
 * \brief 
 * delete from copyright where pfile_fk not in (select pfile_pk from pfile)
 * add foreign constraint on copyright pfile_fk if not exist
 *
 * \return 0 on success, 1 on failure
 **/
function Migrate_20_25($Verbose)
{
    global $PG_CONN;
    $sql = "select count(*) from pg_class where relname='copyright';";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    $row = pg_fetch_assoc($result);
    pg_free_result($result);
    if (1 > $row['count']) {
        return 0;
        // fresh install, even no copyright table
    }
    $sql = "delete from copyright where pfile_fk not in (select pfile_pk from pfile);";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    pg_free_result($result);
    /** add foreign key CONSTRAINT on pfile_fk of copyrigyt table when not exist */
    $sql = "SELECT conname from pg_constraint where conname= 'copyright_pfile_fk_fkey';";
    $conresult = pg_query($PG_CONN, $sql);
    DBCheckResult($conresult, $sql, __FILE__, __LINE__);
    if (pg_num_rows($conresult) == 0) {
        $sql = "ALTER TABLE copyright ADD CONSTRAINT copyright_pfile_fk_fkey FOREIGN KEY (pfile_fk) REFERENCES pfile (pfile_pk) ON DELETE CASCADE; ";
        $result = pg_query($PG_CONN, $sql);
        DBCheckResult($result, $sql, __FILE__, __LINE__);
        pg_free_result($result);
        print "add contr\n";
    }
    pg_free_result($conresult);
    return 0;
}
 /**
  * \brief Generate the text for this plugin.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     global $PG_CONN;
     $V = "";
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             /* Get uploadtree_pk's for all debian uploads */
             $sql = "SELECT uploadtree_pk, upload_pk, upload_filename FROM upload INNER JOIN uploadtree ON upload_fk=upload_pk AND parent IS NULL WHERE upload_filename LIKE '%debian%';";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             $row = pg_fetch_assoc($result);
             if (empty($row['upload_pk'])) {
                 $V .= "There are no uploads with 'debian' in the description.";
             } else {
                 /* Loop thru results to obtain all licenses in their uploadtree recs*/
                 $Lics = array();
                 while ($Row = pg_fetch_array($result)) {
                     if (empty($Row['upload_pk'])) {
                         continue;
                     } else {
                         LicenseGetAll($Row[uploadtree_pk], $Lics);
                     }
                     $V .= "<option value='" . $Row['upload_pk'] . "'>{$Name}</option>\n";
                 }
                 $V .= "</select><P />\n";
                 arsort($Lics);
                 $V .= "<table border=1>\n";
                 foreach ($Lics as $key => $value) {
                     if ($key == " Total ") {
                         $V .= "<tr><th>{$key}<th>{$value}\n";
                     } else {
                         if (plugin_find_id('search_file_by_license') >= 0) {
                             $V .= "<tr><td><a href='/repo/?mod=search_file_by_license&item={$Row['uploadtree_pk']}&lic=" . urlencode($key) . "'>{$key}</a><td align='right'>{$value}\n";
                         } else {
                             $V .= "<tr><td>{$key}<td align='right'>{$value}\n";
                         }
                     }
                 }
                 $V .= "</table>\n";
                 //	  print "<pre>"; print_r($Lics); print "</pre>";
             }
             pg_free_result($result);
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }
 /**
  * \brief Generate the text for this plugin.
  */
 public function Output()
 {
     global $PG_CONN;
     $V = "";
     /* If this is a POST, then process the request. */
     $folder = GetParm('folder', PARM_INTEGER);
     if (!empty($folder)) {
         $rc = $this->Delete($folder);
         $sql = "SELECT * FROM folder where folder_pk = '{$folder}';";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $Folder = pg_fetch_assoc($result);
         pg_free_result($result);
         if (empty($rc)) {
             /* Need to refresh the screen */
             $text = _("Deletion of folder ");
             $text1 = _(" added to job queue");
             $this->vars['message'] = $text . $Folder['folder_name'] . $text1;
         } else {
             $text = _("Deletion of ");
             $text1 = _(" failed: ");
             $this->vars['message'] = $text . $Folder['folder_name'] . $text1 . $rc;
         }
     }
     $V .= "<form method='post'>\n";
     // no url = this url
     $text = _("Select the folder to");
     $text1 = _("delete");
     $V .= "{$text} <em>{$text1}</em>.\n";
     $V .= "<ul>\n";
     $text = _("This will");
     $text1 = _("delete");
     $text2 = _("the folder, all subfolders, and all uploaded files stored within the folder!");
     $V .= "<li>{$text} <em>{$text1}</em> {$text2}\n";
     $text = _("Be very careful with your selection since you can delete a lot of work!");
     $V .= "<li>{$text}\n";
     $text = _("All analysis only associated with the deleted uploads will also be deleted.");
     $V .= "<li>{$text}\n";
     $text = _("THERE IS NO UNDELETE. When you select something to delete, it will be removed from the database and file repository.");
     $V .= "<li>{$text}\n";
     $V .= "</ul>\n";
     $text = _("Select the folder to delete:  ");
     $V .= "<P>{$text}\n";
     $V .= "<select name='folder'>\n";
     $text = _("select folder");
     $V .= "<option value=''>[{$text}]</option>\n";
     $V .= FolderListOption(-1, 0);
     $V .= "</select><P />\n";
     $text = _("Delete");
     $V .= "<input type='submit' value='{$text}!'>\n";
     $V .= "</form>\n";
     return $V;
 }
Esempio n. 5
0
 /**
  * \brief Add an upload to multiple agents.
  *
  * \param $uploadpk 
  * \param $agentlist - list of agents
  * \return NULL on success, error message string on failure
  */
 function AgentsAdd($uploadpk, $agentlist)
 {
     global $Plugins;
     global $PG_CONN;
     global $SysConf;
     $rc = "";
     $Alist = array();
     /* Make sure the uploadpk is valid */
     if (!$uploadpk) {
         return "agent-add.php AgentsAdd(): No upload_pk specified";
     }
     $sql = "SELECT upload_pk, upload_filename FROM upload WHERE upload_pk = '{$uploadpk}';";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) < 1) {
         $ErrMsg = __FILE__ . ":" . __LINE__ . " " . _("Upload") . " " . $uploadpk . " " . _("not found");
         return $ErrMsg;
     }
     $UploadRow = pg_fetch_assoc($result);
     $ShortName = $UploadRow['upload_filename'];
     pg_free_result($result);
     /* Create Job */
     $user_pk = $SysConf['auth']['UserId'];
     $job_pk = JobAddJob($user_pk, $ShortName, $uploadpk);
     /* Validate the agent list and add agents as needed. */
     /** Don't worry about order or duplicates -- it will do the right thing. **/
     $Depth = 0;
     $agent_list = menu_find("Agents", $depth);
     for ($al = 0; !empty($agentlist[$al]); $al++) {
         /* check if the agent exists in the list of viable agents */
         $Found = -1;
         for ($ac = 0; $Found < 0 && !empty($agent_list[$ac]->URI); $ac++) {
             if (!strcmp($agent_list[$ac]->URI, $agentlist[$al])) {
                 $Found = $al;
                 break;
             }
         }
         if ($Found >= 0) {
             //print "Adding to " . $agentlist[$Found] . "<br>\n";
             $Dependencies = array();
             $P =& $Plugins[plugin_find_id($agentlist[$Found])];
             $rv = $P->AgentAdd($job_pk, $uploadpk, $ErrorMsg, $Dependencies);
             if ($rv == -1) {
                 $rc .= $ErrorMsg;
             }
         } else {
             $rc .= "Agent '" . htmlentities($agentlist[$al]) . "' not found.\n";
         }
     }
     return $rc;
 }
function RunSQL($sql, $DryRun)
{
    global $PG_CONN;
    $row = '';
    if ($DryRun) {
        echo "DryRun: {$sql}\n";
    } else {
        $result = pg_query($PG_CONN, $sql);
        DBCheckResult($result, $sql, __FILE__, __LINE__);
        $row = pg_fetch_assoc($result);
        pg_free_result($result);
    }
    return $row;
}
Esempio n. 7
0
 /**
  * \brief Enable/Disable Tag on one folder(all uploads under this folder) or one upload
  * 
  * \param $folder_id - folder id
  * \param $upload_id - upload id
  * \param $manage - enable or disable
  * 
  * \return return null when no uploads to manage, return 1 after setting
  */
 function ManageTag($folder_id, $upload_id, $manage)
 {
     global $PG_CONN;
     /** no operation */
     if (empty($manage)) {
         return;
     }
     if (empty($folder_id) && empty($upload_id)) {
         return;
     }
     /** get upload list */
     $upload_list = array();
     if (!empty($upload_id)) {
         $upload_list[0] = array('upload_pk' => $upload_id);
     } else {
         $upload_list = FolderListUploadsRecurse($folder_id, NULL, Auth::PERM_WRITE);
     }
     // want to manage all uploads under a folder
     foreach ($upload_list as $upload) {
         $upload_id = $upload['upload_pk'];
         if ("Enable" === $manage) {
             $manage_value = false;
         } else {
             $manage_value = true;
         }
         /** check if this upload has been disabled */
         $sql = "select * from tag_manage where upload_fk = {$upload_id} and is_disabled = true;";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $count = pg_num_rows($result);
         pg_free_result($result);
         if (empty($count) && $manage_value == true) {
             $sql = "INSERT INTO tag_manage(upload_fk, is_disabled) VALUES({$upload_id}, true);";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             pg_free_result($result);
         } else {
             if ($count == 1 && $manage_value == false) {
                 $sql = "delete from tag_manage where upload_fk = {$upload_id};";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 pg_free_result($result);
             }
         }
     }
     return 1;
 }
Esempio n. 8
0
 /**
  * \brief Add a group.
  * \param $GroupName raw group name as entered by the user
  * Returns NULL on success, string on failure.
  */
 function Add($GroupName)
 {
     global $PG_CONN;
     global $SysConf;
     $user_pk = $SysConf['auth']['UserId'];
     /* Get the parameters */
     $Group = str_replace("'", "''", $GroupName);
     /* Make sure groupname looks valid */
     if (empty($Group)) {
         $text = _("Error: Group name must be specified.");
         return $text;
     }
     /* See if the group already exists */
     $sql = "SELECT * FROM groups WHERE group_name = '{$Group}'";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) < 1) {
         pg_free_result($result);
         $sql = "INSERT INTO groups (group_name) VALUES ('{$Group}')";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         pg_free_result($result);
     } else {
         pg_free_result($result);
         $text = _("Group already exists.  Not added.");
         return $text;
     }
     /* Make sure it was added and get the group_pk */
     $sql = "SELECT group_pk FROM groups WHERE group_name = '{$Group}'";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) < 1) {
         pg_free_result($result);
         $text = _("Failed to create group");
         return $text . " {$Group}";
     }
     $row = pg_fetch_assoc($result);
     $Group_pk = $row['group_pk'];
     pg_free_result($result);
     /* Add group admin to table group_user_member */
     $sql = "INSERT INTO group_user_member (group_fk,user_fk,group_perm) VALUES ({$Group_pk}, {$user_pk}, 1)";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     pg_free_result($result);
     return NULL;
 }
Esempio n. 9
0
 /**
  * \brief Generate HTML output.
  */
 function HTMLout()
 {
     global $PG_CONN;
     $OutBuf = "";
     /* get config rows from sysconfig table */
     $sql = "select * from sysconfig order by group_name, group_order";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $Group = "";
     $InputStyle = "style='background-color:#dbf0f7'";
     $OutBuf .= "<form method='POST'>";
     while ($row = pg_fetch_assoc($result)) {
         if ($Group != $row['group_name']) {
             if ($Group) {
                 $OutBuf .= "</table><br>";
             }
             $Group = $row['group_name'];
             $OutBuf .= "<table border=1>";
         }
         $OutBuf .= "<tr><td>{$row['ui_label']}</td><td>";
         switch ($row['vartype']) {
             case CONFIG_TYPE_INT:
             case CONFIG_TYPE_TEXT:
                 $ConfVal = htmlentities($row['conf_value']);
                 $OutBuf .= "<INPUT type='text' name='new[{$row['variablename']}]' size='70' value='{$ConfVal}' title='{$row['description']}' {$InputStyle}>";
                 $OutBuf .= "<br>{$row['description']}";
                 break;
             case CONFIG_TYPE_TEXTAREA:
                 $ConfVal = htmlentities($row['conf_value']);
                 $OutBuf .= "<br><textarea name='new[{$row['variablename']}]' rows=3 cols=80 title='{$row['description']}' {$InputStyle}>{$ConfVal}</textarea>";
                 $OutBuf .= "<br>{$row['description']}";
                 break;
             default:
                 $OutBuf .= "Invalid configuration variable.  Unknown type.";
         }
         $OutBuf .= "</td></tr>";
         $OutBuf .= "<INPUT type='hidden' name='old[{$row['variablename']}]' value='{$ConfVal}'>";
     }
     $OutBuf .= "</table>";
     pg_free_result($result);
     $btnlabel = _("Update");
     $OutBuf .= "<p><input type='submit' value='{$btnlabel}'>";
     $OutBuf .= "</form>";
     return $OutBuf;
 }
 function ChangeBuckets()
 {
     global $SysConf;
     global $PG_CONN;
     $uploadId = GetParm("upload", PARM_STRING);
     $uploadTreeId = GetParm("item", PARM_STRING);
     $sql = "SELECT bucketpool_fk from bucket_ars where upload_fk = {$uploadId};";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $bucketpool_array = pg_fetch_all_columns($result, 0);
     pg_free_result($result);
     $buckets_dir = $SysConf['DIRECTORIES']['MODDIR'];
     /** rerun bucket on the file */
     foreach ($bucketpool_array as $bucketpool) {
         $command = "{$buckets_dir}/buckets/agent/buckets -r -t {$uploadTreeId} -p {$bucketpool}";
         exec($command);
     }
 }
Esempio n. 11
0
/**
 * \brief Add a user
 *        This also creates a group for the user and makes the user 
 *        the group admin.
 *
 * Parameters are the user table fields:
 * \param $User  user_name
 * \param $Desc  user_desc
 * \param $Seed  user_seed
 * \param $Hash  user_pass
 * \param $Perm  user_perm
 * \param $Email user_email
 * \param $Email_notify  email_notify
 * \param $agentList user_agent_list
 * \param $Folder root_folder_fk
 * \param $default_bucketpool_fk, default is empty
 * 
 * \return error: exit (1)
 */
function add_user($User, $Desc, $Seed, $Hash, $Perm, $Email, $Email_notify, $agentList, $Folder, $default_bucketpool_fk = '')
{
    global $PG_CONN;
    if (empty($default_bucketpool_fk)) {
        $VALUES = " VALUES ('{$User}','{$Desc}','{$Seed}','{$Hash}',{$Perm},'{$Email}',\n                        '{$Email_notify}','{$agentList}',{$Folder}, NULL)";
    } else {
        $VALUES = " VALUES ('{$User}','{$Desc}','{$Seed}','{$Hash}',{$Perm},'{$Email}',\n                        '{$Email_notify}','{$agentList}',{$Folder}, {$default_bucketpool_fk})";
    }
    $SQL = "INSERT INTO users\n         (user_name,user_desc,user_seed,user_pass,user_perm,user_email,\n          email_notify,user_agent_list,root_folder_fk, default_bucketpool_fk)\n          {$VALUES}";
    $result = pg_query($PG_CONN, $SQL);
    DBCheckResult($result, $SQL, __FILE__, __LINE__);
    pg_free_result($result);
    /* Make sure it was added */
    $SQL = "SELECT * FROM users WHERE user_name = '{$User}' LIMIT 1;";
    $result = pg_query($PG_CONN, $SQL);
    DBCheckResult($result, $SQL, __FILE__, __LINE__);
    $row = pg_fetch_assoc($result);
    pg_free_result($result);
    if (empty($row['user_name'])) {
        $text = _("Failed to insert user.");
        return $text;
    }
    /* The user was added, so create their group and make them the admin */
    $user_name = $row['user_name'];
    $user_pk = $row['user_pk'];
    // Add user group
    $sql = "insert into groups(group_name) values ('{$user_name}')";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    /* Get new group_pk */
    $sql = "select group_pk from groups where group_name='{$user_name}'";
    $GroupResult = pg_query($PG_CONN, $sql);
    DBCheckResult($GroupResult, $sql, __FILE__, __LINE__);
    $GroupRow = pg_fetch_assoc($GroupResult);
    $group_pk = $GroupRow['group_pk'];
    pg_free_result($GroupResult);
    // make user a member of their own group
    $sql = "insert into group_user_member(group_fk, user_fk, group_perm) values({$group_pk}, {$user_pk}, 1)";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    pg_free_result($result);
    return '';
}
Esempio n. 12
0
function list_license($reference_flag, $nomos_flag)
{
    global $PG_CONN;
    $sql_statment = "SELECT rf_shortname from license_ref ";
    if ($reference_flag) {
        $sql_statment .= " where rf_detector_type = 1";
    } else {
        if ($nomos_flag) {
            $sql_statment .= " where rf_detector_type = 2";
        }
    }
    $sql_statment .= " order by rf_shortname";
    $result = pg_query($PG_CONN, $sql_statment);
    DBCheckResult($result, $sql_statment, __FILE__, __LINE__);
    while ($row = pg_fetch_assoc($result)) {
        print $row['rf_shortname'] . "\n";
    }
    pg_free_result($result);
}
 /**
  * \brief Display the loaded menu and plugins.
  */
 public function Output()
 {
     global $Plugins;
     global $PG_CONN;
     $UploadPk = GetParm("upload", PARM_INTEGER);
     $Agent = GetParm("agent", PARM_STRING);
     if (empty($UploadPk) || empty($Agent)) {
         return new Response('missing parameter', Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain'));
     }
     $sql = "SELECT upload_pk, upload_filename FROM upload WHERE upload_pk = '{$UploadPk}'";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) < 1) {
         $errMsg = __FILE__ . ":" . __LINE__ . " " . _("Upload") . " " . $UploadPk . " " . _("not found");
         return new Response($errMsg, Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain'));
     }
     $UploadRow = pg_fetch_assoc($result);
     $ShortName = $UploadRow['upload_filename'];
     pg_free_result($result);
     $user_pk = Auth::getUserId();
     $group_pk = Auth::getGroupId();
     $job_pk = JobAddJob($user_pk, $group_pk, $ShortName, $UploadPk);
     $Dependencies = array();
     $P =& $Plugins[plugin_find_id($Agent)];
     $rv = $P->AgentAdd($job_pk, $UploadPk, $ErrorMsg, $Dependencies);
     if ($rv <= 0) {
         $text = _("Scheduling of Agent(s) failed: ");
         return new Response($text . $rv . $ErrorMsg, Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain'));
     }
     /** check if the scheudler is running */
     $status = GetRunnableJobList();
     $scheduler_msg = "";
     if (empty($status)) {
         $scheduler_msg .= _("Is the scheduler running? ");
     }
     $URL = Traceback_uri() . "?mod=showjobs&upload={$UploadPk}";
     /* Need to refresh the screen */
     $text = _("Your jobs have been added to job queue.");
     $LinkText = _("View Jobs");
     $msg = "{$scheduler_msg}" . "{$text} <a href={$URL}>{$LinkText}</a>";
     $this->vars['message'] = $msg;
     return new Response($msg, Response::HTTP_OK, array('Content-type' => 'text/plain'));
 }
/**
 * \brief get all the copyright for a single file or uploadtree
 * 
 * \param $agent_pk - agent id
 * \param $pfile_pk - pfile id, (if empty, $uploadtree_pk must be given)
 * \param $uploadtree_pk - (used only if $pfile_pk is empty)
 * \param $type - copyright statement/url/email
 * 
 * \return Array of file copyright CopyrightArray[ct_pk] = copyright.content
 * FATAL if neither pfile_pk or uploadtree_pk were passed in
 */
function GetFileCopyrights($agent_pk, $pfile_pk, $uploadtree_pk, $type)
{
    global $PG_CONN;
    if (empty($agent_pk)) {
        Fatal("Missing parameter: agent_pk", __FILE__, __LINE__);
    }
    // if $pfile_pk, then return the copyright for that one file
    if ($pfile_pk) {
        $sql = "SELECT ct_pk, content \n              from copyright\n              where pfile_fk='{$pfile_pk}' and agent_fk={$agent_pk};";
        $result = pg_query($PG_CONN, $sql);
        DBCheckResult($result, $sql, __FILE__, __LINE__);
    } else {
        if ($uploadtree_pk) {
            // Find lft and rgt bounds 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);
            $typesql = '';
            if ($type && "all" != $type) {
                $typesql = "and type = '{$type}'";
            }
            //  Get the copyright under this $uploadtree_pk
            $sql = "SELECT ct_pk, content from copyright ,\n                  (SELECT distinct(pfile_fk) as PF from uploadtree\n                     where upload_fk={$upload_pk}\n                       and uploadtree.lft BETWEEN {$lft} and {$rgt}) as SS\n              where PF=pfile_fk and agent_fk={$agent_pk} {$typesql};";
            $result = pg_query($PG_CONN, $sql);
            DBCheckResult($result, $sql, __FILE__, __LINE__);
        } else {
            Fatal("Missing function inputs", __FILE__, __LINE__);
        }
    }
    $CopyrightArray = array();
    while ($row = pg_fetch_assoc($result)) {
        $CopyrightArray[$row['ct_pk']] = $row["content"];
    }
    pg_free_result($result);
    return $CopyrightArray;
}
 /**
  * \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":
             $upload_id = GetParm("upload", PARM_INTEGER);
             if (empty($upload_id)) {
                 break;
             }
             global $PG_CONN;
             /** check if this upload has been disabled */
             $sql = "select * from tag_manage where upload_fk = {$upload_id} and is_disabled = true;";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             $count = pg_num_rows($result);
             pg_free_result($result);
             if (empty($count)) {
                 $text = _("Disable");
                 $V = "<input type='submit' name='manage'  value='{$text}'>\n";
             } else {
                 $text = _("Enable");
                 $V = "<input type='submit' name='manage' value='{$text}'>\n";
             }
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print "{$V}";
     return;
 }
 /**
  * \brief Generate output.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     $V = "";
     global $PG_CONN;
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             $sql = "SELECT * FROM users WHERE user_pk = '" . @$_SESSION['UserId'] . "';";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             $R = pg_fetch_assoc($result);
             pg_free_result($result);
             $text = _("User Information");
             $V .= "<H2>{$text}</H2>\n";
             $V .= "<table border=1>\n";
             $text = _("Field");
             $text1 = _("Value");
             $V .= "<tr><th>{$text}</th><th>{$text1}</th></tr>\n";
             foreach ($R as $Key => $Val) {
                 if (empty($Key)) {
                     continue;
                 }
                 $V .= "<tr><td>" . htmlentities($Key) . "</td><td>" . htmlentities($Val) . "</td></tr>\n";
             }
             $V .= "</table>\n";
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }
Esempio n. 17
0
 /**
  * \brief Show all tags
  */
 function ShowExistTags()
 {
     global $PG_CONN;
     $VE = "";
     $VE = _("<h3>Current Tags:</h3>\n");
     $sql = "SELECT tag_pk, tag, tag_desc FROM tag ORDER BY tag_pk desc;";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) > 0) {
         $VE .= "<table border=1>\n";
         $text1 = _("Tag pk");
         $text2 = _("Tag");
         $text3 = _("Tag Description");
         $VE .= "<tr><th>{$text1}</th><th>{$text2}</th><th>{$text3}</th></tr>\n";
         while ($row = pg_fetch_assoc($result)) {
             $VE .= "<tr><td align='center'>" . $row['tag_pk'] . "</td><td align='center'>" . $row['tag'] . "</td><td align='center'>" . $row['tag_desc'] . "</td>";
         }
         $VE .= "</table><p>\n";
     }
     pg_free_result($result);
     return $VE;
 }
Esempio n. 18
0
/**
 * \brief  Use two columns in a table to create an array key => val
 * \param $keycol key column
 * \param $valcol can be a comma separated list of value columns
 * \param $tablename
 * \param $separator is used to separate values if there are multiple columns
 * \param $where is an optional where clause eg "where a=b", "order by x", ...
 */
function Table2Array($keycol, $valcol, $tablename, $separator = " ", $where = "")
{
    global $PG_CONN;
    $valarray = explode(",", $valcol);
    $RetArray = array();
    $sql = "select {$keycol}, {$valcol} from {$tablename} {$where}";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    if (pg_num_rows($result) > 0) {
        while ($row = pg_fetch_assoc($result)) {
            $newval = "";
            foreach ($valarray as $sqlcolname) {
                if (!empty($newval)) {
                    $newval .= $separator;
                }
                $newval .= $row[trim($sqlcolname)];
            }
            $RetArray[$row[$keycol]] = $newval;
        }
    }
    pg_free_result($result);
    return $RetArray;
}
Esempio n. 19
0
 public function Output()
 {
     $V = "";
     global $PG_CONN;
     $sql = "SELECT * FROM users WHERE user_pk = '" . @$_SESSION['UserId'] . "';";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $R = pg_fetch_assoc($result);
     pg_free_result($result);
     $text = _("User Information");
     $V .= "<H2>{$text}</H2>\n";
     $V .= "<table border=1>\n";
     $text = _("Field");
     $text1 = _("Value");
     $V .= "<tr><th>{$text}</th><th>{$text1}</th></tr>\n";
     foreach ($R as $Key => $Val) {
         if (empty($Key)) {
             continue;
         }
         $V .= "<tr><td>" . htmlentities($Key) . "</td><td>" . htmlentities($Val) . "</td></tr>\n";
     }
     $V .= "</table>\n";
     return $V;
 }
Esempio n. 20
0
 /**
  * \brief Given a filename, return all uploadtree.
  * \param $Item     uploadtree_pk of tree to search, if empty, do global search
  * \param $Filename filename or pattern to search for, false if unused
  * \param $tag      tag (or tag pattern mytag%) to search for, false if unused
  * \param $Page     display page number
  * \param $SizeMin  Minimum file size, -1 if unused
  * \param $SizeMax  Maximum file size, -1 if unused
  * \param $searchtype "containers" or "allfiles"
  * \return array of uploadtree recs.  Each record contains uploadtree_pk, parent, 
  *         upload_fk, pfile_fk, ufile_mode, and ufile_name
  */
 function GetResults($Item, $Filename, $tag, $Page, $SizeMin, $SizeMax, $searchtype, $License, $Copyright)
 {
     global $PG_CONN;
     $UploadtreeRecs = array();
     // uploadtree record array to return
     $NeedTagfileTable = true;
     $NeedTaguploadtreeTable = true;
     if ($Item) {
         /* Find lft and rgt bounds for this $Uploadtree_pk  */
         $row = $this->uploadDao->getUploadEntry($Item);
         if (empty($row)) {
             $text = _("Invalid URL, nonexistant item");
             return "<h2>{$text} {$Item}</h2>";
         }
         $lft = $row["lft"];
         $rgt = $row["rgt"];
         $upload_pk = $row["upload_fk"];
         /* Check upload permission */
         if (!$this->uploadDao->isAccessible($upload_pk, Auth::getGroupId())) {
             return $UploadtreeRecs;
         }
     }
     /* Start the result select stmt */
     $SQL = "SELECT DISTINCT uploadtree_pk, parent, upload_fk, uploadtree.pfile_fk, ufile_mode, ufile_name FROM uploadtree";
     if (!empty($License)) {
         $SQL .= ", ( SELECT license_ref.rf_shortname, license_file.rf_fk, license_file.pfile_fk\n                  FROM license_file JOIN license_ref ON license_file.rf_fk = license_ref.rf_pk) AS pfile_ref";
     }
     if (!empty($Copyright)) {
         $SQL .= ",copyright";
     }
     /* Figure out the tag_pk's of interest */
     if (!empty($tag)) {
         $sql = "select tag_pk from tag where tag ilike '{$tag}'";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result) < 1) {
             /* tag doesn't match anything, so no results are possible */
             pg_free_result($result);
             return $UploadtreeRecs;
         }
         /* Make a list of the tag_pk's that satisfy the criteria */
         $tag_pk_array = pg_fetch_all($result);
         pg_free_result($result);
         /* add the tables needed for the tag query */
         $sql = "select tag_file_pk from tag_file limit 1";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result) < 1) {
             /* tag_file didn't have data, don't add the tag_file table for tag query */
             $NeedTagfileTable = false;
         } else {
             $SQL .= ", tag_file";
         }
         pg_free_result($result);
         /* add the tables needed for the tag query */
         $sql = "select tag_uploadtree_pk from tag_uploadtree limit 1";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result) < 1) {
             /* tag_uploadtree didn't have data, don't add the tag_uploadtree table for tag query */
             $NeedTaguploadtreeTable = false;
         } else {
             $SQL .= ", tag_uploadtree";
         }
         pg_free_result($result);
         if (!$NeedTagfileTable && !$NeedTaguploadtreeTable) {
             $SQL .= ", tag_file, tag_uploadtree";
         }
     }
     /* do we need the pfile table? Yes, if any of these are a search critieria.  */
     if (!empty($SizeMin) or !empty($SizeMax)) {
         $SQL .= ", pfile where pfile_pk=uploadtree.pfile_fk ";
         $NeedAnd = true;
     } else {
         $SQL .= " where ";
         $NeedAnd = false;
     }
     /* add the tag conditions */
     if (!empty($tag)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= "(";
         $NeedOr = false;
         foreach ($tag_pk_array as $tagRec) {
             if ($NeedOr) {
                 $SQL .= " OR";
             }
             $SQL .= "(";
             $tag_pk = $tagRec['tag_pk'];
             if ($NeedTagfileTable && $NeedTaguploadtreeTable) {
                 $SQL .= "(uploadtree.pfile_fk=tag_file.pfile_fk and tag_file.tag_fk={$tag_pk}) or (uploadtree_pk=tag_uploadtree.uploadtree_fk and tag_uploadtree.tag_fk={$tag_pk}) ";
             } else {
                 if ($NeedTaguploadtreeTable) {
                     $SQL .= "uploadtree_pk=tag_uploadtree.uploadtree_fk and tag_uploadtree.tag_fk={$tag_pk}";
                 } else {
                     if ($NeedTagfileTable) {
                         $SQL .= "uploadtree.pfile_fk=tag_file.pfile_fk and tag_file.tag_fk={$tag_pk}";
                     } else {
                         $SQL .= "(uploadtree.pfile_fk=tag_file.pfile_fk and tag_file.tag_fk={$tag_pk}) or (uploadtree_pk=tag_uploadtree.uploadtree_fk and tag_uploadtree.tag_fk={$tag_pk}) ";
                     }
                 }
             }
             $SQL .= ")";
             $NeedOr = 1;
         }
         $NeedAnd = 1;
         $SQL .= ")";
     }
     if ($Filename) {
         $Filename = str_replace("'", "''", $Filename);
         // protect DB
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " ufile_name ilike '{$Filename}'";
         $NeedAnd = 1;
     }
     if (!empty($SizeMin)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " pfile.pfile_size >= {$SizeMin}";
         $NeedAnd = 1;
     }
     if (!empty($SizeMax)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " pfile.pfile_size <= {$SizeMax}";
         $NeedAnd = 1;
     }
     if ($Item) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= "  upload_fk = {$upload_pk} AND lft >= {$lft} AND rgt <= {$rgt}";
         $NeedAnd = 1;
     }
     /* search only containers */
     $dir_ufile_mode = 536888320;
     if ($searchtype == 'containers') {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " ((ufile_mode & (1<<29))!=0) AND ((ufile_mode & (1<<28))=0)";
         $NeedAnd = 1;
     }
     if ($searchtype == 'directory') {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " ((ufile_mode & (1<<29))!=0) AND ((ufile_mode & (1<<28))=0) AND (ufile_mode != {$dir_ufile_mode}) and pfile_fk != 0";
         $NeedAnd = 1;
     }
     /** license and copyright */
     if (!empty($License)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " uploadtree.pfile_fk=pfile_ref.pfile_fk and pfile_ref.rf_shortname ilike '{$License}'";
         $NeedAnd = 1;
     }
     if (!empty($Copyright)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " uploadtree.pfile_fk=copyright.pfile_fk and copyright.content ilike '%{$Copyright}%'";
     }
     $Offset = $Page * $this->MaxPerPage;
     $SQL .= " ORDER BY ufile_name, uploadtree.pfile_fk";
     $SQL .= " LIMIT {$this->MaxPerPage} OFFSET {$Offset};";
     $result = pg_query($PG_CONN, $SQL);
     DBCheckResult($result, $SQL, __FILE__, __LINE__);
     if (pg_num_rows($result)) {
         while ($row = pg_fetch_assoc($result)) {
             if (!$this->uploadDao->isAccessible($row['upload_fk'], Auth::getGroupId())) {
                 continue;
             }
             $UploadtreeRecs[] = $row;
         }
     }
     pg_free_result($result);
     return $UploadtreeRecs;
 }
Esempio n. 21
0
/**
 * \brief Get an array of all the folders from a $RootFolder on down.
 * Recursive.  This is typically used to build a select list of folder names.
 *
 * \param $RootFolder default is entire software repository
 * \param $FolderArray returned array of folder_pk=>folder_name's
 *
 * \return $FolderArray of {folder_pk=>folder_name, folder_pk=>folder_name, ...}
 * in folder order.
 * If no folders are in the list, an empty array is returned.
 *
 * \todo Possibly this could be a common function and FolderListOption() could 
 *       use this for its data.  In general data collection and data formatting
 *       should be separate functions.
 */
function GetFolderArray($RootFolder, &$FolderArray)
{
    global $PG_CONN;
    if ($RootFolder == "-1") {
        $RootFolder = FolderGetTop();
    }
    if (empty($RootFolder)) {
        return $FolderArray;
    }
    /* Load this folder's name */
    $sql = "SELECT folder_name, folder_pk FROM folder WHERE folder_pk={$RootFolder} LIMIT 1;";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    $row = pg_fetch_assoc($result);
    pg_free_result($result);
    $Name = trim($row['folder_name']);
    $FolderArray[$row['folder_pk']] = $row['folder_name'];
    /* Load any subfolders */
    $sql = "SELECT folder.folder_pk, folder.folder_name,\n            foldercontents.parent_fk\n            FROM folder, foldercontents\n            WHERE foldercontents.foldercontents_mode = " . FolderDao::MODE_FOLDER . "\n            AND foldercontents.parent_fk ={$RootFolder}\n            AND foldercontents.child_id = folder.folder_pk\n            AND folder.folder_pk is not null\n            ORDER BY folder_name";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    if (pg_num_rows($result) > 0) {
        while ($row = pg_fetch_assoc($result)) {
            GetFolderArray($row['folder_pk'], $FolderArray);
        }
    }
    pg_free_result($result);
}
 function Output()
 {
     global $PG_CONN;
     global $PERM_NAMES;
     /* GET parameters */
     $folder_pk = GetParm('folder', PARM_INTEGER);
     $upload_pk = GetParm('upload', PARM_INTEGER);
     $users_group_pk = GetParm('group_pk', PARM_INTEGER);
     $group_pk = GetParm('group', PARM_INTEGER);
     $perm_upload_pk = GetParm('permupk', PARM_INTEGER);
     $perm = GetParm('perm', PARM_INTEGER);
     $newgroup = GetParm('newgroup', PARM_INTEGER);
     $newperm = GetParm('newperm', PARM_INTEGER);
     $public_perm = GetParm('public', PARM_INTEGER);
     // start building the output buffer
     $V = "";
     /* If perm_upload_pk is passed in, update either the perm or group_pk */
     $sql = "";
     if (!empty($perm_upload_pk)) {
         if ($perm === 0) {
             $sql = "delete from perm_upload where perm_upload_pk='{$perm_upload_pk}'";
         } else {
             if (!empty($perm)) {
                 $sql = "update perm_upload set perm='{$perm}' where perm_upload_pk='{$perm_upload_pk}'";
             } else {
                 if (!empty($group_pk)) {
                     $sql = "update perm_upload set group_fk='{$group_pk}' where perm_upload_pk='{$perm_upload_pk}'";
                 }
             }
         }
         if (!empty($sql)) {
             $result = @pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             pg_free_result($result);
         }
     } else {
         if (!empty($newgroup) and !empty($newperm)) {
             // before inserting this new record, delete any record for the same upload and group since
             // that would be a duplicate
             $sql = "delete from perm_upload where upload_fk={$upload_pk} and group_fk={$newgroup}";
             $result = pg_query($PG_CONN, $sql);
             DBCheckResult($result, $sql, __FILE__, __LINE__);
             pg_free_result($result);
             // Don't insert a PERM_NONE.  NONE is the default
             if ($newperm != PERM_NONE) {
                 $sql = "insert into perm_upload (perm, upload_fk, group_fk) values ({$newperm}, {$upload_pk}, {$newgroup})";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 pg_free_result($result);
             }
             $newperm = $newgroup = 0;
         } else {
             if (!empty($public_perm)) {
                 $sql = "update upload set public_perm='{$public_perm}' where upload_pk='{$upload_pk}'";
                 $result = pg_query($PG_CONN, $sql);
                 DBCheckResult($result, $sql, __FILE__, __LINE__);
                 pg_free_result($result);
             }
         }
     }
     $root_folder_pk = GetUserRootFolder();
     if (empty($folder_pk)) {
         $folder_pk = $root_folder_pk;
     }
     // Get folder array folder_pk => folder_name
     $FolderArray = array();
     GetFolderArray($root_folder_pk, $FolderArray);
     /* define js_url */
     $V .= js_url();
     $text = _("Select the folder that contains the upload:  \n");
     $V .= "{$text}";
     /*** Display folder select list, on change request new page with folder= in url ***/
     $url = Traceback_uri() . "?mod=upload_permissions&folder=";
     $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
     $V .= Array2SingleSelect($FolderArray, "folderselect", $folder_pk, false, false, $onchange);
     /*** Display upload select list, on change, request new page with new upload= in url ***/
     $text = _("Select the upload you wish to edit:  \n");
     $V .= "<br>{$text}";
     // Get list of all upload records in this folder that the user has PERM_ADMIN
     $UploadList = FolderListUploads_perm($folder_pk, PERM_ADMIN);
     /*
     if (empty($UploadList))
     {
     echo "You have no uploads in this folder for which you are an admin.  Hit the back button";
     return;
     }
     */
     // Make data array for upload select list.  Key is upload_pk, value is a composite
     // of the upload_filename and upload_ts.
     // Note that $UploadList may be empty so $UploadArray will be empty
     $UploadArray = array();
     foreach ($UploadList as $UploadRec) {
         $SelectText = htmlentities($UploadRec['name']);
         if (!empty($UploadRec['upload_ts'])) {
             $SelectText .= ", " . substr($UploadRec['upload_ts'], 0, 19);
         }
         $UploadArray[$UploadRec['upload_pk']] = $SelectText;
     }
     /* Get selected upload info to display*/
     if (empty($upload_pk)) {
         // no upload selected, so use the top one in the select list
         reset($UploadArray);
         $upload_pk = key($UploadArray);
     }
     /* Upload select list */
     $url = Traceback_uri() . "?mod=upload_permissions&folder={$folder_pk}&upload=";
     $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
     $V .= Array2SingleSelect($UploadArray, "uploadselect", $upload_pk, false, false, $onchange);
     /* Get permissions for this upload */
     if (!empty($UploadArray)) {
         // Get upload.public_perm
         $sql = "select public_perm from upload where upload_pk='{$upload_pk}'";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $Row = pg_fetch_all($result);
         $public_perm = $Row[0]['public_perm'];
         pg_free_result($result);
         $text1 = _("Public Permission");
         $V .= "<p>{$text1} &nbsp;";
         $url = Traceback_uri() . "?mod=upload_permissions&folder={$folder_pk}&upload={$upload_pk}&public=";
         $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
         $V .= Array2SingleSelect($PERM_NAMES, "publicpermselect", $public_perm, false, false, $onchange);
         $sql = "select perm_upload_pk, perm, group_pk, group_name from groups, perm_upload where group_fk=group_pk and upload_fk='{$upload_pk}'";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $PermArray = pg_fetch_all($result);
         pg_free_result($result);
         /* Get master array of groups */
         $sql = "select group_pk, group_name from groups order by group_name";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $GroupArray = array();
         while ($GroupRow = pg_fetch_assoc($result)) {
             $GroupArray[$GroupRow['group_pk']] = $GroupRow['group_name'];
         }
         pg_free_result($result);
         /* Permissions Table */
         $V .= "<p><table border=1>";
         $GroupText = _("Group");
         $PermText = _("Permission");
         $V .= "<tr><th>{$GroupText}</th><th>{$PermText}</th></tr>";
         foreach ($PermArray as $PermRow) {
             $V .= "<tr>";
             $V .= "<td>";
             // group
             $url = Traceback_uri() . "?mod=upload_permissions&group_pk={$users_group_pk}&upload={$upload_pk}&folder={$folder_pk}&permupk={$PermRow['perm_upload_pk']}&group=";
             $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
             $V .= Array2SingleSelect($GroupArray, "groupselect", $PermRow['group_pk'], false, false, $onchange);
             $V .= "</td>";
             $V .= "<td>";
             // permission
             $url = Traceback_uri() . "?mod=upload_permissions&group_pk={$users_group_pk}&upload={$upload_pk}&folder={$folder_pk}&permupk={$PermRow['perm_upload_pk']}&perm=";
             $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
             $V .= Array2SingleSelect($PERM_NAMES, "permselect", $PermRow['perm'], false, false, $onchange);
             $V .= "</td>";
             $V .= "</tr>";
         }
         /* Print one extra row for adding perms */
         $V .= "<tr>";
         $V .= "<td>";
         // group
         $url = Traceback_uri() . "?mod=upload_permissions&group_pk={$users_group_pk}&upload={$upload_pk}&folder={$folder_pk}&newperm={$newperm}&newgroup=";
         $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
         $Selected = empty($newgroup) ? "" : $newgroup;
         $V .= Array2SingleSelect($GroupArray, "groupselectnew", $Selected, true, false, $onchange);
         $V .= "</td>";
         $V .= "<td>";
         // permission
         $url = Traceback_uri() . "?mod=upload_permissions&group_pk={$users_group_pk}&upload={$upload_pk}&folder={$folder_pk}&newgroup={$newgroup}&newperm=";
         $onchange = "onchange=\"js_url(this.value, '{$url}')\"";
         $Selected = empty($newperm) ? "" : $newperm;
         $V .= Array2SingleSelect($PERM_NAMES, "permselectnew", $Selected, false, false, $onchange);
         $V .= "</td>";
         $V .= "</tr>";
         $V .= "</table>";
         $text = _("All upload permissions take place immediately when a value is changed.  There is no submit button.");
         $V .= "<p>" . $text;
         $text = _("Add new groups on the last line.");
         $V .= "<br>" . $text;
     } else {
         $text = _("You have no permission to change permissions on any upload in this folder.");
         $V .= "<p>{$text}<p>";
     }
     $V .= "<hr>";
     $V .= $this->DisplayGroupMembership();
     if (!$this->OutputToStdout) {
         return $V;
     }
     print "{$V}";
     return;
 }
Esempio n. 23
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;
        }
    }
}
Esempio n. 24
0
 /**
  * \brief Given an $Uploadtree_pk, display: \n
  * (1) The histogram for the directory BY bucket. \n
  * (2) The file listing for the directory.
  */
 function ShowUploadHist($Uploadtree_pk, $Uri)
 {
     global $PG_CONN;
     $VF = "";
     // return values for file listing
     $VLic = "";
     // return values for output
     $V = "";
     // total return value
     $UniqueTagArray = array();
     global $Plugins;
     $ModLicView =& $Plugins[plugin_find_id("view-license")];
     /*******  Get Bucket names and counts  ******/
     /* Find lft and rgt bounds for this $Uploadtree_pk  */
     $sql = "SELECT lft,rgt,upload_fk FROM {$this->uploadtree_tablename}\n              WHERE uploadtree_pk = {$Uploadtree_pk}";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) < 1) {
         pg_free_result($result);
         $text = _("Invalid URL, nonexistant item");
         return "<h2>{$text} {$Uploadtree_pk}</h2>";
     }
     $row = pg_fetch_assoc($result);
     $lft = $row["lft"];
     $rgt = $row["rgt"];
     $upload_pk = $row["upload_fk"];
     pg_free_result($result);
     /* Get the ars_pk of the scan to display, also the select list  */
     $ars_pk = GetArrayVal("ars", $_GET);
     $BucketSelect = SelectBucketDataset($upload_pk, $ars_pk, "selectbdata", "onchange=\"addArsGo('newds','selectbdata');\"");
     if ($ars_pk == 0) {
         /* No bucket data for this upload */
         return $BucketSelect;
     }
     /* Get scan keys */
     $sql = "select agent_fk, nomosagent_fk, bucketpool_fk from bucket_ars where ars_pk={$ars_pk}";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $row = pg_fetch_assoc($result);
     $bucketagent_pk = $row["agent_fk"];
     $nomosagent_pk = $row["nomosagent_fk"];
     $bucketpool_pk = $row["bucketpool_fk"];
     pg_free_result($result);
     /* Create bucketDefArray as individual query this is MUCH faster
         than incorporating it with a join in the following queries.
        */
     $bucketDefArray = initBucketDefArray($bucketpool_pk);
     /*select all the buckets for entire tree for this bucketpool */
     $sql = "SELECT distinct(bucket_fk) as bucket_pk,\n                   count(bucket_fk) as bucketcount, bucket_reportorder\n              from bucket_file, bucket_def,\n                  (SELECT distinct(pfile_fk) as PF from {$this->uploadtree_tablename} \n                     where upload_fk={$upload_pk} \n                       and ((ufile_mode & (1<<28))=0)\n                       and ((ufile_mode & (1<<29))=0)\n                       and {$this->uploadtree_tablename}.lft BETWEEN {$lft} and {$rgt}) as SS\n              where PF=pfile_fk and agent_fk={$bucketagent_pk} \n                    and bucket_file.nomosagent_fk={$nomosagent_pk}\n                    and bucket_pk=bucket_fk\n                    and bucketpool_fk={$bucketpool_pk}\n              group by bucket_fk,bucket_reportorder\n              order by bucket_reportorder asc";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $historows = pg_fetch_all($result);
     pg_free_result($result);
     /* Show dataset list */
     if (!empty($BucketSelect)) {
         $action = Traceback_uri() . "?mod=bucketbrowser&upload={$upload_pk}&item={$Uploadtree_pk}";
         $VLic .= "<script type='text/javascript'>\nfunction addArsGo(formid, selectid ) \n{\nvar selectobj = document.getElementById(selectid);\nvar ars_pk = selectobj.options[selectobj.selectedIndex].value;\ndocument.getElementById(formid).action='{$action}'+'&ars='+ars_pk;\ndocument.getElementById(formid).submit();\nreturn;\n}\n</script>";
         /* form to select new dataset (ars_pk) */
         $VLic .= "<form action='{$action}' id='newds' method='POST'>\n";
         $VLic .= $BucketSelect;
         $VLic .= "</form>";
     }
     $sql = "select bucketpool_name, version from bucketpool where bucketpool_pk={$bucketpool_pk}";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $row = pg_fetch_assoc($result);
     $bucketpool_name = $row['bucketpool_name'];
     $bucketpool_version = $row['version'];
     pg_free_result($result);
     /* Write bucket histogram to $VLic  */
     $bucketcount = 0;
     $Uniquebucketcount = 0;
     $NoLicFound = 0;
     if (is_array($historows)) {
         $text = _("Bucket Pool");
         $VLic .= "{$text}: {$bucketpool_name} v{$bucketpool_version}<br>";
         $VLic .= "<table border=1 width='100%'>\n";
         $text = _("Count");
         $VLic .= "<tr><th width='10%'>{$text}</th>";
         $text = _("Files");
         $VLic .= "<th width='10%'>{$text}</th>";
         $text = _("Bucket");
         $VLic .= "<th align='left'>{$text}</th></tr>\n";
         foreach ($historows as $bucketrow) {
             $Uniquebucketcount++;
             $bucket_pk = $bucketrow['bucket_pk'];
             $bucketcount = $bucketrow['bucketcount'];
             $bucket_name = $bucketDefArray[$bucket_pk]['bucket_name'];
             $bucket_color = $bucketDefArray[$bucket_pk]['bucket_color'];
             /*  Count  */
             $VLic .= "<tr><td align='right' style='background-color:{$bucket_color}'>{$bucketcount}</td>";
             /*  Show  */
             $VLic .= "<td align='center'><a href='";
             $VLic .= Traceback_uri();
             $text = _("Show");
             $VLic .= "?mod=list_bucket_files&bapk={$bucketagent_pk}&item={$Uploadtree_pk}&bpk={$bucket_pk}&bp={$bucketpool_pk}&napk={$nomosagent_pk}" . "'>{$text}</a></td>";
             /*  Bucket name  */
             $VLic .= "<td align='left'>";
             $VLic .= "<a id='{$bucket_pk}' onclick='FileColor_Get(\"" . Traceback_uri() . "?mod=ajax_filebucket&bapk={$bucketagent_pk}&item={$Uploadtree_pk}&bucket_pk={$bucket_pk}\")'";
             $VLic .= ">{$bucket_name} </a>";
             /* Allow users to tag an entire bucket */
             /* Future, maybe v 2.1 
                     $TagHref = "<a href=" . Traceback_uri() . "?mod=bucketbrowser&upload=$upload_pk&item=$Uploadtree_pk&bapk=$bucketagent_pk&bpk=$bucket_pk&bp=$bucketpool_pk&napk=$nomosagent_pk&tagbucket=1>Tag</a>";
                     $VLic .= " [$TagHref]";
             */
             $VLic .= "</td>";
             $VLic .= "</tr>\n";
             //      if ($row['bucket_name'] == "No Buckets Found") $NoLicFound =  $row['bucketcount'];
         }
         $VLic .= "</table>\n";
         $VLic .= "<p>\n";
         $text = _("Unique buckets");
         $VLic .= "{$text}: {$Uniquebucketcount}<br>\n";
     }
     /*******    File Listing     ************/
     /* Get ALL the items under this Uploadtree_pk */
     $Children = GetNonArtifactChildren($Uploadtree_pk, $this->uploadtree_tablename);
     if (count($Children) == 0) {
         $sql = "SELECT * FROM {$this->uploadtree_tablename} WHERE uploadtree_pk = '{$Uploadtree_pk}'";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $row = pg_fetch_assoc($result);
         pg_free_result($result);
         if (empty($row) || IsDir($row['ufile_mode'])) {
             return;
         }
         // $ModLicView = &$Plugins[plugin_find_id("view-license")];
         // return($ModLicView->Output() );
     }
     $ChildCount = 0;
     $Childbucketcount = 0;
     /* Countd disabled until we know we need them
         $NumSrcPackages = 0;
        $NumBinPackages = 0;
        $NumBinNoSrcPackages = 0;
        */
     /* get mimetypes for packages */
     $MimetypeArray = GetPkgMimetypes();
     $VF .= "<table border=0>";
     foreach ($Children as $C) {
         if (empty($C)) {
             continue;
         }
         /* update package counts */
         /* This is an expensive count.  Comment out until we know we really need it
             IncrSrcBinCounts($C, $MimetypeArray, $NumSrcPackages, $NumBinPackages, $NumBinNoSrcPackages);
            */
         $IsDir = Isdir($C['ufile_mode']);
         $IsContainer = Iscontainer($C['ufile_mode']);
         /* Determine the hyperlink for non-containers to view-license  */
         if (!empty($C['pfile_fk']) && !empty($ModLicView)) {
             $LinkUri = Traceback_uri();
             $LinkUri .= "?mod=view-license&napk={$nomosagent_pk}&bapk={$bucketagent_pk}&upload={$upload_pk}&item={$C['uploadtree_pk']}";
         } else {
             $LinkUri = NULL;
         }
         /* Determine link for containers */
         if (Iscontainer($C['ufile_mode'])) {
             $uploadtree_pk = DirGetNonArtifact($C['uploadtree_pk'], $this->uploadtree_tablename);
             $tmpuri = "?mod=" . $this->Name . Traceback_parm_keep(array("upload", "folder", "ars"));
             $LicUri = "{$tmpuri}&item=" . $uploadtree_pk;
         } else {
             $LicUri = NULL;
         }
         /* Populate the output ($VF) - file list */
         /* id of each element is its uploadtree_pk */
         $VF .= "<tr><td id='{$C['uploadtree_pk']}' align='left'>";
         $HasHref = 0;
         $HasBold = 0;
         if ($IsContainer) {
             $VF .= "<a href='{$LicUri}'>";
             $HasHref = 1;
             $VF .= "<b>";
             $HasBold = 1;
         } else {
             if (!empty($LinkUri)) {
                 $VF .= "<a href='{$LinkUri}'>";
                 $HasHref = 1;
             }
         }
         $VF .= $C['ufile_name'];
         if ($IsDir) {
             $VF .= "/";
         }
         if ($HasBold) {
             $VF .= "</b>";
         }
         if ($HasHref) {
             $VF .= "</a>";
         }
         /* print buckets */
         $VF .= "<br>";
         $VF .= "<span style='position:relative;left:1em'>";
         /* get color coded string of bucket names */
         $VF .= GetFileBuckets_string($nomosagent_pk, $bucketagent_pk, $C['uploadtree_pk'], $bucketDefArray, ",", True);
         $VF .= "</span>";
         $VF .= "</td><td valign='top'>";
         /* display item links */
         $VF .= FileListLinks($C['upload_fk'], $C['uploadtree_pk'], $nomosagent_pk, $C['pfile_fk'], True, $UniqueTagArray, $this->uploadtree_tablename);
         $VF .= "</td>";
         $VF .= "</tr>\n";
         $ChildCount++;
     }
     $VF .= "</table>\n";
     $V .= ActiveHTTPscript("FileColor");
     /* Add javascript for color highlighting
         This is the response script needed by ActiveHTTPscript
        responseText is bucket_pk',' followed by a comma seperated list of uploadtree_pk's */
     $script = "\n      <script type=\"text/javascript\" charset=\"utf-8\">\n        var Lastutpks='';   /* save last list of uploadtree_pk's */\n        var Lastbupk='';   /* save last bucket_pk */\n        var color = '#4bfe78';\n        function FileColor_Reply()\n        {\n          if ((FileColor.readyState==4) && (FileColor.status==200))\n          {\n            /* remove previous highlighting */\n            var numpks = Lastutpks.length;\n            if (numpks > 0) document.getElementById(Lastbupk).style.backgroundColor='white';\n            while (numpks)\n            {\n              document.getElementById(Lastutpks[--numpks]).style.backgroundColor='white';\n            }\n\n            utpklist = FileColor.responseText.split(',');\n            Lastbupk = utpklist.shift();\n            numpks = utpklist.length;\n            Lastutpks = utpklist;\n\n            /* apply new highlighting */\n            elt = document.getElementById(Lastbupk);\n            if (elt != null) elt.style.backgroundColor=color;\n            while (numpks)\n            {\n              document.getElementById(utpklist[--numpks]).style.backgroundColor=color;\n            }\n          }\n          return;\n        }\n      </script>\n    ";
     $V .= $script;
     /* Display source, binary, and binary missing source package counts */
     /* Counts disabled above until we know we need these
         $VLic .= "<ul>";
        $text = _("source packages");
        $VLic .= "<li> $NumSrcPackages $text";
        $text = _("binary packages");
        $VLic .= "<li> $NumBinPackages $text";
        $text = _("binary packages with no source package");
        $VLic .= "<li> $NumBinNoSrcPackages $text";
        $VLic .= "</ul>";
        */
     /* Combine VF and VLic */
     $V .= "<table border=0 width='100%'>\n";
     $V .= "<tr><td valign='top' width='50%'>{$VLic}</td><td valign='top'>{$VF}</td></tr>\n";
     $V .= "</table>\n";
     $V .= "<hr />\n";
     return $V;
 }
Esempio n. 25
0
/**
 * \brief check if the user has the permission to read the 
 * copyright/license/etc information of this upload
 * 
 * \param $upload - upload id
 * \param $user - user name
 *
 * \return 1: has the permission; 0: no permission
 */
function read_permission($upload, $user)
{
    global $PG_CONN;
    $ADMIN_PERMISSION = 10;
    /** check if the user if the owner of this upload */
    $SQL = "SELECT * FROM upload where upload_pk = {$upload} and user_fk = (SELECT user_pk from users where user_name = '{$user}');";
    $result = pg_query($PG_CONN, $SQL);
    DBCheckResult($result, $SQL, __FILE__, __LINE__);
    $row = pg_fetch_assoc($result);
    pg_free_result($result);
    if (!empty($row)) {
        return 1;
    }
    /** check if the user is administrator */
    $SQL = "SELECT * FROM users where user_name = '{$user}' and user_perm = {$ADMIN_PERMISSION};";
    $result = pg_query($PG_CONN, $SQL);
    DBCheckResult($result, $SQL, __FILE__, __LINE__);
    $row = pg_fetch_assoc($result);
    pg_free_result($result);
    if (!empty($row)) {
        return 1;
    }
    return 0;
}
Esempio n. 26
0
 /**
  * @brief Get job queue data from db.
  *
  * @param $job_pks Array of $job_pk's to display.
  * @param $Page Get data for this display page.  Starts with zero.
  *
  * @return array of job data
  * \code
  *    JobData [job_pk]  Array of job records (JobRec)
  *
  *    JobRec['jobqueue'][jq_pk] = array of JobQueue records
  *    JobRec['jobqueue'][jq_pk]['depends'] = array of jq_pk's for dependencies
  *    JobRec['upload'] = array for upload record
  *    JobRec['job'] = array for job record
  *    JobRec['uploadtree'] = array for parent uploadtree record
  *
  *    JobQueue ['jq_pk'] = jq_pk
  *    JobQueue ['jq_type'] = jq_type
  *    JobQueue ['jq_itemsprocessed'] = jq_itemsprocessed
  *    JobQueue ['jq_starttime'] = jq_starttime
  *    JobQueue ['jq_endtime'] = jq_endtime
  *    JobQueue ['jq_log'] = jq_log
  *    JobQueue ['jq_endtext'] = jq_endtext
  *    JobQueue ['jq_end_bits'] = jq_end_bits
  * \endcode
  **/
 function GetJobInfo($job_pks, $Page = 0)
 {
     global $PG_CONN;
     /* Output data array */
     $JobData = array();
     foreach ($job_pks as $job_pk) {
         /* Get job table data */
         $JobRec = GetSingleRec("job", "where job_pk='{$job_pk}'");
         $JobData[$job_pk]["job"] = $JobRec;
         if (!empty($JobRec["job_upload_fk"])) {
             $upload_pk = $JobRec["job_upload_fk"];
             /* Get Upload record for job */
             $UploadRec = GetSingleRec("upload", "where upload_pk='{$upload_pk}'");
             if (!empty($UploadRec)) {
                 $JobData[$job_pk]["upload"] = $UploadRec;
                 /* Get Upload record for uploadtree */
                 $UploadtreeRec = GetSingleRec("uploadtree", "where upload_fk='{$upload_pk}' and parent is null");
                 $JobData[$job_pk]["uploadtree"] = $UploadtreeRec;
             }
         }
         /* Get jobqueue table data */
         $sql = "select * from jobqueue where jq_job_fk='{$job_pk}' order by jq_pk asc";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result)) {
             $Rows = pg_fetch_all($result);
             foreach ($Rows as $JobQueueRec) {
                 $jq_pk = $JobQueueRec["jq_pk"];
                 /* Get dependencies */
                 $DepArray = array();
                 $sql = "select jdep_jq_depends_fk from jobdepends where jdep_jq_fk='{$jq_pk}' order by jdep_jq_depends_fk asc";
                 $DepResult = pg_query($PG_CONN, $sql);
                 DBCheckResult($DepResult, $sql, __FILE__, __LINE__);
                 while ($DepRow = pg_fetch_assoc($DepResult)) {
                     $DepArray[] = $DepRow["jdep_jq_depends_fk"];
                 }
                 $JobQueueRec["depends"] = $DepArray;
                 pg_free_result($DepResult);
                 $JobData[$job_pk]['jobqueue'][$jq_pk] = $JobQueueRec;
             }
         } else {
             unset($JobData[$job_pk]);
         }
         pg_free_result($result);
     }
     return $JobData;
 }
Esempio n. 27
0
 /**
  * \brief Database queries
  * \returns html table containing query strings, pid, and start time
  */
 function DatabaseQueries()
 {
     global $PG_CONN;
     $V = "<table border=1>\n";
     $head1 = _("PID");
     $head2 = _("Query");
     $head3 = _("Started");
     $head4 = _("Elapsed");
     $V .= "<tr><th>{$head1}</th><th>{$head2}</th><th>{$head3}</th><th>{$head4}</th></tr>\n";
     /**** Version ****/
     $sql = "SELECT * from version();";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $row = pg_fetch_assoc($result);
     pg_free_result($result);
     $version = explode(' ', $row['version'], 3);
     // Get the current query column name in pg_stat_activity
     $current_query = strcmp($this->pgVersion['server'], "9.2") >= 0 ? "state" : "current_query";
     $procpid = strcmp($this->pgVersion['server'], "9.2") >= 0 ? "pid" : "procpid";
     $sql = "SELECT {$procpid} processid, {$current_query}, query_start, now()-query_start AS elapsed FROM pg_stat_activity WHERE {$current_query} != '<IDLE>' AND datname = 'fossology' ORDER BY {$procpid}";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     if (pg_num_rows($result) > 1) {
         while ($row = pg_fetch_assoc($result)) {
             if ($row[$current_query] == $sql) {
                 continue;
             }
             // Don't display this query
             $V .= "<tr>";
             $V .= "<td>{$row['processid']}</td>";
             $V .= "<td>" . htmlspecialchars($row[$current_query]) . "</td>";
             $StartTime = substr($row['query_start'], 0, 19);
             $V .= "<td>{$StartTime}</td>";
             $V .= "<td>{$row['elapsed']}</td>";
             $V .= "</tr>\n";
         }
     } else {
         $V .= "<tr><td colspan=4>There are no active FOSSology queries</td></tr>";
     }
     pg_free_result($result);
     $V .= "</table>\n";
     return $V;
 }
 /**
  * \brief Add a new license_ref to the database
  *
  * \return An add status string
  */
 function Adddb()
 {
     global $PG_CONN;
     $ob = "";
     // output buffer
     $rf_shortname = pg_escape_string($_POST['rf_shortname']);
     $rf_fullname = pg_escape_string($_POST['rf_fullname']);
     $rf_url = pg_escape_string($_POST['rf_url']);
     $rf_notes = pg_escape_string($_POST['rf_notes']);
     $rf_text = pg_escape_string($_POST['rf_text']);
     $rf_text = trim($rf_text);
     /** check if shortname or license text of this license is existing */
     $sql = "SELECT count(*) from license_ref where rf_shortname = '{$rf_shortname}' or (rf_text <> '' \n      and rf_text = '{$rf_text}' and LOWER(rf_text) NOT LIKE 'license by nomos');";
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     $check_count = pg_fetch_assoc($result);
     pg_free_result($result);
     if (0 < $check_count['count']) {
         $text = _("ERROR: The shortname or license text already exist in the license list.  License not added.");
         return "<b>{$text}</b><p>";
     }
     $sql = "";
     if (empty($rf_text) || stristr($rf_text, "License by Nomos")) {
         $sql = "INSERT into license_ref (\n        rf_active, marydone, rf_shortname, rf_fullname,\n        rf_url, rf_notes, rf_md5, rf_text, rf_text_updatable,\n        rf_detector_type) \n          VALUES (\n              '{$_POST['rf_active']}',\n              '{$_POST['marydone']}',\n              '{$rf_shortname}',\n              '{$rf_fullname}',\n              '{$rf_url}',\n              '{$rf_notes}', null, '{$rf_text}',\n              '{$_POST['rf_text_updatable']}',\n              '{$_POST['rf_detector_type']}')";
     } else {
         $licmd5 = md5($rf_text);
         $sql = "INSERT into license_ref (\n        rf_active, marydone, rf_shortname, rf_fullname,\n        rf_url, rf_notes, rf_md5, rf_text, rf_text_updatable,\n        rf_detector_type) \n          VALUES (\n              '{$_POST['rf_active']}',\n              '{$_POST['marydone']}',\n              '{$rf_shortname}',\n              '{$rf_fullname}',\n              '{$rf_url}',\n              '{$rf_notes}', '{$licmd5}', '{$rf_text}',\n              '{$_POST['rf_text_updatable']}',\n              '{$_POST['rf_detector_type']}')";
     }
     $result = pg_query($PG_CONN, $sql);
     DBCheckResult($result, $sql, __FILE__, __LINE__);
     pg_free_result($result);
     $ob = "License {$_POST['rf_shortname']} added.<p>";
     return $ob;
 }
Esempio n. 29
0
/**
 * \brief Get an html linkes string of a file browse path.
 *  This calls Dir2Browse().
 *
 * \param $Mod - Module name (e.g. "browse")
 * \param $UploadPk
 * \param $LinkLast - create link (a href) for last item and use LinkLast as the module name
 * \param $ShowBox - draw a box around the string (default true)
 * \param $ShowMicro - show micro menu (default false)
 * \param $uploadtree_tablename
 *
 * \return string of browse paths
 */
function Dir2BrowseUpload($Mod, $UploadPk, $LinkLast = NULL, $ShowBox = 1, $ShowMicro = NULL, $uploadtree_tablename = 'uploadtree')
{
    global $PG_CONN;
    /* Find the file associated with the upload */
    $sql = "SELECT uploadtree_pk FROM upload INNER JOIN {$uploadtree_tablename} ON upload_fk = '{$UploadPk}' AND parent is null;";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    $row = pg_fetch_assoc($result);
    $UploadtreePk = $row['uploadtree_pk'];
    pg_free_result($result);
    return Dir2Browse($Mod, $UploadtreePk, $LinkLast, $ShowBox, $ShowMicro, -1, '', '', $uploadtree_tablename);
}
Esempio n. 30
0
/**
 * \brief Given an uploadtree_pk, retrieve the pfile path.
 *
 * NOTE: The filename at the path may not exist.
 * In fact, the entire path may not exist!
 *
 * \param $Item - uploadtree pk
 * \param $Repo - repository type
 *
 * \return the path, or NULL if the pfile record does not exist.
 */
function RepPathItem($Item, $Repo = "files")
{
    global $Plugins;
    global $LIBEXECDIR;
    global $PG_CONN;
    if (empty($PG_CONN)) {
        return;
    }
    $sql = "SELECT * FROM pfile INNER JOIN uploadtree ON pfile_fk = pfile_pk\n\t  WHERE uploadtree_pk = {$Item} LIMIT 1;";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    $Row = pg_fetch_assoc($result);
    pg_free_result($result);
    if (empty($Row['pfile_sha1'])) {
        return NULL;
    }
    $Hash = $Row['pfile_sha1'] . "." . $Row['pfile_md5'] . "." . $Row['pfile_size'];
    exec("{$LIBEXECDIR}/reppath {$Repo} {$Hash}", $Path);
    return $Path[0];
}