Shorten things.

This commit is contained in:
Azareal 2019-09-29 15:10:05 +10:00
parent 78c5c62eee
commit 3ba977c75e
8 changed files with 263 additions and 262 deletions

View File

@ -61,63 +61,63 @@ func NewDefaultAttachmentStore(acc *qgen.Accumulator) (*DefaultAttachmentStore,
}, acc.FirstError() }, acc.FirstError()
} }
func (store *DefaultAttachmentStore) MiniGetList(originTable string, originID int) (alist []*MiniAttachment, err error) { func (s *DefaultAttachmentStore) MiniGetList(originTable string, originID int) (alist []*MiniAttachment, err error) {
rows, err := store.getByObj.Query(originTable, originID) rows, err := s.getByObj.Query(originTable, originID)
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
attach := &MiniAttachment{OriginID: originID} a := &MiniAttachment{OriginID: originID}
err := rows.Scan(&attach.ID, &attach.SectionID, &attach.UploadedBy, &attach.Path, &attach.Extra) err := rows.Scan(&a.ID, &a.SectionID, &a.UploadedBy, &a.Path, &a.Extra)
if err != nil { if err != nil {
return nil, err return nil, err
} }
extarr := strings.Split(attach.Path, ".") extarr := strings.Split(a.Path, ".")
if len(extarr) < 2 { if len(extarr) < 2 {
return nil, errors.New("corrupt attachment path") return nil, errors.New("corrupt attachment path")
} }
attach.Ext = extarr[len(extarr)-1] a.Ext = extarr[len(extarr)-1]
attach.Image = ImageFileExts.Contains(attach.Ext) a.Image = ImageFileExts.Contains(a.Ext)
alist = append(alist, attach) alist = append(alist, a)
} }
return alist, rows.Err() return alist, rows.Err()
} }
func (store *DefaultAttachmentStore) BulkMiniGetList(originTable string, ids []int) (amap map[int][]*MiniAttachment, err error) { func (s *DefaultAttachmentStore) BulkMiniGetList(originTable string, ids []int) (amap map[int][]*MiniAttachment, err error) {
if len(ids) == 0 { if len(ids) == 0 {
return nil, sql.ErrNoRows return nil, sql.ErrNoRows
} }
if len(ids) == 1 { if len(ids) == 1 {
res, err := store.MiniGetList(originTable, ids[0]) res, err := s.MiniGetList(originTable, ids[0])
return map[int][]*MiniAttachment{ids[0]: res}, err return map[int][]*MiniAttachment{ids[0]: res}, err
} }
amap = make(map[int][]*MiniAttachment) amap = make(map[int][]*MiniAttachment)
var buffer []*MiniAttachment var buffer []*MiniAttachment
var currentID int var currentID int
rows, err := qgen.NewAcc().Select("attachments").Columns("attachID, sectionID, originID, uploadedBy, path").Where("originTable = ?").In("originID", ids).Orderby("originID ASC").Query(originTable) rows, err := qgen.NewAcc().Select("attachments").Columns("attachID,sectionID,originID,uploadedBy,path").Where("originTable = ?").In("originID", ids).Orderby("originID ASC").Query(originTable)
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
attach := &MiniAttachment{} a := &MiniAttachment{}
err := rows.Scan(&attach.ID, &attach.SectionID, &attach.OriginID, &attach.UploadedBy, &attach.Path) err := rows.Scan(&a.ID, &a.SectionID, &a.OriginID, &a.UploadedBy, &a.Path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
extarr := strings.Split(attach.Path, ".") extarr := strings.Split(a.Path, ".")
if len(extarr) < 2 { if len(extarr) < 2 {
return nil, errors.New("corrupt attachment path") return nil, errors.New("corrupt attachment path")
} }
attach.Ext = extarr[len(extarr)-1] a.Ext = extarr[len(extarr)-1]
attach.Image = ImageFileExts.Contains(attach.Ext) a.Image = ImageFileExts.Contains(a.Ext)
if currentID == 0 { if currentID == 0 {
currentID = attach.OriginID currentID = a.OriginID
} }
if attach.OriginID != currentID { if a.OriginID != currentID {
if len(buffer) > 0 { if len(buffer) > 0 {
amap[currentID] = buffer amap[currentID] = buffer
currentID = attach.OriginID currentID = a.OriginID
buffer = nil buffer = nil
} }
} }
buffer = append(buffer, attach) buffer = append(buffer, a)
} }
if len(buffer) > 0 { if len(buffer) > 0 {
amap[currentID] = buffer amap[currentID] = buffer
@ -125,23 +125,23 @@ func (store *DefaultAttachmentStore) BulkMiniGetList(originTable string, ids []i
return amap, rows.Err() return amap, rows.Err()
} }
func (store *DefaultAttachmentStore) Get(id int) (*MiniAttachment, error) { func (s *DefaultAttachmentStore) Get(id int) (*MiniAttachment, error) {
attach := &MiniAttachment{ID: id} a := &MiniAttachment{ID: id}
err := store.get.QueryRow(id).Scan(&attach.OriginID, &attach.SectionID, &attach.UploadedBy, &attach.Path, &attach.Extra) err := s.get.QueryRow(id).Scan(&a.OriginID, &a.SectionID, &a.UploadedBy, &a.Path, &a.Extra)
if err != nil { if err != nil {
return nil, err return nil, err
} }
extarr := strings.Split(attach.Path, ".") extarr := strings.Split(a.Path, ".")
if len(extarr) < 2 { if len(extarr) < 2 {
return nil, errors.New("corrupt attachment path") return nil, errors.New("corrupt attachment path")
} }
attach.Ext = extarr[len(extarr)-1] a.Ext = extarr[len(extarr)-1]
attach.Image = ImageFileExts.Contains(attach.Ext) a.Image = ImageFileExts.Contains(a.Ext)
return attach, nil return a, nil
} }
func (store *DefaultAttachmentStore) Add(sectionID int, sectionTable string, originID int, originTable string, uploadedBy int, path string, extra string) (int, error) { func (s *DefaultAttachmentStore) Add(sectionID int, sectionTable string, originID int, originTable string, uploadedBy int, path string, extra string) (int, error) {
res, err := store.add.Exec(sectionID, sectionTable, originID, originTable, uploadedBy, path, extra) res, err := s.add.Exec(sectionID, sectionTable, originID, originTable, uploadedBy, path, extra)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -167,23 +167,23 @@ func (s *DefaultAttachmentStore) Count() (count int) {
return count return count
} }
func (store *DefaultAttachmentStore) CountIn(originTable string, oid int) (count int) { func (s *DefaultAttachmentStore) CountIn(originTable string, oid int) (count int) {
err := store.countIn.QueryRow(originTable, oid).Scan(&count) err := s.countIn.QueryRow(originTable, oid).Scan(&count)
if err != nil { if err != nil {
LogError(err) LogError(err)
} }
return count return count
} }
func (store *DefaultAttachmentStore) CountInPath(path string) (count int) { func (s *DefaultAttachmentStore) CountInPath(path string) (count int) {
err := store.countInPath.QueryRow(path).Scan(&count) err := s.countInPath.QueryRow(path).Scan(&count)
if err != nil { if err != nil {
LogError(err) LogError(err)
} }
return count return count
} }
func (store *DefaultAttachmentStore) Delete(aid int) error { func (s *DefaultAttachmentStore) Delete(aid int) error {
_, err := store.delete.Exec(aid) _, err := s.delete.Exec(aid)
return err return err
} }

View File

@ -93,8 +93,8 @@ func FromError(err error) RouteError {
return &RouteErrorImpl{err.Error(), "", false, false, false} return &RouteErrorImpl{err.Error(), "", false, false, false}
} }
func ErrorJSQ(errmsg string, isJs bool) RouteError { func ErrorJSQ(errmsg string, js bool) RouteError {
return &RouteErrorImpl{errmsg, "", false, isJs, false} return &RouteErrorImpl{errmsg, "", false, js, false}
} }
func SysError(errmsg string) RouteError { func SysError(errmsg string) RouteError {
@ -146,8 +146,8 @@ func InternalError(err error, w http.ResponseWriter, r *http.Request) RouteError
// InternalErrorJSQ is the JSON "maybe" version of InternalError which can handle both JSON and normal requests // InternalErrorJSQ is the JSON "maybe" version of InternalError which can handle both JSON and normal requests
// ? - Add a user parameter? // ? - Add a user parameter?
func InternalErrorJSQ(err error, w http.ResponseWriter, r *http.Request, isJs bool) RouteError { func InternalErrorJSQ(err error, w http.ResponseWriter, r *http.Request, js bool) RouteError {
if !isJs { if !js {
return InternalError(err, w, r) return InternalError(err, w, r)
} }
return InternalErrorJS(err, w, r) return InternalErrorJS(err, w, r)
@ -203,8 +203,8 @@ func PreErrorJS(errmsg string, w http.ResponseWriter, r *http.Request) RouteErro
return HandledRouteError() return HandledRouteError()
} }
func PreErrorJSQ(errmsg string, w http.ResponseWriter, r *http.Request, isJs bool) RouteError { func PreErrorJSQ(errmsg string, w http.ResponseWriter, r *http.Request, js bool) RouteError {
if !isJs { if !js {
return PreError(errmsg, w, r) return PreError(errmsg, w, r)
} }
return PreErrorJS(errmsg, w, r) return PreErrorJS(errmsg, w, r)
@ -235,8 +235,8 @@ func SimpleError(errmsg string, w http.ResponseWriter, r *http.Request, header *
return HandledRouteError() return HandledRouteError()
} }
func LocalErrorJSQ(errmsg string, w http.ResponseWriter, r *http.Request, user User, isJs bool) RouteError { func LocalErrorJSQ(errmsg string, w http.ResponseWriter, r *http.Request, user User, js bool) RouteError {
if !isJs { if !js {
return SimpleError(errmsg, w, r, errorHeader(w, user, "")) return SimpleError(errmsg, w, r, errorHeader(w, user, ""))
} }
return LocalErrorJS(errmsg, w, r) return LocalErrorJS(errmsg, w, r)
@ -257,8 +257,8 @@ func NoPermissions(w http.ResponseWriter, r *http.Request, user User) RouteError
return HandledRouteError() return HandledRouteError()
} }
func NoPermissionsJSQ(w http.ResponseWriter, r *http.Request, user User, isJs bool) RouteError { func NoPermissionsJSQ(w http.ResponseWriter, r *http.Request, user User, js bool) RouteError {
if !isJs { if !js {
return NoPermissions(w, r, user) return NoPermissions(w, r, user)
} }
return NoPermissionsJS(w, r, user) return NoPermissionsJS(w, r, user)
@ -280,8 +280,8 @@ func Banned(w http.ResponseWriter, r *http.Request, user User) RouteError {
// nolint // nolint
// BannedJSQ is the version of the banned error page which handles both JavaScript requests and normal page loads // BannedJSQ is the version of the banned error page which handles both JavaScript requests and normal page loads
func BannedJSQ(w http.ResponseWriter, r *http.Request, user User, isJs bool) RouteError { func BannedJSQ(w http.ResponseWriter, r *http.Request, user User, js bool) RouteError {
if !isJs { if !js {
return Banned(w, r, user) return Banned(w, r, user)
} }
return BannedJS(w, r, user) return BannedJS(w, r, user)
@ -294,8 +294,8 @@ func BannedJS(w http.ResponseWriter, r *http.Request, user User) RouteError {
} }
// nolint // nolint
func LoginRequiredJSQ(w http.ResponseWriter, r *http.Request, user User, isJs bool) RouteError { func LoginRequiredJSQ(w http.ResponseWriter, r *http.Request, user User, js bool) RouteError {
if !isJs { if !js {
return LoginRequired(w, r, user) return LoginRequired(w, r, user)
} }
return LoginRequiredJS(w, r, user) return LoginRequiredJS(w, r, user)
@ -373,8 +373,8 @@ func CustomError(errmsg string, errcode int, errtitle string, w http.ResponseWri
} }
// CustomErrorJSQ is a version of CustomError which lets us handle both JSON and regular pages depending on how it's being accessed // CustomErrorJSQ is a version of CustomError which lets us handle both JSON and regular pages depending on how it's being accessed
func CustomErrorJSQ(errmsg string, errcode int, errtitle string, w http.ResponseWriter, r *http.Request, header *Header, user User, isJs bool) RouteError { func CustomErrorJSQ(errmsg string, errcode int, errtitle string, w http.ResponseWriter, r *http.Request, header *Header, user User, js bool) RouteError {
if !isJs { if !js {
return CustomError(errmsg, errcode, errtitle, w, r, header, user) return CustomError(errmsg, errcode, errtitle, w, r, header, user)
} }
return CustomErrorJS(errmsg, errcode, w, r, user) return CustomErrorJS(errmsg, errcode, w, r, user)

View File

@ -24,67 +24,68 @@ type AnalyticsTimeRange struct {
} }
func analyticsTimeRange(rawTimeRange string) (*AnalyticsTimeRange, error) { func analyticsTimeRange(rawTimeRange string) (*AnalyticsTimeRange, error) {
timeRange := &AnalyticsTimeRange{} tRange := &AnalyticsTimeRange{
timeRange.Quantity = 6 Quantity: 6,
timeRange.Unit = "hour" Unit: "hour",
timeRange.Slices = 12 Slices: 12,
timeRange.SliceWidth = 60 * 30 SliceWidth: 60 * 30,
timeRange.Range = "six-hours" Range: "six-hours",
}
switch rawTimeRange { switch rawTimeRange {
// This might be pushing it, we might want to come up with a more efficient scheme for dealing with large timeframes like this // This might be pushing it, we might want to come up with a more efficient scheme for dealing with large timeframes like this
case "one-year": case "one-year":
timeRange.Quantity = 12 tRange.Quantity = 12
timeRange.Unit = "month" tRange.Unit = "month"
timeRange.Slices = 12 tRange.Slices = 12
timeRange.SliceWidth = 60 * 60 * 24 * 30 tRange.SliceWidth = 60 * 60 * 24 * 30
timeRange.Range = "one-year" tRange.Range = "one-year"
case "three-months": case "three-months":
timeRange.Quantity = 90 tRange.Quantity = 90
timeRange.Unit = "day" tRange.Unit = "day"
timeRange.Slices = 30 tRange.Slices = 30
timeRange.SliceWidth = 60 * 60 * 24 * 3 tRange.SliceWidth = 60 * 60 * 24 * 3
timeRange.Range = "three-months" tRange.Range = "three-months"
case "one-month": case "one-month":
timeRange.Quantity = 30 tRange.Quantity = 30
timeRange.Unit = "day" tRange.Unit = "day"
timeRange.Slices = 30 tRange.Slices = 30
timeRange.SliceWidth = 60 * 60 * 24 tRange.SliceWidth = 60 * 60 * 24
timeRange.Range = "one-month" tRange.Range = "one-month"
case "one-week": case "one-week":
timeRange.Quantity = 7 tRange.Quantity = 7
timeRange.Unit = "day" tRange.Unit = "day"
timeRange.Slices = 14 tRange.Slices = 14
timeRange.SliceWidth = 60 * 60 * 12 tRange.SliceWidth = 60 * 60 * 12
timeRange.Range = "one-week" tRange.Range = "one-week"
case "two-days": // Two days is experimental case "two-days": // Two days is experimental
timeRange.Quantity = 2 tRange.Quantity = 2
timeRange.Unit = "day" tRange.Unit = "day"
timeRange.Slices = 24 tRange.Slices = 24
timeRange.SliceWidth = 60 * 60 * 2 tRange.SliceWidth = 60 * 60 * 2
timeRange.Range = "two-days" tRange.Range = "two-days"
case "one-day": case "one-day":
timeRange.Quantity = 1 tRange.Quantity = 1
timeRange.Unit = "day" tRange.Unit = "day"
timeRange.Slices = 24 tRange.Slices = 24
timeRange.SliceWidth = 60 * 60 tRange.SliceWidth = 60 * 60
timeRange.Range = "one-day" tRange.Range = "one-day"
case "twelve-hours": case "twelve-hours":
timeRange.Quantity = 12 tRange.Quantity = 12
timeRange.Slices = 24 tRange.Slices = 24
timeRange.Range = "twelve-hours" tRange.Range = "twelve-hours"
case "six-hours", "": case "six-hours", "":
default: default:
return timeRange, errors.New("Unknown time range") return tRange, errors.New("Unknown time range")
} }
return timeRange, nil return tRange, nil
} }
func analyticsTimeRangeToLabelList(timeRange *AnalyticsTimeRange) (revLabelList []int64, labelList []int64, viewMap map[int64]int64) { func analyticsTimeRangeToLabelList(timeRange *AnalyticsTimeRange) (revLabelList []int64, labelList []int64, viewMap map[int64]int64) {
viewMap = make(map[int64]int64) viewMap = make(map[int64]int64)
var currentTime = time.Now().Unix() currentTime := time.Now().Unix()
for i := 1; i <= timeRange.Slices; i++ { for i := 1; i <= timeRange.Slices; i++ {
var label = currentTime - int64(i*timeRange.SliceWidth) label := currentTime - int64(i*timeRange.SliceWidth)
revLabelList = append(revLabelList, label) revLabelList = append(revLabelList, label)
viewMap[label] = 0 viewMap[label] = 0
} }
@ -103,7 +104,7 @@ func analyticsRowsToViewMap(rows *sql.Rows, labelList []int64, viewMap map[int64
if err != nil { if err != nil {
return viewMap, err return viewMap, err
} }
var unixCreatedAt = createdAt.Unix() unixCreatedAt := createdAt.Unix()
// TODO: Bulk log this // TODO: Bulk log this
if c.Dev.SuperDebug { if c.Dev.SuperDebug {
log.Print("count: ", count) log.Print("count: ", count)
@ -134,14 +135,14 @@ func analyticsRowsToAverageMap(rows *sql.Rows, labelList []int64, avgMap map[int
if err != nil { if err != nil {
return avgMap, err return avgMap, err
} }
var unixCreatedAt = createdAt.Unix() unixCreatedAt := createdAt.Unix()
// TODO: Bulk log this // TODO: Bulk log this
if c.Dev.SuperDebug { if c.Dev.SuperDebug {
log.Print("count: ", count) log.Print("count: ", count)
log.Print("createdAt: ", createdAt) log.Print("createdAt: ", createdAt)
log.Print("unixCreatedAt: ", unixCreatedAt) log.Print("unixCreatedAt: ", unixCreatedAt)
} }
var pAvgMap = make(map[int64]pAvg) pAvgMap := make(map[int64]pAvg)
for _, value := range labelList { for _, value := range labelList {
if unixCreatedAt > value { if unixCreatedAt > value {
prev := pAvgMap[value] prev := pAvgMap[value]
@ -167,7 +168,7 @@ func analyticsRowsToAverageMap2(rows *sql.Rows, labelList []int64, avgMap map[in
if err != nil { if err != nil {
return avgMap, err return avgMap, err
} }
var unixCreatedAt = createdAt.Unix() unixCreatedAt := createdAt.Unix()
// TODO: Bulk log this // TODO: Bulk log this
if c.Dev.SuperDebug { if c.Dev.SuperDebug {
log.Print("stack: ", stack) log.Print("stack: ", stack)
@ -180,7 +181,7 @@ func analyticsRowsToAverageMap2(rows *sql.Rows, labelList []int64, avgMap map[in
} else if typ == 2 { } else if typ == 2 {
stack = 0 stack = 0
} }
var pAvgMap = make(map[int64]pAvg) pAvgMap := make(map[int64]pAvg)
for _, value := range labelList { for _, value := range labelList {
if unixCreatedAt > value { if unixCreatedAt > value {
prev := pAvgMap[value] prev := pAvgMap[value]
@ -198,14 +199,14 @@ func analyticsRowsToAverageMap2(rows *sql.Rows, labelList []int64, avgMap map[in
} }
func PreAnalyticsDetail(w http.ResponseWriter, r *http.Request, user *c.User) (*c.BasePanelPage, c.RouteError) { func PreAnalyticsDetail(w http.ResponseWriter, r *http.Request, user *c.User) (*c.BasePanelPage, c.RouteError) {
basePage, ferr := buildBasePage(w, r, user, "analytics", "analytics") bPage, ferr := buildBasePage(w, r, user, "analytics", "analytics")
if ferr != nil { if ferr != nil {
return nil, ferr return nil, ferr
} }
basePage.AddSheet("chartist/chartist.min.css") bPage.AddSheet("chartist/chartist.min.css")
basePage.AddScript("chartist/chartist.min.js") bPage.AddScript("chartist/chartist.min.js")
basePage.AddScriptAsync("analytics.js") bPage.AddScriptAsync("analytics.js")
return basePage, nil return bPage, nil
} }
func AnalyticsViews(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { func AnalyticsViews(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {

View File

@ -20,7 +20,7 @@ func Backups(w http.ResponseWriter, r *http.Request, user c.User, backupURL stri
// We don't want them trying to break out of this directory, it shouldn't hurt since it's a super admin, but it's always good to practice good security hygiene, especially if this is one of many instances on a managed server not controlled by the superadmin/s // We don't want them trying to break out of this directory, it shouldn't hurt since it's a super admin, but it's always good to practice good security hygiene, especially if this is one of many instances on a managed server not controlled by the superadmin/s
backupURL = c.Stripslashes(backupURL) backupURL = c.Stripslashes(backupURL)
var ext = filepath.Ext("./backups/" + backupURL) ext := filepath.Ext("./backups/" + backupURL)
if ext != ".sql" && ext != ".zip" { if ext != ".sql" && ext != ".zip" {
return c.NotFound(w, r, basePage.Header) return c.NotFound(w, r, basePage.Header)
} }
@ -50,12 +50,12 @@ func Backups(w http.ResponseWriter, r *http.Request, user c.User, backupURL stri
return c.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
for _, backupFile := range backupFiles { for _, backupFile := range backupFiles {
var ext = filepath.Ext(backupFile.Name()) ext := filepath.Ext(backupFile.Name())
if ext != ".sql" { if ext != ".sql" {
continue continue
} }
backupList = append(backupList, c.BackupItem{backupFile.Name(), backupFile.ModTime()}) backupList = append(backupList, c.BackupItem{backupFile.Name(), backupFile.ModTime()})
} }
return renderTemplate("panel", w, r, basePage.Header, c.Panel{basePage,"","","panel_backups", c.PanelBackupPage{basePage, backupList}}) return renderTemplate("panel", w, r, basePage.Header, c.Panel{basePage, "", "", "panel_backups", c.PanelBackupPage{basePage, backupList}})
} }

View File

@ -12,8 +12,8 @@ var tList []interface{}
var successJSONBytes = []byte(`{"success":"1"}`) var successJSONBytes = []byte(`{"success":"1"}`)
// We're trying to reduce the amount of boilerplate in here, so I added these two functions, they might wind up circulating outside this file in the future // We're trying to reduce the amount of boilerplate in here, so I added these two functions, they might wind up circulating outside this file in the future
func successRedirect(dest string, w http.ResponseWriter, r *http.Request, isJs bool) c.RouteError { func successRedirect(dest string, w http.ResponseWriter, r *http.Request, js bool) c.RouteError {
if !isJs { if !js {
http.Redirect(w, r, dest, http.StatusSeeOther) http.Redirect(w, r, dest, http.StatusSeeOther)
} else { } else {
w.Write(successJSONBytes) w.Write(successJSONBytes)

View File

@ -30,9 +30,9 @@ func Forums(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
} }
// ? - Should we generate something similar to the forumView? It might be a little overkill for a page which is rarely loaded in comparison to /forums/ // ? - Should we generate something similar to the forumView? It might be a little overkill for a page which is rarely loaded in comparison to /forums/
for _, forum := range forums { for _, f := range forums {
if forum.Name != "" && forum.ParentID == 0 { if f.Name != "" && f.ParentID == 0 {
fadmin := c.ForumAdmin{forum.ID, forum.Name, forum.Desc, forum.Active, forum.Preset, forum.TopicCount, c.PresetToLang(forum.Preset)} fadmin := c.ForumAdmin{f.ID, f.Name, f.Desc, f.Active, f.Preset, f.TopicCount, c.PresetToLang(f.Preset)}
if fadmin.Preset == "" { if fadmin.Preset == "" {
fadmin.Preset = "custom" fadmin.Preset = "custom"
} }
@ -137,9 +137,9 @@ func ForumsOrderSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.Ro
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
sitems := strings.TrimSuffix(strings.TrimPrefix(r.PostFormValue("items"), "{"), "}") sitems := strings.TrimSuffix(strings.TrimPrefix(r.PostFormValue("items"), "{"), "}")
//fmt.Printf("sitems: %+v\n", sitems) //fmt.Printf("sitems: %+v\n", sitems)
@ -148,13 +148,13 @@ func ForumsOrderSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.Ro
for index, sfid := range strings.Split(sitems, ",") { for index, sfid := range strings.Split(sitems, ",") {
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return c.LocalErrorJSQ("Invalid integer in forum list", w, r, user, isJs) return c.LocalErrorJSQ("Invalid integer in forum list", w, r, user, js)
} }
updateMap[fid] = index updateMap[fid] = index
} }
c.Forums.UpdateOrder(updateMap) c.Forums.UpdateOrder(updateMap)
return successRedirect("/panel/forums/", w, r, isJs) return successRedirect("/panel/forums/", w, r, js)
} }
func ForumsEdit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError { func ForumsEdit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
@ -218,38 +218,38 @@ func ForumsEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return c.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return c.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, isJs) return c.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, js)
} }
forum, err := c.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return c.LocalErrorJSQ("The forum you're trying to edit doesn't exist.", w, r, user, isJs) return c.LocalErrorJSQ("The forum you're trying to edit doesn't exist.", w, r, user, js)
} else if err != nil { } else if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
forumName := r.PostFormValue("forum_name") fname := r.PostFormValue("forum_name")
forumDesc := r.PostFormValue("forum_desc") fdesc := r.PostFormValue("forum_desc")
forumPreset := c.StripInvalidPreset(r.PostFormValue("forum_preset")) fpreset := c.StripInvalidPreset(r.PostFormValue("forum_preset"))
forumActive := r.PostFormValue("forum_active") factive := r.PostFormValue("forum_active")
active := false active := false
if forumActive == "" { if factive == "" {
active = forum.Active active = forum.Active
} else if forumActive == "1" || forumActive == "Show" { } else if factive == "1" || factive == "Show" {
active = true active = true
} }
err = forum.Update(forumName, forumDesc, active, forumPreset) err = forum.Update(fname, fdesc, active, fpreset)
if err != nil { if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
// ? Should we redirect to the forum editor instead? // ? Should we redirect to the forum editor instead?
return successRedirect("/panel/forums/", w, r, isJs) return successRedirect("/panel/forums/", w, r, js)
} }
func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError { func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
@ -260,32 +260,32 @@ func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User,
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return c.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return c.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, isJs) return c.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, js)
} }
gid, err := strconv.Atoi(r.PostFormValue("gid")) gid, err := strconv.Atoi(r.PostFormValue("gid"))
if err != nil { if err != nil {
return c.LocalErrorJSQ("Invalid Group ID", w, r, user, isJs) return c.LocalErrorJSQ("Invalid Group ID", w, r, user, js)
} }
forum, err := c.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return c.LocalErrorJSQ("This forum doesn't exist", w, r, user, isJs) return c.LocalErrorJSQ("This forum doesn't exist", w, r, user, js)
} else if err != nil { } else if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
permPreset := c.StripInvalidGroupForumPreset(r.PostFormValue("perm_preset")) permPreset := c.StripInvalidGroupForumPreset(r.PostFormValue("perm_preset"))
err = forum.SetPreset(permPreset, gid) err = forum.SetPreset(permPreset, gid)
if err != nil { if err != nil {
return c.LocalErrorJSQ(err.Error(), w, r, user, isJs) return c.LocalErrorJSQ(err.Error(), w, r, user, js)
} }
return successRedirect("/panel/forums/edit/"+strconv.Itoa(fid)+"?updated=1", w, r, isJs) return successRedirect("/panel/forums/edit/"+strconv.Itoa(fid)+"?updated=1", w, r, js)
} }
// A helper function for the Advanced portion of the Forum Perms Editor // A helper function for the Advanced portion of the Forum Perms Editor
@ -333,9 +333,9 @@ func ForumsEditPermsAdvance(w http.ResponseWriter, r *http.Request, user c.User,
forum.Preset = "custom" forum.Preset = "custom"
} }
forumPerms, err := c.FPStore.Get(fid, gid) fp, err := c.FPStore.Get(fid, gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
forumPerms = c.BlankForumPerms() fp = c.BlankForumPerms()
} else if err != nil { } else if err != nil {
return c.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
@ -344,21 +344,21 @@ func ForumsEditPermsAdvance(w http.ResponseWriter, r *http.Request, user c.User,
// TODO: Load the phrases in bulk for efficiency? // TODO: Load the phrases in bulk for efficiency?
// TODO: Reduce the amount of code duplication between this and the group editor. Also, can we grind this down into one line or use a code generator to stay current more easily? // TODO: Reduce the amount of code duplication between this and the group editor. Also, can we grind this down into one line or use a code generator to stay current more easily?
var addNameLangToggle = func(permStr string, perm bool) { addNameLangToggle := func(permStr string, perm bool) {
formattedPermList = append(formattedPermList, c.NameLangToggle{permStr, phrases.GetLocalPermPhrase(permStr), perm}) formattedPermList = append(formattedPermList, c.NameLangToggle{permStr, phrases.GetLocalPermPhrase(permStr), perm})
} }
addNameLangToggle("ViewTopic", forumPerms.ViewTopic) addNameLangToggle("ViewTopic", fp.ViewTopic)
addNameLangToggle("LikeItem", forumPerms.LikeItem) addNameLangToggle("LikeItem", fp.LikeItem)
addNameLangToggle("CreateTopic", forumPerms.CreateTopic) addNameLangToggle("CreateTopic", fp.CreateTopic)
//<-- //<--
addNameLangToggle("EditTopic", forumPerms.EditTopic) addNameLangToggle("EditTopic", fp.EditTopic)
addNameLangToggle("DeleteTopic", forumPerms.DeleteTopic) addNameLangToggle("DeleteTopic", fp.DeleteTopic)
addNameLangToggle("CreateReply", forumPerms.CreateReply) addNameLangToggle("CreateReply", fp.CreateReply)
addNameLangToggle("EditReply", forumPerms.EditReply) addNameLangToggle("EditReply", fp.EditReply)
addNameLangToggle("DeleteReply", forumPerms.DeleteReply) addNameLangToggle("DeleteReply", fp.DeleteReply)
addNameLangToggle("PinTopic", forumPerms.PinTopic) addNameLangToggle("PinTopic", fp.PinTopic)
addNameLangToggle("CloseTopic", forumPerms.CloseTopic) addNameLangToggle("CloseTopic", fp.CloseTopic)
addNameLangToggle("MoveTopic", forumPerms.MoveTopic) addNameLangToggle("MoveTopic", fp.MoveTopic)
if r.FormValue("updated") == "1" { if r.FormValue("updated") == "1" {
basePage.AddNotice("panel_forum_perms_updated") basePage.AddNotice("panel_forum_perms_updated")
@ -376,7 +376,7 @@ func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user c
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return c.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
fid, gid, err := forumPermsExtractDash(paramList) fid, gid, err := forumPermsExtractDash(paramList)
if err != nil { if err != nil {
@ -390,35 +390,35 @@ func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user c
return c.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
forumPerms, err := c.FPStore.GetCopy(fid, gid) fp, err := c.FPStore.GetCopy(fid, gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
forumPerms = *c.BlankForumPerms() fp = *c.BlankForumPerms()
} else if err != nil { } else if err != nil {
return c.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
var extractPerm = func(name string) bool { extractPerm := func(name string) bool {
pvalue := r.PostFormValue("forum-perm-" + name) pvalue := r.PostFormValue("forum-perm-" + name)
return (pvalue == "1") return (pvalue == "1")
} }
// TODO: Generate this code? // TODO: Generate this code?
forumPerms.ViewTopic = extractPerm("ViewTopic") fp.ViewTopic = extractPerm("ViewTopic")
forumPerms.LikeItem = extractPerm("LikeItem") fp.LikeItem = extractPerm("LikeItem")
forumPerms.CreateTopic = extractPerm("CreateTopic") fp.CreateTopic = extractPerm("CreateTopic")
forumPerms.EditTopic = extractPerm("EditTopic") fp.EditTopic = extractPerm("EditTopic")
forumPerms.DeleteTopic = extractPerm("DeleteTopic") fp.DeleteTopic = extractPerm("DeleteTopic")
forumPerms.CreateReply = extractPerm("CreateReply") fp.CreateReply = extractPerm("CreateReply")
forumPerms.EditReply = extractPerm("EditReply") fp.EditReply = extractPerm("EditReply")
forumPerms.DeleteReply = extractPerm("DeleteReply") fp.DeleteReply = extractPerm("DeleteReply")
forumPerms.PinTopic = extractPerm("PinTopic") fp.PinTopic = extractPerm("PinTopic")
forumPerms.CloseTopic = extractPerm("CloseTopic") fp.CloseTopic = extractPerm("CloseTopic")
forumPerms.MoveTopic = extractPerm("MoveTopic") fp.MoveTopic = extractPerm("MoveTopic")
err = forum.SetPerms(&forumPerms, "custom", gid) err = forum.SetPerms(&fp, "custom", gid)
if err != nil { if err != nil {
return c.LocalErrorJSQ(err.Error(), w, r, user, isJs) return c.LocalErrorJSQ(err.Error(), w, r, user, js)
} }
return successRedirect("/panel/forums/edit/perms/"+strconv.Itoa(fid)+"-"+strconv.Itoa(gid)+"?updated=1", w, r, isJs) return successRedirect("/panel/forums/edit/perms/"+strconv.Itoa(fid)+"-"+strconv.Itoa(gid)+"?updated=1", w, r, js)
} }

View File

@ -8,7 +8,7 @@ import (
"strings" "strings"
c "github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/common/phrases" p "github.com/Azareal/Gosora/common/phrases"
) )
// TODO: Link the usernames for successful registrations to the profiles // TODO: Link the usernames for successful registrations to the profiles
@ -27,7 +27,7 @@ func LogsRegs(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
if err != nil { if err != nil {
return c.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
var llist = make([]c.PageRegLogItem, len(logs)) llist := make([]c.PageRegLogItem, len(logs))
for index, log := range logs { for index, log := range logs {
llist[index] = c.PageRegLogItem{log, strings.Replace(strings.TrimSuffix(log.FailureReason, "|"), "|", " | ", -1)} llist[index] = c.PageRegLogItem{log, strings.Replace(strings.TrimSuffix(log.FailureReason, "|"), "|", " | ", -1)}
} }
@ -41,13 +41,13 @@ func LogsRegs(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
// TODO: Base the slugs on the localised usernames? // TODO: Base the slugs on the localised usernames?
func handleUnknownUser(user *c.User, err error) *c.User { func handleUnknownUser(user *c.User, err error) *c.User {
if err != nil { if err != nil {
return &c.User{Name: phrases.GetTmplPhrase("user_unknown"), Link: c.BuildProfileURL("unknown", 0)} return &c.User{Name: p.GetTmplPhrase("user_unknown"), Link: c.BuildProfileURL("unknown", 0)}
} }
return user return user
} }
func handleUnknownTopic(topic *c.Topic, err error) *c.Topic { func handleUnknownTopic(topic *c.Topic, err error) *c.Topic {
if err != nil { if err != nil {
return &c.Topic{Title: phrases.GetTmplPhrase("topic_unknown"), Link: c.BuildTopicURL("unknown", 0)} return &c.Topic{Title: p.GetTmplPhrase("topic_unknown"), Link: c.BuildTopicURL("unknown", 0)}
} }
return topic return topic
} }
@ -55,7 +55,7 @@ func handleUnknownTopic(topic *c.Topic, err error) *c.Topic {
// TODO: Move the log building logic into /common/ and it's own abstraction // TODO: Move the log building logic into /common/ and it's own abstraction
func topicElementTypeAction(action string, elementType string, elementID int, actor *c.User, topic *c.Topic) (out string) { func topicElementTypeAction(action string, elementType string, elementID int, actor *c.User, topic *c.Topic) (out string) {
if action == "delete" { if action == "delete" {
return phrases.GetTmplPhrasef("panel_logs_moderation_action_topic_delete", elementID, actor.Link, actor.Name) return p.GetTmplPhrasef("panel_logs_moderation_action_topic_delete", elementID, actor.Link, actor.Name)
} }
var tbit string var tbit string
aarr := strings.Split(action, "-") aarr := strings.Split(action, "-")
@ -67,15 +67,15 @@ func topicElementTypeAction(action string, elementType string, elementID int, ac
fid, _ := strconv.Atoi(aarr[1]) fid, _ := strconv.Atoi(aarr[1])
forum, err := c.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == nil { if err == nil {
return phrases.GetTmplPhrasef("panel_logs_moderation_action_topic_move_dest", topic.Link, topic.Title, forum.Link, forum.Name, actor.Link, actor.Name) return p.GetTmplPhrasef("panel_logs_moderation_action_topic_move_dest", topic.Link, topic.Title, forum.Link, forum.Name, actor.Link, actor.Name)
} }
} }
tbit = "move" tbit = "move"
default: default:
return phrases.GetTmplPhrasef("panel_logs_moderation_action_topic_unknown", action, elementType, actor.Link, actor.Name) return p.GetTmplPhrasef("panel_logs_moderation_action_topic_unknown", action, elementType, actor.Link, actor.Name)
} }
if tbit != "" { if tbit != "" {
return phrases.GetTmplPhrasef("panel_logs_moderation_action_topic_"+tbit, topic.Link, topic.Title, actor.Link, actor.Name) return p.GetTmplPhrasef("panel_logs_moderation_action_topic_"+tbit, topic.Link, topic.Title, actor.Link, actor.Name)
} }
return fmt.Sprintf(out, topic.Link, topic.Title, actor.Link, actor.Name) return fmt.Sprintf(out, topic.Link, topic.Title, actor.Link, actor.Name)
} }
@ -87,16 +87,16 @@ func modlogsElementType(action string, elementType string, elementID int, actor
out = topicElementTypeAction(action, elementType, elementID, actor, topic) out = topicElementTypeAction(action, elementType, elementID, actor, topic)
case "user": case "user":
targetUser := handleUnknownUser(c.Users.Get(elementID)) targetUser := handleUnknownUser(c.Users.Get(elementID))
out = phrases.GetTmplPhrasef("panel_logs_moderation_action_user_"+action, targetUser.Link, targetUser.Name, actor.Link, actor.Name) out = p.GetTmplPhrasef("panel_logs_moderation_action_user_"+action, targetUser.Link, targetUser.Name, actor.Link, actor.Name)
case "reply": case "reply":
if action == "delete" { if action == "delete" {
topic := handleUnknownTopic(c.TopicByReplyID(elementID)) topic := handleUnknownTopic(c.TopicByReplyID(elementID))
out = phrases.GetTmplPhrasef("panel_logs_moderation_action_reply_delete", topic.Link, topic.Title, actor.Link, actor.Name) out = p.GetTmplPhrasef("panel_logs_moderation_action_reply_delete", topic.Link, topic.Title, actor.Link, actor.Name)
} }
} }
if out == "" { if out == "" {
out = phrases.GetTmplPhrasef("panel_logs_moderation_action_unknown", action, elementType, actor.Link, actor.Name) out = p.GetTmplPhrasef("panel_logs_moderation_action_unknown", action, elementType, actor.Link, actor.Name)
} }
return out return out
} }

View File

@ -9,7 +9,7 @@ import (
"strings" "strings"
c "github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/common/phrases" p "github.com/Azareal/Gosora/common/phrases"
) )
func Themes(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { func Themes(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
@ -76,7 +76,7 @@ func ThemesMenus(w http.ResponseWriter, r *http.Request, user c.User) c.RouteErr
for mid, list := range c.Menus.GetAllMap() { for mid, list := range c.Menus.GetAllMap() {
var name = "" var name = ""
if mid == 1 { if mid == 1 {
name = phrases.GetTmplPhrase("panel_themes_menus_main") name = p.GetTmplPhrase("panel_themes_menus_main")
} }
menuList = append(menuList, c.PanelMenuListItem{ menuList = append(menuList, c.PanelMenuListItem{
Name: name, Name: name,
@ -102,7 +102,7 @@ func ThemesMenusEdit(w http.ResponseWriter, r *http.Request, user c.User, smid s
mid, err := strconv.Atoi(smid) mid, err := strconv.Atoi(smid)
if err != nil { if err != nil {
return c.LocalError(phrases.GetErrorPhrase("url_id_must_be_integer"), w, r, user) return c.LocalError(p.GetErrorPhrase("url_id_must_be_integer"), w, r, user)
} }
menuHold, err := c.Menus.Get(mid) menuHold, err := c.Menus.Get(mid)
@ -114,7 +114,7 @@ func ThemesMenusEdit(w http.ResponseWriter, r *http.Request, user c.User, smid s
var menuList []c.MenuItem var menuList []c.MenuItem
for _, item := range menuHold.List { for _, item := range menuHold.List {
var menuTmpls = map[string]c.MenuTmpl{ menuTmpls := map[string]c.MenuTmpl{
item.TmplName: menuHold.Parse(item.Name, []byte("{{.Name}}")), item.TmplName: menuHold.Parse(item.Name, []byte("{{.Name}}")),
} }
var renderBuffer [][]byte var renderBuffer [][]byte
@ -147,7 +147,7 @@ func ThemesMenuItemEdit(w http.ResponseWriter, r *http.Request, user c.User, sit
itemID, err := strconv.Atoi(sitemID) itemID, err := strconv.Atoi(sitemID)
if err != nil { if err != nil {
return c.LocalError(phrases.GetErrorPhrase("url_id_must_be_integer"), w, r, user) return c.LocalError(p.GetErrorPhrase("url_id_must_be_integer"), w, r, user)
} }
menuItem, err := c.Menus.ItemStore().Get(itemID) menuItem, err := c.Menus.ItemStore().Get(itemID)
@ -160,50 +160,50 @@ func ThemesMenuItemEdit(w http.ResponseWriter, r *http.Request, user c.User, sit
return renderTemplate("panel", w, r, basePage.Header, c.Panel{basePage,"","","panel_themes_menus_item_edit", &c.PanelMenuItemPage{basePage, menuItem}}) return renderTemplate("panel", w, r, basePage.Header, c.Panel{basePage,"","","panel_themes_menus_item_edit", &c.PanelMenuItemPage{basePage, menuItem}})
} }
func themesMenuItemSetters(r *http.Request, menuItem c.MenuItem) c.MenuItem { func themesMenuItemSetters(r *http.Request, mItem c.MenuItem) c.MenuItem {
var getItem = func(name string) string { getItem := func(name string) string {
return c.SanitiseSingleLine(r.PostFormValue("item-" + name)) return c.SanitiseSingleLine(r.PostFormValue("item-" + name))
} }
menuItem.Name = getItem("name") mItem.Name = getItem("name")
menuItem.HTMLID = getItem("htmlid") mItem.HTMLID = getItem("htmlid")
menuItem.CSSClass = getItem("cssclass") mItem.CSSClass = getItem("cssclass")
menuItem.Position = getItem("position") mItem.Position = getItem("position")
if menuItem.Position != "left" && menuItem.Position != "right" { if mItem.Position != "left" && mItem.Position != "right" {
menuItem.Position = "left" mItem.Position = "left"
} }
menuItem.Path = getItem("path") mItem.Path = getItem("path")
menuItem.Aria = getItem("aria") mItem.Aria = getItem("aria")
menuItem.Tooltip = getItem("tooltip") mItem.Tooltip = getItem("tooltip")
menuItem.TmplName = getItem("tmplname") mItem.TmplName = getItem("tmplname")
switch getItem("permissions") { switch getItem("permissions") {
case "everyone": case "everyone":
menuItem.GuestOnly = false mItem.GuestOnly = false
menuItem.MemberOnly = false mItem.MemberOnly = false
menuItem.SuperModOnly = false mItem.SuperModOnly = false
menuItem.AdminOnly = false mItem.AdminOnly = false
case "guest-only": case "guest-only":
menuItem.GuestOnly = true mItem.GuestOnly = true
menuItem.MemberOnly = false mItem.MemberOnly = false
menuItem.SuperModOnly = false mItem.SuperModOnly = false
menuItem.AdminOnly = false mItem.AdminOnly = false
case "member-only": case "member-only":
menuItem.GuestOnly = false mItem.GuestOnly = false
menuItem.MemberOnly = true mItem.MemberOnly = true
menuItem.SuperModOnly = false mItem.SuperModOnly = false
menuItem.AdminOnly = false mItem.AdminOnly = false
case "supermod-only": case "supermod-only":
menuItem.GuestOnly = false mItem.GuestOnly = false
menuItem.MemberOnly = true mItem.MemberOnly = true
menuItem.SuperModOnly = true mItem.SuperModOnly = true
menuItem.AdminOnly = false mItem.AdminOnly = false
case "admin-only": case "admin-only":
menuItem.GuestOnly = false mItem.GuestOnly = false
menuItem.MemberOnly = true mItem.MemberOnly = true
menuItem.SuperModOnly = true mItem.SuperModOnly = true
menuItem.AdminOnly = true mItem.AdminOnly = true
} }
return menuItem return mItem
} }
func ThemesMenuItemEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sitemID string) c.RouteError { func ThemesMenuItemEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sitemID string) c.RouteError {
@ -211,30 +211,30 @@ func ThemesMenuItemEditSubmit(w http.ResponseWriter, r *http.Request, user c.Use
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
itemID, err := strconv.Atoi(sitemID) itemID, err := strconv.Atoi(sitemID)
if err != nil { if err != nil {
return c.LocalErrorJSQ(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user, isJs) return c.LocalErrorJSQ(p.GetErrorPhrase("id_must_be_integer"), w, r, user, js)
} }
menuItem, err := c.Menus.ItemStore().Get(itemID) menuItem, err := c.Menus.ItemStore().Get(itemID)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return c.LocalErrorJSQ("This item doesn't exist.", w, r, user, isJs) return c.LocalErrorJSQ("This item doesn't exist.", w, r, user, js)
} else if err != nil { } else if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
//menuItem = menuItem.Copy() // If we switch this for a pointer, we might need this as a scratchpad //menuItem = menuItem.Copy() // If we switch this for a pointer, we might need this as a scratchpad
menuItem = themesMenuItemSetters(r, menuItem) menuItem = themesMenuItemSetters(r, menuItem)
err = menuItem.Commit() err = menuItem.Commit()
if err != nil { if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
return successRedirect("/panel/themes/menus/item/edit/"+strconv.Itoa(itemID), w, r, isJs) return successRedirect("/panel/themes/menus/item/edit/"+strconv.Itoa(itemID), w, r, js)
} }
func ThemesMenuItemCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { func ThemesMenuItemCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
@ -243,26 +243,26 @@ func ThemesMenuItemCreateSubmit(w http.ResponseWriter, r *http.Request, user c.U
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
smenuID := r.PostFormValue("mid") smenuID := r.PostFormValue("mid")
if smenuID == "" { if smenuID == "" {
return c.LocalErrorJSQ("No menuID provided", w, r, user, isJs) return c.LocalErrorJSQ("No menuID provided", w, r, user, js)
} }
menuID, err := strconv.Atoi(smenuID) menuID, err := strconv.Atoi(smenuID)
if err != nil { if err != nil {
return c.LocalErrorJSQ(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user, isJs) return c.LocalErrorJSQ(p.GetErrorPhrase("id_must_be_integer"), w, r, user, js)
} }
menuItem := c.MenuItem{MenuID: menuID} menuItem := c.MenuItem{MenuID: menuID}
menuItem = themesMenuItemSetters(r, menuItem) menuItem = themesMenuItemSetters(r, menuItem)
itemID, err := menuItem.Create() itemID, err := menuItem.Create()
if err != nil { if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
return successRedirect("/panel/themes/menus/item/edit/"+strconv.Itoa(itemID), w, r, isJs) return successRedirect("/panel/themes/menus/item/edit/"+strconv.Itoa(itemID), w, r, js)
} }
func ThemesMenuItemDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, sitemID string) c.RouteError { func ThemesMenuItemDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, sitemID string) c.RouteError {
@ -270,28 +270,28 @@ func ThemesMenuItemDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.U
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
itemID, err := strconv.Atoi(sitemID) itemID, err := strconv.Atoi(sitemID)
if err != nil { if err != nil {
return c.LocalErrorJSQ(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user, isJs) return c.LocalErrorJSQ(p.GetErrorPhrase("id_must_be_integer"), w, r, user, js)
} }
menuItem, err := c.Menus.ItemStore().Get(itemID) menuItem, err := c.Menus.ItemStore().Get(itemID)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return c.LocalErrorJSQ("This item doesn't exist.", w, r, user, isJs) return c.LocalErrorJSQ("This item doesn't exist.", w, r, user, js)
} else if err != nil { } else if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
//menuItem = menuItem.Copy() // If we switch this for a pointer, we might need this as a scratchpad //menuItem = menuItem.Copy() // If we switch this for a pointer, we might need this as a scratchpad
err = menuItem.Delete() err = menuItem.Delete()
if err != nil { if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
return successRedirect("/panel/themes/menus/", w, r, isJs) return successRedirect("/panel/themes/menus/", w, r, js)
} }
func ThemesMenuItemOrderSubmit(w http.ResponseWriter, r *http.Request, user c.User, smid string) c.RouteError { func ThemesMenuItemOrderSubmit(w http.ResponseWriter, r *http.Request, user c.User, smid string) c.RouteError {
@ -299,36 +299,36 @@ func ThemesMenuItemOrderSubmit(w http.ResponseWriter, r *http.Request, user c.Us
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
mid, err := strconv.Atoi(smid) mid, err := strconv.Atoi(smid)
if err != nil { if err != nil {
return c.LocalErrorJSQ(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user, isJs) return c.LocalErrorJSQ(p.GetErrorPhrase("id_must_be_integer"), w, r, user, js)
} }
menuHold, err := c.Menus.Get(mid) menuHold, err := c.Menus.Get(mid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return c.LocalErrorJSQ("Can't find menu", w, r, user, isJs) return c.LocalErrorJSQ("Can't find menu", w, r, user, js)
} else if err != nil { } else if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
sitems := strings.TrimSuffix(strings.TrimPrefix(r.PostFormValue("items"), "{"), "}") sitems := strings.TrimSuffix(strings.TrimPrefix(r.PostFormValue("items"), "{"), "}")
//fmt.Printf("sitems: %+v\n", sitems) //fmt.Printf("sitems: %+v\n", sitems)
var updateMap = make(map[int]int) updateMap := make(map[int]int)
for index, smiid := range strings.Split(sitems, ",") { for index, smiid := range strings.Split(sitems, ",") {
miid, err := strconv.Atoi(smiid) miid, err := strconv.Atoi(smiid)
if err != nil { if err != nil {
return c.LocalErrorJSQ("Invalid integer in menu item list", w, r, user, isJs) return c.LocalErrorJSQ("Invalid integer in menu item list", w, r, user, js)
} }
updateMap[miid] = index updateMap[miid] = index
} }
menuHold.UpdateOrder(updateMap) menuHold.UpdateOrder(updateMap)
return successRedirect("/panel/themes/menus/edit/"+strconv.Itoa(mid), w, r, isJs) return successRedirect("/panel/themes/menus/edit/"+strconv.Itoa(mid), w, r, js)
} }
func ThemesWidgets(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { func ThemesWidgets(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
@ -402,59 +402,59 @@ func ThemesWidgetsEditSubmit(w http.ResponseWriter, r *http.Request, user c.User
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
wid, err := strconv.Atoi(swid) wid, err := strconv.Atoi(swid)
if err != nil { if err != nil {
return c.LocalErrorJSQ(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user, isJs) return c.LocalErrorJSQ(p.GetErrorPhrase("id_must_be_integer"), w, r, user, js)
} }
widget, err := c.Widgets.Get(wid) widget, err := c.Widgets.Get(wid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return c.NotFoundJSQ(w, r, nil, isJs) return c.NotFoundJSQ(w, r, nil, js)
} else if err != nil { } else if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
ewidget, err := widgetsParseInputs(r, widget.Copy()) ewidget, err := widgetsParseInputs(r, widget.Copy())
if err != nil { if err != nil {
return c.LocalErrorJSQ(err.Error(), w, r, user, isJs) return c.LocalErrorJSQ(err.Error(), w, r, user, js)
} }
err = ewidget.Commit() err = ewidget.Commit()
if err != nil { if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
return successRedirect("/panel/themes/widgets/", w, r, isJs) return successRedirect("/panel/themes/widgets/", w, r, js)
} }
// ThemesWidgetsCreateSubmit is an action which is triggered when someone sends a create request for a widget // ThemesWidgetsCreateSubmit is an action which is triggered when someone sends a create request for a widget
func ThemesWidgetsCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { func ThemesWidgetsCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
//fmt.Println("in ThemesWidgetsCreateSubmit") //fmt.Println("in ThemesWidgetsCreateSubmit")
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
_, ferr := c.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
ewidget, err := widgetsParseInputs(r, &c.Widget{}) ewidget, err := widgetsParseInputs(r, &c.Widget{})
if err != nil { if err != nil {
return c.LocalErrorJSQ(err.Error(), w, r, user, isJs) return c.LocalErrorJSQ(err.Error(), w, r, user, js)
} }
err = ewidget.Create() err = ewidget.Create()
if err != nil { if err != nil {
return c.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, js)
} }
return successRedirect("/panel/themes/widgets/", w, r, isJs) return successRedirect("/panel/themes/widgets/", w, r, js)
} }
func ThemesWidgetsDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, swid string) c.RouteError { func ThemesWidgetsDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, swid string) c.RouteError {
@ -462,14 +462,14 @@ func ThemesWidgetsDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.Us
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
isJs := (r.PostFormValue("js") == "1") js := (r.PostFormValue("js") == "1")
if !user.Perms.ManageThemes { if !user.Perms.ManageThemes {
return c.NoPermissionsJSQ(w, r, user, isJs) return c.NoPermissionsJSQ(w, r, user, js)
} }
wid, err := strconv.Atoi(swid) wid, err := strconv.Atoi(swid)
if err != nil { if err != nil {
return c.LocalErrorJSQ(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user, isJs) return c.LocalErrorJSQ(p.GetErrorPhrase("id_must_be_integer"), w, r, user, js)
} }
widget, err := c.Widgets.Get(wid) widget, err := c.Widgets.Get(wid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
@ -483,5 +483,5 @@ func ThemesWidgetsDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.Us
return c.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
return successRedirect("/panel/themes/widgets/", w, r, isJs) return successRedirect("/panel/themes/widgets/", w, r, js)
} }