Exemplo n.º 1
0
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $errorMessage = "";
     $jobqueueId = -1;
     $userId = $_SESSION['UserId'];
     $groupId = $_SESSION['GroupId'];
     $uploadId = intval($_POST['uploadId']);
     $agentName = $_POST['agentName'];
     if ($uploadId > 0) {
         $upload = $this->uploadDao->getUpload($uploadId);
         $uploadName = $upload->getFilename();
         $jobId = JobAddJob($userId, $groupId, $uploadName, $uploadId);
         $ourPlugin = plugin_find($agentName);
         $jobqueueId = $ourPlugin->AgentAdd($jobId, $uploadId, $errorMessage, array());
     } else {
         $errorMessage = "bad request";
     }
     ReportCachePurgeAll();
     $headers = array('Content-type' => 'text/json');
     if (empty($errorMessage) && $jobqueueId > 0) {
         return new Response(json_encode(array("jqid" => $jobqueueId)), Response::HTTP_OK, $headers);
     } else {
         return new Response(json_encode(array("error" => $errorMessage)), Response::HTTP_INTERNAL_SERVER_ERROR, $headers);
     }
 }
Exemplo n.º 2
0
 /**
  * @brief : returns 1 when jobs are running else 0
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $response = '1';
     $jobInfo = $this->dbManager->getSingleRow("SELECT jq_end_bits FROM jobqueue WHERE jq_end_bits ='0' LIMIT 1");
     if (empty($jobInfo)) {
         $response = '0';
     }
     $status = 1;
     ReportCachePurgeAll();
     $status = empty($status) ? Response::HTTP_INTERNAL_SERVER_ERROR : Response::HTTP_OK;
     return new Response(json_encode(array("status" => $response)), $status, array('content-type' => 'text/json'));
 }
Exemplo n.º 3
0
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $uploadTreeId = intval($request->get('uploadTreeId'));
     if ($uploadTreeId <= 0) {
         return new JsonResponse(array("error" => 'bad request'), JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
     }
     try {
         $jobQueueId = $this->getJobQueueId($uploadTreeId, $request);
     } catch (Exception $ex) {
         $errorMsg = $ex->getMessage();
         return new JsonResponse(array("error" => $errorMsg), JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
     }
     ReportCachePurgeAll();
     return new JsonResponse(array("jqid" => $jobQueueId));
 }
Exemplo n.º 4
0
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         throw new \Fossology\Lib\Exception("plugin " . $this->Name . " is not ready");
     }
     $uploadTreeId = intval($_POST['uploadTreeId']);
     if ($uploadTreeId <= 0) {
         return new Response(json_encode(array("error" => 'bad request')), 500, array('Content-type' => 'text/json'));
     }
     try {
         $jobQueueId = $this->getJobQueueId($uploadTreeId);
     } catch (Exception $ex) {
         $errorMsg = $ex->getMessage();
         return new Response(json_encode(array("error" => $errorMsg)), 500, array('Content-type' => 'text/json'));
     }
     ReportCachePurgeAll();
     return new Response(json_encode(array("jqid" => $jobQueueId)), Response::HTTP_OK, array('Content-type' => 'text/json'));
 }
Exemplo n.º 5
0
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $userId = $_SESSION['UserId'];
     $jqIds = (array) $request->get('jqIds');
     $result = array();
     foreach ($jqIds as $jq_pk) {
         $jobInfo = $this->dbManager->getSingleRow("SELECT jobqueue.jq_end_bits as end_bits FROM jobqueue INNER JOIN job ON jobqueue.jq_job_fk = job.job_pk\n          WHERE jobqueue.jq_pk = \$1 AND job_user_fk = \$2", array($jq_pk, $userId));
         if ($jobInfo !== false) {
             $result[$jq_pk] = array('end_bits' => $jobInfo['end_bits']);
         }
     }
     ReportCachePurgeAll();
     $status = empty($result) ? Response::HTTP_INTERNAL_SERVER_ERROR : Response::HTTP_OK;
     if (empty($result)) {
         $result = array("error" => "no info");
     }
     $response = new Response(json_encode($result), $status, array('content-type' => 'text/json'));
     return $response;
 }
 /**
  * \brief Generate output.
  */
 function Output()
 {
     if ($this->State != PLUGIN_STATE_READY) {
         return;
     }
     $V = "";
     switch ($this->OutputType) {
         case "XML":
             break;
         case "HTML":
             ReportCachePurgeAll();
             $V .= _("All cached pages have been removed.\n");
             break;
         case "Text":
             break;
         default:
             break;
     }
     if (!$this->OutputToStdout) {
         return $V;
     }
     print $V;
     return;
 }
