package fic import ( "errors" "fmt" "time" ) // PartialValidation allows a Team to validate an Exercice at a given point if // it has ever found all classical flags, even if the last validation is not // complete or contains mistakes on previously validated flags. var PartialValidation bool // PartialMCQValidation allows a Team to validate each MCQ independently. // Otherwise, all MCQ has to be correct for being validated. var PartialMCQValidation bool // ExerciceCurrentCoefficient is the current coefficient applied on solved exercices var ExerciceCurrentCoefficient = 1.0 // Exercice represents a challenge inside a Theme. type Exercice struct { Id int64 `json:"id"` IdTheme int64 `json:"id_theme"` Title string `json:"title"` // URLid is used to reference the challenge from the URL path URLId string `json:"urlid"` // Path is the relative import location where find challenge data Path string `json:"path"` // Statement is the challenge description shown to players Statement string `json:"statement"` // Overview is the challenge description shown to public Overview string `json:"overview"` // Headline is the challenge headline to fill in small part Headline string `json:"headline"` // Finished is the text shown when the exercice is solved Finished string `json:"finished"` // Issue is an optional text describing an issue with the exercice Issue string `json:"issue"` // IssueKind is the criticity level of the previous issue IssueKind string `json:"issuekind"` Depend *int64 `json:"depend"` // Gain is the basis amount of points player will earn if it solve the challenge // If this value fluctuate during the challenge, players' scores will follow changes. // Use Coefficient value to create temporary bonus/malus. Gain int64 `json:"gain"` // Coefficient is a temporary bonus/malus applied on Gain when the challenge is solved. // This value is saved along with solved informations: changing it doesn't affect Team that already solved the challenge. Coefficient float64 `json:"coefficient"` // VideoURI is the link to the resolution video VideoURI string `json:"videoURI"` } // GetExercice retrieves the challenge with the given id. func GetExercice(id int64) (Exercice, error) { var e Exercice if err := DBQueryRow("SELECT id_exercice, id_theme, title, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, finished FROM exercices WHERE id_exercice = ?", id).Scan(&e.Id, &e.IdTheme, &e.Title, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &e.Gain, &e.Coefficient, &e.VideoURI, &e.Finished); err != nil { return Exercice{}, err } return e, nil } // GetExercice retrieves the challenge with the given id. func (t Theme) GetExercice(id int) (Exercice, error) { var e Exercice if err := DBQueryRow("SELECT id_exercice, id_theme, title, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, finished FROM exercices WHERE id_theme = ? AND id_exercice = ?", t.Id, id).Scan(&e.Id, &e.IdTheme, &e.Title, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &e.Gain, &e.Coefficient, &e.VideoURI, &e.Finished); err != nil { return Exercice{}, err } return e, nil } // GetExerciceByTitle retrieves the challenge with the given title. func (t Theme) GetExerciceByTitle(title string) (Exercice, error) { var e Exercice if err := DBQueryRow("SELECT id_exercice, id_theme, title, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, finished FROM exercices WHERE id_theme = ? AND title = ?", t.Id, title).Scan(&e.Id, &e.IdTheme, &e.Title, &t.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &e.Gain, &e.Coefficient, &e.VideoURI, &e.Finished); err != nil { return Exercice{}, err } return e, nil } // GetExercices returns the list of all challenges present in the database. func GetExercices() ([]Exercice, error) { if rows, err := DBQuery("SELECT id_exercice, id_theme, title, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, finished FROM exercices"); err != nil { return nil, err } else { defer rows.Close() var exos = make([]Exercice, 0) for rows.Next() { var e Exercice if err := rows.Scan(&e.Id, &e.IdTheme, &e.Title, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &e.Gain, &e.Coefficient, &e.VideoURI, &e.Finished); err != nil { return nil, err } exos = append(exos, e) } if err := rows.Err(); err != nil { return nil, err } return exos, nil } } // GetExercices returns the list of all challenges in the Theme. func (t Theme) GetExercices() ([]Exercice, error) { if rows, err := DBQuery("SELECT id_exercice, id_theme, title, url_id, path, statement, overview, headline, issue, issue_kind, depend, gain, coefficient_cur, video_uri, finished FROM exercices WHERE id_theme = ?", t.Id); err != nil { return nil, err } else { defer rows.Close() var exos = make([]Exercice, 0) for rows.Next() { var e Exercice if err := rows.Scan(&e.Id, &e.IdTheme, &e.Title, &e.URLId, &e.Path, &e.Statement, &e.Overview, &e.Headline, &e.Issue, &e.IssueKind, &e.Depend, &e.Gain, &e.Coefficient, &e.VideoURI, &e.Finished); err != nil { return nil, err } exos = append(exos, e) } if err := rows.Err(); err != nil { return nil, err } return exos, nil } } // SaveNamedExercice looks for an exercice with the same title to update it, or create it if it doesn't exists yet. func (t Theme) SaveNamedExercice(e *Exercice) (err error) { var search Exercice if search, err = t.GetExerciceByTitle(e.Title); err == nil { // Force ID e.Id = search.Id // Don't expect those values if e.Coefficient == 0 { e.Coefficient = search.Coefficient } if len(e.Issue) == 0 { e.Issue = search.Issue } if len(e.IssueKind) == 0 { e.IssueKind = search.IssueKind } _, err = e.Update() } else { err = t.addExercice(e) } return } func (t Theme) addExercice(e *Exercice) (err error) { var ik = "DEFAULT" if len(e.IssueKind) > 0 { ik = fmt.Sprintf("%q", e.IssueKind) } var cc = "DEFAULT" if e.Coefficient != 0 { cc = fmt.Sprintf("%f", e.Coefficient) } if res, err := DBExec("INSERT INTO exercices (id_theme, title, url_id, path, statement, overview, finished, headline, issue, depend, gain, video_uri, issue_kind, coefficient_cur) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "+ik+", "+cc+")", t.Id, e.Title, e.URLId, e.Path, e.Statement, e.Overview, e.Finished, e.Headline, e.Issue, e.Depend, e.Gain, e.VideoURI); err != nil { return err } else if eid, err := res.LastInsertId(); err != nil { return err } else { e.Id = eid return nil } } // AddExercice creates and fills a new struct Exercice and registers it into the database. func (t Theme) AddExercice(title string, urlId string, path string, statement string, overview string, headline string, depend *Exercice, gain int64, videoURI string, finished string) (e Exercice, err error) { var dpd *int64 = nil if depend != nil { dpd = &depend.Id } e = Exercice{ Title: title, URLId: urlId, Path: path, Statement: statement, Overview: overview, Headline: headline, Depend: dpd, Finished: finished, Gain: gain, VideoURI: videoURI, } err = t.addExercice(&e) return } // Update applies modifications back to the database. func (e Exercice) Update() (int64, error) { if res, err := DBExec("UPDATE exercices SET title = ?, url_id = ?, path = ?, statement = ?, overview = ?, headline = ?, issue = ?, issue_kind = ?, depend = ?, gain = ?, coefficient_cur = ?, video_uri = ?, finished = ? WHERE id_exercice = ?", e.Title, e.URLId, e.Path, e.Statement, e.Overview, e.Headline, e.Issue, e.IssueKind, e.Depend, e.Gain, e.Coefficient, e.VideoURI, e.Finished, e.Id); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } } // FixURLId generates a valid URLid from the challenge Title. // It returns true if something has been generated. func (e *Exercice) FixURLId() bool { if e.URLId == "" { e.URLId = ToURLid(e.Title) return true } return false } // Delete the challenge from the database. func (e Exercice) Delete() (int64, error) { if res, err := DBExec("DELETE FROM exercices WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } } // DeleteCascade the challenge from the database, including inner content but not player content. func (e Exercice) DeleteCascade() (int64, error) { if _, err := DBExec("UPDATE exercices SET depend = NULL WHERE depend = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_files_okey_deps WHERE id_file IN (SELECT id_file FROM exercice_files WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_files_omcq_deps WHERE id_file IN (SELECT id_file FROM exercice_files WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_files WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_hints_okey_deps WHERE id_hint IN (SELECT id_hint FROM exercice_hints WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_hints_omcq_deps WHERE id_hint IN (SELECT id_hint FROM exercice_hints WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_hints WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_flags_deps WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM flag_choices WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM mcq_entries WHERE id_mcq IN (SELECT id_mcq FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_mcq WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_tags WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM teams_qa_todo WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM teams_qa_view WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else { return e.Delete() } } // DeleteDeep the challenge from the database, including player content. func (e Exercice) DeleteDeep() (int64, error) { if _, err := DBExec("DELETE FROM mcq_found WHERE id_mcq IN (SELECT id_mcq FROM exercice_mcq WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM flag_found WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM team_hints WHERE id_hint IN (SELECT id_hint FROM exercice_hints WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM team_wchoices WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_solved WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else if _, err := DBExec("DELETE FROM exercice_tries WHERE id_exercice = ?", e.Id); err != nil { return 0, err } else { return e.DeleteCascade() } } // GetLevel returns the number of dependancy challenges. func (e Exercice) GetLevel() (int, error) { dep := e.Depend nb := 1 for dep != nil { nb += 1 if nb > 10 || *dep == e.Id { return nb, errors.New("Exceed number of levels") } else if edep, err := GetExercice(*dep); err != nil { return nb, err } else { dep = edep.Depend } } return nb, nil } // NewTry registers a solving attempt for the given Team. func (e Exercice) NewTry(t Team, cksum []byte) error { if _, err := DBExec("INSERT INTO exercice_tries (id_exercice, id_team, time, cksum) VALUES (?, ?, ?, ?)", e.Id, t.Id, time.Now(), cksum); err != nil { return err } else { return nil } } // UpdateTry applies modifications to the latest try registered for the given Team. // Updated values are time and the given nbdiff. func (e Exercice) UpdateTry(t Team, nbdiff int, oneGood bool) error { if _, err := DBExec("UPDATE exercice_tries SET nbdiff = ?, onegood = ?, time = ? WHERE id_exercice = ? AND id_team = ? ORDER BY time DESC LIMIT 1", nbdiff, oneGood, time.Now(), e.Id, t.Id); err != nil { return err } else { return nil } } // Solved registers that the given Team solves the challenge. func (e Exercice) Solved(t Team) error { if _, err := DBExec("INSERT INTO exercice_solved (id_exercice, id_team, time, coefficient) VALUES (?, ?, ?, ?)", e.Id, t.Id, time.Now(), e.Coefficient*ExerciceCurrentCoefficient); err != nil { return err } else { return nil } } // SolvedCount returns the number of Team that already have solved the challenge. func (e Exercice) SolvedCount() int64 { var nb int64 if err := DBQueryRow("SELECT COUNT(id_exercice) FROM exercice_solved WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil { return 0 } else { return nb } } // TriedTeamCount returns the number of Team that attempted to solve the exercice. func (e Exercice) TriedTeamCount() int64 { tries_table := "exercice_tries" if SubmissionUniqueness { tries_table = "exercice_distinct_tries" } var nb int64 if err := DBQueryRow("SELECT COUNT(DISTINCT id_team) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil { return 0 } else { return nb } } // TriedCount returns the number of cumulative attempts, all Team combined, for the exercice. func (e Exercice) TriedCount() int64 { tries_table := "exercice_tries" if SubmissionUniqueness { tries_table = "exercice_distinct_tries" } var nb int64 if err := DBQueryRow("SELECT COUNT(id_team) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil { return 0 } else { return nb } } // FlagSolved returns the list of flags solved. func (e Exercice) FlagSolved() (res []int64) { if rows, err := DBQuery("SELECT F.id_flag FROM flag_found F INNER JOIN exercice_flags E ON E.id_flag = F.id_flag WHERE E.id_exercice = ? GROUP BY id_flag", e.Id); err != nil { return } else { defer rows.Close() for rows.Next() { var n int64 if err := rows.Scan(&n); err != nil { return } res = append(res, n) } return } } // MCQSolved returns the list of mcqs solved. func (e Exercice) MCQSolved() (res []int64) { if rows, err := DBQuery("SELECT F.id_mcq FROM mcq_found F INNER JOIN exercice_mcq E ON E.id_mcq = F.id_mcq WHERE E.id_exercice = ? GROUP BY id_mcq", e.Id); err != nil { return } else { defer rows.Close() for rows.Next() { var n int64 if err := rows.Scan(&n); err != nil { return } res = append(res, n) } return } } // CheckResponse, given both flags and MCQ responses, figures out if thoses are correct (or if they are previously solved). // In the meanwhile, CheckResponse registers good answers given (but it does not mark the challenge as solved at the end). func (e Exercice) CheckResponse(cksum []byte, respflags map[int]string, respmcq map[int]bool, t Team) (bool, error) { if err := e.NewTry(t, cksum); err != nil { return false, err } else if flags, err := e.GetFlagKeys(); err != nil { return false, err } else if mcqs, err := e.GetMCQ(); err != nil { return false, err } else if len(flags) < 1 && len(mcqs) < 1 { return true, errors.New("Exercice with no flag registered") } else { valid := true diff := 0 goodResponses := 0 // Check MCQs for _, mcq := range mcqs { if d := mcq.Check(respmcq); d > 0 { if !PartialValidation || t.HasPartiallySolved(mcq) == nil { valid = false diff += d } } else if !PartialMCQValidation && d == 0 { mcq.FoundBy(t) goodResponses += 1 } } // Validate MCQs if no error if valid { for _, mcq := range mcqs { mcq.FoundBy(t) goodResponses += 1 } } // Check flags for _, flag := range flags { if res, ok := respflags[flag.Id]; !ok && (!PartialValidation || t.HasPartiallySolved(flag) == nil) { valid = false } else if flag.Check([]byte(res)) != 0 { if !PartialValidation || t.HasPartiallySolved(flag) == nil { valid = false } } else { flag.FoundBy(t) goodResponses += 1 } } if diff > 0 || goodResponses > 0 { e.UpdateTry(t, diff, goodResponses > 0) } return valid, nil } } // IsSolved returns the number of time this challenge has been solved and the time of the first solve occurence. func (e Exercice) IsSolved() (int, time.Time) { var nb *int var tm *time.Time if DBQueryRow("SELECT COUNT(id_exercice), MIN(time) FROM exercice_solved WHERE id_exercice = ?", e.Id).Scan(&nb, &tm); nb == nil || tm == nil { return 0, time.Time{} } else { return *nb, *tm } }