func (h *HighLev) userChecks(user iface.User) error { verbSpec, ok := jsonp.GetM(h.nouns, fmt.Sprint("%v.verbs.%v.userCrit", h.desc.Sentence.Noun, h.desc.Sentence.Verb)) if ok { _, err := sanitize.Fast(verbSpec, user.Data()) return err } nounSpec, ok := jsonp.GetM(h.nouns, fmt.Sprintf("%v.userCrit", h.desc.Sentence.Noun)) if !ok { return nil } _, err := sanitize.Fast(nounSpec, user.Data()) return err }
func (v *V) Index() error { uni := v.uni visible_types := []string{} types, has := jsonp.GetM(uni.Opt, "Modules.content.types") if !has { return fmt.Errorf("Can't find content types.") } for i, _ := range types { visible_types = append(visible_types, i) } q := m{"type": m{"$in": visible_types}} search_sl, has := uni.Req.Form["search"] if has && len(search_sl[0]) > 0 { q["$and"] = content_model.GenerateQuery(search_sl[0]) uni.Dat["search"] = search_sl[0] } paging_inf := display_model.DoPaging(uni.Db, "contents", q, "page", map[string][]string(uni.Req.Form), uni.P+"?"+uni.Req.URL.RawQuery, 10) var res []interface{} uni.Db.C("contents").Find(q).Sort("-created").Skip(paging_inf.Skip).Limit(10).All(&res) uni.Dat["paging"] = paging_inf res = basic.Convert(res).([]interface{}) content_model.HaveUpToDateDrafts(uni.Db, res) uni.Dat["latest"] = res uni.Dat["_points"] = []string{"content/index"} return nil }
func (c *C) getScheme(noun, verb string) (map[string]interface{}, error) { scheme, ok := jsonp.GetM(c.uni.Opt, fmt.Sprintf("nouns.%v.verbs.%v.input", noun, verb)) if !ok { return nil, fmt.Errorf("Can't find scheme for noun %v, verb %v.", noun, verb) } return scheme, nil }
// Writes the entries in sitename_to_port into the proxy table. // // sitename_to_port example: // { // "example1": 51986 // } // // Can be used to write one or more (all, see bootstrap.StartAll) sites to the proxy table. // table_key now does not support dot notation, eg "x.y." will not create x and y if they don't exist. func writeProxyTable(proxy_abs, table_key, host_format string, sitename_to_port map[string]int) error { mut := new(sync.Mutex) mut.Lock() defer mut.Unlock() file_b, err := ioutil.ReadFile(proxy_abs) if err != nil { return err } var proxy_table_i interface{} err = json.Unmarshal(file_b, &proxy_table_i) if err != nil { return err } place, ok := jsonp.GetM(proxy_table_i, table_key) if !ok { return fmt.Errorf("Proxy table member %v is not a map.", table_key) } for i, v := range sitename_to_port { proxy_from := fmt.Sprintf(host_format, i) proxy_to := []interface{}{ "http://127.0.0.1:" + strconv.Itoa(v), } place[proxy_from] = proxy_to } marshalled_table, err := json.MarshalIndent(proxy_table_i, "", "\t") if err != nil { return err } return ioutil.WriteFile(proxy_abs, marshalled_table, os.ModePerm) }
func puzzleOpt(uni *context.Uni, puzzlename string) (map[string]interface{}, error) { puzzle_locate := fmt.Sprintf("user.puzzles.%v", puzzlename) puzzle_opt, ok := jsonp.GetM(uni.Opt, puzzle_locate) if !ok { return nil, fmt.Errorf("Cant find puzzle named %v.", puzzlename) } return puzzle_opt, nil }
// We never update drafts, they are immutable. func (a *A) saveDraft() error { uni := a.uni post := uni.Req.Form typ_s, has_typ := post["type"] if !has_typ { return fmt.Errorf("No type when saving draft.") } typ := typ_s[0] content_type_opt, has_opt := jsonp.GetM(uni.Opt, "Modules.content.types."+typ) if !has_opt { return fmt.Errorf("Can't find options of content type %v.", typ) } allows := content_model.AllowsDraft(content_type_opt, scut.Ulev(uni.Dat["_user"]), typ) if allows != nil { return allows } rules, has_rules := jsonp.GetM(uni.Opt, "Modules.content.types."+typ+".rules") if !has_rules { return fmt.Errorf("Can't find rules of content type %v.", typ) } draft_id, err := content_model.SaveDraft(uni.Db, rules, map[string][]string(post)) // Handle redirect. cont := map[string]interface{}{} if err == nil { // Go to the fresh draft if we succeeded to save it. cont["!type"] = typ + "_draft" cont["!id"] = draft_id.Hex() } else { // Go back to the previous draft if we couldn't save the new one, or to the insert page if we tried to save a parentless draft. draft_id, has_draft_id := uni.Req.Form[content_model.Parent_draft_field] if has_draft_id && len(draft_id[0]) > 0 { cont["!type"] = typ + "_draft" cont["!id"] = draft_id[0] } else if id, has_id := uni.Req.Form["id"]; has_id { cont["!type"] = typ cont["!id"] = id[0] } else { cont["!type"] = typ cont["!id"] = "" } } uni.Dat["_cont"] = cont return err }
// This function should be used only when neither of the processes are running, eg. // when the server was restarted, or the forker process was killed, and all child processes died with it. func (a *A) StartAll() error { uni := a.uni opt, has := jsonp.GetM(uni.Opt, "Modules.bootstrap") if !has { return fmt.Errorf("Bootstrap module is not installd properly.") } if uni.Session == nil { return fmt.Errorf("This is not an admin instance.") } return bm.StartAll(uni.Db, opt) }
func (h *HighLev) ownLev() (int, bool) { verbL, ok := jsonp.Get(h.nouns, fmt.Sprintf("%v.verbs.%v.ownLevel", h.desc.Sentence.Noun, h.desc.Sentence.Verb)) if ok { return numcon.IntP(verbL), true } nounL, ok := jsonp.GetM(h.nouns, fmt.Sprintf("%v.ownLevel", h.desc.Sentence.Noun)) if ok { return numcon.IntP(nounL), true } return 0, false }
// Example bootstrap options: // All keys listed here are required to be able to ignite a site. // { // "default_must": false, // "exec_abs": "c:/gowork/bin/hypecms", // "host_format": "%v.hypecms.com", // "max_cap": 500, // "proxy_abs": "c:/jsonfile.json", // "root_db": "hypecms", // "table_key": "proxy_table" // } func (a *A) Ignite() error { uni := a.uni opt, has := jsonp.GetM(uni.Opt, "Modules.bootstrap") if !has { return fmt.Errorf("Bootstrap module is not installd properly.") } sitename, err := bm.Ignite(uni.Session, uni.Db, opt, uni.Req.Form) if err == nil { uni.Dat["_cont"] = map[string]interface{}{"sitename": sitename} } return err }
func guestRules(uni *context.Uni) map[string]interface{} { rules, has := jsonp.GetM(uni.Opt, "user.guest_rules") // RegksterGuest will do fine with nil. if has { return rules } return map[string]interface{}{ "guest_name": map[string]interface{}{ "must": true, "min": 1, "max": 50, }, "website": 1, } }
func (h *H) BeforeDisplay() { uni := h.uni opt, has := jsonp.GetM(uni.Opt, "Modules.bootstrap") if !has { return } count, err := bm.SiteCount(uni.Db) if err != nil { return } max_cap := numcon.IntP(opt["max_cap"]) ratio := float64(count) / float64(max_cap) perc := float64(ratio * 100) uni.Dat["capacity_percentage"] = perc }
// Currently, Verbs having no input scheme will receive the incoming data untouched. func (h *HighLev) validate(noun, verb string, data map[string]interface{}) (map[string]interface{}, error) { schemeMap, ok := jsonp.GetM(h.nouns, fmt.Sprintf("%v.verbs.%v.input", noun, verb)) if ok { ex, err := sanitize.New(schemeMap) if err != nil { return nil, err } h.hooks.Select("SanitizerMangler").Fire(ex) data, err = ex.Extract(data) if err != nil { return nil, err } } h.hooks.Select("SanitizedDataMangler").Fire(data) return data, nil }
func do(uni *context.Uni, module, action string, params interface{}) map[string]interface{} { values, err := doParams(params) if err != nil { return ma{"error": err} } var url_path string if module == "admin" { url_path = fmt.Sprintf("/admin/b/%v", action) } else { _, has := jsonp.GetM(uni.Opt, "Modules."+module) if !has { return ma{"error": fmt.Sprintf("Module %v is not installed.", module)} } url_path = fmt.Sprintf("/b/%v/%v", module, action) } values.Add("json", "true") full_body := values.Encode() req, err := http.NewRequest("POST", "http://"+uni.Req.Host+url_path, bytes.NewBufferString(full_body)) if err != nil { return ma{"error": err} } if cookie, err := uni.Req.Cookie("user"); err == nil { req.AddCookie(cookie) } req.Header.Add("Content-Length", strconv.Itoa(len(full_body))) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, err := new(http.Client).Do(req) if err != nil { return ma{"error": err} } defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { return ma{"error": err} } var i interface{} err = json.Unmarshal(contents, &i) if err != nil { return ma{"error": "do request response is not a valid json."} // Happens when the requested page panics. } ret := i.(map[string]interface{}) err_val, has := ret["error"] if has { return ma{"error": err_val.(string)} } return ret }
func (t *Top) validate(noun, verb string, data map[string]interface{}) (map[string]interface{}, error) { scheme_map, ok := jsonp.GetM(t.uni.Opt, fmt.Sprintf("nouns.%v.verbs.%v.input", noun, verb)) if !ok { return nil, fmt.Errorf("Can't find scheme for %v %v.", noun, verb) } ex, err := sanitize.New(scheme_map) if err != nil { return nil, err } t.uni.Ev.Fire("SanitizerMangler", ex) data, err = ex.Extract(data) if err != nil { return nil, err } t.uni.Ev.Fire("SanitizedDataMangler", data) return data, nil }
func (a *A) UpdateComment() error { uni := a.uni typ, allow_err, _ := a.allowsComment("update") if allow_err != nil { return allow_err } comment_rule, hasrule := jsonp.GetM(uni.Opt, "Modules.content.types."+typ+".comment_rules") if !hasrule { return fmt.Errorf("Can't find comment rules of content type " + typ) } uid, has_uid := jsonp.Get(uni.Dat, "_user._id") if !has_uid { return fmt.Errorf("Can't update comment, you have no id.") } inp := uni.Req.Form return content_model.UpdateComment(uni.Db, uni.Ev, comment_rule, inp, uid.(bson.ObjectId)) }
// Called from both admin and outside editing. // ma containts type and id members extracted out of the url. func (v *V) Edit() error { uni := v.uni typ := uni.Req.Form["type"][0] rtyp := realType(typ) rules, hasr := jsonp.GetM(uni.Opt, "Modules.content.types."+rtyp+".rules") if !hasr { return fmt.Errorf("Can't find rules of " + rtyp) } uni.Dat["content_type"] = rtyp uni.Dat["type"] = rtyp var id string if val, has := uni.Req.Form["id"]; has { id = val[0] } hasid := len(id) > 0 // Corrigate routep.Comp because it sets a map key with an empty value... var field_dat interface{} var err error subt := subType(typ) switch subt { case "content": field_dat, err = v.editContent(typ, id) case "draft": field_dat, err = v.editDraft(rtyp, id) case "version": if !hasid { return fmt.Errorf("Version must have id.") } field_dat, err = v.editVersion(rtyp, id) default: panic(fmt.Sprintf("Unkown content subtype: %v.", subt)) } if err != nil { return err } fields, err := scut.RulesToFields(rules, field_dat) if err != nil { return err } uni.Dat["fields"] = fields return nil }
func (a *A) Execute() error { uni := a.uni action_name := uni.Req.Form["action"][0] action, has := jsonp.GetM(uni.Opt, "Modules.custom_actions.actions."+action_name) if !has { return fmt.Errorf("Can't find action %v in custom actions module.", action_name) } db := uni.Db user := uni.Dat["_user"].(map[string]interface{}) opt := uni.Opt inp := map[string][]string(uni.Req.Form) typ := action["type"].(string) var r error switch typ { case "vote": r = ca_model.Vote(db, user, action, inp) case "respond_content": r = ca_model.RespondContent(db, user, action, inp, opt) default: r = fmt.Errorf("Unkown action %v at RunAction.", action_name) } return r }
func (v *V) Edit() error { uni := v.uni point_name := uni.Req.Form["point"][0] point, ok := jsonp.GetM(uni.Opt, "Display-points."+point_name) if !ok { return fmt.Errorf("Can't find point named ", point_name) } var queries map[string]interface{} if q, has := point["queries"]; has { queries = q.(map[string]interface{}) } else { queries = map[string]interface{}{} } query_b, err := json.MarshalIndent(queries, "", " ") var query string if err != nil { query = err.Error() } else { query = string(query_b) } uni.Dat["point"] = map[string]interface{}{"name": point_name, "queries": query} uni.Dat["_points"] = []string{"display_editor/edit"} return nil }
func (a *A) InsertComment() error { uni := a.uni typ, allow_err, puzzle_err := a.allowsComment("insert") if allow_err != nil { return allow_err } uid, has_uid := jsonp.Get(uni.Dat, "_user._id") if !has_uid { return fmt.Errorf("You must have user id to comment.") } user_id := uid.(bson.ObjectId) comment_rule, hasrule := jsonp.GetM(uni.Opt, "Modules.content.types."+typ+".comment_rules") if !hasrule { return fmt.Errorf("Can't find comment rules of content type " + typ) } mf, has := jsonp.GetB(uni.Opt, "Modules.content.types."+typ+".moderate_comment") var moderate_first bool if (has && mf) || puzzle_err != nil { moderate_first = true uni.Dat["_cont"] = map[string]interface{}{"awaits-moderation": true} } inp := uni.Req.Form return content_model.InsertComment(uni.Db, uni.Ev, comment_rule, inp, user_id, typ, moderate_first) }
func (a *A) Register() error { inp := a.uni.Req.Form rules, _ := jsonp.GetM(a.uni.Opt, "Modules.user.rules") // RegisterUser will be fine with nil. _, err := user_model.RegisterUser(a.uni.Db, a.uni.Ev, rules, inp) return err }
func (d *Db) NewFilter(c string, m map[string]interface{}) (iface.Filter, error) { s := set.New(d.db, c) filterScheme, _ := jsonp.GetM(d.opt, "nouns."+c+".filterScheme") return filter.New(s, d.hooks, filterScheme, m) }