Changed tags to allow same-name taggs with different categories, added tag list

This commit is contained in:
2017-10-14 13:57:17 +02:00
parent 4b814cedad
commit 85bf3a73db
10 changed files with 220 additions and 13 deletions
+38 -7
View File
@@ -129,8 +129,9 @@ func (tag Tag) Hook() string {
return strings.Replace(tag.Name, " ", "_", -1)
}
// FindTag finds a tag by ID
func FindTag(key string, id string) (*Tag, error) {
// FindTag finds a tag by ID. Leave tagtype blank to ignore it. Both key and
// id are checked against their respective lists to prevent SQL injection attacks.
func FindTag(key string, id string, tagType string) (*Tag, error) {
db := server.Main.DB
// Make damn sure that – should this take user data as key – it
@@ -139,7 +140,24 @@ func FindTag(key string, id string) (*Tag, error) {
return nil, errors.New("invalid key")
}
rows, err := db.Query("SELECT id,type,name FROM `tag` WHERE "+key+"=? AND disabled=false", id)
query := "SELECT id,type,name FROM `tag` WHERE " + key + "=? AND disabled=false"
if tagType != "" {
// Prevent more shenanigans
found := false
for _, existing := range TagTypes {
if existing == tagType {
found = true
break
}
}
if !found {
return nil, errors.New("invalid tag type")
}
query += fmt.Sprintf(` AND type="%s"`, tagType)
}
rows, err := db.Query(query, id)
if err != nil {
return nil, err
}
@@ -156,7 +174,7 @@ func FindTag(key string, id string) (*Tag, error) {
// EnsureTag finds or creates a tag.
func EnsureTag(tagType, tagName string) (*Tag, error) {
// Try to find it first
tag, err := FindTag("name", tagName)
tag, err := FindTag("name", tagName, tagType)
if err != nil && err.Error() != "not found" { // You saw nothing
return nil, err
}
@@ -179,7 +197,15 @@ func EnsureTag(tagType, tagName string) (*Tag, error) {
func ListTags() ([]Tag, error) {
db := server.Main.DB
rows, err := db.Query("SELECT id,type,name FROM `tag` WHERE disabled=false")
query := `
SELECT id,type,name,count(pt.page_id) FROM tag
LEFT JOIN page_tag AS pt ON (pt.tag_id = tag.id)
WHERE disabled=false
GROUP BY pt.tag_id
ORDER BY type,name
`
rows, err := db.Query(query)
if err != nil {
return nil, err
}
@@ -187,9 +213,14 @@ func ListTags() ([]Tag, error) {
results := make([]Tag, 0, 64)
for rows.Next() {
count := 0
tag := Tag{}
rows.Scan(&tag.ID, &tag.Type, &tag.Name)
results = append(results, tag)
rows.Scan(&tag.ID, &tag.Type, &tag.Name, &count)
// Let's pretend unused tags don't exist. >_>
if count > 0 {
results = append(results, tag)
}
}
return results, nil