Replaced most of the uses of fmt with log.

Replaced the io.Writers with http.ResponseWriters.
Refactored the compiled template calls.
Redirect port 443 to port 80.
Catch more errors from templates.
Fixed a few mutexes which are never unlocked.
Eliminated an unnecessary parameter in InternalError()
Temporarily commented out users_penalties so that the installer will succeed.
A couple more template types can be remapped now.
Tweaked the theme.
This commit is contained in:
Azareal 2017-08-13 12:22:34 +01:00
parent f41c281e43
commit 5a43432b80
35 changed files with 833 additions and 688 deletions

1
.gitignore vendored
View File

@ -8,4 +8,5 @@ bin/*
*.exe *.exe
*.exe~ *.exe~
*.prof *.prof
*.log
.DS_Store .DS_Store

View File

@ -131,7 +131,7 @@ func (auth *DefaultAuth) SessionCheck(w http.ResponseWriter, r *http.Request) (u
if err == ErrNoRows { if err == ErrNoRows {
return &guest_user, false return &guest_user, false
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return &guest_user, true return &guest_user, true
} }

View File

@ -1,7 +1,6 @@
package main package main
import "log" import "log"
import "fmt"
import "encoding/json" import "encoding/json"
import "database/sql" import "database/sql"
@ -46,7 +45,7 @@ func init_database() (err error) {
} }
if dev.DebugMode { if dev.DebugMode {
log.Print(group.Name + ": ") log.Print(group.Name + ": ")
fmt.Printf("%+v\n", group.Perms) log.Printf("%+v\n", group.Perms)
} }
err = json.Unmarshal(group.PluginPermsText, &group.PluginPerms) err = json.Unmarshal(group.PluginPermsText, &group.PluginPerms)
@ -55,7 +54,7 @@ func init_database() (err error) {
} }
if dev.DebugMode { if dev.DebugMode {
log.Print(group.Name + ": ") log.Print(group.Name + ": ")
fmt.Printf("%+v\n", group.PluginPerms) log.Printf("%+v\n", group.PluginPerms)
} }
//group.Perms.ExtData = make(map[string]bool) //group.Perms.ExtData = make(map[string]bool)

View File

@ -34,7 +34,7 @@ func LogError(err error) {
log.Fatal("") log.Fatal("")
} }
func InternalError(err error, w http.ResponseWriter, r *http.Request) { func InternalError(err error, w http.ResponseWriter) {
w.Write(error_internal) w.Write(error_internal)
log.Print(err) log.Print(err)
debug.PrintStack() debug.PrintStack()

View File

@ -2,7 +2,7 @@
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
package main package main
import "fmt" import "log"
import "strings" import "strings"
import "sync" import "sync"
import "errors" import "errors"
@ -64,10 +64,10 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("before route_static") log.Print("before route_static")
fmt.Println("prefix:",prefix) log.Print("prefix:", prefix)
fmt.Println("req.URL.Path:",req.URL.Path) log.Print("req.URL.Path:", req.URL.Path)
fmt.Println("extra_data:",extra_data) log.Print("extra_data:", extra_data)
} }
if prefix == "/static" { if prefix == "/static" {
@ -77,7 +77,7 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("before PreRoute") log.Print("before PreRoute")
} }
// Deal with the session stuff, etc. // Deal with the session stuff, etc.
@ -87,7 +87,7 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("after PreRoute") log.Print("after PreRoute")
} }
switch(prefix) { switch(prefix) {

View File

@ -237,7 +237,7 @@ func BenchmarkStaticRouteParallel(b *testing.B) {
static_w.Body.Reset() static_w.Body.Reset()
static_handler.ServeHTTP(static_w,static_req) static_handler.ServeHTTP(static_w,static_req)
//if static_w.Code != 200 { //if static_w.Code != 200 {
// fmt.Println(static_w.Body) // pb.Print(static_w.Body)
// panic("HTTP Error!") // panic("HTTP Error!")
//} //}
} }
@ -450,8 +450,8 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
static_w.Body.Reset() static_w.Body.Reset()
static_handler.ServeHTTP(static_w,static_req) static_handler.ServeHTTP(static_w,static_req)
//if static_w.Code != 200 { //if static_w.Code != 200 {
// fmt.Println(static_w.Body) // b.Print(static_w.Body)
// panic("HTTP Error!") // b.Fatal("HTTP Error!")
//} //}
} }
}) })
@ -459,7 +459,7 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
b.Run("topic_admin_recorder", func(b *testing.B) { b.Run("topic_admin_recorder", func(b *testing.B) {
//f, err := os.Create("routes_bench_topic_cpu.prof") //f, err := os.Create("routes_bench_topic_cpu.prof")
//if err != nil { //if err != nil {
// log.Fatal(err) // b.Fatal(err)
//} //}
//pprof.StartCPUProfile(f) //pprof.StartCPUProfile(f)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -467,8 +467,8 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
topic_w.Body.Reset() topic_w.Body.Reset()
topic_handler.ServeHTTP(topic_w,topic_req_admin) topic_handler.ServeHTTP(topic_w,topic_req_admin)
//if topic_w.Code != 200 { //if topic_w.Code != 200 {
// fmt.Println(topic_w.Body) // b.Print(topic_w.Body)
// panic("HTTP Error!") // b.Fatal("HTTP Error!")
//} //}
} }
//pprof.StopCPUProfile() //pprof.StopCPUProfile()
@ -476,7 +476,7 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
b.Run("topic_guest_recorder", func(b *testing.B) { b.Run("topic_guest_recorder", func(b *testing.B) {
f, err := os.Create("routes_bench_topic_cpu_2.prof") f, err := os.Create("routes_bench_topic_cpu_2.prof")
if err != nil { if err != nil {
log.Fatal(err) b.Fatal(err)
} }
pprof.StartCPUProfile(f) pprof.StartCPUProfile(f)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -524,7 +524,7 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
b.Run("forums_guest_recorder", func(b *testing.B) { b.Run("forums_guest_recorder", func(b *testing.B) {
//f, err := os.Create("routes_bench_forums_cpu_2.prof") //f, err := os.Create("routes_bench_forums_cpu_2.prof")
//if err != nil { //if err != nil {
// log.Fatal(err) // b.Fatal(err)
//} //}
//pprof.StartCPUProfile(f) //pprof.StartCPUProfile(f)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -542,7 +542,7 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
b.Run("topic_admin_recorder_with_plugins", func(b *testing.B) { b.Run("topic_admin_recorder_with_plugins", func(b *testing.B) {
//f, err := os.Create("routes_bench_topic_cpu.prof") //f, err := os.Create("routes_bench_topic_cpu.prof")
//if err != nil { //if err != nil {
// log.Fatal(err) // b.Fatal(err)
//} //}
//pprof.StartCPUProfile(f) //pprof.StartCPUProfile(f)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -550,8 +550,8 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
topic_w.Body.Reset() topic_w.Body.Reset()
topic_handler.ServeHTTP(topic_w,topic_req_admin) topic_handler.ServeHTTP(topic_w,topic_req_admin)
//if topic_w.Code != 200 { //if topic_w.Code != 200 {
// fmt.Println(topic_w.Body) // b.Print(topic_w.Body)
// panic("HTTP Error!") // b.Fatal("HTTP Error!")
//} //}
} }
//pprof.StopCPUProfile() //pprof.StopCPUProfile()
@ -559,7 +559,7 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
b.Run("topic_guest_recorder_with_plugins", func(b *testing.B) { b.Run("topic_guest_recorder_with_plugins", func(b *testing.B) {
//f, err := os.Create("routes_bench_topic_cpu_2.prof") //f, err := os.Create("routes_bench_topic_cpu_2.prof")
//if err != nil { //if err != nil {
// log.Fatal(err) // b.Fatal(err)
//} //}
//pprof.StartCPUProfile(f) //pprof.StartCPUProfile(f)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -607,7 +607,7 @@ func BenchmarkForumsGuestRouteParallel(b *testing.B) {
b.Run("forums_guest_recorder_with_plugins", func(b *testing.B) { b.Run("forums_guest_recorder_with_plugins", func(b *testing.B) {
//f, err := os.Create("routes_bench_forums_cpu_2.prof") //f, err := os.Create("routes_bench_forums_cpu_2.prof")
//if err != nil { //if err != nil {
// log.Fatal(err) // b.Fatal(err)
//} //}
//pprof.StartCPUProfile(f) //pprof.StartCPUProfile(f)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -651,10 +651,10 @@ func BenchmarkQueryPreparedTopicParallel(b *testing.B) {
for pb.Next() { for pb.Next() {
err := get_topic_user_stmt.QueryRow(1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.Is_Closed, &tu.Sticky, &tu.ParentID, &tu.IpAddress, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level) err := get_topic_user_stmt.QueryRow(1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.Is_Closed, &tu.Sticky, &tu.ParentID, &tu.IpAddress, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level)
if err == ErrNoRows { if err == ErrNoRows {
log.Fatal("No rows found!") b.Fatal("No rows found!")
return return
} else if err != nil { } else if err != nil {
log.Fatal(err) b.Fatal(err)
return return
} }
} }
@ -668,10 +668,10 @@ func BenchmarkQueriesSerial(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
err := db.QueryRow("select topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level from topics left join users ON topics.createdBy = users.uid where tid = ?", 1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.Is_Closed, &tu.Sticky, &tu.ParentID, &tu.IpAddress, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level) err := db.QueryRow("select topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level from topics left join users ON topics.createdBy = users.uid where tid = ?", 1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.Is_Closed, &tu.Sticky, &tu.ParentID, &tu.IpAddress, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level)
if err == ErrNoRows { if err == ErrNoRows {
log.Fatal("No rows found!") b.Fatal("No rows found!")
return return
} else if err != nil { } else if err != nil {
log.Fatal(err) b.Fatal(err)
return return
} }
} }
@ -680,16 +680,17 @@ func BenchmarkQueriesSerial(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
rows, err := db.Query("select replies.rid, replies.content, replies.createdBy, replies.createdAt, replies.lastEdit, replies.lastEditBy, users.avatar, users.name, users.is_super_admin, users.group, users.url_prefix, users.url_name, users.level, replies.ipaddress from replies left join users ON replies.createdBy = users.uid where tid = ?", 1) rows, err := db.Query("select replies.rid, replies.content, replies.createdBy, replies.createdAt, replies.lastEdit, replies.lastEditBy, users.avatar, users.name, users.is_super_admin, users.group, users.url_prefix, users.url_name, users.level, replies.ipaddress from replies left join users ON replies.createdBy = users.uid where tid = ?", 1)
if err != nil { if err != nil {
log.Fatal(err) b.Fatal(err)
return
}
for rows.Next() {}
err = rows.Err()
if err != nil {
log.Fatal(err)
return return
} }
defer rows.Close() defer rows.Close()
for rows.Next() {}
err = rows.Err()
if err != nil {
b.Fatal(err)
return
}
} }
}) })
@ -700,22 +701,23 @@ func BenchmarkQueriesSerial(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
rows, err := db.Query("select replies.rid, replies.content, replies.createdBy, replies.createdAt, replies.lastEdit, replies.lastEditBy, users.avatar, users.name, users.is_super_admin, users.group, users.url_prefix, users.url_name, users.level, replies.ipaddress from replies left join users ON replies.createdBy = users.uid where tid = ?", 1) rows, err := db.Query("select replies.rid, replies.content, replies.createdBy, replies.createdAt, replies.lastEdit, replies.lastEditBy, users.avatar, users.name, users.is_super_admin, users.group, users.url_prefix, users.url_name, users.level, replies.ipaddress from replies left join users ON replies.createdBy = users.uid where tid = ?", 1)
if err != nil { if err != nil {
log.Fatal(err) b.Fatal(err)
return return
} }
for rows.Next() { for rows.Next() {
err := rows.Scan(&replyItem.ID, &replyItem.Content, &replyItem.CreatedBy, &replyItem.CreatedAt, &replyItem.LastEdit, &replyItem.LastEditBy, &replyItem.Avatar, &replyItem.CreatedByName, &is_super_admin, &group, &replyItem.URLPrefix, &replyItem.URLName, &replyItem.Level, &replyItem.IpAddress) err := rows.Scan(&replyItem.ID, &replyItem.Content, &replyItem.CreatedBy, &replyItem.CreatedAt, &replyItem.LastEdit, &replyItem.LastEditBy, &replyItem.Avatar, &replyItem.CreatedByName, &is_super_admin, &group, &replyItem.URLPrefix, &replyItem.URLName, &replyItem.Level, &replyItem.IpAddress)
if err != nil { if err != nil {
log.Fatal(err) b.Fatal(err)
return return
} }
} }
defer rows.Close()
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
log.Fatal(err) b.Fatal(err)
return return
} }
defer rows.Close()
} }
}) })
} }
@ -1285,10 +1287,10 @@ func TestStaticRoute(t *testing.T) {
topic_handler.ServeHTTP(topic_w,topic_req_admin) topic_handler.ServeHTTP(topic_w,topic_req_admin)
if topic_w.Code != 200 { if topic_w.Code != 200 {
fmt.Println(topic_w.Body) t.Print(topic_w.Body)
panic("HTTP Error!") t.Fatal("HTTP Error!")
} }
fmt.Println("No problems found in the topic-admin route!") t.Print("No problems found in the topic-admin route!")
}*/ }*/
/*func TestTopicGuestRoute(t *testing.T) { /*func TestTopicGuestRoute(t *testing.T) {
@ -1305,10 +1307,10 @@ func TestStaticRoute(t *testing.T) {
topic_handler.ServeHTTP(topic_w,topic_req) topic_handler.ServeHTTP(topic_w,topic_req)
if topic_w.Code != 200 { if topic_w.Code != 200 {
fmt.Println(topic_w.Body) t.Print(topic_w.Body)
panic("HTTP Error!") t.Fatal("HTTP Error!")
} }
fmt.Println("No problems found in the topic-guest route!") t.Print("No problems found in the topic-guest route!")
}*/ }*/
// TO-DO: Make these routes compatible with the changes to the router // TO-DO: Make these routes compatible with the changes to the router
@ -1390,10 +1392,9 @@ func TestForumsGuestRoute(t *testing.T) {
forum_handler.ServeHTTP(forum_w,forum_req_admin) forum_handler.ServeHTTP(forum_w,forum_req_admin)
if forum_w.Code != 200 { if forum_w.Code != 200 {
fmt.Println(forum_w.Body) t.Print(forum_w.Body)
panic("HTTP Error!") t.Fatal("HTTP Error!")
} }
fmt.Println("No problems found in the forum-admin route!")
}*/ }*/
/*func TestForumGuestRoute(t *testing.T) { /*func TestForumGuestRoute(t *testing.T) {
@ -1410,10 +1411,9 @@ func TestForumsGuestRoute(t *testing.T) {
forum_handler.ServeHTTP(forum_w,forum_req) forum_handler.ServeHTTP(forum_w,forum_req)
if forum_w.Code != 200 { if forum_w.Code != 200 {
fmt.Println(forum_w.Body) t.Print(forum_w.Body)
panic("HTTP Error!") t.Fatal("HTTP Error!")
} }
fmt.Println("No problems found in the forum-guest route!")
}*/ }*/
/*func TestAlerts(t *testing.T) { /*func TestAlerts(t *testing.T) {
@ -1436,12 +1436,10 @@ func TestForumsGuestRoute(t *testing.T) {
}) })
alert_handler.ServeHTTP(alert_w,alert_req) alert_handler.ServeHTTP(alert_w,alert_req)
fmt.Println(alert_w.Body) t.Print(alert_w.Body)
if alert_w.Code != 200 { if alert_w.Code != 200 {
panic("HTTP Error!") t.Fatal("HTTP Error!")
} }
fmt.Println("No problems found in the alert handler!")
db = db_prod db = db_prod
}*/ }*/

138
main.go
View File