Exemplo n.º 7
0
 /**
  * @brief Make schema match $Filename.  This is a single transaction.
  * @param string $filename Schema file written by schema-export.php
  * @param bool $debug Turn on debugging (echo sql as it is being executed)
  * @param string $catalog Optional database name
  * @param array[] $migrateColumns array('tablename'=>array('col1','col2'),...) of columns which should not be deleted
  * @return false=success, on error return string with error message.
  **/
 function applySchema($filename = NULL, $debug = false, $catalog = 'fossology', $migrateColumns = array())
 {
     global $PG_CONN;
     // first check to make sure we don't already have the plpgsql language installed
     $sql_statement = "select lanname from pg_language where lanname = 'plpgsql'";
     $result = pg_query($PG_CONN, $sql_statement);
     if (!$result) {
         throw new Exception("Could not check the database for plpgsql language");
     }
     $plpgsql_already_installed = FALSE;
     if (pg_fetch_row($result)) {
         $plpgsql_already_installed = TRUE;
     }
     // then create language plpgsql if not already created
     if ($plpgsql_already_installed == FALSE) {
         $sql_statement = "CREATE LANGUAGE plpgsql";
         $result = pg_query($PG_CONN, $sql_statement);
         if (!$result) {
             throw new Exception("Could not create plpgsql language in the database");
         }
     }
     $this->debug = $debug;
     if (!file_exists($filename)) {
         $errMsg = "{$filename} does not exist.";
         return $errMsg;
     }
     $Schema = array();
     /* will be filled in next line */
     require $filename;
     /* this cause Fatal Error if the file does not exist. */
     $this->schema = $Schema;
     /* Very basic sanity check (so we don't delete everything!) */
     if (count($this->schema['TABLE']) < 5 || count($this->schema['SEQUENCE']) < 5 || count($this->schema['INDEX']) < 5 || count($this->schema['CONSTRAINT']) < 5) {
         $errMsg = "Schema from '{$filename}' appears invalid.";
         return $errMsg;
     }
     if (!$debug) {
         $result = $this->dbman->getSingleRow("show statement_timeout", array(), $stmt = __METHOD__ . '.getTimeout');
         $statementTimeout = $result['statement_timeout'];
         $this->dbman->queryOnce("SET statement_timeout = 0", $stmt = __METHOD__ . '.setTimeout');
     }
     $this->applyOrEchoOnce('BEGIN');
     $this->getCurrSchema();
     $errlev = error_reporting(E_ERROR | E_WARNING | E_PARSE);
     $this->applySequences();
     $this->applyTables();
     $this->applyInheritedRelations();
     $this->updateSequences();
     $this->applyViews();
     $this->dropConstraints();
     /* Reload current since the CASCADE may have changed things */
     $this->getCurrSchema();
     /* constraints and indexes are linked, recheck */
     $this->dropIndexes();
     $this->applyIndexes();
     $this->applyConstraints();
     error_reporting($errlev);
     /* return to previous error reporting level */
     $this->makeFunctions();
     /* Reload current since CASCADE during migration may have changed things */
     $this->getCurrSchema();
     $this->dropViews($catalog);
     foreach ($this->currSchema['TABLE'] as $table => $columns) {
         $skipColumns = array_key_exists($table, $migrateColumns) ? $migrateColumns[$table] : array();
         $dropColumns = array_diff(array_keys($columns), $skipColumns);
         $this->dropColumnsFromTable($dropColumns, $table);
     }
     $this->applyOrEchoOnce('COMMIT');
     flush();
     ReportCachePurgeAll();
     if (!$debug) {
         $this->dbman->getSingleRow("SET statement_timeout = {$statementTimeout}", array(), $stmt = __METHOD__ . '.resetTimeout');
         print "DB schema has been updated for {$catalog}.\n";
     } else {
         print "These queries could update DB schema for {$catalog}.\n";
     }
     return false;
 }