@ -2,12 +2,13 @@
package main package main
import ( import (
"net/http"
"fmt" "fmt"
"log" "log"
"strings" "strings"
"time" "time"
"io" "io"
"os"
"net/http"
"html/template" "html/template"
//"runtime/pprof" //"runtime/pprof"
) )
@ -38,14 +39,71 @@ var external_sites map[string]string = map[string]string{
var groups []Group var groups []Group
var groupCapCount int var groupCapCount int
var static_files map[string]SFile = make(map[string]SFile) var static_files map[string]SFile = make(map[string]SFile)
var logWriter io.Writer = io.MultiWriter(os.Stderr)
var template_topic_handle func(TopicPage,io.Writer) = nil func interpreted_topic_template(pi TopicPage, w http.ResponseWriter) {
var template_topic_alt_handle func(TopicPage,io.Writer) = nil mapping, ok := themes[defaultTheme].TemplatesMap["topic"]
var template_topics_handle func(TopicsPage,io.Writer) = nil if !ok {
var template_forum_handle func(ForumPage,io.Writer) = nil mapping = "topic"
var template_forums_handle func(ForumsPage,io.Writer) = nil }
var template_profile_handle func(ProfilePage,io.Writer) = nil err := templates.ExecuteTemplate(w,mapping + ".html", pi)
var template_create_topic_handle func(CreateTopicPage,io.Writer) = nil if err != nil {
InternalError(err,w)
}
}
var template_topic_handle func(TopicPage,http.ResponseWriter) = interpreted_topic_template
var template_topic_alt_handle func(TopicPage,http.ResponseWriter) = interpreted_topic_template
var template_topics_handle func(TopicsPage,http.ResponseWriter) = func(pi TopicsPage, w http.ResponseWriter) {
mapping, ok := themes[defaultTheme].TemplatesMap["topics"]
if !ok {
mapping = "topics"
}
err := templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w)
}
}
var template_forum_handle func(ForumPage,http.ResponseWriter) = func(pi ForumPage, w http.ResponseWriter) {
mapping, ok := themes[defaultTheme].TemplatesMap["forum"]
if !ok {
mapping = "forum"
}
err := templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w)
}
}
var template_forums_handle func(ForumsPage,http.ResponseWriter) = func(pi ForumsPage, w http.ResponseWriter) {
mapping, ok := themes[defaultTheme].TemplatesMap["forums"]
if !ok {
mapping = "forums"
}
err := templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w)
}
}
var template_profile_handle func(ProfilePage,http.ResponseWriter) = func(pi ProfilePage, w http.ResponseWriter) {
mapping, ok := themes[defaultTheme].TemplatesMap["profile"]
if !ok {
mapping = "profile"
}
err := templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w)
}
}
var template_create_topic_handle func(CreateTopicPage,http.ResponseWriter) = func(pi CreateTopicPage, w http.ResponseWriter) {
mapping, ok := themes[defaultTheme].TemplatesMap["create-topic"]
if !ok {
mapping = "create-topic"
}
err := templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w)
}
}
func compile_templates() error { func compile_templates() error {
var c CTemplateSet var c CTemplateSet
@ -71,12 +129,21 @@ func compile_templates() error {
var varList map[string]VarItem = make(map[string]VarItem) var varList map[string]VarItem = make(map[string]VarItem)
tpage := TopicPage{"Title",user,headerVars,replyList,topic,1,1,extData} tpage := TopicPage{"Title",user,headerVars,replyList,topic,1,1,extData}
topic_id_tmpl := c.compile_template("topic.html","templates/","TopicPage", tpage, varList) topic_id_tmpl, err := c.compile_template("topic.html","templates/","TopicPage", tpage, varList)
topic_id_alt_tmpl := c.compile_template("topic_alt.html","templates/","TopicPage", tpage, varList) if err != nil {
return err
}
topic_id_alt_tmpl, err := c.compile_template("topic_alt.html","templates/","TopicPage", tpage, varList)
if err != nil {
return err
}
varList = make(map[string]VarItem) varList = make(map[string]VarItem)
ppage := ProfilePage{"User 526",user,headerVars,replyList,user,extData} ppage := ProfilePage{"User 526",user,headerVars,replyList,user,extData}
profile_tmpl := c.compile_template("profile.html","templates/","ProfilePage", ppage, varList) profile_tmpl, err := c.compile_template("profile.html","templates/","ProfilePage", ppage, varList)
if err != nil {
return err
}
var forumList []Forum var forumList []Forum
forums, err := fstore.GetAll() forums, err := fstore.GetAll()
@ -91,18 +158,27 @@ func compile_templates() error {
} }
varList = make(map[string]VarItem) varList = make(map[string]VarItem)
forums_page := ForumsPage{"Forum List",user,headerVars,forumList,extData} forums_page := ForumsPage{"Forum List",user,headerVars,forumList,extData}
forums_tmpl := c.compile_template("forums.html","templates/","ForumsPage",forums_page,varList) forums_tmpl, err := c.compile_template("forums.html","templates/","ForumsPage",forums_page,varList)
if err != nil {
return err
}
var topicsList []*TopicsRow var topicsList []*TopicsRow
topicsList = append(topicsList,&TopicsRow{1,"topic-title","Topic Title","The topic content.",1,false,false,"Date","Date",user3.ID,1,"","127.0.0.1",0,1,"classname","",&user2,"",0,&user3,"General","/forum/general.2"}) topicsList = append(topicsList,&TopicsRow{1,"topic-title","Topic Title","The topic content.",1,false,false,"Date","Date",user3.ID,1,"","127.0.0.1",0,1,"classname","",&user2,"",0,&user3,"General","/forum/general.2"})
topics_page := TopicsPage{"Topic List",user,headerVars,topicsList,extData} topics_page := TopicsPage{"Topic List",user,headerVars,topicsList,extData}
topics_tmpl := c.compile_template("topics.html","templates/","TopicsPage",topics_page,varList) topics_tmpl, err := c.compile_template("topics.html","templates/","TopicsPage",topics_page,varList)
if err != nil {
return err
}
//var topicList []TopicUser //var topicList []TopicUser
//topicList = append(topicList,TopicUser{1,"topic-title","Topic Title","The topic content.",1,false,false,"Date","Date",1,"","127.0.0.1",0,1,"classname","","admin-fred","Admin Fred",config.DefaultGroup,"",0,"","","","",58,false}) //topicList = append(topicList,TopicUser{1,"topic-title","Topic Title","The topic content.",1,false,false,"Date","Date",1,"","127.0.0.1",0,1,"classname","","admin-fred","Admin Fred",config.DefaultGroup,"",0,"","","","",58,false})
forum_item := Forum{1,"general","General Forum","Where the general stuff happens",true,"all",0,"",0,"","",0,"",0,""} forum_item := Forum{1,"general","General Forum","Where the general stuff happens",true,"all",0,"",0,"","",0,"",0,""}
forum_page := ForumPage{"General Forum",user,headerVars,topicsList,forum_item,1,1,extData} forum_page := ForumPage{"General Forum",user,headerVars,topicsList,forum_item,1,1,extData}
forum_tmpl := c.compile_template("forum.html","templates/","ForumPage",forum_page,varList) forum_tmpl, err := c.compile_template("forum.html","templates/","ForumPage",forum_page,varList)
if err != nil {
return err
}
log.Print("Writing the templates") log.Print("Writing the templates")
go write_template("topic", topic_id_tmpl) go write_template("topic", topic_id_tmpl)
@ -111,7 +187,12 @@ func compile_templates() error {
go write_template("forums", forums_tmpl) go write_template("forums", forums_tmpl)
go write_template("topics", topics_tmpl) go write_template("topics", topics_tmpl)
go write_template("forum", forum_tmpl) go write_template("forum", forum_tmpl)
go write_file("./template_list.go","package main\n\n" + c.FragOut) go func() {
err := write_file("./template_list.go","package main\n\n" + c.FragOut)
if err != nil {
log.Fatal(err)
}
}()
return nil return nil
} }
@ -159,6 +240,15 @@ func process_config() {
} }
func main(){ func main(){
// TO-DO: Have a file for each run with the time/date the server started as the file name?
// TO-DO: Log panics with recover()
f, err := os.OpenFile("./operations.log",os.O_WRONLY|os.O_APPEND|os.O_CREATE,0755)
if err != nil {
log.Fatal(err)
}
logWriter = io.MultiWriter(os.Stderr,f)
log.SetOutput(logWriter)
//if profiling { //if profiling {
// f, err := os.Create("startup_cpu.prof") // f, err := os.Create("startup_cpu.prof")
// if err != nil { // if err != nil {
@ -172,11 +262,11 @@ func main(){
startTime = time.Now() startTime = time.Now()
//timeLocation = startTime.Location() //timeLocation = startTime.Location()
fmt.Println("Processing configuration data") log.Print("Processing configuration data")
process_config() process_config()
init_themes() init_themes()
err := init_database() err = init_database()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -306,12 +396,22 @@ func main(){
log.Print("Initialising the HTTP server") log.Print("Initialising the HTTP server")
if !site.EnableSsl { if !site.EnableSsl {
if site.Port == "" { if site.Port == "" {
site.Port = "80" site.Port = "80"
} }
err = http.ListenAndServe(":" + site.Port, router) err = http.ListenAndServe(":" + site.Port, router)
} else { } else {
if site.Port == "" { if site.Port == "" {
site.Port = "443" site.Port = "443"
}
if site.Port == "80" || site.Port == "443" {
// We should also run the server on port 80
// TO-DO: Redirect to port 443
go func() {
err = http.ListenAndServe(":80", &HttpsRedirect{})
if err != nil {
log.Fatal(err)
}
}()
} }
err = http.ListenAndServeTLS(":" + site.Port, config.SslFullchain, config.SslPrivkey, router) err = http.ListenAndServeTLS(":" + site.Port, config.SslFullchain, config.SslPrivkey, router)
} }

View File

@ -72,23 +72,23 @@ func route_edit_topic(w http.ResponseWriter, r *http.Request, user User) {
err = addModLog(action,tid,"topic",ipaddress,user.ID) err = addModLog(action,tid,"topic",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = create_action_reply_stmt.Exec(tid,action,ipaddress,user.ID) _, err = create_action_reply_stmt.Exec(tid,action,ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_replies_to_topic_stmt.Exec(1, tid) _, err = add_replies_to_topic_stmt.Exec(1, tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = update_forum_cache_stmt.Exec(topic_name, tid, user.Name, user.ID, 1) _, err = update_forum_cache_stmt.Exec(topic_name, tid, user.Name, user.ID, 1)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -121,7 +121,7 @@ func route_delete_topic(w http.ResponseWriter, r *http.Request, user User) {
PreError("The topic you tried to delete doesn't exist.",w,r) PreError("The topic you tried to delete doesn't exist.",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -136,7 +136,7 @@ func route_delete_topic(w http.ResponseWriter, r *http.Request, user User) {
_, err = delete_topic_stmt.Exec(tid) _, err = delete_topic_stmt.Exec(tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -147,14 +147,14 @@ func route_delete_topic(w http.ResponseWriter, r *http.Request, user User) {
} }
err = addModLog("delete",tid,"topic",ipaddress,user.ID) err = addModLog("delete",tid,"topic",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
// Might need soft-delete before we can do an action reply for this // Might need soft-delete before we can do an action reply for this
/*_, err = create_action_reply_stmt.Exec(tid,"delete",ipaddress,user.ID) /*_, err = create_action_reply_stmt.Exec(tid,"delete",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
}*/ }*/
@ -164,13 +164,13 @@ func route_delete_topic(w http.ResponseWriter, r *http.Request, user User) {
wcount := word_count(topic.Content) wcount := word_count(topic.Content)
err = decrease_post_user_stats(wcount,topic.CreatedBy,true,user) err = decrease_post_user_stats(wcount,topic.CreatedBy,true,user)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
err = fstore.DecrementTopicCount(topic.ParentID) err = fstore.DecrementTopicCount(topic.ParentID)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
topics.Remove(tid) topics.Remove(tid)
@ -188,7 +188,7 @@ func route_stick_topic(w http.ResponseWriter, r *http.Request, user User) {
PreError("The topic you tried to pin doesn't exist.",w,r) PreError("The topic you tried to pin doesn't exist.",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -203,7 +203,7 @@ func route_stick_topic(w http.ResponseWriter, r *http.Request, user User) {
_, err = stick_topic_stmt.Exec(tid) _, err = stick_topic_stmt.Exec(tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -214,12 +214,12 @@ func route_stick_topic(w http.ResponseWriter, r *http.Request, user User) {
} }
err = addModLog("stick",tid,"topic",ipaddress,user.ID) err = addModLog("stick",tid,"topic",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = create_action_reply_stmt.Exec(tid,"stick",ipaddress,user.ID) _, err = create_action_reply_stmt.Exec(tid,"stick",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -243,7 +243,7 @@ func route_unstick_topic(w http.ResponseWriter, r *http.Request, user User) {
PreError("The topic you tried to unpin doesn't exist.",w,r) PreError("The topic you tried to unpin doesn't exist.",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -258,7 +258,7 @@ func route_unstick_topic(w http.ResponseWriter, r *http.Request, user User) {
_, err = unstick_topic_stmt.Exec(tid) _, err = unstick_topic_stmt.Exec(tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -269,12 +269,12 @@ func route_unstick_topic(w http.ResponseWriter, r *http.Request, user User) {
} }
err = addModLog("unstick",tid,"topic",ipaddress,user.ID) err = addModLog("unstick",tid,"topic",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = create_action_reply_stmt.Exec(tid,"unstick",ipaddress,user.ID) _, err = create_action_reply_stmt.Exec(tid,"unstick",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -419,7 +419,7 @@ func route_reply_delete_submit(w http.ResponseWriter, r *http.Request, user User
} }
err = addModLog("delete",reply.ParentID,"reply",ipaddress,user.ID) err = addModLog("delete",reply.ParentID,"reply",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -542,7 +542,7 @@ func route_ban(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The user you're trying to ban no longer exists.",w,r,user) LocalError("The user you're trying to ban no longer exists.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -585,7 +585,7 @@ func route_ban_submit(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The user you're trying to ban no longer exists.",w,r,user) LocalError("The user you're trying to ban no longer exists.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -605,7 +605,7 @@ func route_ban_submit(w http.ResponseWriter, r *http.Request, user User) {
_, err = change_group_stmt.Exec(4, uid) _, err = change_group_stmt.Exec(4, uid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -616,7 +616,7 @@ func route_ban_submit(w http.ResponseWriter, r *http.Request, user User) {
} }
err = addModLog("ban",uid,"user",ipaddress,user.ID) err = addModLog("ban",uid,"user",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -650,7 +650,7 @@ func route_unban(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The user you're trying to unban no longer exists.",w,r,user) LocalError("The user you're trying to unban no longer exists.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -661,7 +661,7 @@ func route_unban(w http.ResponseWriter, r *http.Request, user User) {
_, err = change_group_stmt.Exec(config.DefaultGroup, uid) _, err = change_group_stmt.Exec(config.DefaultGroup, uid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -672,7 +672,7 @@ func route_unban(w http.ResponseWriter, r *http.Request, user User) {
} }
err = addModLog("unban",uid,"user",ipaddress,user.ID) err = addModLog("unban",uid,"user",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -681,7 +681,7 @@ func route_unban(w http.ResponseWriter, r *http.Request, user User) {
LocalError("This user no longer exists!",w,r,user) LocalError("This user no longer exists!",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -710,7 +710,7 @@ func route_activate(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The account you're trying to activate no longer exists.",w,r,user) LocalError("The account you're trying to activate no longer exists.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -720,13 +720,13 @@ func route_activate(w http.ResponseWriter, r *http.Request, user User) {
} }
_, err = activate_user_stmt.Exec(uid) _, err = activate_user_stmt.Exec(uid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = change_group_stmt.Exec(config.DefaultGroup, uid) _, err = change_group_stmt.Exec(config.DefaultGroup, uid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -737,7 +737,7 @@ func route_activate(w http.ResponseWriter, r *http.Request, user User) {
} }
err = addModLog("activate",uid,"user",ipaddress,user.ID) err = addModLog("activate",uid,"user",ipaddress,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }

View File

@ -389,35 +389,33 @@ func parse_message(msg string/*, user User*/) string {
//msg = url_reg.ReplaceAllString(msg,"<a href=\"$2$3//$4\" rel=\"nofollow\">$2$3//$4</a>") //msg = url_reg.ReplaceAllString(msg,"<a href=\"$2$3//$4\" rel=\"nofollow\">$2$3//$4</a>")
// Search for URLs, mentions and hashlinks in the messages... // Search for URLs, mentions and hashlinks in the messages...
//fmt.Println("Parser Loop!") //log.Print("Parser Loop!")
var msgbytes = []byte(msg) var msgbytes = []byte(msg)
var outbytes []byte var outbytes []byte
msgbytes = append(msgbytes,space_gap...) msgbytes = append(msgbytes,space_gap...)
//fmt.Println(`"`+string(msgbytes)+`"`) //log.Print(`"`+string(msgbytes)+`"`)
lastItem := 0 lastItem := 0
i := 0 i := 0
for ; len(msgbytes) > (i + 1); i++ { for ; len(msgbytes) > (i + 1); i++ {
//fmt.Println("Index:") //log.Print("Index:",i)
//fmt.Println(i) //log.Print("Index Item:",msgbytes[i])
//fmt.Println("Index Item:")
//fmt.Println(msgbytes[i])
//if msgbytes[i] == 10 { //if msgbytes[i] == 10 {
// fmt.Println("NEWLINE") // log.Print("NEWLINE")
//} else if msgbytes[i] == 32 { //} else if msgbytes[i] == 32 {
// fmt.Println("SPACE") // log.Print("SPACE")
//} else { //} else {
// fmt.Println(string(msgbytes[i])) // log.Print("string(msgbytes[i])",string(msgbytes[i]))
//} //}
//fmt.Println("End Index") //log.Print("End Index")
if (i==0 && (msgbytes[0] > 32)) || ((msgbytes[i] < 33) && (msgbytes[i + 1] > 32)) { if (i==0 && (msgbytes[0] > 32)) || ((msgbytes[i] < 33) && (msgbytes[i + 1] > 32)) {
//fmt.Println("IN") //log.Print("IN")
//fmt.Println(msgbytes[i]) //log.Print(msgbytes[i])
if (i != 0) || msgbytes[i] < 33 { if (i != 0) || msgbytes[i] < 33 {
i++ i++
} }
if msgbytes[i]=='#' { if msgbytes[i]=='#' {
//fmt.Println("IN #") //log.Print("IN #")
if bytes.Equal(msgbytes[i+1:i+5],[]byte("tid-")) { if bytes.Equal(msgbytes[i+1:i+5],[]byte("tid-")) {
outbytes = append(outbytes,msgbytes[lastItem:i]...) outbytes = append(outbytes,msgbytes[lastItem:i]...)
i += 5 i += 5
@ -441,12 +439,12 @@ func parse_message(msg string/*, user User*/) string {
outbytes = append(outbytes, url_close...) outbytes = append(outbytes, url_close...)
lastItem = i lastItem = i
//fmt.Println(string(msgbytes)) //log.Print("string(msgbytes)",string(msgbytes))
//fmt.Println(msgbytes) //log.Print(msgbytes)
//fmt.Println(msgbytes[lastItem - 1]) //log.Print(msgbytes[lastItem - 1])
//fmt.Println(lastItem - 1) //log.Print(lastItem - 1)
//fmt.Println(msgbytes[lastItem]) //log.Print(msgbytes[lastItem])
//fmt.Println(lastItem) //log.Print(lastItem)
} else if bytes.Equal(msgbytes[i+1:i+5],[]byte("rid-")) { } else if bytes.Equal(msgbytes[i+1:i+5],[]byte("rid-")) {
outbytes = append(outbytes,msgbytes[lastItem:i]...) outbytes = append(outbytes,msgbytes[lastItem:i]...)
i += 5 i += 5
@ -494,7 +492,7 @@ func parse_message(msg string/*, user User*/) string {
// TO-DO: Forum Shortcode Link // TO-DO: Forum Shortcode Link
} }
} else if msgbytes[i]=='@' { } else if msgbytes[i]=='@' {
//fmt.Println("IN @") //log.Print("IN @")
outbytes = append(outbytes,msgbytes[lastItem:i]...) outbytes = append(outbytes,msgbytes[lastItem:i]...)
i++ i++
start := i start := i
@ -519,14 +517,14 @@ func parse_message(msg string/*, user User*/) string {
outbytes = append(outbytes, url_close...) outbytes = append(outbytes, url_close...)
lastItem = i lastItem = i
//fmt.Println(string(msgbytes)) //log.Print(string(msgbytes))
//fmt.Println(msgbytes) //log.Print(msgbytes)
//fmt.Println(msgbytes[lastItem - 1]) //log.Print(msgbytes[lastItem - 1])
//fmt.Println("lastItem - 1",lastItem - 1) //log.Print("lastItem - 1",lastItem - 1)
//fmt.Println("msgbytes[lastItem]",msgbytes[lastItem]) //log.Print("msgbytes[lastItem]",msgbytes[lastItem])
//fmt.Println("lastItem",lastItem) //log.Print("lastItem",lastItem)
} else if msgbytes[i]=='h' || msgbytes[i]=='f' || msgbytes[i]=='g' { } else if msgbytes[i]=='h' || msgbytes[i]=='f' || msgbytes[i]=='g' {
//fmt.Println("IN hfg") //log.Print("IN hfg")
if msgbytes[i + 1]=='t' && msgbytes[i + 2]=='t' && msgbytes[i + 3]=='p' { if msgbytes[i + 1]=='t' && msgbytes[i + 2]=='t' && msgbytes[i + 3]=='p' {
if msgbytes[i + 4] == 's' && msgbytes[i + 5] == ':' && msgbytes[i + 6] == '/' && msgbytes[i + 7] == '/' { if msgbytes[i + 4] == 's' && msgbytes[i + 5] == ':' && msgbytes[i + 6] == '/' && msgbytes[i + 7] == '/' {
// Do nothing // Do nothing
@ -562,14 +560,14 @@ func parse_message(msg string/*, user User*/) string {
} }
if lastItem != i && len(outbytes) != 0 { if lastItem != i && len(outbytes) != 0 {
//fmt.Println("lastItem:",msgbytes[lastItem]) //log.Print("lastItem:",msgbytes[lastItem])
//fmt.Println("lastItem index:") //log.Print("lastItem index:")
//fmt.Println(lastItem) //log.Print(lastItem)
//fmt.Println("i:") //log.Print("i:")
//fmt.Println(i) //log.Print(i)
//fmt.Println("lastItem to end:") //log.Print("lastItem to end:")
//fmt.Println(msgbytes[lastItem:]) //log.Print(msgbytes[lastItem:])
//fmt.Println("-----") //log.Print("-----")
calclen := len(msgbytes) - 10 calclen := len(msgbytes) - 10
if calclen <= lastItem { if calclen <= lastItem {
calclen = lastItem calclen = lastItem
@ -577,8 +575,8 @@ func parse_message(msg string/*, user User*/) string {
outbytes = append(outbytes, msgbytes[lastItem:calclen]...) outbytes = append(outbytes, msgbytes[lastItem:calclen]...)
msg = string(outbytes) msg = string(outbytes)
} }
//fmt.Println(`"`+string(outbytes)+`"`) //log.Print(`"`+string(outbytes)+`"`)
//fmt.Println(`"`+msg+`"`) //log.Print("msg",`"`+msg+`"`)
msg = strings.Replace(msg,"\n","<br>",-1) msg = strings.Replace(msg,"\n","<br>",-1)
if sshooks["parse_assign"] != nil { if sshooks["parse_assign"] != nil {
@ -677,7 +675,7 @@ func partial_url_bytes_len(data []byte) int {
i := 0 i := 0
if datalen >= 6 { if datalen >= 6 {
//fmt.Println(string(data[0:5])) //log.Print(string(data[0:5]))
if bytes.Equal(data[0:6],[]byte("ftp://")) || bytes.Equal(data[0:6],[]byte("git://")) { if bytes.Equal(data[0:6],[]byte("ftp://")) || bytes.Equal(data[0:6],[]byte("git://")) {
i = 6 i = 6
} else if datalen >= 7 && bytes.Equal(data[0:7],http_prot_b) { } else if datalen >= 7 && bytes.Equal(data[0:7],http_prot_b) {
@ -689,14 +687,12 @@ func partial_url_bytes_len(data []byte) int {
for ;datalen > i; i++ { for ;datalen > i; i++ {
if data[i] != '\\' && data[i] != '_' && !(data[i] > 44 && data[i] < 58) && !(data[i] > 64 && data[i] < 91) && !(data[i] > 96 && data[i] < 123) { if data[i] != '\\' && data[i] != '_' && !(data[i] > 44 && data[i] < 58) && !(data[i] > 64 && data[i] < 91) && !(data[i] > 96 && data[i] < 123) {
//fmt.Println("Bad Character:") //log.Print("Bad Character:",data[i])
//fmt.Println(data[i])
return i return i
} }
} }
//fmt.Println("Data Length:") //log.Print("Data Length:",datalen)
//fmt.Println(datalen)
return datalen return datalen
} }

View File

@ -20,10 +20,6 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
return return
} }
if dev.SuperDebug {
fmt.Println("past PanelSessionCheck")
}
// We won't calculate this on the spot anymore, as the system doesn't seem to like it if we do multiple fetches simultaneously. Should we constantly calculate this on a background thread? Perhaps, the watchdog to scale back heavy features under load? One plus side is that we'd get immediate CPU percentages here instead of waiting it to kick in with WebSockets // We won't calculate this on the spot anymore, as the system doesn't seem to like it if we do multiple fetches simultaneously. Should we constantly calculate this on a background thread? Perhaps, the watchdog to scale back heavy features under load? One plus side is that we'd get immediate CPU percentages here instead of waiting it to kick in with WebSockets
var cpustr string = "Unknown" var cpustr string = "Unknown"
var cpuColour string var cpuColour string
@ -37,7 +33,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
used_count := convert_byte_in_unit(float64(memres.Total - memres.Available),total_unit) used_count := convert_byte_in_unit(float64(memres.Total - memres.Available),total_unit)
// Round totals with .9s up, it's how most people see it anyway. Floats are notoriously imprecise, so do it off 0.85 // Round totals with .9s up, it's how most people see it anyway. Floats are notoriously imprecise, so do it off 0.85
//fmt.Println(used_count) //log.Print("pre used_count",used_count)
var totstr string var totstr string
if (total_count - float64(int(total_count))) > 0.85 { if (total_count - float64(int(total_count))) > 0.85 {
used_count += 1.0 - (total_count - float64(int(total_count))) used_count += 1.0 - (total_count - float64(int(total_count)))
@ -45,7 +41,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
} else { } else {
totstr = fmt.Sprintf("%.1f",total_count) totstr = fmt.Sprintf("%.1f",total_count)
} }
//fmt.Println(used_count) //log.Print("post used_count",used_count)
if used_count > total_count { if used_count > total_count {
used_count = total_count used_count = total_count
@ -53,7 +49,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
ramstr = fmt.Sprintf("%.1f",used_count) + " / " + totstr + total_unit ramstr = fmt.Sprintf("%.1f",used_count) + " / " + totstr + total_unit
ramperc := ((memres.Total - memres.Available) * 100) / memres.Total ramperc := ((memres.Total - memres.Available) * 100) / memres.Total
//fmt.Println(ramperc) //log.Print("ramperc",ramperc)
if ramperc < 50 { if ramperc < 50 {
ramColour = "stat_green" ramColour = "stat_green"
} else if ramperc < 75 { } else if ramperc < 75 {
@ -66,7 +62,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
var postCount int var postCount int
err = todays_post_count_stmt.QueryRow().Scan(&postCount) err = todays_post_count_stmt.QueryRow().Scan(&postCount)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
var postInterval string = "day" var postInterval string = "day"
@ -83,7 +79,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
var topicCount int var topicCount int
err = todays_topic_count_stmt.QueryRow().Scan(&topicCount) err = todays_topic_count_stmt.QueryRow().Scan(&topicCount)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
var topicInterval string = "day" var topicInterval string = "day"
@ -100,7 +96,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
var reportCount int var reportCount int
err = todays_report_count_stmt.QueryRow().Scan(&reportCount) err = todays_report_count_stmt.QueryRow().Scan(&reportCount)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
var reportInterval string = "week" var reportInterval string = "week"
@ -108,7 +104,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
var newUserCount int var newUserCount int
err = todays_newuser_count_stmt.QueryRow().Scan(&newUserCount) err = todays_newuser_count_stmt.QueryRow().Scan(&newUserCount)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
var newUserInterval string = "week" var newUserInterval string = "week"
@ -180,7 +176,7 @@ func route_panel(w http.ResponseWriter, r *http.Request, user User){
} }
err = templates.ExecuteTemplate(w,"panel-dashboard.html",pi) err = templates.ExecuteTemplate(w,"panel-dashboard.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -197,7 +193,7 @@ func route_panel_forums(w http.ResponseWriter, r *http.Request, user User){
var forumList []interface{} var forumList []interface{}
forums, err := fstore.GetAll() forums, err := fstore.GetAll()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -218,7 +214,7 @@ func route_panel_forums(w http.ResponseWriter, r *http.Request, user User){
} }
err = templates.ExecuteTemplate(w,"panel-forums.html",pi) err = templates.ExecuteTemplate(w,"panel-forums.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -250,7 +246,7 @@ func route_panel_forums_create_submit(w http.ResponseWriter, r *http.Request, us
_, err = fstore.CreateForum(fname,fdesc,active,fpreset) _, err = fstore.CreateForum(fname,fdesc,active,fpreset)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -282,7 +278,7 @@ func route_panel_forums_delete(w http.ResponseWriter, r *http.Request, user User
LocalError("The forum you're trying to delete doesn't exist.",w,r,user) LocalError("The forum you're trying to delete doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -295,7 +291,10 @@ func route_panel_forums_delete(w http.ResponseWriter, r *http.Request, user User
return return
} }
} }
templates.ExecuteTemplate(w,"areyousure.html",pi) err = templates.ExecuteTemplate(w,"areyousure.html",pi)
if err != nil {
InternalError(err,w)
}
} }
func route_panel_forums_delete_submit(w http.ResponseWriter, r *http.Request, user User, sfid string) { func route_panel_forums_delete_submit(w http.ResponseWriter, r *http.Request, user User, sfid string) {
@ -323,7 +322,7 @@ func route_panel_forums_delete_submit(w http.ResponseWriter, r *http.Request, us
LocalError("The forum you're trying to delete doesn't exist.",w,r,user) LocalError("The forum you're trying to delete doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -351,7 +350,7 @@ func route_panel_forums_edit(w http.ResponseWriter, r *http.Request, user User,
LocalError("The forum you're trying to edit doesn't exist.",w,r,user) LocalError("The forum you're trying to edit doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -376,7 +375,7 @@ func route_panel_forums_edit(w http.ResponseWriter, r *http.Request, user User,
} }
err = templates.ExecuteTemplate(w,"panel-forum-edit.html",pi) err = templates.ExecuteTemplate(w,"panel-forum-edit.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -515,6 +514,7 @@ func route_panel_forums_edit_perms_submit(w http.ResponseWriter, r *http.Request
} }
forum_update_mutex.Lock() forum_update_mutex.Lock()
defer forum_update_mutex.Unlock()
if changed { if changed {
permupdate_mutex.Lock() permupdate_mutex.Lock()
groups[gid].Forums[fid] = fperms groups[gid].Forums[fid] = fperms
@ -539,7 +539,6 @@ func route_panel_forums_edit_perms_submit(w http.ResponseWriter, r *http.Request
} }
forum.Preset = "" forum.Preset = ""
} }
forum_update_mutex.Unlock()
if is_js == "0" { if is_js == "0" {
http.Redirect(w,r,"/panel/forums/edit/" + strconv.Itoa(fid),http.StatusSeeOther) http.Redirect(w,r,"/panel/forums/edit/" + strconv.Itoa(fid),http.StatusSeeOther)
@ -561,7 +560,7 @@ func route_panel_settings(w http.ResponseWriter, r *http.Request, user User){
var settingList map[string]interface{} = make(map[string]interface{}) var settingList map[string]interface{} = make(map[string]interface{})
rows, err := get_settings_stmt.Query() rows, err := get_settings_stmt.Query()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -570,7 +569,7 @@ func route_panel_settings(w http.ResponseWriter, r *http.Request, user User){
for rows.Next() { for rows.Next() {
err := rows.Scan(&sname,&scontent,&stype) err := rows.Scan(&sname,&scontent,&stype)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -594,7 +593,7 @@ func route_panel_settings(w http.ResponseWriter, r *http.Request, user User){
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -604,7 +603,10 @@ func route_panel_settings(w http.ResponseWriter, r *http.Request, user User){
return return
} }
} }
templates.ExecuteTemplate(w,"panel-settings.html",pi) err = templates.ExecuteTemplate(w,"panel-settings.html",pi)
if err != nil {
InternalError(err,w)
}
} }
func route_panel_setting(w http.ResponseWriter, r *http.Request, user User, sname string){ func route_panel_setting(w http.ResponseWriter, r *http.Request, user User, sname string){
@ -623,7 +625,7 @@ func route_panel_setting(w http.ResponseWriter, r *http.Request, user User, snam
LocalError("The setting you want to edit doesn't exist.",w,r,user) LocalError("The setting you want to edit doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -657,7 +659,10 @@ func route_panel_setting(w http.ResponseWriter, r *http.Request, user User, snam
return return
} }
} }
templates.ExecuteTemplate(w,"panel-setting.html",pi) err = templates.ExecuteTemplate(w,"panel-setting.html",pi)
if err != nil {
InternalError(err,w)
}
} }
func route_panel_setting_edit(w http.ResponseWriter, r *http.Request, user User, sname string) { func route_panel_setting_edit(w http.ResponseWriter, r *http.Request, user User, sname string) {
@ -688,7 +693,7 @@ func route_panel_setting_edit(w http.ResponseWriter, r *http.Request, user User,
LocalError("The setting you want to edit doesn't exist.",w,r,user) LocalError("The setting you want to edit doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -702,7 +707,7 @@ func route_panel_setting_edit(w http.ResponseWriter, r *http.Request, user User,
_, err = update_setting_stmt.Exec(scontent,sname) _, err = update_setting_stmt.Exec(scontent,sname)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -726,8 +731,8 @@ func route_panel_plugins(w http.ResponseWriter, r *http.Request, user User){
var pluginList []interface{} var pluginList []interface{}
for _, plugin := range plugins { for _, plugin := range plugins {
//fmt.Println("plugin.Name",plugin.Name) //log.Print("plugin.Name",plugin.Name)
//fmt.Println("plugin.Installed",plugin.Installed) //log.Print("plugin.Installed",plugin.Installed)
pluginList = append(pluginList,plugin) pluginList = append(pluginList,plugin)
} }
@ -737,7 +742,10 @@ func route_panel_plugins(w http.ResponseWriter, r *http.Request, user User){
return return
} }
} }
templates.ExecuteTemplate(w,"panel-plugins.html",pi) err := templates.ExecuteTemplate(w,"panel-plugins.html",pi)
if err != nil {
InternalError(err,w)
}
} }
func route_panel_plugins_activate(w http.ResponseWriter, r *http.Request, user User, uname string){ func route_panel_plugins_activate(w http.ResponseWriter, r *http.Request, user User, uname string){
@ -754,7 +762,7 @@ func route_panel_plugins_activate(w http.ResponseWriter, r *http.Request, user U
return return
} }
//fmt.Println("uname","'"+uname+"'") //log.Print("uname","'"+uname+"'")
plugin, ok := plugins[uname] plugin, ok := plugins[uname]
if !ok { if !ok {
LocalError("The plugin isn't registered in the system",w,r,user) LocalError("The plugin isn't registered in the system",w,r,user)
@ -769,7 +777,7 @@ func route_panel_plugins_activate(w http.ResponseWriter, r *http.Request, user U
var active bool var active bool
err := is_plugin_active_stmt.QueryRow(uname).Scan(&active) err := is_plugin_active_stmt.QueryRow(uname).Scan(&active)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
var has_plugin bool = (err == nil) var has_plugin bool = (err == nil)
@ -782,24 +790,24 @@ func route_panel_plugins_activate(w http.ResponseWriter, r *http.Request, user U
} }
} }
//fmt.Println("err",err) //log.Print("err",err)
//fmt.Println("active",active) //log.Print("active",active)
if has_plugin { if has_plugin {
if active { if active {
LocalError("The plugin is already active",w,r,user) LocalError("The plugin is already active",w,r,user)
return return
} }
//fmt.Println("update_plugin") //log.Print("update_plugin")
_, err = update_plugin_stmt.Exec(1,uname) _, err = update_plugin_stmt.Exec(1,uname)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} else { } else {
//fmt.Println("add_plugin") //log.Print("add_plugin")
_, err := add_plugin_stmt.Exec(uname,1,0) _, err := add_plugin_stmt.Exec(uname,1,0)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -843,7 +851,7 @@ func route_panel_plugins_deactivate(w http.ResponseWriter, r *http.Request, user
LocalError("The plugin you're trying to deactivate isn't active",w,r,user) LocalError("The plugin you're trying to deactivate isn't active",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -853,7 +861,7 @@ func route_panel_plugins_deactivate(w http.ResponseWriter, r *http.Request, user
} }
_, err = update_plugin_stmt.Exec(0,uname) _, err = update_plugin_stmt.Exec(0,uname)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -897,7 +905,7 @@ func route_panel_plugins_install(w http.ResponseWriter, r *http.Request, user Us
var active bool var active bool
err := is_plugin_active_stmt.QueryRow(uname).Scan(&active) err := is_plugin_active_stmt.QueryRow(uname).Scan(&active)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
var has_plugin bool = (err == nil) var has_plugin bool = (err == nil)
@ -922,18 +930,18 @@ func route_panel_plugins_install(w http.ResponseWriter, r *http.Request, user Us
if has_plugin { if has_plugin {
_, err = update_plugin_install_stmt.Exec(1,uname) _, err = update_plugin_install_stmt.Exec(1,uname)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = update_plugin_stmt.Exec(1,uname) _, err = update_plugin_stmt.Exec(1,uname)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} else { } else {
_, err := add_plugin_stmt.Exec(uname,1,1) _, err := add_plugin_stmt.Exec(uname,1,1)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -960,7 +968,7 @@ func route_panel_users(w http.ResponseWriter, r *http.Request, user User){
var userList []interface{} var userList []interface{}
rows, err := get_users_stmt.Query() rows, err := get_users_stmt.Query()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -970,7 +978,7 @@ func route_panel_users(w http.ResponseWriter, r *http.Request, user User){
puser := User{ID: 0,} puser := User{ID: 0,}
err := rows.Scan(&puser.ID, &puser.Name, &puser.Group, &puser.Active, &puser.Is_Super_Admin, &puser.Avatar) err := rows.Scan(&puser.ID, &puser.Name, &puser.Group, &puser.Active, &puser.Is_Super_Admin, &puser.Avatar)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -992,7 +1000,7 @@ func route_panel_users(w http.ResponseWriter, r *http.Request, user User){
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1004,7 +1012,7 @@ func route_panel_users(w http.ResponseWriter, r *http.Request, user User){
} }
err = templates.ExecuteTemplate(w,"panel-users.html",pi) err = templates.ExecuteTemplate(w,"panel-users.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -1030,7 +1038,7 @@ func route_panel_users_edit(w http.ResponseWriter, r *http.Request, user User, s
LocalError("The user you're trying to edit doesn't exist.",w,r,user) LocalError("The user you're trying to edit doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1058,7 +1066,7 @@ func route_panel_users_edit(w http.ResponseWriter, r *http.Request, user User, s
} }
err = templates.ExecuteTemplate(w,"panel-user-edit.html",pi) err = templates.ExecuteTemplate(w,"panel-user-edit.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -1087,7 +1095,7 @@ func route_panel_users_edit_submit(w http.ResponseWriter, r *http.Request, user
LocalError("The user you're trying to edit doesn't exist.",w,r,user) LocalError("The user you're trying to edit doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1140,7 +1148,7 @@ func route_panel_users_edit_submit(w http.ResponseWriter, r *http.Request, user
_, err = update_user_stmt.Exec(newname,newemail,newgroup,targetUser.ID) _, err = update_user_stmt.Exec(newname,newemail,newgroup,targetUser.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1190,7 +1198,7 @@ func route_panel_groups(w http.ResponseWriter, r *http.Request, user User){
can_edit = user.Perms.EditGroup && (!group.Is_Admin || user.Perms.EditGroupAdmin) && (!group.Is_Mod || user.Perms.EditGroupSuperMod) can_edit = user.Perms.EditGroup && (!group.Is_Admin || user.Perms.EditGroupAdmin) && (!group.Is_Mod || user.Perms.EditGroupSuperMod)
groupList = append(groupList, GroupAdmin{group.ID,group.Name,rank,rank_class,can_edit,can_delete}) groupList = append(groupList, GroupAdmin{group.ID,group.Name,rank,rank_class,can_edit,can_delete})
} }
//fmt.Printf("%+v\n", groupList) //log.Printf("groupList: %+v\n", groupList)
pi := Page{"Group Manager",user,headerVars,groupList,nil} pi := Page{"Group Manager",user,headerVars,groupList,nil}
if pre_render_hooks["pre_render_panel_groups"] != nil { if pre_render_hooks["pre_render_panel_groups"] != nil {
@ -1198,7 +1206,11 @@ func route_panel_groups(w http.ResponseWriter, r *http.Request, user User){
return return
} }
} }
templates.ExecuteTemplate(w,"panel-groups.html",pi)
err := templates.ExecuteTemplate(w,"panel-groups.html",pi)
if err != nil {
InternalError(err,w)
}
} }
func route_panel_groups_edit(w http.ResponseWriter, r *http.Request, user User, sgid string){ func route_panel_groups_edit(w http.ResponseWriter, r *http.Request, user User, sgid string){
@ -1218,7 +1230,7 @@ func route_panel_groups_edit(w http.ResponseWriter, r *http.Request, user User,
} }
if !group_exists(gid) { if !group_exists(gid) {
//fmt.Println("aaaaa monsters") //log.Print("aaaaa monsters")
NotFound(w,r) NotFound(w,r)
return return
} }
@ -1256,7 +1268,7 @@ func route_panel_groups_edit(w http.ResponseWriter, r *http.Request, user User,
} }
err = templates.ExecuteTemplate(w,"panel-group-edit.html",pi) err = templates.ExecuteTemplate(w,"panel-group-edit.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -1277,7 +1289,7 @@ func route_panel_groups_edit_perms(w http.ResponseWriter, r *http.Request, user
} }
if !group_exists(gid) { if !group_exists(gid) {
//fmt.Println("aaaaa monsters") //log.Print("aaaaa monsters")
NotFound(w,r) NotFound(w,r)
return return
} }
@ -1334,7 +1346,7 @@ func route_panel_groups_edit_perms(w http.ResponseWriter, r *http.Request, user
} }
err = templates.ExecuteTemplate(w,"panel-group-edit-perms.html",pi) err = templates.ExecuteTemplate(w,"panel-group-edit-perms.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -1359,7 +1371,7 @@ func route_panel_groups_edit_submit(w http.ResponseWriter, r *http.Request, user
} }
if !group_exists(gid) { if !group_exists(gid) {
//fmt.Println("aaaaa monsters") //log.Print("aaaaa monsters")
NotFound(w,r) NotFound(w,r)
return return
} }
@ -1412,7 +1424,7 @@ func route_panel_groups_edit_submit(w http.ResponseWriter, r *http.Request, user
_, err = update_group_rank_stmt.Exec(1,1,0,gid) _, err = update_group_rank_stmt.Exec(1,1,0,gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
groups[gid].Is_Admin = true groups[gid].Is_Admin = true
@ -1426,7 +1438,7 @@ func route_panel_groups_edit_submit(w http.ResponseWriter, r *http.Request, user
_, err = update_group_rank_stmt.Exec(0,1,0,gid) _, err = update_group_rank_stmt.Exec(0,1,0,gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
groups[gid].Is_Admin = false groups[gid].Is_Admin = false
@ -1435,7 +1447,7 @@ func route_panel_groups_edit_submit(w http.ResponseWriter, r *http.Request, user
case "Banned": case "Banned":
_, err = update_group_rank_stmt.Exec(0,0,1,gid) _, err = update_group_rank_stmt.Exec(0,0,1,gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
groups[gid].Is_Admin = false groups[gid].Is_Admin = false
@ -1447,7 +1459,7 @@ func route_panel_groups_edit_submit(w http.ResponseWriter, r *http.Request, user
case "Member": case "Member":
_, err = update_group_rank_stmt.Exec(0,0,0,gid) _, err = update_group_rank_stmt.Exec(0,0,0,gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
groups[gid].Is_Admin = false groups[gid].Is_Admin = false
@ -1461,7 +1473,7 @@ func route_panel_groups_edit_submit(w http.ResponseWriter, r *http.Request, user
_, err = update_group_stmt.Exec(gname,gtag,gid) _, err = update_group_stmt.Exec(gname,gtag,gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
groups[gid].Name = gname groups[gid].Name = gname
@ -1491,7 +1503,7 @@ func route_panel_groups_edit_perms_submit(w http.ResponseWriter, r *http.Request
} }
if !group_exists(gid) { if !group_exists(gid) {
//fmt.Println("aaaaa monsters o.o") //log.Print("aaaaa monsters o.o")
NotFound(w,r) NotFound(w,r)
return return
} }
@ -1533,13 +1545,13 @@ func route_panel_groups_edit_perms_submit(w http.ResponseWriter, r *http.Request
_, err = update_group_perms_stmt.Exec(pjson,gid) _, err = update_group_perms_stmt.Exec(pjson,gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
err = rebuild_group_permissions(gid) err = rebuild_group_permissions(gid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1590,10 +1602,9 @@ func route_panel_groups_create_submit(w http.ResponseWriter, r *http.Request, us
gid, err := create_group(group_name, group_tag, is_admin, is_mod, is_banned) gid, err := create_group(group_name, group_tag, is_admin, is_mod, is_banned)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
fmt.Println(groups)
http.Redirect(w,r,"/panel/groups/edit/" + strconv.Itoa(gid),http.StatusSeeOther) http.Redirect(w,r,"/panel/groups/edit/" + strconv.Itoa(gid),http.StatusSeeOther)
} }
@ -1628,7 +1639,7 @@ func route_panel_themes(w http.ResponseWriter, r *http.Request, user User){
} }
err := templates.ExecuteTemplate(w,"panel-themes.html",pi) err := templates.ExecuteTemplate(w,"panel-themes.html",pi)
if err != nil { if err != nil {
log.Print(err) InternalError(err,w)
} }
} }
@ -1657,36 +1668,36 @@ func route_panel_themes_default(w http.ResponseWriter, r *http.Request, user Use
} }
var isDefault bool var isDefault bool
fmt.Println("uname",uname) log.Print("uname",uname)
err := is_theme_default_stmt.QueryRow(uname).Scan(&isDefault) err := is_theme_default_stmt.QueryRow(uname).Scan(&isDefault)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
has_theme := err != ErrNoRows has_theme := err != ErrNoRows
if has_theme { if has_theme {
fmt.Println("isDefault",isDefault) log.Print("isDefault",isDefault)
if isDefault { if isDefault {
LocalError("The theme is already active",w,r,user) LocalError("The theme is already active",w,r,user)
return return
} }
_, err = update_theme_stmt.Exec(1,uname) _, err = update_theme_stmt.Exec(1,uname)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} else { } else {
_, err := add_theme_stmt.Exec(uname,1) _, err := add_theme_stmt.Exec(uname,1)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
_, err = update_theme_stmt.Exec(0,defaultTheme) _, err = update_theme_stmt.Exec(0,defaultTheme)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1696,7 +1707,7 @@ func route_panel_themes_default(w http.ResponseWriter, r *http.Request, user Use
dTheme, ok := themes[defaultTheme] dTheme, ok := themes[defaultTheme]
if !ok { if !ok {
InternalError(errors.New("The default theme is missing"),w,r) InternalError(errors.New("The default theme is missing"),w)
return return
} }
dTheme.Active = false dTheme.Active = false
@ -1718,7 +1729,7 @@ func route_panel_logs_mod(w http.ResponseWriter, r *http.Request, user User){
rows, err := get_modlogs_stmt.Query() rows, err := get_modlogs_stmt.Query()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -1729,7 +1740,7 @@ func route_panel_logs_mod(w http.ResponseWriter, r *http.Request, user User){
for rows.Next() { for rows.Next() {
err := rows.Scan(&action,&elementID,&elementType, &ipaddress, &actorID, &doneAt) err := rows.Scan(&action,&elementID,&elementType, &ipaddress, &actorID, &doneAt)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1798,7 +1809,7 @@ func route_panel_logs_mod(w http.ResponseWriter, r *http.Request, user User){
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }

View File

@ -1,7 +1,6 @@
package main package main
import "log" import "log"
import "fmt"
import "sync" import "sync"
import "strconv" import "strconv"
import "encoding/json" import "encoding/json"
@ -206,10 +205,8 @@ func init() {
guest_user.Perms = GuestPerms guest_user.Perms = GuestPerms
if dev.DebugMode { if dev.DebugMode {
fmt.Printf("Guest Perms: ") log.Printf("Guest Perms: %+v\n", GuestPerms)
fmt.Printf("%+v\n", GuestPerms) log.Printf("All Perms: %+v\n", AllPerms)
fmt.Printf("All Perms: ")
fmt.Printf("%+v\n", AllPerms)
} }
} }
@ -370,9 +367,9 @@ func rebuild_forum_permissions(fid int) error {
} }
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Printf("groups[gid].CanSee %+v\n", groups[gid].CanSee) log.Printf("groups[gid].CanSee %+v\n", groups[gid].CanSee)
fmt.Printf("groups[gid].Forums %+v\n", groups[gid].Forums) log.Printf("groups[gid].Forums %+v\n", groups[gid].Forums)
fmt.Println("len(groups[gid].Forums)",len(groups[gid].Forums)) log.Print("len(groups[gid].Forums)",len(groups[gid].Forums))
} }
} }
return nil return nil
@ -442,10 +439,10 @@ func build_forum_permissions() error {
} }
} }
if dev.SuperDebug { if dev.SuperDebug {
//fmt.Printf("groups[gid].CanSee %+v\n", groups[gid].CanSee) //log.Printf("groups[gid].CanSee %+v\n", groups[gid].CanSee)
//fmt.Printf("groups[gid].Forums %+v\n", groups[gid].Forums) //log.Printf("groups[gid].Forums %+v\n", groups[gid].Forums)
//fmt.Println("len(groups[gid].CanSee)",len(groups[gid].CanSee)) //log.Print("len(groups[gid].CanSee)",len(groups[gid].CanSee))
//fmt.Println("len(groups[gid].Forums)",len(groups[gid].Forums)) //log.Print("len(groups[gid].Forums)",len(groups[gid].Forums))
} }
} }
return nil return nil

View File

@ -211,9 +211,8 @@ func bbcode_full_parse(msg string) string {
msgbytes := []byte(msg) msgbytes := []byte(msg)
msgbytes = append(msgbytes,space_gap...) msgbytes = append(msgbytes,space_gap...)
//fmt.Println("BBCode Simple Pre:") //log.Print("BBCode Simple Pre:","`"+string(msgbytes)+"`")
//fmt.Println("`"+string(msgbytes)+"`") //log.Print("----")
//fmt.Println("----")
for i := 0; i < len(msgbytes); i++ { for i := 0; i < len(msgbytes); i++ {
if msgbytes[i] == '[' { if msgbytes[i] == '[' {
@ -246,10 +245,10 @@ func bbcode_full_parse(msg string) string {
i += 7 i += 7
} }
//if msglen >= (i+6) { //if msglen >= (i+6) {
// fmt.Println("boo") // log.Print("boo")
// fmt.Println(msglen) // log.Print(msglen)
// fmt.Println(i+6) // log.Print(i+6)
// fmt.Println(string(msgbytes[i:i+6])) // log.Print(string(msgbytes[i:i+6]))
//} //}
complex_bbc = true complex_bbc = true
} }
@ -259,8 +258,8 @@ func bbcode_full_parse(msg string) string {
i += 6 i += 6
} }
//if msglen >= (i+5) { //if msglen >= (i+5) {
// fmt.Println("boo2") // log.Print("boo2")
// fmt.Println(string(msgbytes[i:i+5])) // log.Print(string(msgbytes[i:i+5]))
//} //}
complex_bbc = true complex_bbc = true
} }
@ -312,9 +311,8 @@ func bbcode_full_parse(msg string) string {
i := 0 i := 0
var start, lastTag int var start, lastTag int
var outbytes []byte var outbytes []byte
//fmt.Println("BBCode Pre:") //log.Print("BBCode Pre:","`"+string(msgbytes)+"`")
//fmt.Println("`"+string(msgbytes)+"`") //log.Print("----")
//fmt.Println("----")
for ; i < len(msgbytes); i++ { for ; i < len(msgbytes); i++ {
MainLoop: MainLoop:
if msgbytes[i] == '[' { if msgbytes[i] == '[' {
@ -325,13 +323,11 @@ func bbcode_full_parse(msg string) string {
outbytes = append(outbytes, msgbytes[lastTag:i]...) outbytes = append(outbytes, msgbytes[lastTag:i]...)
i = start i = start
i += partial_url_bytes_len(msgbytes[start:]) i += partial_url_bytes_len(msgbytes[start:])
//fmt.Println("Partial Bytes:") //log.Print("Partial Bytes:",string(msgbytes[start:]))
//fmt.Println(string(msgbytes[start:])) //log.Print("-----")
//fmt.Println("-----")
if !bytes.Equal(msgbytes[i:i+6],[]byte("[/url]")) { if !bytes.Equal(msgbytes[i:i+6],[]byte("[/url]")) {
//fmt.Println("Invalid Bytes:") //log.Print("Invalid Bytes:",string(msgbytes[i:i+6]))
//fmt.Println(string(msgbytes[i:i+6])) //log.Print("-----")
//fmt.Println("-----")
outbytes = append(outbytes, invalid_url...) outbytes = append(outbytes, invalid_url...)
goto MainLoop goto MainLoop
} }
@ -389,16 +385,16 @@ func bbcode_full_parse(msg string) string {
} }
} }
} }
//fmt.Println(string(outbytes)) //log.Print(string(outbytes))
if lastTag != i { if lastTag != i {
outbytes = append(outbytes, msgbytes[lastTag:]...) outbytes = append(outbytes, msgbytes[lastTag:]...)
//fmt.Println("Outbytes:",`"`+string(outbytes)+`"`) //log.Print("Outbytes:",`"`+string(outbytes)+`"`)
//fmt.Println("----") //log.Print("----")
} }
if len(outbytes) != 0 { if len(outbytes) != 0 {
//fmt.Println("BBCode Post:",`"`+string(outbytes[0:len(outbytes) - 10])+`"`) //log.Print("BBCode Post:",`"`+string(outbytes[0:len(outbytes) - 10])+`"`)
//fmt.Println("----") //log.Print("----")
msg = string(outbytes[0:len(outbytes) - 10]) msg = string(outbytes[0:len(outbytes) - 10])
} else { } else {
msg = string(msgbytes[0:len(msgbytes) - 10]) msg = string(msgbytes[0:len(msgbytes) - 10])

View File

@ -76,16 +76,16 @@ func _markdown_parse(msg string, n int) string {
var outbytes []byte var outbytes []byte
var lastElement int var lastElement int
//fmt.Println("enter message loop") //log.Print("enter message loop")
//fmt.Printf("Message: %v\n",strings.Replace(msg,"\r","\\r",-1)) //log.Print("Message: %v\n",strings.Replace(msg,"\r","\\r",-1))
for index := 0; index < len(msg); index++ { for index := 0; index < len(msg); index++ {
/*//fmt.Println("--OUTER MARKDOWN LOOP START--") /*//log.Print("--OUTER MARKDOWN LOOP START--")
//fmt.Println("index",index) //log.Print("index",index)
//fmt.Println("msg[index]",msg[index]) //log.Print("msg[index]",msg[index])
//fmt.Println("string(msg[index])",string(msg[index])) //log.Print("string(msg[index])",string(msg[index]))
//fmt.Println("--OUTER MARKDOWN LOOP END--") //log.Print("--OUTER MARKDOWN LOOP END--")
//fmt.Println(" ")*/ //log.Print(" ")*/
switch(msg[index]) { switch(msg[index]) {
case '_': case '_':
@ -135,45 +135,45 @@ func _markdown_parse(msg string, n int) string {
lastElement = index lastElement = index
index-- index--
case '*': case '*':
//fmt.Println("------") //log.Print("------")
//fmt.Println("[]byte(msg):",[]byte(msg)) //log.Print("[]byte(msg):",[]byte(msg))
//fmt.Println("len(msg)",len(msg)) //log.Print("len(msg)",len(msg))
//fmt.Println("start index",index) //log.Print("start index",index)
//fmt.Println("start msg[index]",msg[index]) //log.Print("start msg[index]",msg[index])
//fmt.Println("start string(msg[index])",string(msg[index])) //log.Print("start string(msg[index])",string(msg[index]))
//fmt.Println("start []byte(msg[:index])",[]byte(msg[:index])) //log.Print("start []byte(msg[:index])",[]byte(msg[:index]))
var startIndex int = index var startIndex int = index
var italic bool = true var italic bool = true
var bold bool var bold bool
if (index + 2) < len(msg) { if (index + 2) < len(msg) {
//fmt.Println("start index + 1",index + 1) //log.Print("start index + 1",index + 1)
//fmt.Println("start msg[index]",msg[index + 1]) //log.Print("start msg[index]",msg[index + 1])
//fmt.Println("start string(msg[index])",string(msg[index + 1])) //log.Print("start string(msg[index])",string(msg[index + 1]))
if msg[index + 1] == '*' { if msg[index + 1] == '*' {
//fmt.Println("two asterisks") //log.Print("two asterisks")
bold = true bold = true
index++ index++
if msg[index + 1] != '*' { if msg[index + 1] != '*' {
italic = false italic = false
} else { } else {
//fmt.Println("three asterisks") //log.Print("three asterisks")
index++ index++
} }
} }
} }
//fmt.Println("lastElement",lastElement) //log.Print("lastElement",lastElement)
//fmt.Println("startIndex:",startIndex) //log.Print("startIndex:",startIndex)
//fmt.Println("msg[startIndex]",msg[startIndex]) //log.Print("msg[startIndex]",msg[startIndex])
//fmt.Println("string(msg[startIndex])",string(msg[startIndex])) //log.Print("string(msg[startIndex])",string(msg[startIndex]))
//fmt.Println("preabrupt index",index) //log.Print("preabrupt index",index)
//fmt.Println("preabrupt msg[index]",msg[index]) //log.Print("preabrupt msg[index]",msg[index])
//fmt.Println("preabrupt string(msg[index])",string(msg[index])) //log.Print("preabrupt string(msg[index])",string(msg[index]))
//fmt.Println("preabrupt []byte(msg[:index])",[]byte(msg[:index])) //log.Print("preabrupt []byte(msg[:index])",[]byte(msg[:index]))
//fmt.Println("preabrupt msg[:index]",msg[:index]) //log.Print("preabrupt msg[:index]",msg[:index])
// Does the string terminate abruptly? // Does the string terminate abruptly?
if (index + 1) >= len(msg) { if (index + 1) >= len(msg) {
@ -182,9 +182,9 @@ func _markdown_parse(msg string, n int) string {
index++ index++
//fmt.Println("preskip index",index) //log.Print("preskip index",index)
//fmt.Println("preskip msg[index]",msg[index]) //log.Print("preskip msg[index]",msg[index])
//fmt.Println("preskip string(msg[index])",string(msg[index])) //log.Print("preskip string(msg[index])",string(msg[index]))
index = markdown_skip_until_asterisk(msg,index) index = markdown_skip_until_asterisk(msg,index)
@ -192,16 +192,16 @@ func _markdown_parse(msg string, n int) string {
break break
} }
//fmt.Println("index",index) //log.Print("index",index)
//fmt.Println("[]byte(msg[:index])",[]byte(msg[:index])) //log.Print("[]byte(msg[:index])",[]byte(msg[:index]))
//fmt.Println("msg[index]",msg[index]) //log.Print("msg[index]",msg[index])
sIndex := startIndex sIndex := startIndex
lIndex := index lIndex := index
if bold && italic { if bold && italic {
//fmt.Println("bold & italic final code") //log.Print("bold & italic final code")
if (index + 3) >= len(msg) { if (index + 3) >= len(msg) {
//fmt.Println("unclosed markdown element @ exit element") //log.Print("unclosed markdown element @ exit element")
outbytes = append(outbytes, msg[lastElement:startIndex]...) outbytes = append(outbytes, msg[lastElement:startIndex]...)
outbytes = append(outbytes, markdown_unclosed_element...) outbytes = append(outbytes, markdown_unclosed_element...)
lastElement = startIndex lastElement = startIndex
@ -210,9 +210,9 @@ func _markdown_parse(msg string, n int) string {
index += 3 index += 3
sIndex += 3 sIndex += 3
} else if bold { } else if bold {
//fmt.Println("bold final code") //log.Print("bold final code")
if (index + 2) >= len(msg) { if (index + 2) >= len(msg) {
//fmt.Println("true unclosed markdown element @ exit element") //log.Print("true unclosed markdown element @ exit element")
outbytes = append(outbytes, msg[lastElement:startIndex]...) outbytes = append(outbytes, msg[lastElement:startIndex]...)
outbytes = append(outbytes, markdown_unclosed_element...) outbytes = append(outbytes, markdown_unclosed_element...)
lastElement = startIndex lastElement = startIndex
@ -221,9 +221,9 @@ func _markdown_parse(msg string, n int) string {
index += 2 index += 2
sIndex += 2 sIndex += 2
} else { } else {
//fmt.Println("italic final code") //log.Print("italic final code")
if (index + 1) >= len(msg) { if (index + 1) >= len(msg) {
//fmt.Println("true unclosed markdown element @ exit element") //log.Print("true unclosed markdown element @ exit element")
outbytes = append(outbytes, msg[lastElement:startIndex]...) outbytes = append(outbytes, msg[lastElement:startIndex]...)
outbytes = append(outbytes, markdown_unclosed_element...) outbytes = append(outbytes, markdown_unclosed_element...)
lastElement = startIndex lastElement = startIndex
@ -233,11 +233,11 @@ func _markdown_parse(msg string, n int) string {
sIndex++ sIndex++
} }
//fmt.Println("sIndex",sIndex) //log.Print("sIndex",sIndex)
//fmt.Println("lIndex",lIndex) //log.Print("lIndex",lIndex)
if lIndex <= sIndex { if lIndex <= sIndex {
//fmt.Println("unclosed markdown element @ lIndex <= sIndex") //log.Print("unclosed markdown element @ lIndex <= sIndex")
outbytes = append(outbytes, msg[lastElement:startIndex]...) outbytes = append(outbytes, msg[lastElement:startIndex]...)
outbytes = append(outbytes, markdown_unclosed_element...) outbytes = append(outbytes, markdown_unclosed_element...)
lastElement = startIndex lastElement = startIndex
@ -245,26 +245,26 @@ func _markdown_parse(msg string, n int) string {
} }
if sIndex < 0 || lIndex < 0 { if sIndex < 0 || lIndex < 0 {
//fmt.Println("unclosed markdown element @ sIndex < 0 || lIndex < 0") //log.Print("unclosed markdown element @ sIndex < 0 || lIndex < 0")
outbytes = append(outbytes, msg[lastElement:startIndex]...) outbytes = append(outbytes, msg[lastElement:startIndex]...)
outbytes = append(outbytes, markdown_unclosed_element...) outbytes = append(outbytes, markdown_unclosed_element...)
lastElement = startIndex lastElement = startIndex
break break
} }
//fmt.Println("final sIndex",sIndex) //log.Print("final sIndex",sIndex)
//fmt.Println("final lIndex",lIndex) //log.Print("final lIndex",lIndex)
//fmt.Println("final index",index) //log.Print("final index",index)
//fmt.Println("final msg[index]",msg[index]) //log.Print("final msg[index]",msg[index])
//fmt.Println("final string(msg[index])",string(msg[index])) //log.Print("final string(msg[index])",string(msg[index]))
//fmt.Println("final msg[sIndex]",msg[sIndex]) //log.Print("final msg[sIndex]",msg[sIndex])
//fmt.Println("final string(msg[sIndex])",string(msg[sIndex])) //log.Print("final string(msg[sIndex])",string(msg[sIndex]))
//fmt.Println("final msg[lIndex]",msg[lIndex]) //log.Print("final msg[lIndex]",msg[lIndex])
//fmt.Println("final string(msg[lIndex])",string(msg[lIndex])) //log.Print("final string(msg[lIndex])",string(msg[lIndex]))
//fmt.Println("[]byte(msg[:sIndex])",[]byte(msg[:sIndex])) //log.Print("[]byte(msg[:sIndex])",[]byte(msg[:sIndex]))
//fmt.Println("[]byte(msg[:lIndex])",[]byte(msg[:lIndex])) //log.Print("[]byte(msg[:lIndex])",[]byte(msg[:lIndex]))
outbytes = append(outbytes, msg[lastElement:startIndex]...) outbytes = append(outbytes, msg[lastElement:startIndex]...)
@ -293,8 +293,7 @@ func _markdown_parse(msg string, n int) string {
} }
} }
//fmt.Println("exit message loop") //log.Print("exit message loop")
//fmt.Println(" ")
if len(outbytes) == 0 { if len(outbytes) == 0 {
return msg return msg

View File

@ -293,7 +293,7 @@ func socialgroups_group_list(w http.ResponseWriter, r *http.Request, user User)
rows, err := socialgroups_list_stmt.Query() rows, err := socialgroups_list_stmt.Query()
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -302,7 +302,7 @@ func socialgroups_group_list(w http.ResponseWriter, r *http.Request, user User)
sgItem := SocialGroup{ID:0} sgItem := SocialGroup{ID:0}
err := rows.Scan(&sgItem.ID, &sgItem.Name, &sgItem.Desc, &sgItem.Active, &sgItem.Privacy, &sgItem.Joinable, &sgItem.Owner, &sgItem.MemberCount, &sgItem.CreatedAt, &sgItem.LastUpdateTime) err := rows.Scan(&sgItem.ID, &sgItem.Name, &sgItem.Desc, &sgItem.Active, &sgItem.Privacy, &sgItem.Joinable, &sgItem.Owner, &sgItem.MemberCount, &sgItem.CreatedAt, &sgItem.LastUpdateTime)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
sgItem.Link = socialgroups_build_group_url(name_to_slug(sgItem.Name),sgItem.ID) sgItem.Link = socialgroups_build_group_url(name_to_slug(sgItem.Name),sgItem.ID)
@ -310,7 +310,7 @@ func socialgroups_group_list(w http.ResponseWriter, r *http.Request, user User)
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
rows.Close() rows.Close()
@ -318,7 +318,7 @@ func socialgroups_group_list(w http.ResponseWriter, r *http.Request, user User)
pi := SocialGroupListPage{"Group List",user,headerVars,sgList,extData} pi := SocialGroupListPage{"Group List",user,headerVars,sgList,extData}
err = templates.ExecuteTemplate(w,"socialgroups_group_list.html", pi) err = templates.ExecuteTemplate(w,"socialgroups_group_list.html", pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -369,7 +369,7 @@ func socialgroups_create_group(w http.ResponseWriter, r *http.Request, user User
pi := Page{"Create Group",user,headerVars,tList,nil} pi := Page{"Create Group",user,headerVars,tList,nil}
err := templates.ExecuteTemplate(w,"socialgroups_create_group.html", pi) err := templates.ExecuteTemplate(w,"socialgroups_create_group.html", pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -396,31 +396,31 @@ func socialgroups_create_group_submit(w http.ResponseWriter, r *http.Request, us
// Create the backing forum // Create the backing forum
fid, err := fstore.CreateForum(group_name,"",true,"") fid, err := fstore.CreateForum(group_name,"",true,"")
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
res, err := socialgroups_create_group_stmt.Exec(group_name, group_desc, group_active, group_privacy, user.ID, fid) res, err := socialgroups_create_group_stmt.Exec(group_name, group_desc, group_active, group_privacy, user.ID, fid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
lastId, err := res.LastInsertId() lastId, err := res.LastInsertId()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
// Add the main backing forum to the forum list // Add the main backing forum to the forum list
err = socialgroups_attach_forum(int(lastId),fid) err = socialgroups_attach_forum(int(lastId),fid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = socialgroups_add_member_stmt.Exec(lastId,user.ID,2) _, err = socialgroups_add_member_stmt.Exec(lastId,user.ID,2)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -457,7 +457,7 @@ func socialgroups_member_list(w http.ResponseWriter, r *http.Request, user User)
rows, err := socialgroups_member_list_join_stmt.Query(sgid) rows, err := socialgroups_member_list_join_stmt.Query(sgid)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -466,7 +466,7 @@ func socialgroups_member_list(w http.ResponseWriter, r *http.Request, user User)
sgMember := SocialGroupMember{PostCount:0} sgMember := SocialGroupMember{PostCount:0}
err := rows.Scan(&sgMember.User.ID,&sgMember.Rank,&sgMember.PostCount,&sgMember.JoinedAt,&sgMember.User.Name, &sgMember.User.Avatar) err := rows.Scan(&sgMember.User.ID,&sgMember.Rank,&sgMember.PostCount,&sgMember.JoinedAt,&sgMember.User.Name, &sgMember.User.Avatar)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
sgMember.Link = build_profile_url(name_to_slug(sgMember.User.Name),sgMember.User.ID) sgMember.Link = build_profile_url(name_to_slug(sgMember.User.Name),sgMember.User.ID)
@ -491,7 +491,7 @@ func socialgroups_member_list(w http.ResponseWriter, r *http.Request, user User)
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
rows.Close() rows.Close()
@ -505,7 +505,7 @@ func socialgroups_member_list(w http.ResponseWriter, r *http.Request, user User)
} }
err = templates.ExecuteTemplate(w,"socialgroups_member_list.html", pi) err = templates.ExecuteTemplate(w,"socialgroups_member_list.html", pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -583,7 +583,7 @@ func socialgroups_forum_check(args ...interface{}) (skip interface{}) {
if !ok { if !ok {
sgItem, err = socialgroups_get_group(forum.ParentID) sgItem, err = socialgroups_get_group(forum.ParentID)
if err != nil { if err != nil {
InternalError(errors.New("Unable to find the parent group for a forum"),w,r) InternalError(errors.New("Unable to find the parent group for a forum"),w)
*success = false *success = false
return false return false
} }
@ -610,7 +610,7 @@ func socialgroups_forum_check(args ...interface{}) (skip interface{}) {
err = socialgroups_get_member_stmt.QueryRow(sgItem.ID,user.ID).Scan(&rank,&posts,&joinedAt) err = socialgroups_get_member_stmt.QueryRow(sgItem.ID,user.ID).Scan(&rank,&posts,&joinedAt)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
*success = false *success = false
InternalError(err,w,r) InternalError(err,w)
return false return false
} else if err != nil { } else if err != nil {
return true return true

View File

@ -117,9 +117,10 @@ func create_tables(adapter qgen.DB_Adapter) error {
}, },
) )
// Coming Soon!
// What should we do about global penalties? Put them on the users table for speed? Or keep them here? // What should we do about global penalties? Put them on the users table for speed? Or keep them here?
// Should we add IP Penalties? // Should we add IP Penalties?
qgen.Install.CreateTable("users_penalties","","", /*qgen.Install.CreateTable("users_penalties","","",
[]qgen.DB_Table_Column{ []qgen.DB_Table_Column{
qgen.DB_Table_Column{"uid","int",0,false,false,""}, qgen.DB_Table_Column{"uid","int",0,false,false,""},
qgen.DB_Table_Column{"element_id","int",0,false,false,""}, qgen.DB_Table_Column{"element_id","int",0,false,false,""},
@ -143,7 +144,7 @@ func create_tables(adapter qgen.DB_Adapter) error {
qgen.DB_Table_Column{"expiry","duration",0,false,false,""}, // TO-DO: Implement the duration parsing code on the adapter side qgen.DB_Table_Column{"expiry","duration",0,false,false,""}, // TO-DO: Implement the duration parsing code on the adapter side
}, },
[]qgen.DB_Table_Key{}, []qgen.DB_Table_Key{},
) )*/
return nil return nil
} }

View File

@ -53,6 +53,6 @@ func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
handle(w,req) handle(w,req)
return return
} }
//fmt.Println(req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')]) //log.Print("req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')]",req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')])
NotFound(w,req) NotFound(w,req)
} }

View File

@ -2,7 +2,6 @@
package main package main
import "log" import "log"
import "fmt"
//import "strings" //import "strings"
import "os" import "os"
@ -10,7 +9,7 @@ var route_list []Route
var route_groups []RouteGroup var route_groups []RouteGroup
func main() { func main() {
fmt.Println("Generating the router...") log.Println("Generating the router...")
// Load all the routes... // Load all the routes...
routes() routes()
@ -80,7 +79,7 @@ func main() {
fdata += `package main fdata += `package main
import "fmt" import "log"
import "strings" import "strings"
import "sync" import "sync"
import "errors" import "errors"
@ -142,10 +141,10 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("before route_static") log.Print("before route_static")
fmt.Println("prefix:",prefix) log.Print("prefix:", prefix)
fmt.Println("req.URL.Path:",req.URL.Path) log.Print("req.URL.Path:", req.URL.Path)
fmt.Println("extra_data:",extra_data) log.Print("extra_data:", extra_data)
} }
if prefix == "/static" { if prefix == "/static" {
@ -155,7 +154,7 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("before PreRoute") log.Print("before PreRoute")
} }
// Deal with the session stuff, etc. // Deal with the session stuff, etc.
@ -165,7 +164,7 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("after PreRoute") log.Print("after PreRoute")
} }
switch(prefix) {` + out + ` switch(prefix) {` + out + `
@ -209,7 +208,7 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
` `
write_file("./gen_router.go",fdata) write_file("./gen_router.go",fdata)
fmt.Println("Successfully generated the router") log.Println("Successfully generated the router")
} }
func write_file(name string, content string) { func write_file(name string, content string) {

269
routes.go
View File

@ -29,6 +29,17 @@ func init() {
hvars.Site = site hvars.Site = site
} }
type HttpsRedirect struct {
}
func (red *HttpsRedirect) ServeHTTP(w http.ResponseWriter, req *http.Request) {
dest := "https://" + req.Host + req.URL.Path
if len(req.URL.RawQuery) > 0 {
dest += "?" + req.URL.RawQuery
}
http.Redirect(w,req,dest,http.StatusTemporaryRedirect)
}
// GET functions // GET functions
func route_static(w http.ResponseWriter, r *http.Request){ func route_static(w http.ResponseWriter, r *http.Request){
//log.Print("Outputting static file '" + r.URL.Path + "'") //log.Print("Outputting static file '" + r.URL.Path + "'")
@ -98,7 +109,7 @@ func route_overview(w http.ResponseWriter, r *http.Request, user User){
err := templates.ExecuteTemplate(w,"overview.html",pi) err := templates.ExecuteTemplate(w,"overview.html",pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -124,7 +135,7 @@ func route_custom_page(w http.ResponseWriter, r *http.Request, user User){
err := templates.ExecuteTemplate(w,"page_" + name,pi) err := templates.ExecuteTemplate(w,"page_" + name,pi)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -150,13 +161,13 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
//stmt, err := qgen.Builder.SimpleLeftJoin("topics","users","topics.tid, topics.title, topics.content, topics.createdBy, topics.is_closed, topics.sticky, topics.createdAt, topics.lastReplyAt, topics.parentID, topics.postCount, topics.likeCount, users.name, users.avatar","topics.createdBy = users.uid","parentID IN("+qlist+")","topics.sticky DESC, topics.lastReplyAt DESC, topics.createdBy DESC","") //stmt, err := qgen.Builder.SimpleLeftJoin("topics","users","topics.tid, topics.title, topics.content, topics.createdBy, topics.is_closed, topics.sticky, topics.createdAt, topics.lastReplyAt, topics.parentID, topics.postCount, topics.likeCount, users.name, users.avatar","topics.createdBy = users.uid","parentID IN("+qlist+")","topics.sticky DESC, topics.lastReplyAt DESC, topics.createdBy DESC","")
stmt, err := qgen.Builder.SimpleSelect("topics","tid, title, content, createdBy, is_closed, sticky, createdAt, lastReplyAt, lastReplyBy, parentID, postCount, likeCount","parentID IN("+qlist+")","sticky DESC, lastReplyAt DESC, createdBy DESC","") stmt, err := qgen.Builder.SimpleSelect("topics","tid, title, content, createdBy, is_closed, sticky, createdAt, lastReplyAt, lastReplyBy, parentID, postCount, likeCount","parentID IN("+qlist+")","sticky DESC, lastReplyAt DESC, createdBy DESC","")
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
rows, err := stmt.Query(fidList...) rows, err := stmt.Query(fidList...)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -166,7 +177,7 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
topicItem := TopicsRow{ID: 0} topicItem := TopicsRow{ID: 0}
err := rows.Scan(&topicItem.ID, &topicItem.Title, &topicItem.Content, &topicItem.CreatedBy, &topicItem.Is_Closed, &topicItem.Sticky, &topicItem.CreatedAt, &topicItem.LastReplyAt, &topicItem.LastReplyBy, &topicItem.ParentID, &topicItem.PostCount, &topicItem.LikeCount) err := rows.Scan(&topicItem.ID, &topicItem.Title, &topicItem.Content, &topicItem.CreatedBy, &topicItem.Is_Closed, &topicItem.Sticky, &topicItem.CreatedAt, &topicItem.LastReplyAt, &topicItem.LastReplyBy, &topicItem.ParentID, &topicItem.PostCount, &topicItem.LikeCount)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -178,6 +189,7 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
topicItem.ForumLink = forum.Link topicItem.ForumLink = forum.Link
} else { } else {
topicItem.ForumName = "" topicItem.ForumName = ""
//topicItem.ForumLink = ""
} }
/*topicItem.CreatedAt, err = relative_time(topicItem.CreatedAt) /*topicItem.CreatedAt, err = relative_time(topicItem.CreatedAt)
@ -186,7 +198,7 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
}*/ }*/
topicItem.LastReplyAt, err = relative_time(topicItem.LastReplyAt) topicItem.LastReplyAt, err = relative_time(topicItem.LastReplyAt)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
if hooks["topics_topic_row_assign"] != nil { if hooks["topics_topic_row_assign"] != nil {
@ -198,7 +210,7 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -213,7 +225,7 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
// TO-DO: What if a user is deleted via the Control Panel? // TO-DO: What if a user is deleted via the Control Panel?
userList, err := users.BulkCascadeGetMap(idSlice) userList, err := users.BulkCascadeGetMap(idSlice)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -231,18 +243,12 @@ func route_topics(w http.ResponseWriter, r *http.Request, user User){
} }
} }
if template_topics_handle != nil { // TO-DO: Is there a more type-safe way of doing this?
template_topics_handle(pi,w) //RunThemeTemplate(defaultTheme,"topics",pi,w)
} else { //RunTemplate(GetThemeTemplate(defaultTheme,"topics"),pi,w)
mapping, ok := themes[defaultTheme].TemplatesMap["topics"] //GetThemeTemplate(defaultTheme,"topics").(func(TopicsPage,http.ResponseWriter))(pi,w)
if !ok { //GetThemeTemplate(defaultTheme,"topics").Execute(pi,w)
mapping = "topics" template_topics_handle(pi,w)
}
err = templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w,r)
}
}
} }
func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string){ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string){
@ -263,7 +269,7 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
if !ok { if !ok {
return return
} }
//fmt.Printf("%+v\n", groups[user.Group].Forums) //log.Printf("groups[user.Group]: %+v\n", groups[user.Group].Forums)
if !user.Perms.ViewTopic { if !user.Perms.ViewTopic {
NoPermissions(w,r,user) NoPermissions(w,r,user)
return return
@ -275,7 +281,7 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
NotFound(w,r) NotFound(w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -294,7 +300,7 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
} }
rows, err := get_forum_topics_offset_stmt.Query(fid,offset,config.ItemsPerPage) rows, err := get_forum_topics_offset_stmt.Query(fid,offset,config.ItemsPerPage)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -306,14 +312,14 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
var topicItem TopicsRow = TopicsRow{ID: 0} var topicItem TopicsRow = TopicsRow{ID: 0}
err := rows.Scan(&topicItem.ID, &topicItem.Title, &topicItem.Content, &topicItem.CreatedBy, &topicItem.Is_Closed, &topicItem.Sticky, &topicItem.CreatedAt, &topicItem.LastReplyAt, &topicItem.LastReplyBy, &topicItem.ParentID, &topicItem.PostCount, &topicItem.LikeCount) err := rows.Scan(&topicItem.ID, &topicItem.Title, &topicItem.Content, &topicItem.CreatedBy, &topicItem.Is_Closed, &topicItem.Sticky, &topicItem.CreatedAt, &topicItem.LastReplyAt, &topicItem.LastReplyBy, &topicItem.ParentID, &topicItem.PostCount, &topicItem.LikeCount)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
topicItem.Link = build_topic_url(name_to_slug(topicItem.Title),topicItem.ID) topicItem.Link = build_topic_url(name_to_slug(topicItem.Title),topicItem.ID)
topicItem.LastReplyAt, err = relative_time(topicItem.LastReplyAt) topicItem.LastReplyAt, err = relative_time(topicItem.LastReplyAt)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
if hooks["forum_trow_assign"] != nil { if hooks["forum_trow_assign"] != nil {
@ -325,7 +331,7 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -340,7 +346,7 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
// TO-DO: What if a user is deleted via the Control Panel? // TO-DO: What if a user is deleted via the Control Panel?
userList, err := users.BulkCascadeGetMap(idSlice) userList, err := users.BulkCascadeGetMap(idSlice)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -358,18 +364,7 @@ func route_forum(w http.ResponseWriter, r *http.Request, user User, sfid string)
} }
} }
if template_forum_handle != nil { template_forum_handle(pi,w)
template_forum_handle(pi,w)
} else {
mapping, ok := themes[defaultTheme].TemplatesMap["forum"]
if !ok {
mapping = "forum"
}
err = templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w,r)
}
}
} }
func route_forums(w http.ResponseWriter, r *http.Request, user User){ func route_forums(w http.ResponseWriter, r *http.Request, user User){
@ -385,24 +380,24 @@ func route_forums(w http.ResponseWriter, r *http.Request, user User){
if user.Is_Super_Admin { if user.Is_Super_Admin {
canSee, err = fstore.GetAllIDs() canSee, err = fstore.GetAllIDs()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
//fmt.Println("canSee",canSee) //log.Print("canSee",canSee)
} else { } else {
group := groups[user.Group] group := groups[user.Group]
canSee = group.CanSee canSee = group.CanSee
//fmt.Println("group.CanSee",group.CanSee) //log.Print("group.CanSee",group.CanSee)
} }
for _, fid := range canSee { for _, fid := range canSee {
//fmt.Println(forums[fid]) //log.Print(forums[fid])
var forum Forum = *fstore.DirtyGet(fid) var forum Forum = *fstore.DirtyGet(fid)
if forum.Active && forum.Name != "" && forum.ParentID == 0 { if forum.Active && forum.Name != "" && forum.ParentID == 0 {
if forum.LastTopicID != 0 { if forum.LastTopicID != 0 {
forum.LastTopicTime, err = relative_time(forum.LastTopicTime) forum.LastTopicTime, err = relative_time(forum.LastTopicTime)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
} }
} else { } else {
forum.LastTopic = "None" forum.LastTopic = "None"
@ -422,18 +417,7 @@ func route_forums(w http.ResponseWriter, r *http.Request, user User){
} }
} }
if template_forums_handle != nil { template_forums_handle(pi,w)
template_forums_handle(pi,w)
} else {
mapping, ok := themes[defaultTheme].TemplatesMap["forums"]
if !ok {
mapping = "forums"
}
err = templates.ExecuteTemplate(w,mapping + ".html", pi)
if err != nil {
InternalError(err,w,r)
}
}
} }
func route_topic_id(w http.ResponseWriter, r *http.Request, user User){ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
@ -461,7 +445,7 @@ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
NotFound(w,r) NotFound(w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
topic.ClassName = "" topic.ClassName = ""
@ -471,7 +455,7 @@ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
return return
} }
if !user.Perms.ViewTopic { if !user.Perms.ViewTopic {
//fmt.Printf("%+v\n", user.Perms) //log.Printf("user.Perms: %+v\n", user.Perms)
NoPermissions(w,r,user) NoPermissions(w,r,user)
return return
} }
@ -524,7 +508,7 @@ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
LocalError("Bad Page. Some of the posts may have been deleted or you got here by directly typing in the page number.",w,r,user) LocalError("Bad Page. Some of the posts may have been deleted or you got here by directly typing in the page number.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -533,7 +517,7 @@ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
for rows.Next() { for rows.Next() {
err := rows.Scan(&replyItem.ID, &replyItem.Content, &replyItem.CreatedBy, &replyItem.CreatedAt, &replyItem.LastEdit, &replyItem.LastEditBy, &replyItem.Avatar, &replyItem.CreatedByName, &replyItem.Group, &replyItem.URLPrefix, &replyItem.URLName, &replyItem.Level, &replyItem.IpAddress, &replyItem.LikeCount, &replyItem.ActionType) err := rows.Scan(&replyItem.ID, &replyItem.Content, &replyItem.CreatedBy, &replyItem.CreatedAt, &replyItem.LastEdit, &replyItem.LastEditBy, &replyItem.Avatar, &replyItem.CreatedByName, &replyItem.Group, &replyItem.URLPrefix, &replyItem.URLName, &replyItem.Level, &replyItem.IpAddress, &replyItem.LikeCount, &replyItem.ActionType)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -604,7 +588,7 @@ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -615,18 +599,7 @@ func route_topic_id(w http.ResponseWriter, r *http.Request, user User){
} }
} }
if template_topic_handle != nil { template_topic_handle(tpage,w)
template_topic_handle(tpage,w)
} else {
mapping, ok := themes[defaultTheme].TemplatesMap["topic"]
if !ok {
mapping = "topic"
}
err = templates.ExecuteTemplate(w,mapping + ".html", tpage)
if err != nil {
InternalError(err,w,r)
}
}
} }
func route_profile(w http.ResponseWriter, r *http.Request, user User){ func route_profile(w http.ResponseWriter, r *http.Request, user User){
@ -663,7 +636,7 @@ func route_profile(w http.ResponseWriter, r *http.Request, user User){
NotFound(w,r) NotFound(w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -671,7 +644,7 @@ func route_profile(w http.ResponseWriter, r *http.Request, user User){
// Get the replies.. // Get the replies..
rows, err := get_profile_replies_stmt.Query(puser.ID) rows, err := get_profile_replies_stmt.Query(puser.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -679,7 +652,7 @@ func route_profile(w http.ResponseWriter, r *http.Request, user User){
for rows.Next() { for rows.Next() {
err := rows.Scan(&rid, &replyContent, &replyCreatedBy, &replyCreatedAt, &replyLastEdit, &replyLastEditBy, &replyAvatar, &replyCreatedByName, &replyGroup) err := rows.Scan(&rid, &replyContent, &replyCreatedBy, &replyCreatedAt, &replyLastEdit, &replyLastEditBy, &replyAvatar, &replyCreatedByName, &replyGroup)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -714,7 +687,7 @@ func route_profile(w http.ResponseWriter, r *http.Request, user User){
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -725,14 +698,7 @@ func route_profile(w http.ResponseWriter, r *http.Request, user User){
} }
} }
if template_profile_handle != nil { template_profile_handle(ppage,w)
template_profile_handle(ppage,w)
} else {
err = templates.ExecuteTemplate(w,"profile.html",ppage)
if err != nil {
InternalError(err,w,r)
}
}
} }
func route_topic_create(w http.ResponseWriter, r *http.Request, user User, sfid string){ func route_topic_create(w http.ResponseWriter, r *http.Request, user User, sfid string){
@ -769,7 +735,7 @@ func route_topic_create(w http.ResponseWriter, r *http.Request, user User, sfid
if user.Is_Super_Admin { if user.Is_Super_Admin {
canSee, err = fstore.GetAllIDs() canSee, err = fstore.GetAllIDs()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} else { } else {
@ -805,14 +771,7 @@ func route_topic_create(w http.ResponseWriter, r *http.Request, user User, sfid
} }
} }
if template_create_topic_handle != nil { template_create_topic_handle(ctpage,w)
template_create_topic_handle(ctpage,w)
} else {
err = templates.ExecuteTemplate(w,"create-topic.html",ctpage)
if err != nil {
InternalError(err,w,r)
}
}
} }
// POST functions. Authorised users only. // POST functions. Authorised users only.
@ -849,37 +808,37 @@ func route_topic_create_submit(w http.ResponseWriter, r *http.Request, user User
wcount := word_count(content) wcount := word_count(content)
res, err := create_topic_stmt.Exec(fid,topic_name,content,parse_message(content),user.ID,ipaddress,wcount,user.ID) res, err := create_topic_stmt.Exec(fid,topic_name,content,parse_message(content),user.ID,ipaddress,wcount,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
lastId, err := res.LastInsertId() lastId, err := res.LastInsertId()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
err = fstore.IncrementTopicCount(fid) err = fstore.IncrementTopicCount(fid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_subscription_stmt.Exec(user.ID,lastId,"topic") _, err = add_subscription_stmt.Exec(user.ID,lastId,"topic")
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
http.Redirect(w,r,"/topic/" + strconv.FormatInt(lastId,10), http.StatusSeeOther) http.Redirect(w,r,"/topic/" + strconv.FormatInt(lastId,10), http.StatusSeeOther)
err = increase_post_user_stats(wcount,user.ID,true,user) err = increase_post_user_stats(wcount,user.ID,true,user)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
err = fstore.UpdateLastTopic(topic_name,int(lastId),user.Name,user.ID,"",fid) err = fstore.UpdateLastTopic(topic_name,int(lastId),user.Name,user.ID,"",fid)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
} }
} }
@ -900,7 +859,7 @@ func route_create_reply(w http.ResponseWriter, r *http.Request, user User) {
PreError("Couldn't find the parent topic",w,r) PreError("Couldn't find the parent topic",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -923,35 +882,35 @@ func route_create_reply(w http.ResponseWriter, r *http.Request, user User) {
wcount := word_count(content) wcount := word_count(content)
_, err = create_reply_stmt.Exec(tid,content,parse_message(content),ipaddress,wcount,user.ID) _, err = create_reply_stmt.Exec(tid,content,parse_message(content),ipaddress,wcount,user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_replies_to_topic_stmt.Exec(1,user.ID,tid) _, err = add_replies_to_topic_stmt.Exec(1,user.ID,tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = update_forum_cache_stmt.Exec(topic.Title,tid,user.Name,user.ID,1) _, err = update_forum_cache_stmt.Exec(topic.Title,tid,user.Name,user.ID,1)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
res, err := add_activity_stmt.Exec(user.ID,topic.CreatedBy,"reply","topic",tid) res, err := add_activity_stmt.Exec(user.ID,topic.CreatedBy,"reply","topic",tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
lastId, err := res.LastInsertId() lastId, err := res.LastInsertId()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = notify_watchers_stmt.Exec(lastId) _, err = notify_watchers_stmt.Exec(lastId)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -966,14 +925,14 @@ func route_create_reply(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The destination no longer exists",w,r,user) LocalError("The destination no longer exists",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
http.Redirect(w,r,"/topic/" + strconv.Itoa(tid), http.StatusSeeOther) http.Redirect(w,r,"/topic/" + strconv.Itoa(tid), http.StatusSeeOther)
err = increase_post_user_stats(wcount, user.ID, false, user) err = increase_post_user_stats(wcount, user.ID, false, user)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -996,7 +955,7 @@ func route_like_topic(w http.ResponseWriter, r *http.Request, user User) {
PreError("The requested topic doesn't exist.",w,r) PreError("The requested topic doesn't exist.",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1016,7 +975,7 @@ func route_like_topic(w http.ResponseWriter, r *http.Request, user User) {
err = has_liked_topic_stmt.QueryRow(user.ID,tid).Scan(&tid) err = has_liked_topic_stmt.QueryRow(user.ID,tid).Scan(&tid)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} else if err != ErrNoRows { } else if err != ErrNoRows {
LocalError("You already liked this!",w,r,user) LocalError("You already liked this!",w,r,user)
@ -1028,37 +987,37 @@ func route_like_topic(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The target user doesn't exist",w,r,user) LocalError("The target user doesn't exist",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
score := 1 score := 1
_, err = create_like_stmt.Exec(score,tid,"topics",user.ID) _, err = create_like_stmt.Exec(score,tid,"topics",user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_likes_to_topic_stmt.Exec(1,tid) _, err = add_likes_to_topic_stmt.Exec(1,tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
res, err := add_activity_stmt.Exec(user.ID,topic.CreatedBy,"like","topic",tid) res, err := add_activity_stmt.Exec(user.ID,topic.CreatedBy,"like","topic",tid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
lastId, err := res.LastInsertId() lastId, err := res.LastInsertId()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = notify_one_stmt.Exec(topic.CreatedBy,lastId) _, err = notify_one_stmt.Exec(topic.CreatedBy,lastId)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1071,7 +1030,7 @@ func route_like_topic(w http.ResponseWriter, r *http.Request, user User) {
LocalError("The liked topic no longer exists",w,r,user) LocalError("The liked topic no longer exists",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1096,7 +1055,7 @@ func route_reply_like_submit(w http.ResponseWriter, r *http.Request, user User)
PreError("You can't like something which doesn't exist!",w,r) PreError("You can't like something which doesn't exist!",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1106,7 +1065,7 @@ func route_reply_like_submit(w http.ResponseWriter, r *http.Request, user User)
PreError("The parent topic doesn't exist.",w,r) PreError("The parent topic doesn't exist.",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1126,7 +1085,7 @@ func route_reply_like_submit(w http.ResponseWriter, r *http.Request, user User)
err = has_liked_reply_stmt.QueryRow(user.ID, rid).Scan(&rid) err = has_liked_reply_stmt.QueryRow(user.ID, rid).Scan(&rid)
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} else if err != ErrNoRows { } else if err != ErrNoRows {
LocalError("You already liked this!",w,r,user) LocalError("You already liked this!",w,r,user)
@ -1138,37 +1097,37 @@ func route_reply_like_submit(w http.ResponseWriter, r *http.Request, user User)
LocalError("The target user doesn't exist",w,r,user) LocalError("The target user doesn't exist",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
score := 1 score := 1
_, err = create_like_stmt.Exec(score,rid,"replies",user.ID) _, err = create_like_stmt.Exec(score,rid,"replies",user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_likes_to_reply_stmt.Exec(1,rid) _, err = add_likes_to_reply_stmt.Exec(1,rid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
res, err := add_activity_stmt.Exec(user.ID,reply.CreatedBy,"like","post",rid) res, err := add_activity_stmt.Exec(user.ID,reply.CreatedBy,"like","post",rid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
lastId, err := res.LastInsertId() lastId, err := res.LastInsertId()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = notify_one_stmt.Exec(reply.CreatedBy,lastId) _, err = notify_one_stmt.Exec(reply.CreatedBy,lastId)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1203,7 +1162,7 @@ func route_profile_reply_create(w http.ResponseWriter, r *http.Request, user Use
_, err = create_profile_reply_stmt.Exec(uid,html.EscapeString(preparse_message(r.PostFormValue("reply-content"))),parse_message(html.EscapeString(preparse_message(r.PostFormValue("reply-content")))),user.ID,ipaddress) _, err = create_profile_reply_stmt.Exec(uid,html.EscapeString(preparse_message(r.PostFormValue("reply-content"))),parse_message(html.EscapeString(preparse_message(r.PostFormValue("reply-content")))),user.ID,ipaddress)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1213,7 +1172,7 @@ func route_profile_reply_create(w http.ResponseWriter, r *http.Request, user Use
LocalError("The profile you're trying to post on doesn't exist.",w,r,user) LocalError("The profile you're trying to post on doesn't exist.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1256,7 +1215,7 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
LocalError("We were unable to find the reported post",w,r,user) LocalError("We were unable to find the reported post",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1265,7 +1224,7 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
LocalError("We weren't able to find the topic the reported post is supposed to be in",w,r,user) LocalError("We weren't able to find the topic the reported post is supposed to be in",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1277,7 +1236,7 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
LocalError("We weren't able to find the reported post",w,r,user) LocalError("We weren't able to find the reported post",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1286,7 +1245,7 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
LocalError("We weren't able to find the profile the reported post is supposed to be on",w,r,user) LocalError("We weren't able to find the profile the reported post is supposed to be on",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
title = "Profile: " + title title = "Profile: " + title
@ -1297,7 +1256,7 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
NotFound(w,r) NotFound(w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
title = "Topic: " + title title = "Topic: " + title
@ -1315,14 +1274,14 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
var count int var count int
rows, err := report_exists_stmt.Query(item_type + "_" + strconv.Itoa(item_id)) rows, err := report_exists_stmt.Query(item_type + "_" + strconv.Itoa(item_id))
if err != nil && err != ErrNoRows { if err != nil && err != ErrNoRows {
InternalError(err,w,r) InternalError(err,w)
return return
} }
for rows.Next() { for rows.Next() {
err = rows.Scan(&count) err = rows.Scan(&count)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -1333,24 +1292,24 @@ func route_report_submit(w http.ResponseWriter, r *http.Request, user User, site
res, err := create_report_stmt.Exec(title,content,parse_message(content),user.ID,item_type + "_" + strconv.Itoa(item_id)) res, err := create_report_stmt.Exec(title,content,parse_message(content),user.ID,item_type + "_" + strconv.Itoa(item_id))
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
lastId, err := res.LastInsertId() lastId, err := res.LastInsertId()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_topics_to_forum_stmt.Exec(1, fid) _, err = add_topics_to_forum_stmt.Exec(1, fid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = update_forum_cache_stmt.Exec(title, lastId, user.Name, user.ID, fid) _, err = update_forum_cache_stmt.Exec(title, lastId, user.Name, user.ID, fid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1402,7 +1361,7 @@ func route_account_own_edit_critical_submit(w http.ResponseWriter, r *http.Reque
LocalError("Your account no longer exists.",w,r,user) LocalError("Your account no longer exists.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1411,7 +1370,7 @@ func route_account_own_edit_critical_submit(w http.ResponseWriter, r *http.Reque
LocalError("That's not the correct password.",w,r,user) LocalError("That's not the correct password.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
if new_password != confirm_password { if new_password != confirm_password {
@ -1529,7 +1488,7 @@ func route_account_own_edit_avatar_submit(w http.ResponseWriter, r *http.Request
_, err = set_avatar_stmt.Exec("." + ext, strconv.Itoa(user.ID)) _, err = set_avatar_stmt.Exec("." + ext, strconv.Itoa(user.ID))
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
user.Avatar = "/uploads/avatar_" + strconv.Itoa(user.ID) + "." + ext user.Avatar = "/uploads/avatar_" + strconv.Itoa(user.ID) + "." + ext
@ -1677,7 +1636,7 @@ func route_account_own_edit_email_token_submit(w http.ResponseWriter, r *http.Re
var emailList []interface{} var emailList []interface{}
rows, err := get_emails_by_user_stmt.Query(user.ID) rows, err := get_emails_by_user_stmt.Query(user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
defer rows.Close() defer rows.Close()
@ -1685,7 +1644,7 @@ func route_account_own_edit_email_token_submit(w http.ResponseWriter, r *http.Re
for rows.Next() { for rows.Next() {
err := rows.Scan(&email.Email, &email.Validated, &email.Token) err := rows.Scan(&email.Email, &email.Validated, &email.Token)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1699,7 +1658,7 @@ func route_account_own_edit_email_token_submit(w http.ResponseWriter, r *http.Re
} }
err = rows.Err() err = rows.Err()
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1714,7 +1673,7 @@ func route_account_own_edit_email_token_submit(w http.ResponseWriter, r *http.Re
_, err = verify_email_stmt.Exec(user.Email) _, err = verify_email_stmt.Exec(user.Email)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1722,7 +1681,7 @@ func route_account_own_edit_email_token_submit(w http.ResponseWriter, r *http.Re
if settings["activation_type"] == 2 { if settings["activation_type"] == 2 {
_, err = activate_user_stmt.Exec(user.ID) _, err = activate_user_stmt.Exec(user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} }
@ -1788,7 +1747,7 @@ func route_login_submit(w http.ResponseWriter, r *http.Request, user User) {
if user.Session == "" { if user.Session == "" {
session, err = auth.CreateSession(uid) session, err = auth.CreateSession(uid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
} else { } else {
@ -1880,7 +1839,7 @@ func route_register_submit(w http.ResponseWriter, r *http.Request, user User) {
LocalError("This username isn't available. Try another.",w,r,user) LocalError("This username isn't available. Try another.",w,r,user)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1888,12 +1847,12 @@ func route_register_submit(w http.ResponseWriter, r *http.Request, user User) {
if site.EnableEmails { if site.EnableEmails {
token, err := GenerateSafeString(80) token, err := GenerateSafeString(80)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
_, err = add_email_stmt.Exec(email, uid, 0, token) _, err = add_email_stmt.Exec(email, uid, 0, token)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1905,7 +1864,7 @@ func route_register_submit(w http.ResponseWriter, r *http.Request, user User) {
session, err := auth.CreateSession(uid) session, err := auth.CreateSession(uid)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1958,7 +1917,7 @@ func route_api(w http.ResponseWriter, r *http.Request, user User) {
PreError("Couldn't find the parent topic",w,r) PreError("Couldn't find the parent topic",w,r)
return return
} else if err != nil { } else if err != nil {
InternalError(err,w,r) InternalError(err,w)
return return
} }
@ -1993,7 +1952,7 @@ func route_api(w http.ResponseWriter, r *http.Request, user User) {
msglist = msglist[0:len(msglist)-1] msglist = msglist[0:len(msglist)-1]
} }
w.Write([]byte(`{"msgs":[` + msglist + `],"msgCount":` + strconv.Itoa(msgCount) + `}`)) w.Write([]byte(`{"msgs":[` + msglist + `],"msgCount":` + strconv.Itoa(msgCount) + `}`))
//fmt.Println(`{"msgs":[` + msglist + `],"msgCount":` + strconv.Itoa(msgCount) + `}`) //log.Print(`{"msgs":[` + msglist + `],"msgCount":` + strconv.Itoa(msgCount) + `}`)
//case "topics": //case "topics":
//case "forums": //case "forums":
//case "users": //case "users":

View File

@ -33,4 +33,6 @@ if %errorlevel% neq 0 (
echo Running Gosora echo Running Gosora
gosora.exe gosora.exe
rem Or you could redirect the output to a file
rem gosora.exe > operations.log 2>&1
pause pause

View File

@ -1,9 +1,10 @@
// +build !no_templategen
// Code generated by Gosora. More below: // Code generated by Gosora. More below:
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
// +build !no_templategen
package main package main
import "net/http"
import "strconv" import "strconv"
import "io"
func init() { func init() {
template_forum_handle = template_forum template_forum_handle = template_forum
@ -13,7 +14,7 @@ func init() {
tmpl_ptr_map["o_forum"] = template_forum tmpl_ptr_map["o_forum"] = template_forum
} }
func template_forum(tmpl_forum_vars ForumPage, w io.Writer) { func template_forum(tmpl_forum_vars ForumPage, w http.ResponseWriter) {
w.Write(header_0) w.Write(header_0)
w.Write([]byte(tmpl_forum_vars.Title)) w.Write([]byte(tmpl_forum_vars.Title))
w.Write(header_1) w.Write(header_1)

View File

@ -1,8 +1,9 @@
// +build !no_templategen
// Code generated by Gosora. More below: // Code generated by Gosora. More below:
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
// +build !no_templategen
package main package main
import "io" import "net/http"
func init() { func init() {
template_forums_handle = template_forums template_forums_handle = template_forums
@ -12,7 +13,7 @@ func init() {
tmpl_ptr_map["o_forums"] = template_forums tmpl_ptr_map["o_forums"] = template_forums
} }
func template_forums(tmpl_forums_vars ForumsPage, w io.Writer) { func template_forums(tmpl_forums_vars ForumsPage, w http.ResponseWriter) {
w.Write(header_0) w.Write(header_0)
w.Write([]byte(tmpl_forums_vars.Title)) w.Write([]byte(tmpl_forums_vars.Title))
w.Write(header_1) w.Write(header_1)

View File

@ -1,8 +1,9 @@
// +build !no_templategen
// Code generated by Gosora. More below: // Code generated by Gosora. More below:
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
// +build !no_templategen
package main package main
import "io" import "net/http"
import "strconv" import "strconv"
func init() { func init() {
@ -13,7 +14,7 @@ func init() {
tmpl_ptr_map["o_profile"] = template_profile tmpl_ptr_map["o_profile"] = template_profile
} }
func template_profile(tmpl_profile_vars ProfilePage, w io.Writer) { func template_profile(tmpl_profile_vars ProfilePage, w http.ResponseWriter) {
w.Write(header_0) w.Write(header_0)
w.Write([]byte(tmpl_profile_vars.Title)) w.Write([]byte(tmpl_profile_vars.Title))
w.Write(header_1) w.Write(header_1)

View File

@ -1,9 +1,10 @@
// +build !no_templategen
// Code generated by Gosora. More below: // Code generated by Gosora. More below:
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
// +build !no_templategen
package main package main
import "io"
import "strconv" import "strconv"
import "net/http"
func init() { func init() {
template_topic_handle = template_topic template_topic_handle = template_topic
@ -13,7 +14,7 @@ func init() {
tmpl_ptr_map["o_topic"] = template_topic tmpl_ptr_map["o_topic"] = template_topic
} }
func template_topic(tmpl_topic_vars TopicPage, w io.Writer) { func template_topic(tmpl_topic_vars TopicPage, w http.ResponseWriter) {
w.Write(header_0) w.Write(header_0)
w.Write([]byte(tmpl_topic_vars.Title)) w.Write([]byte(tmpl_topic_vars.Title))
w.Write(header_1) w.Write(header_1)

View File

@ -1,8 +1,9 @@
// +build !no_templategen
// Code generated by Gosora. More below: // Code generated by Gosora. More below:
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
// +build !no_templategen
package main package main
import "io" import "net/http"
import "strconv" import "strconv"
func init() { func init() {
@ -13,7 +14,7 @@ func init() {
tmpl_ptr_map["o_topic_alt"] = template_topic_alt tmpl_ptr_map["o_topic_alt"] = template_topic_alt
} }
func template_topic_alt(tmpl_topic_alt_vars TopicPage, w io.Writer) { func template_topic_alt(tmpl_topic_alt_vars TopicPage, w http.ResponseWriter) {
w.Write(header_0) w.Write(header_0)
w.Write([]byte(tmpl_topic_alt_vars.Title)) w.Write([]byte(tmpl_topic_alt_vars.Title))
w.Write(header_1) w.Write(header_1)

View File

@ -1,9 +1,10 @@
// +build !no_templategen
// Code generated by Gosora. More below: // Code generated by Gosora. More below:
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */ /* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
// +build !no_templategen
package main package main
import "net/http"
import "strconv" import "strconv"
import "io"
func init() { func init() {
template_topics_handle = template_topics template_topics_handle = template_topics
@ -13,7 +14,7 @@ func init() {
tmpl_ptr_map["o_topics"] = template_topics tmpl_ptr_map["o_topics"] = template_topics
} }
func template_topics(tmpl_topics_vars TopicsPage, w io.Writer) { func template_topics(tmpl_topics_vars TopicsPage, w http.ResponseWriter) {
w.Write(header_0) w.Write(header_0)
w.Write([]byte(tmpl_topics_vars.Title)) w.Write([]byte(tmpl_topics_vars.Title))
w.Write(header_1) w.Write(header_1)

View File

@ -58,7 +58,7 @@ type CTemplateSet struct
expectsInt interface{} expectsInt interface{}
} }
func (c *CTemplateSet) compile_template(name string, dir string, expects string, expectsInt interface{}, varList map[string]VarItem) (out string) { func (c *CTemplateSet) compile_template(name string, dir string, expects string, expectsInt interface{}, varList map[string]VarItem) (out string, err error) {
if dev.DebugMode { if dev.DebugMode {
fmt.Println("Compiling template '" + name + "'") fmt.Println("Compiling template '" + name + "'")
} }
@ -82,7 +82,7 @@ func (c *CTemplateSet) compile_template(name string, dir string, expects string,
} }
c.importMap = map[string]string{ c.importMap = map[string]string{
"io":"io", "net/http":"net/http",
} }
c.varList = varList c.varList = varList
//c.pVarList = "" //c.pVarList = ""
@ -93,7 +93,7 @@ func (c *CTemplateSet) compile_template(name string, dir string, expects string,
res, err := ioutil.ReadFile(dir + name) res, err := ioutil.ReadFile(dir + name)
if err != nil { if err != nil {
log.Fatal(err) return "", err
} }
content := string(res) content := string(res)
@ -105,7 +105,7 @@ func (c *CTemplateSet) compile_template(name string, dir string, expects string,
var treeSet map[string]*parse.Tree = make(map[string]*parse.Tree) var treeSet map[string]*parse.Tree = make(map[string]*parse.Tree)
tree, err = tree.Parse(content,"{{","}}", treeSet, c.funcMap) tree, err = tree.Parse(content,"{{","}}", treeSet, c.funcMap)
if err != nil { if err != nil {
log.Fatal(err) return "", err
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(name) fmt.Println(name)
@ -160,10 +160,10 @@ func (c *CTemplateSet) compile_template(name string, dir string, expects string,
varString += "var " + varItem.Name + " " + varItem.Type + " = " + varItem.Destination + "\n" varString += "var " + varItem.Name + " " + varItem.Type + " = " + varItem.Destination + "\n"
} }
fout := "// Code generated by Gosora. More below:\n/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */\n" fout := "// +build !no_templategen\n\n// Code generated by Gosora. More below:\n/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */\n"
fout += "// +build !no_templategen\npackage main\n" + importList + c.pVarList + "\n" fout += "package main\n" + importList + c.pVarList + "\n"
fout += "func init() {\n\ttemplate_" + fname +"_handle = template_" + fname + "\n\t//o_template_" + fname +"_handle = template_" + fname + "\n\tctemplates = append(ctemplates,\"" + fname + "\")\n\ttmpl_ptr_map[\"" + fname + "\"] = &template_" + fname + "_handle\n\ttmpl_ptr_map[\"o_" + fname + "\"] = template_" + fname + "\n}\n\n" fout += "func init() {\n\ttemplate_" + fname +"_handle = template_" + fname + "\n\t//o_template_" + fname +"_handle = template_" + fname + "\n\tctemplates = append(ctemplates,\"" + fname + "\")\n\ttmpl_ptr_map[\"" + fname + "\"] = &template_" + fname + "_handle\n\ttmpl_ptr_map[\"o_" + fname + "\"] = template_" + fname + "\n}\n\n"
fout += "func template_" + fname + "(tmpl_" + fname + "_vars " + expects + ", w io.Writer) {\n" + varString + out + "}\n" fout += "func template_" + fname + "(tmpl_" + fname + "_vars " + expects + ", w http.ResponseWriter) {\n" + varString + out + "}\n"
fout = strings.Replace(fout,`)) fout = strings.Replace(fout,`))
w.Write([]byte(`," + ",-1) w.Write([]byte(`," + ",-1)
@ -183,7 +183,7 @@ w.Write([]byte(`," + ",-1)
fmt.Println("Output!") fmt.Println("Output!")
fmt.Println(fout) fmt.Println(fout)
} }
return fout return fout, nil
} }
func (c *CTemplateSet) compile_switch(varholder string, holdreflect reflect.Value, template_name string, node interface{}) (out string) { func (c *CTemplateSet) compile_switch(varholder string, holdreflect reflect.Value, template_name string, node interface{}) (out string) {
@ -255,13 +255,13 @@ func (c *CTemplateSet) compile_switch(varholder string, holdreflect reflect.Valu
var outVal reflect.Value var outVal reflect.Value
for _, cmd := range node.Pipe.Cmds { for _, cmd := range node.Pipe.Cmds {
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Range Bit:",cmd) fmt.Println("Range Bit:", cmd)
} }
out, outVal = c.compile_reflectswitch(varholder, holdreflect, template_name, cmd) out, outVal = c.compile_reflectswitch(varholder, holdreflect, template_name, cmd)
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Returned:",out) fmt.Println("Returned:", out)
fmt.Println("Range Kind Switch!") fmt.Println("Range Kind Switch!")
} }
@ -341,8 +341,8 @@ func (c *CTemplateSet) compile_subswitch(varholder string, holdreflect reflect.V
for _, id := range n.Ident { for _, id := range n.Ident {
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Data Kind:",cur.Kind().String()) fmt.Println("Data Kind:", cur.Kind().String())
fmt.Println("Field Bit:",id) fmt.Println("Field Bit:", id)
} }
if cur.Kind() == reflect.Ptr { if cur.Kind() == reflect.Ptr {
@ -354,8 +354,8 @@ func (c *CTemplateSet) compile_subswitch(varholder string, holdreflect reflect.V
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Data Kind:",cur.Kind().String()) fmt.Println("Data Kind:", cur.Kind().String())
fmt.Println("Field Bit:",id) fmt.Println("Field Bit:", id)
} }
} }
@ -400,7 +400,7 @@ func (c *CTemplateSet) compile_subswitch(varholder string, holdreflect reflect.V
panic("Nil is not a command x.x") panic("Nil is not a command x.x")
case *parse.VariableNode: case *parse.VariableNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Variable Node:",n.String()) fmt.Println("Variable Node:", n.String())
fmt.Println(n.Ident) fmt.Println(n.Ident)
} }
varname, reflectVal := c.compile_if_varsub(n.String(), varholder, template_name, holdreflect) varname, reflectVal := c.compile_if_varsub(n.String(), varholder, template_name, holdreflect)
@ -409,13 +409,13 @@ func (c *CTemplateSet) compile_subswitch(varholder string, holdreflect reflect.V
return n.Quoted return n.Quoted
case *parse.IdentifierNode: case *parse.IdentifierNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Identifier Node:",node) fmt.Println("Identifier Node:", node)
fmt.Println("Identifier Node Args:",node.Args) fmt.Println("Identifier Node Args:", node.Args)
} }
return c.compile_varsub(c.compile_identswitch(varholder, holdreflect, template_name, node)) return c.compile_varsub(c.compile_identswitch(varholder, holdreflect, template_name, node))
default: default:
fmt.Println("Unknown Kind:",reflect.ValueOf(firstWord).Elem().Kind()) fmt.Println("Unknown Kind:", reflect.ValueOf(firstWord).Elem().Kind())
fmt.Println("Unknown Type:",reflect.ValueOf(firstWord).Elem().Type().Name()) fmt.Println("Unknown Type:", reflect.ValueOf(firstWord).Elem().Type().Name())
panic("I don't know what node this is") panic("I don't know what node this is")
} }
return "" return ""
@ -429,9 +429,9 @@ func (c *CTemplateSet) compile_varswitch(varholder string, holdreflect reflect.V
switch n := firstWord.(type) { switch n := firstWord.(type) {
case *parse.FieldNode: case *parse.FieldNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Field Node:",n.Ident) fmt.Println("Field Node:", n.Ident)
for _, id := range n.Ident { for _, id := range n.Ident {
fmt.Println("Field Bit:",id) fmt.Println("Field Bit:", id)
} }
} }
@ -439,22 +439,22 @@ func (c *CTemplateSet) compile_varswitch(varholder string, holdreflect reflect.V
return c.compile_boolsub(n.String(), varholder, template_name, holdreflect) return c.compile_boolsub(n.String(), varholder, template_name, holdreflect)
case *parse.ChainNode: case *parse.ChainNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Chain Node:",n.Node) fmt.Println("Chain Node:", n.Node)
fmt.Println("Chain Node Args:",node.Args) fmt.Println("Chain Node Args:", node.Args)
} }
break break
case *parse.IdentifierNode: case *parse.IdentifierNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Identifier Node:",node) fmt.Println("Identifier Node:", node)
fmt.Println("Identifier Node Args:",node.Args) fmt.Println("Identifier Node Args:", node.Args)
} }
return c.compile_identswitch_n(varholder, holdreflect, template_name, node) return c.compile_identswitch_n(varholder, holdreflect, template_name, node)
case *parse.DotNode: case *parse.DotNode:
return varholder return varholder
case *parse.VariableNode: case *parse.VariableNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Variable Node:",n.String()) fmt.Println("Variable Node:", n.String())
fmt.Println("Variable Node Identifier:",n.Ident) fmt.Println("Variable Node Identifier:", n.Ident)
} }
out, _ = c.compile_if_varsub(n.String(), varholder, template_name, holdreflect) out, _ = c.compile_if_varsub(n.String(), varholder, template_name, holdreflect)
return out return out
@ -464,17 +464,17 @@ func (c *CTemplateSet) compile_varswitch(varholder string, holdreflect reflect.V
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Pipe Node!") fmt.Println("Pipe Node!")
fmt.Println(n) fmt.Println(n)
fmt.Println("Args:",node.Args) fmt.Println("Args:", node.Args)
} }
out += c.compile_identswitch_n(varholder, holdreflect, template_name, node) out += c.compile_identswitch_n(varholder, holdreflect, template_name, node)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Out:",out) fmt.Println("Out:", out)
} }
return out return out
default: default:
fmt.Println("Unknown Kind:",reflect.ValueOf(firstWord).Elem().Kind()) fmt.Println("Unknown Kind:", reflect.ValueOf(firstWord).Elem().Kind())
fmt.Println("Unknown Type:",reflect.ValueOf(firstWord).Elem().Type().Name()) fmt.Println("Unknown Type:", reflect.ValueOf(firstWord).Elem().Type().Name())
panic("I don't know what node this is! Grr...") panic("I don't know what node this is! Grr...")
} }
return "" return ""
@ -498,8 +498,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
for pos := 0; pos < len(node.Args); pos++ { for pos := 0; pos < len(node.Args); pos++ {
id := node.Args[pos] id := node.Args[pos]
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("pos:",pos) fmt.Println("pos:", pos)
fmt.Println("ID:",id) fmt.Println("ID:", id)
} }
switch id.String() { switch id.String() {
case "not": case "not":
@ -509,13 +509,13 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
fmt.Println("Building or function") fmt.Println("Building or function")
} }
if pos == 0 { if pos == 0 {
fmt.Println("pos:",pos) fmt.Println("pos:", pos)
panic("or is missing a left operand") panic("or is missing a left operand")
return out, val return out, val
} }
if len(node.Args) <= pos { if len(node.Args) <= pos {
fmt.Println("post pos:",pos) fmt.Println("post pos:", pos)
fmt.Println("len(node.Args):",len(node.Args)) fmt.Println("len(node.Args):", len(node.Args))
panic("or is missing a right operand") panic("or is missing a right operand")
return out, val return out, val
} }
@ -531,8 +531,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
out += left + " || " + right out += left + " || " + right
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Left operand:",node.Args[pos - 1]) fmt.Println("Left operand:", node.Args[pos - 1])
fmt.Println("Right operand:",node.Args[pos + 1]) fmt.Println("Right operand:", node.Args[pos + 1])
} }
if !funcExists { if !funcExists {
@ -540,21 +540,21 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("pos:",pos) fmt.Println("pos:", pos)
fmt.Println("len(node.Args):",len(node.Args)) fmt.Println("len(node.Args):", len(node.Args))
} }
case "and": case "and":
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Building and function") fmt.Println("Building and function")
} }
if pos == 0 { if pos == 0 {
fmt.Println("pos:",pos) fmt.Println("pos:", pos)
panic("and is missing a left operand") panic("and is missing a left operand")
return out, val return out, val
} }
if len(node.Args) <= pos { if len(node.Args) <= pos {
fmt.Println("post pos:",pos) fmt.Println("post pos:", pos)
fmt.Println("len(node.Args):",len(node.Args)) fmt.Println("len(node.Args):", len(node.Args))
panic("and is missing a right operand") panic("and is missing a right operand")
return out, val return out, val
} }
@ -570,8 +570,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
out += left + " && " + right out += left + " && " + right
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Left operand:",node.Args[pos - 1]) fmt.Println("Left operand:", node.Args[pos - 1])
fmt.Println("Right operand:",node.Args[pos + 1]) fmt.Println("Right operand:", node.Args[pos + 1])
} }
if !funcExists { if !funcExists {
@ -579,49 +579,49 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("pos:",pos) fmt.Println("pos:", pos)
fmt.Println("len(node.Args):",len(node.Args)) fmt.Println("len(node.Args):", len(node.Args))
} }
case "le": case "le":
out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " <= " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect) out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " <= " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "lt": case "lt":
out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " < " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect) out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " < " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "gt": case "gt":
out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " > " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect) out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " > " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "ge": case "ge":
out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " >= " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect) out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " >= " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "eq": case "eq":
out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " == " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect) out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " == " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "ne": case "ne":
out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " != " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect) out += c.compile_if_varsub_n(node.Args[pos + 1].String(), varholder, template_name, holdreflect) + " != " + c.compile_if_varsub_n(node.Args[pos + 2].String(), varholder, template_name, holdreflect)
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "add": case "add":
@ -640,8 +640,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
out += param1 + " + " + param2 out += param1 + " + " + param2
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("add") fmt.Println("add")
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "subtract": case "subtract":
@ -660,8 +660,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
out += param1 + " - " + param2 out += param1 + " - " + param2
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("subtract") fmt.Println("subtract")
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "divide": case "divide":
@ -680,8 +680,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
out += param1 + " / " + param2 out += param1 + " / " + param2
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("divide") fmt.Println("divide")
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
case "multiply": case "multiply":
@ -700,8 +700,8 @@ func (c *CTemplateSet) compile_identswitch(varholder string, holdreflect reflect
out += param1 + " * " + param2 out += param1 + " * " + param2
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("multiply") fmt.Println("multiply")
fmt.Println(node.Args[pos + 1]) fmt.Println("node.Args[pos + 1]", node.Args[pos + 1])
fmt.Println(node.Args[pos + 2]) fmt.Println("node.Args[pos + 2]", node.Args[pos + 2])
} }
break ArgLoop break ArgLoop
default: default:
@ -732,18 +732,17 @@ func (c *CTemplateSet) compile_reflectswitch(varholder string, holdreflect refle
switch n := firstWord.(type) { switch n := firstWord.(type) {
case *parse.FieldNode: case *parse.FieldNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Field Node:",n.Ident) fmt.Println("Field Node:", n.Ident)
for _, id := range n.Ident { for _, id := range n.Ident {
fmt.Println("Field Bit:",id) fmt.Println("Field Bit:", id)
} }
} }
/* Use reflect to determine if the field is for a method, otherwise assume it's a variable. Coming Soon. */ /* Use reflect to determine if the field is for a method, otherwise assume it's a variable. Coming Soon. */
return c.compile_if_varsub(n.String(), varholder, template_name, holdreflect) return c.compile_if_varsub(n.String(), varholder, template_name, holdreflect)
case *parse.ChainNode: case *parse.ChainNode:
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Chain Node: ") fmt.Println("Chain Node:", n.Node)
fmt.Println(n.Node) fmt.Println("node.Args", node.Args)
fmt.Println(node.Args)
} }
return "", outVal return "", outVal
case *parse.DotNode: case *parse.DotNode:
@ -797,14 +796,13 @@ func (c *CTemplateSet) compile_if_varsub(varname string, varholder string, templ
bits[0] = strings.TrimPrefix(bits[0],"$") bits[0] = strings.TrimPrefix(bits[0],"$")
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Cur Kind:",cur.Kind()) fmt.Println("Cur Kind:", cur.Kind())
fmt.Println("Cur Type:",cur.Type().Name()) fmt.Println("Cur Type:", cur.Type().Name())
} }
for _, bit := range bits { for _, bit := range bits {
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Variable Field!") fmt.Println("Variable Field:", bit)
fmt.Println(bit)
} }
if bit == "" { if bit == "" {
continue continue
@ -820,8 +818,8 @@ func (c *CTemplateSet) compile_if_varsub(varname string, varholder string, templ
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Data Kind:",cur.Kind().String()) fmt.Println("Data Kind:", cur.Kind().String())
fmt.Println("Field Bit:",bit) fmt.Println("Field Bit:", bit)
} }
} }
@ -838,15 +836,15 @@ func (c *CTemplateSet) compile_if_varsub(varname string, varholder string, templ
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Data Kind:",cur.Kind()) fmt.Println("Data Kind:", cur.Kind())
fmt.Println("Data Type:",cur.Type().Name()) fmt.Println("Data Type:", cur.Type().Name())
} }
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Out Value:",out) fmt.Println("Out Value:", out)
fmt.Println("Out Kind:",cur.Kind()) fmt.Println("Out Kind:", cur.Kind())
fmt.Println("Out Type:",cur.Type().Name()) fmt.Println("Out Type:", cur.Type().Name())
} }
for _, varItem := range c.varList { for _, varItem := range c.varList {
@ -856,9 +854,9 @@ func (c *CTemplateSet) compile_if_varsub(varname string, varholder string, templ
} }
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Out Value:",out) fmt.Println("Out Value:", out)
fmt.Println("Out Kind:",cur.Kind()) fmt.Println("Out Kind:", cur.Kind())
fmt.Println("Out Type:",cur.Type().Name()) fmt.Println("Out Type:", cur.Type().Name())
} }
_, ok := c.stats[out] _, ok := c.stats[out]
@ -882,9 +880,9 @@ func (c *CTemplateSet) compile_boolsub(varname string, varholder string, templat
case reflect.String: out += " != \"\"" case reflect.String: out += " != \"\""
case reflect.Int64: out += " > 0" case reflect.Int64: out += " > 0"
default: default:
fmt.Println("Variable Name:",varname) fmt.Println("Variable Name:", varname)
fmt.Println("Variable Holder:",varholder) fmt.Println("Variable Holder:", varholder)
fmt.Println("Variable Kind:",val.Kind()) fmt.Println("Variable Kind:", val.Kind())
panic("I don't know what this variable's type is o.o\n") panic("I don't know what this variable's type is o.o\n")
} }
return out return out
@ -930,9 +928,9 @@ func (c *CTemplateSet) compile_varsub(varname string, val reflect.Value) string
if !val.IsValid() { if !val.IsValid() {
panic(varname + "^\n" + "Invalid value. Maybe, it doesn't exist?") panic(varname + "^\n" + "Invalid value. Maybe, it doesn't exist?")
} }
fmt.Println("Unknown Variable Name:",varname) fmt.Println("Unknown Variable Name:", varname)
fmt.Println("Unknown Kind:",val.Kind()) fmt.Println("Unknown Kind:", val.Kind())
fmt.Println("Unknown Type:",val.Type().Name()) fmt.Println("Unknown Type:", val.Type().Name())
panic("// I don't know what this variable's type is o.o\n") panic("// I don't know what this variable's type is o.o\n")
} }
} }
@ -940,7 +938,7 @@ func (c *CTemplateSet) compile_varsub(varname string, val reflect.Value) string
func (c *CTemplateSet) compile_subtemplate(pvarholder string, pholdreflect reflect.Value, node *parse.TemplateNode) (out string) { func (c *CTemplateSet) compile_subtemplate(pvarholder string, pholdreflect reflect.Value, node *parse.TemplateNode) (out string) {
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("in compile_subtemplate") fmt.Println("in compile_subtemplate")
fmt.Println("Template Node: " + node.Name) fmt.Println("Template Node:", node.Name)
} }
fname := strings.TrimSuffix(node.Name, filepath.Ext(node.Name)) fname := strings.TrimSuffix(node.Name, filepath.Ext(node.Name))
@ -963,6 +961,7 @@ func (c *CTemplateSet) compile_subtemplate(pvarholder string, pholdreflect refle
} }
} }
// TO-DO: Cascade errors back up the tree to the caller?
res, err := ioutil.ReadFile(c.dir + node.Name) res, err := ioutil.ReadFile(c.dir + node.Name)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -983,7 +982,7 @@ func (c *CTemplateSet) compile_subtemplate(pvarholder string, pholdreflect refle
c.tlist[fname] = tree c.tlist[fname] = tree
subtree := c.tlist[fname] subtree := c.tlist[fname]
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println(subtree.Root) fmt.Println("subtree.Root", subtree.Root)
} }
c.localVars[fname] = make(map[string]VarItemReflect) c.localVars[fname] = make(map[string]VarItemReflect)
@ -993,7 +992,7 @@ func (c *CTemplateSet) compile_subtemplate(pvarholder string, pholdreflect refle
treeLength := len(subtree.Root.Nodes) treeLength := len(subtree.Root.Nodes)
for index, node := range subtree.Root.Nodes { for index, node := range subtree.Root.Nodes {
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("Node:",node.String()) fmt.Println("Node:", node.String())
} }
c.previousNode = c.currentNode c.previousNode = c.currentNode

106
themes.go
View File

@ -4,10 +4,10 @@ package main
import ( import (
//"fmt" //"fmt"
"log" "log"
"io"
"os" "os"
"bytes" "bytes"
"strings" "strings"
"errors"
"mime" "mime"
"io/ioutil" "io/ioutil"
"path/filepath" "path/filepath"
@ -39,6 +39,7 @@ type Theme struct
Settings map[string]ThemeSetting Settings map[string]ThemeSetting
Templates []TemplateMapping Templates []TemplateMapping
TemplatesMap map[string]string TemplatesMap map[string]string
TmplPtr map[string]interface{} // Coming Soon
Resources []ThemeResource Resources []ThemeResource
ResourceTemplates *template.Template ResourceTemplates *template.Template
@ -224,54 +225,63 @@ func map_theme_templates(theme Theme) {
} }
switch d_tmpl_ptr := dest_tmpl_ptr.(type) { switch d_tmpl_ptr := dest_tmpl_ptr.(type) {
case *func(TopicPage,io.Writer): case *func(TopicPage,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) { switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(TopicPage,io.Writer): case *func(TopicPage,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr //overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr *d_tmpl_ptr = *s_tmpl_ptr
default: default:
log.Fatal("The source and destination templates are incompatible") log.Fatal("The source and destination templates are incompatible")
} }
case *func(TopicsPage,io.Writer): case *func(TopicsPage,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) { switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(TopicsPage,io.Writer): case *func(TopicsPage,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr //overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr *d_tmpl_ptr = *s_tmpl_ptr
default: default:
log.Fatal("The source and destination templates are incompatible") log.Fatal("The source and destination templates are incompatible")
} }
case *func(ForumPage,io.Writer): case *func(ForumPage,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) { switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(ForumPage,io.Writer): case *func(ForumPage,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr //overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr *d_tmpl_ptr = *s_tmpl_ptr
default: default:
log.Fatal("The source and destination templates are incompatible") log.Fatal("The source and destination templates are incompatible")
} }
case *func(ForumsPage,io.Writer): case *func(ForumsPage,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) { switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(ForumsPage,io.Writer): case *func(ForumsPage,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr //overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr *d_tmpl_ptr = *s_tmpl_ptr
default: default:
log.Fatal("The source and destination templates are incompatible") log.Fatal("The source and destination templates are incompatible")
} }
case *func(ProfilePage,io.Writer): case *func(ProfilePage,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) { switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(ProfilePage,io.Writer): case *func(ProfilePage,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr //overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr *d_tmpl_ptr = *s_tmpl_ptr
default: default:
log.Fatal("The source and destination templates are incompatible") log.Fatal("The source and destination templates are incompatible")
} }
case *func(Page,io.Writer): case *func(CreateTopicPage,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) { switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(Page,io.Writer): case *func(CreateTopicPage,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr
default:
log.Fatal("The source and destination templates are incompatible")
}
case *func(Page,http.ResponseWriter):
switch s_tmpl_ptr := source_tmpl_ptr.(type) {
case *func(Page,http.ResponseWriter):
//overriden_templates[themeTmpl.Name] = d_tmpl_ptr //overriden_templates[themeTmpl.Name] = d_tmpl_ptr
overriden_templates[themeTmpl.Name] = true overriden_templates[themeTmpl.Name] = true
*d_tmpl_ptr = *s_tmpl_ptr *d_tmpl_ptr = *s_tmpl_ptr
@ -307,37 +317,51 @@ func reset_template_overrides() {
// Not really a pointer, more of a function handle, an artifact from one of the earlier versions of themes.go // Not really a pointer, more of a function handle, an artifact from one of the earlier versions of themes.go
switch o_ptr := origin_pointer.(type) { switch o_ptr := origin_pointer.(type) {
case func(TopicPage,io.Writer): case func(TopicPage,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) { switch d_ptr := dest_tmpl_ptr.(type) {
case *func(TopicPage,io.Writer): case *func(TopicPage,http.ResponseWriter):
*d_ptr = o_ptr *d_ptr = o_ptr
default: default:
log.Fatal("The origin and destination templates are incompatible") log.Fatal("The origin and destination templates are incompatible")
} }
case func(TopicsPage,io.Writer): case func(TopicsPage,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) { switch d_ptr := dest_tmpl_ptr.(type) {
case *func(TopicsPage,io.Writer): case *func(TopicsPage,http.ResponseWriter):
*d_ptr = o_ptr *d_ptr = o_ptr
default: default:
log.Fatal("The origin and destination templates are incompatible") log.Fatal("The origin and destination templates are incompatible")
} }
case func(ForumPage,io.Writer): case func(ForumPage,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) { switch d_ptr := dest_tmpl_ptr.(type) {
case *func(ForumPage,io.Writer): case *func(ForumPage,http.ResponseWriter):
*d_ptr = o_ptr *d_ptr = o_ptr
default: default:
log.Fatal("The origin and destination templates are incompatible") log.Fatal("The origin and destination templates are incompatible")
} }
case func(ForumsPage,io.Writer): case func(ForumsPage,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) { switch d_ptr := dest_tmpl_ptr.(type) {
case *func(ForumsPage,io.Writer): case *func(ForumsPage,http.ResponseWriter):
*d_ptr = o_ptr *d_ptr = o_ptr
default: default:
log.Fatal("The origin and destination templates are incompatible") log.Fatal("The origin and destination templates are incompatible")
} }
case func(ProfilePage,io.Writer): case func(ProfilePage,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) { switch d_ptr := dest_tmpl_ptr.(type) {
case *func(ProfilePage,io.Writer): case *func(ProfilePage,http.ResponseWriter):
*d_ptr = o_ptr
default:
log.Fatal("The origin and destination templates are incompatible")
}
case func(CreateTopicPage,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) {
case *func(CreateTopicPage,http.ResponseWriter):
*d_ptr = o_ptr
default:
log.Fatal("The origin and destination templates are incompatible")
}
case func(Page,http.ResponseWriter):
switch d_ptr := dest_tmpl_ptr.(type) {
case *func(Page,http.ResponseWriter):
*d_ptr = o_ptr *d_ptr = o_ptr
default: default:
log.Fatal("The origin and destination templates are incompatible") log.Fatal("The origin and destination templates are incompatible")
@ -350,3 +374,39 @@ func reset_template_overrides() {
overriden_templates = make(map[string]bool) overriden_templates = make(map[string]bool)
log.Print("All of the template overrides have been reset") log.Print("All of the template overrides have been reset")
} }
// NEW method of doing theme templates to allow one user to have a different theme to another. Under construction.
// TO-DO: Generate the type switch instead of writing it by hand
func RunThemeTemplate(theme string, template string, pi interface{}, w http.ResponseWriter) {
switch tmpl := GetThemeTemplate(theme,template).(type) {
case func(TopicPage,http.ResponseWriter): tmpl(pi.(TopicPage),w)
case func(TopicsPage,http.ResponseWriter): tmpl(pi.(TopicsPage),w)
case func(ForumPage,http.ResponseWriter): tmpl(pi.(ForumPage),w)
case func(ForumsPage,http.ResponseWriter): tmpl(pi.(ForumsPage),w)
case func(ProfilePage,http.ResponseWriter): tmpl(pi.(ProfilePage),w)
case func(CreateTopicPage,http.ResponseWriter): tmpl(pi.(CreateTopicPage),w)
case func(Page,http.ResponseWriter): tmpl(pi.(Page),w)
default: LogError(errors.New("Unknown template type"))
}
}
func GetThemeTemplate(theme string, template string) interface{} {
tmpl, ok := themes[theme].TmplPtr[template]
if !ok {
return tmpl
}
return nil
}
func CreateThemeTemplate(theme string, name string) {
themes[theme].TmplPtr[name] = func(pi ProfilePage, w http.ResponseWriter) {
mapping, ok := themes[defaultTheme].TemplatesMap[name]
if !ok {
mapping = name
}
err := templates.ExecuteTemplate(w, mapping + ".html", pi)
if err != nil {
InternalError(err,w)
}
}
}

View File

@ -24,12 +24,12 @@ ul {
padding-left: 15%; padding-left: 15%;
padding-right: 15%; padding-right: 15%;
margin: 0; margin: 0;
height: 45px; height: 41px;
} }
li { li {
float: left; float: left;
height: 35px; height: 29.5px;
padding-top: 12px; padding-top: 12px;
margin: 0; margin: 0;
} }
@ -65,7 +65,7 @@ li {
.alert_counter { .alert_counter {
background-color: rgb(200,0,0); background-color: rgb(200,0,0);
border-radius: 2px; border-radius: 2px;
font-size: 12px; font-size: 11px;
padding: 3px; padding: 3px;
float: right; float: right;
position: relative; position: relative;
@ -75,7 +75,7 @@ li {
.alert_aftercounter { .alert_aftercounter {
float: right; float: right;
margin-right: 4px; margin-right: 4px;
font-size: 15px; font-size: 14px;
} }
.alert_aftercounter:before { .alert_aftercounter:before {
content: "Alerts"; content: "Alerts";
@ -578,6 +578,23 @@ input, select, textarea {
.rowsmall { .rowsmall {
font-size: 11px; font-size: 11px;
} }
@media(min-width: 400px) {
ul {
height: 40px;
}
.menu_overview {
font-size: 16px;
}
.menu_left:not(.menu_overview) {
font-size: 14px;
padding-top: 13px;
}
.alert_aftercounter {
font-size: 14px;
padding-top: 4px;
}
}
} }
@media(max-width: 520px) { @media(max-width: 520px) {

View File

@ -116,7 +116,7 @@ func get_topicuser(tid int) (TopicUser,error) {
tu.UserLink = build_profile_url(name_to_slug(tu.CreatedByName),tu.CreatedBy) tu.UserLink = build_profile_url(name_to_slug(tu.CreatedByName),tu.CreatedBy)
the_topic := Topic{ID:tu.ID, Link:tu.Link, Title:tu.Title, Content:tu.Content, CreatedBy:tu.CreatedBy, Is_Closed:tu.Is_Closed, Sticky:tu.Sticky, CreatedAt:tu.CreatedAt, LastReplyAt:tu.LastReplyAt, ParentID:tu.ParentID, IpAddress:tu.IpAddress, PostCount:tu.PostCount, LikeCount:tu.LikeCount} the_topic := Topic{ID:tu.ID, Link:tu.Link, Title:tu.Title, Content:tu.Content, CreatedBy:tu.CreatedBy, Is_Closed:tu.Is_Closed, Sticky:tu.Sticky, CreatedAt:tu.CreatedAt, LastReplyAt:tu.LastReplyAt, ParentID:tu.ParentID, IpAddress:tu.IpAddress, PostCount:tu.PostCount, LikeCount:tu.LikeCount}
//fmt.Printf("%+v\n", the_topic) //log.Printf("the_topic: %+v\n", the_topic)
tu.Tag = groups[tu.Group].Tag tu.Tag = groups[tu.Group].Tag
topics.Add(&the_topic) topics.Add(&the_topic)
return tu, err return tu, err

12
user.go
View File

@ -118,7 +118,7 @@ func BuildWidgets(zone string, data interface{}, headerVars *HeaderVars, r *http
} }
} }
//fmt.Println("themes[defaultTheme].Sidebars",themes[defaultTheme].Sidebars) //log.Print("themes[defaultTheme].Sidebars",themes[defaultTheme].Sidebars)
if themes[defaultTheme].Sidebars == "right" { if themes[defaultTheme].Sidebars == "right" {
if len(docks.RightSidebar) != 0 { if len(docks.RightSidebar) != 0 {
var sbody string var sbody string
@ -184,8 +184,8 @@ func _forum_session_check(w http.ResponseWriter, r *http.Request, user *User, fi
} }
fperms := groups[user.Group].Forums[fid] fperms := groups[user.Group].Forums[fid]
//fmt.Printf("%+v\n", user.Perms) //log.Printf("user.Perms: %+v\n", user.Perms)
//fmt.Printf("%+v\n", fperms) //log.Printf("fperms: %+v\n", fperms)
if fperms.Overrides && !user.Is_Super_Admin { if fperms.Overrides && !user.Is_Super_Admin {
user.Perms.ViewTopic = fperms.ViewTopic user.Perms.ViewTopic = fperms.ViewTopic
user.Perms.LikeItem = fperms.LikeItem user.Perms.LikeItem = fperms.LikeItem
@ -306,7 +306,7 @@ func _pre_route(w http.ResponseWriter, r *http.Request) (User,bool) {
if host != user.Last_IP { if host != user.Last_IP {
_, err = update_last_ip_stmt.Exec(host, user.ID) _, err = update_last_ip_stmt.Exec(host, user.ID)
if err != nil { if err != nil {
InternalError(err,w,r) InternalError(err,w)
return *user, false return *user, false
} }
user.Last_IP = host user.Last_IP = host
@ -362,8 +362,8 @@ func increase_post_user_stats(wcount int, uid int, topic bool, user User) error
if err != nil { if err != nil {
return err return err
} }
//fmt.Println(user.Score + base_score + mod) //log.Print(user.Score + base_score + mod)
//fmt.Println(getLevel(user.Score + base_score + mod)) //log.Print(getLevel(user.Score + base_score + mod))
_, err = update_user_level_stmt.Exec(getLevel(user.Score + base_score + mod), uid) _, err = update_user_level_stmt.Exec(getLevel(user.Score + base_score + mod), uid)
return err return err
} }

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"log" "log"
"sync" "sync"
"errors" "errors"
@ -210,10 +209,10 @@ func (sus *MemoryUserStore) BulkCascadeGetMap(ids []int) (list map[int]*User, er
// We probably don't need this, but it might be useful in case of bugs in BulkCascadeGetMap // We probably don't need this, but it might be useful in case of bugs in BulkCascadeGetMap
if sid_list == "" { if sid_list == "" {
if dev.DebugMode { if dev.DebugMode {
fmt.Println("This data is sampled later in the BulkCascadeGetMap function, so it might miss the cached IDs") log.Print("This data is sampled later in the BulkCascadeGetMap function, so it might miss the cached IDs")
fmt.Println("id_count",id_count) log.Print("id_count",id_count)
fmt.Println("ids",ids) log.Print("ids",ids)
fmt.Println("list",list) log.Print("list",list)
} }
return list, errors.New("We weren't able to find a user, but we don't know which one") return list, errors.New("We weren't able to find a user, but we don't know which one")
} }

View File

@ -244,6 +244,12 @@ func weak_password(password string) error {
return nil return nil
} }
func create_file(name string) error {
f, err := os.Create(name)
f.Close()
return err
}
func write_file(name string, content string) (err error) { func write_file(name string, content string) (err error) {
f, err := os.Create(name) f, err := os.Create(name)
if err != nil { if err != nil {

View File

@ -88,7 +88,7 @@ func (hub *WS_Hub) push_message(targetUser int, msg string) error {
} }
func(hub *WS_Hub) push_alert(targetUser int, event string, elementType string, actor_id int, targetUser_id int, elementID int) error { func(hub *WS_Hub) push_alert(targetUser int, event string, elementType string, actor_id int, targetUser_id int, elementID int) error {
//fmt.Println("In push_alert") //log.Print("In push_alert")
hub.users.RLock() hub.users.RLock()
ws_user, ok := hub.online_users[targetUser] ws_user, ok := hub.online_users[targetUser]
hub.users.RUnlock() hub.users.RUnlock()
@ -96,13 +96,13 @@ func(hub *WS_Hub) push_alert(targetUser int, event string, elementType string, a
return ws_nouser return ws_nouser
} }
//fmt.Println("Building alert") //log.Print("Building alert")
alert, err := build_alert(event, elementType, actor_id, targetUser_id, elementID, *ws_user.User) alert, err := build_alert(event, elementType, actor_id, targetUser_id, elementID, *ws_user.User)
if err != nil { if err != nil {
return err return err
} }
//fmt.Println("Getting WS Writer") //log.Print("Getting WS Writer")
w, err := ws_user.conn.NextWriter(websocket.TextMessage) w, err := ws_user.conn.NextWriter(websocket.TextMessage)
if err != nil { if err != nil {
return err return err
@ -114,7 +114,7 @@ func(hub *WS_Hub) push_alert(targetUser int, event string, elementType string, a
} }
func(hub *WS_Hub) push_alerts(users []int, event string, elementType string, actor_id int, targetUser_id int, elementID int) error { func(hub *WS_Hub) push_alerts(users []int, event string, elementType string, actor_id int, targetUser_id int, elementID int) error {
//fmt.Println("In push_alerts") //log.Print("In push_alerts")
var ws_users []*WS_User var ws_users []*WS_User
hub.users.RLock() hub.users.RLock()
// We don't want to keep a lock on this for too long, so we'll accept some nil pointers // We don't want to keep a lock on this for too long, so we'll accept some nil pointers
@ -132,13 +132,13 @@ func(hub *WS_Hub) push_alerts(users []int, event string, elementType string, act
continue continue
} }
//fmt.Println("Building alert") //log.Print("Building alert")
alert, err := build_alert(event, elementType, actor_id, targetUser_id, elementID, *ws_user.User) alert, err := build_alert(event, elementType, actor_id, targetUser_id, elementID, *ws_user.User)
if err != nil { if err != nil {
errs = append(errs,err) errs = append(errs,err)
} }
//fmt.Println("Getting WS Writer") //log.Print("Getting WS Writer")
w, err := ws_user.conn.NextWriter(websocket.TextMessage) w, err := ws_user.conn.NextWriter(websocket.TextMessage)
if err != nil { if err != nil {
errs = append(errs,err) errs = append(errs,err)
@ -196,12 +196,12 @@ func route_websockets(w http.ResponseWriter, r *http.Request, user User) {
break break
} }
//fmt.Println("Message",message) //log.Print("Message",message)
//fmt.Println("Message",string(message)) //log.Print("string(Message)",string(message))
messages := bytes.Split(message,[]byte("\r")) messages := bytes.Split(message,[]byte("\r"))
for _, msg := range messages { for _, msg := range messages {
//fmt.Println("Submessage",msg) //log.Print("Submessage",msg)
//fmt.Println("Submessage",string(msg)) //log.Print("Submessage",string(msg))
if bytes.HasPrefix(msg,[]byte("page ")) { if bytes.HasPrefix(msg,[]byte("page ")) {
msgblocks := bytes.SplitN(msg,[]byte(" "),2) msgblocks := bytes.SplitN(msg,[]byte(" "),2)
if len(msgblocks) < 2 { if len(msgblocks) < 2 {
@ -211,8 +211,8 @@ func route_websockets(w http.ResponseWriter, r *http.Request, user User) {
if !bytes.Equal(msgblocks[1],current_page) { if !bytes.Equal(msgblocks[1],current_page) {
ws_leave_page(ws_user, current_page) ws_leave_page(ws_user, current_page)
current_page = msgblocks[1] current_page = msgblocks[1]
//fmt.Println("Current Page: ",current_page) //log.Print("Current Page:",current_page)
//fmt.Println("Current Page: ",string(current_page)) //log.Print("Current Page:",string(current_page))
ws_page_responses(ws_user, current_page) ws_page_responses(ws_user, current_page)
} }
} }
@ -229,14 +229,14 @@ func route_websockets(w http.ResponseWriter, r *http.Request, user User) {
func ws_page_responses(ws_user *WS_User, page []byte) { func ws_page_responses(ws_user *WS_User, page []byte) {
switch(string(page)) { switch(string(page)) {
case "/panel/": case "/panel/":
//fmt.Println("/panel/ WS Route") //log.Print("/panel/ WS Route")
/*w, err := ws_user.conn.NextWriter(websocket.TextMessage) /*w, err := ws_user.conn.NextWriter(websocket.TextMessage)
if err != nil { if err != nil {
//fmt.Println(err.Error()) //log.Print(err.Error())
return return
} }
fmt.Println(ws_hub.online_users) log.Print(ws_hub.online_users)
uonline := ws_hub.user_count() uonline := ws_hub.user_count()
gonline := ws_hub.guest_count() gonline := ws_hub.guest_count()
totonline := uonline + gonline totonline := uonline + gonline
@ -392,7 +392,7 @@ AdminStatLoop:
for watcher, _ := range watchers { for watcher, _ := range watchers {
w, err := watcher.conn.NextWriter(websocket.TextMessage) w, err := watcher.conn.NextWriter(websocket.TextMessage)
if err != nil { if err != nil {
//fmt.Println(err.Error()) //log.Print(err.Error())
admin_stats_mutex.Lock() admin_stats_mutex.Lock()
delete(admin_stats_watchers,watcher) delete(admin_stats_watchers,watcher)
admin_stats_mutex.Unlock() admin_stats_mutex.Unlock()

View File

@ -1,7 +1,7 @@
/* Copyright Azareal 2017 - 2018 */ /* Copyright Azareal 2017 - 2018 */
package main package main
import "fmt" import "log"
import "bytes" import "bytes"
import "sync" import "sync"
import "encoding/json" import "encoding/json"
@ -100,8 +100,8 @@ func init_widgets() error {
widget_update_mutex.Unlock() widget_update_mutex.Unlock()
if dev.SuperDebug { if dev.SuperDebug {
fmt.Println("docks.LeftSidebar",docks.LeftSidebar) log.Print("docks.LeftSidebar",docks.LeftSidebar)
fmt.Println("docks.RightSidebar",docks.RightSidebar) log.Print("docks.RightSidebar",docks.RightSidebar)
} }
return nil return nil