Exemplo n.º 8
0
/**
 * @brief Make schema match $Filename.  This is a single transaction.
 * @param $Filename Schema file written by schema-export.php
 * @param $Debug Turn on debugging (echo sql as it is being executed)
 * @param $Catalog Optional database name
 * @return false=success, on error return string with error message.
 **/
function ApplySchema($Filename = NULL, $Debug = false, $Catalog = 'fossology')
{
    global $PG_CONN;
    if (!file_exists($Filename)) {
        $ErrMsg = $Filename . " does not exist.";
        return $ErrMsg;
    }
    require_once $Filename;
    /* this will DIE if the file does not exist. */
    /* Very basic sanity check (so we don't delete everything!) */
    if (count($Schema['TABLE']) < 5 || count($Schema['SEQUENCE']) < 5 || count($Schema['INDEX']) < 5 || count($Schema['CONSTRAINT']) < 5) {
        $ErrMsg = "Schema from '{$Filename}' appears invalid.";
        return $ErrMsg;
    }
    /* get the current statement timeout */
    $SQL = "show statement_timeout";
    $result = pg_query($PG_CONN, $SQL);
    DBCheckResult($result, $SQL, __FILE__, __LINE__);
    $Results = pg_fetch_all($result);
    $Statement_Timeout = $Results[0]['statement_timeout'];
    pg_free_result($result);
    pg_query($PG_CONN, "SET statement_timeout = 0;");
    /* turn off DB timeouts */
    pg_query($PG_CONN, "BEGIN;");
    $Curr = GetSchema();
    /* The gameplan: Make $Curr look like $Schema. */
    // print "<pre>"; print_r($Schema); print "</pre>";
    /* turn off E_NOTICE so this stops reporting undefined index */
    $errlev = error_reporting(E_ERROR | E_WARNING | E_PARSE);
    /************************************/
    /* Add sequences */
    /************************************/
    if (!empty($Schema['SEQUENCE'])) {
        foreach ($Schema['SEQUENCE'] as $Name => $SQL) {
            if (empty($Name)) {
                echo "warning empty sequence in .dat\n";
                continue;
            }
            if ($Curr['SEQUENCE'][$Name] == $SQL) {
                continue;
            }
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
    }
    /************************************/
    /* Add tables/columns (dependent on sequences for default values) */
    /************************************/
    if (!empty($Schema['TABLE'])) {
        foreach ($Schema['TABLE'] as $Table => $Columns) {
            if (empty($Table)) {
                continue;
            }
            if (!DB_TableExists($Table)) {
                $SQL = "CREATE TABLE \"{$Table}\" ();";
                if ($Debug) {
                    print "{$SQL}\n";
                } else {
                    $result = pg_query($PG_CONN, $SQL);
                    DBCheckResult($result, $SQL, __FILE__, __LINE__);
                }
            }
            foreach ($Columns as $Column => $Val) {
                if ($Curr['TABLE'][$Table][$Column]['ADD'] != $Val['ADD']) {
                    $Rename = "";
                    if (DB_ColExists($Table, $Column)) {
                        /* The column exists, but it looks different!
                           Solution: Delete the column! */
                        $Rename = $Column . "_old";
                        $SQL = "ALTER TABLE \"{$Table}\" RENAME COLUMN \"{$Column}\" TO \"{$Rename}\";";
                        if ($Debug) {
                            print "{$SQL}\n";
                        } else {
                            $result = pg_query($PG_CONN, $SQL);
                            DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        }
                    }
                    $SQL = $Val['ADD'];
                    if ($Debug) {
                        print "{$SQL}\n";
                    } else {
                        // Add the new column, then set the default value with update
                        $result = pg_query($PG_CONN, $SQL);
                        DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        if (!empty($Val['UPDATE'])) {
                            $SQL = $Val['UPDATE'];
                            $result = pg_query($PG_CONN, $SQL);
                            DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        }
                    }
                    if (!empty($Rename)) {
                        /* copy over the old data */
                        $SQL = "UPDATE \"{$Table}\" SET \"{$Column}\" = \"{$Rename}\";";
                        if ($Debug) {
                            print "{$SQL}\n";
                        } else {
                            $result = pg_query($PG_CONN, $SQL);
                            DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        }
                        $SQL = "ALTER TABLE \"{$Table}\" DROP COLUMN \"{$Rename}\";";
                        if ($Debug) {
                            print "{$SQL}\n";
                        } else {
                            $result = pg_query($PG_CONN, $SQL);
                            DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        }
                    }
                }
                // if
                if ($Curr['TABLE'][$Table][$Column]['ALTER'] != $Val['ALTER']) {
                    if ($Debug) {
                        print $Val['ALTER'] . "\n";
                    } else {
                        $SQL = $Val['ALTER'];
                        $result = pg_query($PG_CONN, $SQL);
                        DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        $SQL = $Val['UPDATE'];
                        if (!empty($Val['UPDATE'])) {
                            $SQL = $Val['UPDATE'];
                            $result = pg_query($PG_CONN, $SQL);
                            DBCheckResult($result, $SQL, __FILE__, __LINE__);
                        }
                    }
                }
                if ($Curr['TABLE'][$Table][$Column]['DESC'] != $Val['DESC']) {
                    if (empty($Val['DESC'])) {
                        $SQL = "COMMENT ON COLUMN \"{$Table}\".\"{$Column}\" IS '';";
                    } else {
                        $SQL = $Val['DESC'];
                    }
                    if ($Debug) {
                        print "{$SQL}\n";
                    } else {
                        $result = pg_query($PG_CONN, $SQL);
                        DBCheckResult($result, $SQL, __FILE__, __LINE__);
                    }
                }
            }
        }
    }
    /************************************/
    /* Add views (dependent on columns) */
    /************************************/
    if (!empty($Schema['VIEW'])) {
        foreach ($Schema['VIEW'] as $Name => $SQL) {
            if (empty($Name)) {
                continue;
            }
            if ($Curr['VIEW'][$Name] == $SQL) {
                continue;
            }
            if (!empty($Curr['VIEW'][$Name])) {
                /* Delete it if it exists and looks different */
                $SQL1 = "DROP VIEW {$Name};";
                if ($Debug) {
                    print "{$SQL1}\n";
                } else {
                    $result = pg_query($PG_CONN, $SQL1);
                    DBCheckResult($result, $SQL1, __FILE__, __LINE__);
                }
            }
            /* Create the view */
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
    }
    /************************************/
    /* Delete constraints */
    /* Delete now, so they won't interfere with migrations. */
    /************************************/
    if (!empty($Curr['CONSTRAINT'])) {
        foreach ($Curr['CONSTRAINT'] as $Name => $SQL) {
            if (empty($Name)) {
                continue;
            }
            /* Only process tables that I know about */
            $Table = preg_replace("/^ALTER TABLE \"(.*)\" ADD CONSTRAINT.*/", '${1}', $SQL);
            $TableFk = preg_replace("/^.*FOREIGN KEY .* REFERENCES \"(.*)\" \\(.*/", '${1}', $SQL);
            if ($TableFk == $SQL) {
                $TableFk = $Table;
            }
            /* If I don't know the primary or foreign table... */
            if (empty($Schema['TABLE'][$Table]) && empty($Schema['TABLE'][$TableFk])) {
                continue;
            }
            /* If it is already set correctly, then skip it. */
            if ($Schema['CONSTRAINT'][$Name] == $SQL) {
                continue;
            }
            $SQL = "ALTER TABLE \"{$Table}\" DROP CONSTRAINT \"{$Name}\" CASCADE;";
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = @pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
    }
    /* Reload current since the CASCADE may have changed things */
    /************************************/
    /* Delete indexes */
    /************************************/
    $Curr = GetSchema();
    /* constraints and indexes are linked, recheck */
    if (!empty($Curr['INDEX'])) {
        foreach ($Curr['INDEX'] as $Table => $IndexInfo) {
            if (empty($Table)) {
                continue;
            }
            /* Only delete indexes on known tables */
            if (empty($Schema['TABLE'][$Table])) {
                continue;
            }
            foreach ($IndexInfo as $Name => $SQL) {
                if (empty($Name)) {
                    continue;
                }
                /* Only delete indexes that are different */
                if ($Schema['INDEX'][$Table][$Name] == $SQL) {
                    continue;
                }
                $SQL = "DROP INDEX \"{$Name}\";";
                if ($Debug) {
                    print "{$SQL}\n";
                } else {
                    $result = pg_query($PG_CONN, $SQL);
                    DBCheckResult($result, $SQL, __FILE__, __LINE__);
                }
            }
        }
    }
    /************************************/
    /* Add indexes (dependent on columns) */
    /************************************/
    if (!empty($Schema['INDEX'])) {
        foreach ($Schema['INDEX'] as $Table => $IndexInfo) {
            if (empty($Table)) {
                continue;
            }
            // bobg
            if (!array_key_exists($Table, $Schema["TABLE"])) {
                echo "skipping orphan table: {$Table}\n";
                continue;
            }
            foreach ($IndexInfo as $Name => $SQL) {
                if (empty($Name)) {
                    continue;
                }
                if ($Curr['INDEX'][$Table][$Name] == $SQL) {
                    continue;
                }
                if ($Debug) {
                    print "{$SQL}\n";
                } else {
                    $result = pg_query($PG_CONN, $SQL);
                    DBCheckResult($result, $SQL, __FILE__, __LINE__);
                }
                $SQL = "REINDEX INDEX \"{$Name}\";";
                if ($Debug) {
                    print "{$SQL}\n";
                } else {
                    $result = pg_query($PG_CONN, $SQL);
                    DBCheckResult($result, $SQL, __FILE__, __LINE__);
                }
            }
        }
    }
    /************************************/
    /* Add constraints (dependent on columns, views, and indexes) */
    /************************************/
    $Curr = GetSchema();
    /* constraints and indexes are linked, recheck */
    if (!empty($Schema['CONSTRAINT'])) {
        /* Constraints must be added in the correct order! */
        /* CONSTRAINT: PRIMARY KEY */
        foreach ($Schema['CONSTRAINT'] as $Name => $SQL) {
            if (empty($Name)) {
                continue;
            }
            if ($Curr['CONSTRAINT'][$Name] == $SQL) {
                continue;
            }
            if (!preg_match("/PRIMARY KEY/", $SQL)) {
                continue;
            }
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
        /* CONSTRAINT: UNIQUE */
        foreach ($Schema['CONSTRAINT'] as $Name => $SQL) {
            if (empty($Name)) {
                continue;
            }
            if ($Curr['CONSTRAINT'][$Name] == $SQL) {
                continue;
            }
            if (!preg_match("/UNIQUE/", $SQL)) {
                continue;
            }
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
        /* CONSTRAINT: FOREIGN KEY */
        foreach ($Schema['CONSTRAINT'] as $Name => $SQL) {
            if (empty($Name)) {
                continue;
            }
            if ($Curr['CONSTRAINT'][$Name] == $SQL) {
                continue;
            }
            if (!preg_match("/FOREIGN KEY/", $SQL)) {
                continue;
            }
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
        /* All other constraints */
        foreach ($Schema['CONSTRAINT'] as $Name => $SQL) {
            if (empty($Name)) {
                continue;
            }
            if ($Curr['CONSTRAINT'][$Name] == $SQL) {
                continue;
            }
            if (preg_match("/PRIMARY KEY/", $SQL)) {
                continue;
            }
            if (preg_match("/UNIQUE/", $SQL)) {
                continue;
            }
            if (preg_match("/FOREIGN KEY/", $SQL)) {
                continue;
            }
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $result = pg_query($PG_CONN, $SQL);
                DBCheckResult($result, $SQL, __FILE__, __LINE__);
            }
        }
    }
    /* Add constraints */
    error_reporting($errlev);
    /* return to previous error reporting level */
    /************************************/
    /* CREATE FUNCTIONS */
    /************************************/
    MakeFunctions($Debug);
    /* Reload current since CASCADE during migration may have changed things */
    $Curr = GetSchema();
    /************************************/
    /* Delete views */
    /************************************/
    print "  Removing obsolete views\n";
    flush();
    /* Get current tables and columns used by all views */
    /* Delete if: uses table I know and column I do not know. */
    /* Without this delete, we won't be able to drop columns. */
    $SQL = "SELECT view_name,table_name,column_name\n  FROM information_schema.view_column_usage\n  WHERE table_catalog='{$Catalog}'\n  ORDER BY view_name,table_name,column_name;";
    $result = pg_query($PG_CONN, $SQL);
    DBCheckResult($result, $SQL, __FILE__, __LINE__);
    $Results = pg_fetch_all($result);
    for ($i = 0; !empty($Results[$i]['view_name']); $i++) {
        $View = $Results[$i]['view_name'];
        $Table = $Results[$i]['table_name'];
        if (empty($Schema['TABLE'][$Table])) {
            continue;
        }
        $Column = $Results[$i]['column_name'];
        if (empty($Schema['TABLE'][$Table][$Column])) {
            $SQL = "DROP VIEW \"{$View}\";";
            if ($Debug) {
                print "{$SQL}\n";
            } else {
                $results = pg_query($PG_CONN, $SQL);
                DBCheckResult($results, $SQL, __FILE__, __LINE__);
            }
        }
    }
    /************************************/
    /* Delete columns/tables */
    /************************************/
    print "  Removing obsolete columns\n";
    flush();
    if (!empty($Curr['TABLE'])) {
        foreach ($Curr['TABLE'] as $Table => $Columns) {
            if (empty($Table)) {
                continue;
            }
            /* only delete from tables I know */
            if (empty($Schema['TABLE'][$Table])) {
                continue;
            }
            foreach ($Columns as $Column => $Val) {
                if (empty($Column)) {
                    continue;
                }
                if (empty($Schema['TABLE'][$Table][$Column])) {
                    $SQL = "ALTER TABLE \"{$Table}\" DROP COLUMN \"{$Column}\";";
                    if ($Debug) {
                        print "{$SQL}\n";
                    } else {
                        $results = pg_query($PG_CONN, $SQL);
                        DBCheckResult($results, $SQL, __FILE__, __LINE__);
                    }
                }
            }
        }
    }
    /************************************/
    /* Commit changes */
    /************************************/
    $results = pg_query($PG_CONN, "COMMIT;");
    DBCheckResult($results, $SQL, __FILE__, __LINE__);
    /************************************/
    /* Flush any cached data. */
    /************************************/
    ReportCachePurgeAll();
    /* restore DB timeouts */
    pg_query($PG_CONN, "SET statement_timeout = {$Statement_Timeout};");
    return false;
}
 /**
  * \brief Generate output.
  */
 public function Output()
 {
     ReportCachePurgeAll();
     return _("All cached pages have been removed.");
 }
Exemplo n.º 10
0
 /** 
  * \brief change the license reference 
  * 
  * \param $OriginalLicense - original license 
  * \param $ObjectiveLicense - objective license
  * \param $Reason - why do this change
  * \param $FileName - file name 
  *
  * \return succeed: return NULL, fail: return -1
  */
 function Change(&$OriginalLicense, &$ObjectiveLicense, &$Reason, &$FileName)
 {
     global $SysConf;
     global $PG_CONN;
     $fl_pk = GetParm("fl_pk", PARM_STRING);
     /** get original license reference short name */
     if (!empty($fl_pk)) {
         $sql = "select rf_shortname from license_file_ref where fl_pk = {$fl_pk};";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $row = pg_fetch_assoc($result);
         $OriginalLicense = $row['rf_shortname'];
         pg_free_result($result);
     } else {
         return NULL;
     }
     /** change the license */
     if (!empty($fl_pk) && !empty($ObjectiveLicense) && empty($DeleteFlag)) {
         $sql = "select rf_pk from license_ref where rf_shortname = '{$ObjectiveLicense}';";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $count = pg_num_rows($result);
         if (0 == $count) {
             // the objective license does not exist in FOSSology
             pg_free_result($result);
             $text = _("Error: license ");
             $text1 = _("does not exist in FOSSology.");
             $Msg = "{$text} '{$ObjectiveLicense}' {$text1}";
             print displayMessage($Msg, "");
             return -1;
         }
         $row = pg_fetch_assoc($result);
         $rf_fk = $row['rf_pk'];
         pg_free_result($result);
         if ($ObjectiveLicense === $OriginalLicense) {
             // original license is same with objective license
             $text = _("Error: can not change");
             $text1 = _("to");
             $Msg = "{$text} '{$OriginalLicense}' {$text1} '{$ObjectiveLicense}'.";
             print displayMessage($Msg, "");
             return -1;
         } else {
             if (!empty($ObjectiveLicense)) {
                 // complete change
                 $text = _("is changed to");
                 $Msg = "'{$OriginalLicense}' {$text} '{$ObjectiveLicense}'.";
                 // print displayMessage($Msg,"");
                 /** after changing one license, purge all the report cache */
                 ReportCachePurgeAll();
             }
         }
         $user_pk = $SysConf['auth']['UserId'];
         /** get original license reference ID */
         $sql = "select rf_pk from license_ref where rf_shortname = '{$OriginalLicense}';";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         $row = pg_fetch_assoc($result);
         $org_rf_fk = $row['rf_pk'];
         pg_free_result($result);
         $Reason = pg_escape_string($Reason);
         // perhaps there are special characters in reason field
         /** save the changed license */
         $sql = "INSERT INTO license_file_audit (fl_fk, rf_fk, user_fk, reason) VALUES ({$fl_pk}, {$org_rf_fk}, {$user_pk}, '{$Reason}');";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         pg_free_result($result);
         /** update license_file table */
         $sql = "UPDATE license_file SET rf_fk = {$rf_fk}, rf_timestamp=now() WHERE fl_pk = {$fl_pk};";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         pg_free_result($result);
         $this->ChangeBuckets();
         // change bucket accordingly
         return NULL;
     }
 }
 function doEdit($userId, $groupId, $itemId)
 {
     $licenses = GetParm("licenseNumbersToBeSubmitted", PARM_RAW);
     $removed = $_POST['removed'] === 't' || $_POST['removed'] === 'true';
     $itemTreeBounds = $this->uploadDao->getItemTreeBounds($itemId);
     $uploadId = $itemTreeBounds->getUploadId();
     $upload = $this->uploadDao->getUpload($uploadId);
     $uploadName = $upload->getFilename();
     $jobId = JobAddJob($userId, $groupId, $uploadName, $uploadId);
     if (isset($licenses)) {
         if (!is_array($licenses)) {
             return $this->errorJson("bad license array");
         }
         foreach ($licenses as $licenseId) {
             if (intval($licenseId) <= 0) {
                 return $this->errorJson("bad license");
             }
             $this->clearingDao->insertClearingEvent($itemId, $userId, $groupId, $licenseId, $removed, ClearingEventTypes::USER, $reportInfo = '', $comment = '', $jobId);
         }
     }
     /** @var agent_fodecider $deciderPlugin */
     $deciderPlugin = plugin_find("agent_deciderjob");
     $conflictStrategyId = null;
     $errorMsg = "";
     $jq_pk = $deciderPlugin->AgentAdd($jobId, $uploadId, $errorMsg, array(), $conflictStrategyId);
     /** after changing one license, purge all the report cache */
     ReportCachePurgeAll();
     //Todo: Change sql statement of fossology/src/buckets/agent/leaf.c line 124 to take the newest valid license, then uncomment this line
     // $this->ChangeBuckets(); // change bucket accordingly
     if (empty($errorMsg) && $jq_pk > 0) {
         return new JsonResponse(array("jqid" => $jq_pk));
     } else {
         return $this->errorJson($errorMsg, 500);
     }
 }