Compare commits

...

2 Commits

Author SHA1 Message Date
a 6d4bd5cdf2 remove more useless files 2022-02-21 03:16:28 +00:00
a 89265ee383 remove more useless files 2022-02-21 03:16:15 +00:00
227 changed files with 10880 additions and 11945 deletions

View File

@ -1,3 +0,0 @@
# Gosora doesn't use Apache, this file is just here to stop Apache from blindly serving our config files, etc. when this program isn't intended to be served in such a manner at all
deny from all

View File

@ -1,26 +0,0 @@
language: go
go:
- "1.13"
- "1.14"
- "1.15"
- "1.16"
- master
before_install:
- cd $HOME
- git clone https://github.com/Azareal/Gosora gosora
- cd gosora
- chmod -R 0777 .
- mv ./config/config_example.json ./config/config.json
- ./update-deps-linux
- ./dev-update-travis
- mv ./experimental/plugin_sendmail.go ..
install: true
before_script:
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- ./cc-test-reporter before-build
script: ./run-linux-tests
after_script:
- ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
addons:
mariadb: '10.3'

View File

@ -1,4 +1,4 @@
// Place your settings in this file to overwrite default and user settings.
{
"editor.insertSpaces": false
"editor.insertSpaces": true
}

View File

@ -1,53 +0,0 @@
# Contributing
First and foremost, if you want to add a contribution, you'll have to open a pull request and to sign the CLA (contributor level agreement).
It's mainly there to deal with any legal issues which may come our way and to switch licenses without having to track down every contributor who has ever contributed.
Some things we could do is commercial licensing for companies which are not authorised to use open source licenses or moving to a more permissive license, although I'm not too experianced in these matters, if anyone has any ideas, then feel free to put them forward.
Try to prefix commits which introduce a lot of bugs or otherwise has a large impact on the usability of Gosora with UNSTABLE.
If something seems to be strange, then feel free to bring up an alternative for it, although I'd rather not get hung up on the little details, if it's something which is purely a matter of opinion.
# Coding Standards
All code must be unit tested where ever possible with the exception of JavaScript which is untestable with our current technologies, tread with caution there.
Use tabs not spaces for indentation.
# Golang
Use the standard linter and listen to what it tells you to do.
The route assignments in main.go are *legacy code*, add new routes to `router_gen/routes.go` instead.
Try to use the single responsibility principle where ever possible, with the exception for if doing so will cause a large performance drop. In other words, don't give your interfaces / structs too many responsibilities, keep them simple.
Avoid hand-rolling queries. Use the builders, a ready built statement or a datastore structure instead. Preferably a datastore.
Commits which require the patcher / update script to be run should be prefixed with "Database Changes: "
More coming up.
# JavaScript
Use semicolons at the end of statements. If you don't, you might wind up breaking a minifier or two.
Always use strict mode.
Don't worry about ES5, we're targetting modern browsers. If we decide to backport code to older browsers, then we'll transpile the files.
Please don't use await. It incurs too much of a cognitive overhead as to where and when you can use it. We can't use it everywhere quite yet, which means that we really should be using it nowhere.
Please don't abuse `const` just to shave off a few nanoseconds. Even in the Go server where I care about performance the most, I don't use const everywhere, only in about five spots in thirty thousand lines and I don't use it for performance at all there.
To keep consistency with Go code, variables must be camelCase.
# JSON
To keep consistency with Go code, map keys must be camelCase.
# Phrases
Try to keep the name of the phrase close to the actual phrase in english to make it easier for localisers to reason about which phrase is which.

189
README.md
View File

@ -1,189 +0,0 @@
# Gosora ![Build Status](https://travis-ci.org/Azareal/Gosora.svg?branch=master) [![Azareal's Discord Chat](https://img.shields.io/badge/style-Invite-7289DA.svg?style=flat&label=Discord)](https://discord.gg/eyYvtTf)
A super fast forum software written in Go. You can talk to us on our Discord chat!
The initial code-base was forked from one of my side projects, but has now gone far beyond that. We've moved along in a development and the software should be somewhat stable for general use.
Features may break from time to time, however I will generally try to warn of the biggest offenders in advance, so that you can tread with caution around certain commits, the upcoming v0.1 will undergo even more rigorous testing.
File an issue or open a topic on the forum, if there's something you want and you very well might find it landing in the software fairly quickly.
For plugin and theme developers, things are a little dicier, as the internal APIs and ways of writing themes are in constant flux, however some stability in that area should be coming fairly soon.
If you like this software, please give it a star and give us some feedback :)
If you dislike it, please give us some feedback on how to make it better! We're always looking for feedback. We love hearing your opinions. If there's something missing or something doesn't look quite right, don't worry! We plan to add many, many things in the run up to v0.1!
# Features
Standard Forum Functionality. All of the little things you would expect of any forum software. E.g. Common Moderation features, modlogs, theme system, avatars, bbcode parser, markdown parser, report system, per-forum permissions, group permissions and so on.
Custom Pages. There are some rough edges
Emojis. Allow your users to express themselves without resorting to serving tons upon tons of image files.
In-memory static file, forum and group caches. We have a slightly more dynamic cache for users and topics.
A profile system, including profile comments and moderation tools for the profile owner.
A template engine which compiles templates down to machine code. Over forty times faster than the standard template library `html/templates`, although it does remove some of the hand holding to achieve this. Compatible with templates written for `html/templates`, so you don't need to learn any new templating language.
A plugin system. We have a number of APIs and hooks for plugins, however they're currently subject to change and don't cover as much of the software as we'd like yet.
A responsive design. Looks great on mobile phones, tablets, laptops, desktops and more!
Other modern features like alerts, likes, advanced dashboard with live stats (CPU, RAM, online user count, and so on), etc.
# Requirements
Go 1.13 or newer - You will need to install this. Pick the .msi, if you want everything sorted out for you rather than having to go around updating the environment settings. https://golang.org/doc/install
For Ubuntu, you can consult: https://tecadmin.net/install-go-on-ubuntu/
You will also want to run `ln -s /usr/local/go/bin/go` (replace /usr/local with where ever you put Go), so that go becomes visible to other users.
If you followed the instructions above, you can update to the latest version of Go simply by deleting the `/go/` folder and replacing it with a `/go/` folder for the latest version of Go.
Git - You may need this for downloading updates via the updater. You might already have this installed on your server, if the `git` commands don't work, then install this. https://git-scm.com/downloads
MySQL Database - You will need to setup a MySQL Database somewhere. A MariaDB Database works equally well and is much faster than MySQL. You could use something like WNMP / XAMPP which have a little PHP script called PhpMyAdmin for managing MySQL databases or you could install MariaDB directly.
Download the .msi installer from [MariaDB](https://mariadb.com/downloads) and run that. You may want to set it up as a service to avoid running it every-time the computer starts up.
Instructions on how to set MariaDB up on Linux: https://downloads.mariadb.org/mariadb/repositories/
We recommend changing the root password (that is the password for the user 'root'). Remember that password, you will need it for the installation process. Of course, we would advise using a user other than root for maximum security, although that adds additional steps to the process of getting everything setup.
You might also want to run `mysql_secure_installation` to further harden (aka make it more secure) MySQL / MariaDB.
If you're using Ubuntu, you might want to look at: https://www.itzgeek.com/how-tos/linux/ubuntu-how-tos/install-mariadb-on-ubuntu-16-04.html
It's entirely possible that your host already has MySQL installed and ready to go, so you might be able to skip this step, particularly if it's a managed VPS or a shared host. Or they might have a quicker and easier method of setting up MySQL.
# How to download
For Linux, you can skip down to the Installation section as it covers this.
On Windows, you might want to try the [GosoraBootstrapper](https://github.com/Azareal/GosoraBootstrapper), if you can't find the command prompt or otherwise can't follow those instructions. It's just a matter of double-clicking on the bat file there and it'll download the rest of the files for you.
# Installation
Consult [installation](https://github.com/Azareal/Gosora/blob/master/docs/installation.md) for instructions on how to install Gosora.
# Updating
Consult [updating](https://github.com/Azareal/Gosora/blob/master/docs/updating.md) for instructions on how to update Gosora.
# Running the program
*Linux*
If you have setup a service, you can run:
`./pre-run-linux`
`service gosora start`
You can then, check Gosora's current status (to see if it started up properly) with:
`service gosora status`
And you can stop it with:
`service gosora stop`
If you haven't setup a service, you can run `./run-linux`, although you will be responsible for finding a way to run it in the background, so that it doesn't close when the terminal does.
One method might be to use: https://serverfault.com/questions/34750/is-it-possible-to-detach-a-process-from-its-terminal-or-i-should-have-used-s
*Windows*
Run `run.bat`, e.g. double-clicking on it.
# How do I install plugins?
For the default plugins like Markdown and Helloworld, you can find them in the Plugin Manager of your Control Panel. For ones which aren't included by default, you will need to drop them down in the `/extend/` directory.
You will then need to recompile Gosora in order to link the plugin code with Gosora's code. For plugins not written in Go (e.g. JavaScript), they will automatically show up in your Control Panel ready to be installed, although we currently don't support these types of plugins at this time.
There are also some experimental plugins in the `/experimental/` folder like plugin_sendmail which you may want to make use of, although there aren't any particular guarantees about whether they will continue to function or not.
We're currently in the process of moving plugins from the `/` to the `/extend/` folder, if there is a piece of functionality that you would like to tap into, but which you cannot from that package, then feel free to poke me, otherwise you may need to drop it in `/` and name the package accordingly.
# Images
![Shadow Theme](https://github.com/Azareal/Gosora/blob/master/images/shadow.png)
![Shadow Quick Topic](https://github.com/Azareal/Gosora/blob/master/images/quick-topics.png)
![Tempra Simple Theme](https://github.com/Azareal/Gosora/blob/master/images/tempra-simple.png)
![Tempra Simple Topic List](https://github.com/Azareal/Gosora/blob/master/images/topic-list.png)
![Tempra Simple Mobile](https://github.com/Azareal/Gosora/blob/master/images/tempra-simple-mobile-375px.png)
![Cosora Prototype WIP](https://github.com/Azareal/Gosora/blob/master/images/cosora-wip.png)
More images in the /images/ folder. Beware though, some of them are *really* outdated. Also, keep in mind that a new theme is in the works.
# Dependencies
These are the libraries and pieces of software which Gosora relies on to function, an "ingredients" list so to speak.
A few of these like Rez aren't currently in use, but are things we think we'll need in the very near future and want to have those things ready, so that we can quickly slot them in.
* Go 1.11+
* MariaDB (or any other MySQL compatible database engine). We'll allow other database engines in the future.
* github.com/go-sql-driver/mysql For interfacing with MariaDB.
* golang.org/x/crypto/bcrypt For hashing passwords.
* golang.org/x/crypto/argon2 For hashing passwords.
* github.com/Azareal/gopsutil For pulling information on CPU and memory usage. I've temporarily forked this, as we were having stability issues with the latest build.
* github.com/StackExchange/wmi Dependency for gopsutil on Windows.
* golang.org/x/sys/windows Also a dependency for gopsutil on Windows. This isn't needed at the moment, as I've rolled things back to an older more stable build.
* github.com/gorilla/websocket Needed for Gosora's Optional WebSockets Module.
* github.com/robertkrimen/otto Needed for the upcoming JS plugin type.
* gopkg.in/sourcemap.v1 Dependency for Otto.
* github.com/lib/pq For interfacing with PostgreSQL. You will be able to pick this instead of MariaDB soon.
* ithub.com/denisenkom/go-mssqldb For interfacing with MSSQL. You will be able to pick this instead of MSSQL soon.
* github.com/bamiaux/rez An image resizer (e.g. for spitting out thumbnails)
* github.com/esimov/caire The other image resizer, slower but may be useful for covering cases Rez does not. A third faster one we might point to at some point is probably Discord's Lilliput, however it requires a C Compiler and we don't want to add that as a dependency at this time.
* github.com/fsnotify/fsnotify A library for watching events on the file system.
* github.com/pkg/errors Some helpers to make it easier for us to track down bugs.
* More items to come here, our dependencies are going through a lot of changes, and I'll be documenting those soon ;)
# Bundled Plugins
There are several plugins which are bundled with the software by default. These cover various common tasks which aren't common enough to clutter the core with or which have competing implementation methods (E.g. plugin_markdown vs plugin_bbcode for post mark-up).
* Hey There / Skeleton / Hey There (JS Version) - Example plugins for helping you learn how to develop plugins.
* BBCode - A plugin in early development for converting BBCode Tags into HTML.
* Markdown - An extremely simple plugin for converting Markdown into HTML.
* Social Groups - An extremely unstable WIP plugin which lets users create their own little discussion areas which they can administrate / moderate on their own.
# Developers
There are a few things you'll need to know before running the more developer oriented features like the tests or the benchmarks.
The benchmarks are currently being rewritten as they're currently extremely serial which can lead to severe slow-downs when run on a home computer due to the benchmarks being run on the one core everything else is being run on (Browser, OS, etc.) and the tests not taking parallelism into account.

38
TODO.md
View File

@ -1,38 +0,0 @@
# TO-DO
Oh my, you caught me right at the start of this project. There's nothing to see here yet, asides from the absolute basics. You might want to look again later!
The various little features which somehow got stuck in the net. Don't worry, I'll get to them!
More moderation features. E.g. Move, Approval Queue (Posts made by users in certain usergroups will need to be approved by a moderator before they're publically visible), etc.
Add a simple anti-spam measure. I have quite a few ideas in mind, but it'll take a while to implement the more advanced ones, so I'd like to put off some of those to a later date and focus on the basics. E.g. CAPTCHAs, hidden fields, etc.
Add more granular permissions management to the Forum Manager.
Add a *better* plugin system. E.g. Allow for plugins written in Javascript and ones written in Go. Also, we need to add many, many, many more plugin hooks.
I will need to ponder over implementing an even faster router. We don't need one immediately, although it would be nice if we could get one in the near future. It really depends. Ideally, it would be one which can easily integrate with the current structure without much work, although I'm not beyond making some alterations to faciliate it, assuming that we don't get too tightly bound to that specific router.
Allow themes to define their own templates and to override core templates with their own.
Add a friend system.
Improve profile customisability.
Implement all the common BBCode tags in plugin_bbcode
Implement all the common Markdown codes in plugin_markdown
Add more administration features.
Add more features for improving user engagement. E.g. A like system. I have a few of these in mind, but I've been pre-occupied with implementing other features.
Add a widget system.
Add support for multi-factor authentication.
Add support for secondary emails for users.
Improve the shell scripts and possibly add support for Make? A make.go might be a good solution?

View File

@ -1,63 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the executable
go build -ldflags="-s -w" -o gosora.exe -tags no_ws
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the installer
go build -ldflags="-s -w" "./cmd/install"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Gosora was successfully built
pause

View File

@ -1,63 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the executable
go build -ldflags="-s -w" -o gosora.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the installer
go build -ldflags="-s -w" "./cmd/install"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Gosora was successfully built
pause

View File

@ -1,11 +0,0 @@
echo Building the templates
gosora.exe -build-templates
echo Rebuilding the executable
go build -ldflags="-s -w" -o gosora.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
pause

View File

@ -1,115 +1,115 @@
package hookgen
import (
"bytes"
"log"
"os"
"text/template"
"bytes"
"log"
"os"
"text/template"
)
type HookVars struct {
Imports []string
Hooks []Hook
Imports []string
Hooks []Hook
}
type Hook struct {
Name string
Params string
Params2 string
Ret string
Type string
Any bool
MultiHook bool
Skip bool
DefaultRet string
Pure string
Name string
Params string
Params2 string
Ret string
Type string
Any bool
MultiHook bool
Skip bool
DefaultRet string
Pure string
}
func AddHooks(add func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string)) {
vhookskip := func(name, params string) {
add(name, params, "(bool,RouteError)", "VhookSkippable_", false, true, "false,nil", "")
}
vhookskip("simple_forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *HeaderLite")
vhookskip("forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *Header")
vhookskip("router_after_filters", "w http.ResponseWriter,r *http.Request,prefix string")
vhookskip("router_pre_route", "w http.ResponseWriter,r *http.Request,u *User,prefix string")
vhookskip("route_forum_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
vhookskip("route_topic_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
vhookskip("route_attach_start", "w http.ResponseWriter,r *http.Request,u *User,fname string")
vhookskip("route_attach_post_get", "w http.ResponseWriter,r *http.Request,u *User,a *Attachment")
vhookskip := func(name, params string) {
add(name, params, "(bool,RouteError)", "VhookSkippable_", false, true, "false,nil", "")
}
vhookskip("simple_forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *HeaderLite")
vhookskip("forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *Header")
vhookskip("router_after_filters", "w http.ResponseWriter,r *http.Request,prefix string")
vhookskip("router_pre_route", "w http.ResponseWriter,r *http.Request,u *User,prefix string")
vhookskip("route_forum_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
vhookskip("route_topic_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
vhookskip("route_attach_start", "w http.ResponseWriter,r *http.Request,u *User,fname string")
vhookskip("route_attach_post_get", "w http.ResponseWriter,r *http.Request,u *User,a *Attachment")
vhooknoret := func(name, params string) {
add(name, params, "", "Vhooks", false, false, "false,nil", "")
}
vhooknoret("router_end", "w http.ResponseWriter,r *http.Request,u *User,prefix string,extraData string")
vhooknoret("topic_reply_row_assign", "r *ReplyUser")
vhooknoret("counters_perf_tick_row", "low int64,high int64,avg int64")
//forums_frow_assign
//Hook(name string, data interface{}) interface{}
/*hook := func(name, params, ret, pure string) {
add(name,params,ret,"Hooks",true,false,ret,pure)
}*/
vhooknoret := func(name, params string) {
add(name, params, "", "Vhooks", false, false, "false,nil", "")
}
vhooknoret("router_end", "w http.ResponseWriter,r *http.Request,u *User,prefix string,extraData string")
vhooknoret("topic_reply_row_assign", "r *ReplyUser")
vhooknoret("counters_perf_tick_row", "low int64,high int64,avg int64")
//forums_frow_assign
//Hook(name string, data interface{}) interface{}
/*hook := func(name, params, ret, pure string) {
add(name,params,ret,"Hooks",true,false,ret,pure)
}*/
hooknoret := func(name, params string) {
add(name, params, "", "HooksNoRet", true, false, "", "")
}
hooknoret("forums_frow_assign", "f *Forum")
hooknoret := func(name, params string) {
add(name, params, "", "HooksNoRet", true, false, "", "")
}
hooknoret("forums_frow_assign", "f *Forum")
hookskip := func(name, params string) {
add(name, params, "(skip bool)", "HooksSkip", true, true, "", "")
}
//hookskip("forums_frow_assign","f *Forum")
hookskip("topic_create_frow_assign", "f *Forum")
hookskip := func(name, params string) {
add(name, params, "(skip bool)", "HooksSkip", true, true, "", "")
}
//hookskip("forums_frow_assign","f *Forum")
hookskip("topic_create_frow_assign", "f *Forum")
hookss := func(name string) {
add(name, "d string", "string", "Sshooks", true, false, "", "d")
}
hookss("topic_ogdesc_assign")
hookss := func(name string) {
add(name, "d string", "string", "Sshooks", true, false, "", "d")
}
hookss("topic_ogdesc_assign")
}
func Write(hookVars HookVars) {
fileData := `// Code generated by Gosora's Hook Generator. DO NOT EDIT.
fileData := `// Code generated by Gosora's Hook Generator. DO NOT EDIT.
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
package common
import ({{range .Imports}}
"{{.}}"{{end}}
"{{.}}"{{end}}
)
{{range .Hooks}}
func H_{{.Name}}_hook(t *HookTable,{{.Params}}) {{.Ret}} { {{if .Any}}
{{if .MultiHook}}for _, hook := range t.{{.Type}}["{{.Name}}"] {
{{if .Skip}}if skip = hook({{.Params2}}); skip {
break
}{{else}}{{if .Pure}}{{.Pure}} = {{else if .Ret}}return {{end}}hook({{.Params2}}){{end}}
}{{else}}hook := t.{{.Type}}["{{.Name}}"]
if hook != nil {
{{if .Ret}}return {{end}}hook({{.Params2}})
} {{end}}{{end}}{{if .Pure}}
return {{.Pure}}{{else if .Ret}}
return {{.DefaultRet}}{{end}}
{{if .MultiHook}}for _, hook := range t.{{.Type}}["{{.Name}}"] {
{{if .Skip}}if skip = hook({{.Params2}}); skip {
break
}{{else}}{{if .Pure}}{{.Pure}} = {{else if .Ret}}return {{end}}hook({{.Params2}}){{end}}
}{{else}}hook := t.{{.Type}}["{{.Name}}"]
if hook != nil {
{{if .Ret}}return {{end}}hook({{.Params2}})
} {{end}}{{end}}{{if .Pure}}
return {{.Pure}}{{else if .Ret}}
return {{.DefaultRet}}{{end}}
}{{end}}
`
tmpl := template.Must(template.New("hooks").Parse(fileData))
var b bytes.Buffer
if e := tmpl.Execute(&b, hookVars); e != nil {
log.Fatal(e)
}
tmpl := template.Must(template.New("hooks").Parse(fileData))
var b bytes.Buffer
if e := tmpl.Execute(&b, hookVars); e != nil {
log.Fatal(e)
}
err := writeFile("./common/gen_extend.go", b.String())
if err != nil {
log.Fatal(err)
}
err := writeFile("./common/gen_extend.go", b.String())
if err != nil {
log.Fatal(err)
}
}
func writeFile(name, body string) error {
f, e := os.Create(name)
if e != nil {
return e
}
if _, e = f.WriteString(body); e != nil {
return e
}
if e = f.Sync(); e != nil {
return e
}
return f.Close()
f, e := os.Create(name)
if e != nil {
return e
}
if _, e = f.WriteString(body); e != nil {
return e
}
if e = f.Sync(); e != nil {
return e
}
return f.Close()
}

View File

@ -2,265 +2,265 @@
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"log"
"os"
"strconv"
"context"
"database/sql"
"encoding/json"
"errors"
"log"
"os"
"strconv"
c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/query_gen"
"gopkg.in/olivere/elastic.v6"
c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/query_gen"
"gopkg.in/olivere/elastic.v6"
)
func main() {
log.Print("Loading the configuration data")
err := c.LoadConfig()
if err != nil {
log.Fatal(err)
}
log.Print("Loading the configuration data")
err := c.LoadConfig()
if err != nil {
log.Fatal(err)
}
log.Print("Processing configuration data")
err = c.ProcessConfig()
if err != nil {
log.Fatal(err)
}
log.Print("Processing configuration data")
err = c.ProcessConfig()
if err != nil {
log.Fatal(err)
}
if c.DbConfig.Adapter != "mysql" && c.DbConfig.Adapter != "" {
log.Fatal("Only MySQL is supported for upgrades right now, please wait for a newer build of the patcher")
}
if c.DbConfig.Adapter != "mysql" && c.DbConfig.Adapter != "" {
log.Fatal("Only MySQL is supported for upgrades right now, please wait for a newer build of the patcher")
}
err = prepMySQL()
if err != nil {
log.Fatal(err)
}
err = prepMySQL()
if err != nil {
log.Fatal(err)
}
client, err := elastic.NewClient(elastic.SetErrorLog(log.New(os.Stdout, "ES ", log.LstdFlags)))
if err != nil {
log.Fatal(err)
}
_, _, err = client.Ping("http://127.0.0.1:9200").Do(context.Background())
if err != nil {
log.Fatal(err)
}
client, err := elastic.NewClient(elastic.SetErrorLog(log.New(os.Stdout, "ES ", log.LstdFlags)))
if err != nil {
log.Fatal(err)
}
_, _, err = client.Ping("http://127.0.0.1:9200").Do(context.Background())
if err != nil {
log.Fatal(err)
}
err = setupIndices(client)
if err != nil {
log.Fatal(err)
}
err = setupIndices(client)
if err != nil {
log.Fatal(err)
}
err = setupData(client)
if err != nil {
log.Fatal(err)
}
err = setupData(client)
if err != nil {
log.Fatal(err)
}
}
func prepMySQL() error {
return qgen.Builder.Init("mysql", map[string]string{
"host": c.DbConfig.Host,
"port": c.DbConfig.Port,
"name": c.DbConfig.Dbname,
"username": c.DbConfig.Username,
"password": c.DbConfig.Password,
"collation": "utf8mb4_general_ci",
})
return qgen.Builder.Init("mysql", map[string]string{
"host": c.DbConfig.Host,
"port": c.DbConfig.Port,
"name": c.DbConfig.Dbname,
"username": c.DbConfig.Username,
"password": c.DbConfig.Password,
"collation": "utf8mb4_general_ci",
})
}
type ESIndexBase struct {
Mappings ESIndexMappings `json:"mappings"`
Mappings ESIndexMappings `json:"mappings"`
}
type ESIndexMappings struct {
Doc ESIndexDoc `json:"_doc"`
Doc ESIndexDoc `json:"_doc"`
}
type ESIndexDoc struct {
Properties map[string]map[string]string `json:"properties"`
Properties map[string]map[string]string `json:"properties"`
}
type ESDocMap map[string]map[string]string
func (d ESDocMap) Add(column string, cType string) {
d["column"] = map[string]string{"type": cType}
d["column"] = map[string]string{"type": cType}
}
func setupIndices(client *elastic.Client) error {
exists, err := client.IndexExists("topics").Do(context.Background())
if err != nil {
return err
}
if exists {
deleteIndex, err := client.DeleteIndex("topics").Do(context.Background())
if err != nil {
return err
}
if !deleteIndex.Acknowledged {
return errors.New("delete not acknowledged")
}
}
exists, err := client.IndexExists("topics").Do(context.Background())
if err != nil {
return err
}
if exists {
deleteIndex, err := client.DeleteIndex("topics").Do(context.Background())
if err != nil {
return err
}
if !deleteIndex.Acknowledged {
return errors.New("delete not acknowledged")
}
}
docMap := make(ESDocMap)
docMap.Add("tid", "integer")
docMap.Add("title", "text")
docMap.Add("content", "text")
docMap.Add("createdBy", "integer")
docMap.Add("ip", "ip")
docMap.Add("suggest", "completion")
indexBase := ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
oBytes, err := json.Marshal(indexBase)
if err != nil {
return err
}
createIndex, err := client.CreateIndex("topics").Body(string(oBytes)).Do(context.Background())
if err != nil {
return err
}
if !createIndex.Acknowledged {
return errors.New("not acknowledged")
}
docMap := make(ESDocMap)
docMap.Add("tid", "integer")
docMap.Add("title", "text")
docMap.Add("content", "text")
docMap.Add("createdBy", "integer")
docMap.Add("ip", "ip")
docMap.Add("suggest", "completion")
indexBase := ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
oBytes, err := json.Marshal(indexBase)
if err != nil {
return err
}
createIndex, err := client.CreateIndex("topics").Body(string(oBytes)).Do(context.Background())
if err != nil {
return err
}
if !createIndex.Acknowledged {
return errors.New("not acknowledged")
}
exists, err = client.IndexExists("replies").Do(context.Background())
if err != nil {
return err
}
if exists {
deleteIndex, err := client.DeleteIndex("replies").Do(context.Background())
if err != nil {
return err
}
if !deleteIndex.Acknowledged {
return errors.New("delete not acknowledged")
}
}
exists, err = client.IndexExists("replies").Do(context.Background())
if err != nil {
return err
}
if exists {
deleteIndex, err := client.DeleteIndex("replies").Do(context.Background())
if err != nil {
return err
}
if !deleteIndex.Acknowledged {
return errors.New("delete not acknowledged")
}
}
docMap = make(ESDocMap)
docMap.Add("rid", "integer")
docMap.Add("tid", "integer")
docMap.Add("content", "text")
docMap.Add("createdBy", "integer")
docMap.Add("ip", "ip")
docMap.Add("suggest", "completion")
indexBase = ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
oBytes, err = json.Marshal(indexBase)
if err != nil {
return err
}
createIndex, err = client.CreateIndex("replies").Body(string(oBytes)).Do(context.Background())
if err != nil {
return err
}
if !createIndex.Acknowledged {
return errors.New("not acknowledged")
}
docMap = make(ESDocMap)
docMap.Add("rid", "integer")
docMap.Add("tid", "integer")
docMap.Add("content", "text")
docMap.Add("createdBy", "integer")
docMap.Add("ip", "ip")
docMap.Add("suggest", "completion")
indexBase = ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
oBytes, err = json.Marshal(indexBase)
if err != nil {
return err
}
createIndex, err = client.CreateIndex("replies").Body(string(oBytes)).Do(context.Background())
if err != nil {
return err
}
if !createIndex.Acknowledged {
return errors.New("not acknowledged")
}
return nil
return nil
}
type ESTopic struct {
ID int `json:"tid"`
Title string `json:"title"`
Content string `json:"content"`
CreatedBy int `json:"createdBy"`
IP string `json:"ip"`
ID int `json:"tid"`
Title string `json:"title"`
Content string `json:"content"`
CreatedBy int `json:"createdBy"`
IP string `json:"ip"`
}
type ESReply struct {
ID int `json:"rid"`
TID int `json:"tid"`
Content string `json:"content"`
CreatedBy int `json:"createdBy"`
IP string `json:"ip"`
ID int `json:"rid"`
TID int `json:"tid"`
Content string `json:"content"`
CreatedBy int `json:"createdBy"`
IP string `json:"ip"`
}
func setupData(client *elastic.Client) error {
tcount := 4
errs := make(chan error)
tcount := 4
errs := make(chan error)
go func() {
tin := make([]chan ESTopic, tcount)
tf := func(tin chan ESTopic) {
for {
topic, more := <-tin
if !more {
break
}
_, err := client.Index().Index("topics").Type("_doc").Id(strconv.Itoa(topic.ID)).BodyJson(topic).Do(context.Background())
if err != nil {
errs <- err
}
}
}
for i := 0; i < 4; i++ {
go tf(tin[i])
}
go func() {
tin := make([]chan ESTopic, tcount)
tf := func(tin chan ESTopic) {
for {
topic, more := <-tin
if !more {
break
}
_, err := client.Index().Index("topics").Type("_doc").Id(strconv.Itoa(topic.ID)).BodyJson(topic).Do(context.Background())
if err != nil {
errs <- err
}
}
}
for i := 0; i < 4; i++ {
go tf(tin[i])
}
oi := 0
err := qgen.NewAcc().Select("topics").Cols("tid,title,content,createdBy,ip").Each(func(rows *sql.Rows) error {
t := ESTopic{}
err := rows.Scan(&t.ID, &t.Title, &t.Content, &t.CreatedBy, &t.IP)
if err != nil {
return err
}
tin[oi] <- t
if oi < 3 {
oi++
}
return nil
})
for i := 0; i < 4; i++ {
close(tin[i])
}
errs <- err
}()
oi := 0
err := qgen.NewAcc().Select("topics").Cols("tid,title,content,createdBy,ip").Each(func(rows *sql.Rows) error {
t := ESTopic{}
err := rows.Scan(&t.ID, &t.Title, &t.Content, &t.CreatedBy, &t.IP)
if err != nil {
return err
}
tin[oi] <- t
if oi < 3 {
oi++
}
return nil
})
for i := 0; i < 4; i++ {
close(tin[i])
}
errs <- err
}()
go func() {
rin := make([]chan ESReply, tcount)
rf := func(rin chan ESReply) {
for {
reply, more := <-rin
if !more {
break
}
_, err := client.Index().Index("replies").Type("_doc").Id(strconv.Itoa(reply.ID)).BodyJson(reply).Do(context.Background())
if err != nil {
errs <- err
}
}
}
for i := 0; i < 4; i++ {
rf(rin[i])
}
oi := 0
err := qgen.NewAcc().Select("replies").Cols("rid,tid,content,createdBy,ip").Each(func(rows *sql.Rows) error {
r := ESReply{}
err := rows.Scan(&r.ID, &r.TID, &r.Content, &r.CreatedBy, &r.IP)
if err != nil {
return err
}
rin[oi] <- r
if oi < 3 {
oi++
}
return nil
})
for i := 0; i < 4; i++ {
close(rin[i])
}
errs <- err
}()
go func() {
rin := make([]chan ESReply, tcount)
rf := func(rin chan ESReply) {
for {
reply, more := <-rin
if !more {
break
}
_, err := client.Index().Index("replies").Type("_doc").Id(strconv.Itoa(reply.ID)).BodyJson(reply).Do(context.Background())
if err != nil {
errs <- err
}
}
}
for i := 0; i < 4; i++ {
rf(rin[i])
}
oi := 0
err := qgen.NewAcc().Select("replies").Cols("rid,tid,content,createdBy,ip").Each(func(rows *sql.Rows) error {
r := ESReply{}
err := rows.Scan(&r.ID, &r.TID, &r.Content, &r.CreatedBy, &r.IP)
if err != nil {
return err
}
rin[oi] <- r
if oi < 3 {
oi++
}
return nil
})
for i := 0; i < 4; i++ {
close(rin[i])
}
errs <- err
}()
fin := 0
for {
err := <-errs
if err == nil {
fin++
if fin == 2 {
return nil
}
} else {
return err
}
}
fin := 0
for {
err := <-errs
if err == nil {
fin++
if fin == 2 {
return nil
}
} else {
return err
}
}
}

View File

@ -3,67 +3,67 @@
package main // import "github.com/Azareal/Gosora/hook_gen"
import (
"fmt"
"log"
"runtime/debug"
"strings"
"fmt"
"log"
"runtime/debug"
"strings"
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
c "github.com/Azareal/Gosora/common"
_ "github.com/Azareal/Gosora/extend"
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
c "github.com/Azareal/Gosora/common"
_ "github.com/Azareal/Gosora/extend"
)
// TODO: Make sure all the errors in this file propagate upwards properly
func main() {
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
}
}()
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
}
}()
hooks := make(map[string]int)
for _, pl := range c.Plugins {
if len(pl.Meta.Hooks) > 0 {
for _, hook := range pl.Meta.Hooks {
hooks[hook]++
}
continue
}
if pl.Init != nil {
if e := pl.Init(pl); e != nil {
log.Print("early plugin init err: ", e)
return
}
}
if pl.Hooks != nil {
log.Print("Hooks not nil for ", pl.UName)
for hook, _ := range pl.Hooks {
hooks[hook] += 1
}
}
}
log.Printf("hooks: %+v\n", hooks)
hooks := make(map[string]int)
for _, pl := range c.Plugins {
if len(pl.Meta.Hooks) > 0 {
for _, hook := range pl.Meta.Hooks {
hooks[hook]++
}
continue
}
if pl.Init != nil {
if e := pl.Init(pl); e != nil {
log.Print("early plugin init err: ", e)
return
}
}
if pl.Hooks != nil {
log.Print("Hooks not nil for ", pl.UName)
for hook, _ := range pl.Hooks {
hooks[hook] += 1
}
}
}
log.Printf("hooks: %+v\n", hooks)
imports := []string{"net/http"}
hookVars := h.HookVars{imports, nil}
var params2sb strings.Builder
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
first := true
for _, param := range strings.Split(params, ",") {
if !first {
params2sb.WriteRune(',')
}
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param), " ", " "), " ")
params2sb.WriteString(pspl[0])
first = false
}
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2sb.String(), ret, htype, hooks[name] > 0, multiHook, skip, defaultRet, pure})
params2sb.Reset()
}
imports := []string{"net/http"}
hookVars := h.HookVars{imports, nil}
var params2sb strings.Builder
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
first := true
for _, param := range strings.Split(params, ",") {
if !first {
params2sb.WriteRune(',')
}
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param), " ", " "), " ")
params2sb.WriteString(pspl[0])
first = false
}
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2sb.String(), ret, htype, hooks[name] > 0, multiHook, skip, defaultRet, pure})
params2sb.Reset()
}
h.AddHooks(add)
h.Write(hookVars)
log.Println("Successfully generated the hooks")
h.AddHooks(add)
h.Write(hookVars)
log.Println("Successfully generated the hooks")
}

View File

@ -1,41 +1,41 @@
package main // import "github.com/Azareal/Gosora/hook_stub_gen"
import (
"fmt"
"log"
"strings"
"runtime/debug"
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
"fmt"
"log"
"strings"
"runtime/debug"
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
)
// TODO: Make sure all the errors in this file propagate upwards properly
func main() {
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
}
}()
imports := []string{"net/http"}
hookVars := h.HookVars{imports,nil}
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
var params2 string
first := true
for _, param := range strings.Split(params,",") {
if !first {
params2 += ","
}
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param)," "," ")," ")
params2 += pspl[0]
first = false
}
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2, ret, htype, true, multiHook, skip, defaultRet,pure})
}
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
}
}()
imports := []string{"net/http"}
hookVars := h.HookVars{imports,nil}
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
var params2 string
first := true
for _, param := range strings.Split(params,",") {
if !first {
params2 += ","
}
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param)," "," ")," ")
params2 += pspl[0]
first = false
}
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2, ret, htype, true, multiHook, skip, defaultRet,pure})
}
h.AddHooks(add)
h.Write(hookVars)
log.Println("Successfully generated the hooks")
h.AddHooks(add)
h.Write(hookVars)
log.Println("Successfully generated the hooks")
}

View File

@ -7,15 +7,15 @@
package main
import (
"bufio"
"errors"
"fmt"
"os"
"runtime/debug"
"strconv"
"strings"
"bufio"
"errors"
"fmt"
"os"
"runtime/debug"
"strconv"
"strings"
"github.com/Azareal/Gosora/install"
"github.com/Azareal/Gosora/install"
)
var scanner *bufio.Scanner
@ -35,287 +35,287 @@ var defaultsiteURL = "localhost"
var defaultServerPort = "80" // 8080's a good one, if you're testing and don't want it to clash with port 80
func main() {
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
pressAnyKey()
return
}
}()
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
pressAnyKey()
return
}
}()
scanner = bufio.NewScanner(os.Stdin)
fmt.Println("Welcome to Gosora's Installer")
fmt.Println("We're going to take you through a few steps to help you get started :)")
adap, ok := handleDatabaseDetails()
if !ok {
err := scanner.Err()
if err != nil {
fmt.Println(err)
} else {
err = errors.New("Something went wrong!")
}
abortError(err)
return
}
scanner = bufio.NewScanner(os.Stdin)
fmt.Println("Welcome to Gosora's Installer")
fmt.Println("We're going to take you through a few steps to help you get started :)")
adap, ok := handleDatabaseDetails()
if !ok {
err := scanner.Err()
if err != nil {
fmt.Println(err)
} else {
err = errors.New("Something went wrong!")
}
abortError(err)
return
}
if !getSiteDetails() {
err := scanner.Err()
if err != nil {
fmt.Println(err)
} else {
err = errors.New("Something went wrong!")
}
abortError(err)
return
}
if !getSiteDetails() {
err := scanner.Err()
if err != nil {
fmt.Println(err)
} else {
err = errors.New("Something went wrong!")
}
abortError(err)
return
}
err := adap.InitDatabase()
if err != nil {
abortError(err)
return
}
err := adap.InitDatabase()
if err != nil {
abortError(err)
return
}
err = adap.TableDefs()
if err != nil {
abortError(err)
return
}
err = adap.TableDefs()
if err != nil {
abortError(err)
return
}
err = adap.CreateAdmin()
if err != nil {
abortError(err)
return
}
err = adap.CreateAdmin()
if err != nil {
abortError(err)
return
}
err = adap.InitialData()
if err != nil {
abortError(err)
return
}
err = adap.InitialData()
if err != nil {
abortError(err)
return
}
configContents := []byte(`{
"Site": {
"ShortName":"` + siteShortName + `",
"Name":"` + siteName + `",
"URL":"` + siteURL + `",
"Port":"` + serverPort + `",
"EnableSsl":false,
"EnableEmails":false,
"HasProxy":false,
"Language": "english"
},
"Config": {
"SslPrivkey": "",
"SslFullchain": "",
"SMTPServer": "",
"SMTPUsername": "",
"SMTPPassword": "",
"SMTPPort": "25",
configContents := []byte(`{
"Site": {
"ShortName":"` + siteShortName + `",
"Name":"` + siteName + `",
"URL":"` + siteURL + `",
"Port":"` + serverPort + `",
"EnableSsl":false,
"EnableEmails":false,
"HasProxy":false,
"Language": "english"
},
"Config": {
"SslPrivkey": "",
"SslFullchain": "",
"SMTPServer": "",
"SMTPUsername": "",
"SMTPPassword": "",
"SMTPPort": "25",
"MaxRequestSizeStr":"5MB",
"UserCache":"static",
"TopicCache":"static",
"ReplyCache":"static",
"UserCacheCapacity":180,
"TopicCacheCapacity":400,
"ReplyCacheCapacity":20,
"DefaultPath":"/topics/",
"DefaultGroup":3,
"ActivationGroup":5,
"StaffCSS":"staff_post",
"DefaultForum":2,
"MinifyTemplates":true,
"BuildSlugs":true,
"ServerCount":1,
"Noavatar":"https://api.adorable.io/avatars/{width}/{id}.png",
"ItemsPerPage":25
},
"Database": {
"Adapter": "` + adap.Name() + `",
"Host": "` + adap.DBHost() + `",
"Username": "` + adap.DBUsername() + `",
"Password": "` + adap.DBPassword() + `",
"Dbname": "` + adap.DBName() + `",
"Port": "` + adap.DBPort() + `",
"MaxRequestSizeStr":"5MB",
"UserCache":"static",
"TopicCache":"static",
"ReplyCache":"static",
"UserCacheCapacity":180,
"TopicCacheCapacity":400,
"ReplyCacheCapacity":20,
"DefaultPath":"/topics/",
"DefaultGroup":3,
"ActivationGroup":5,
"StaffCSS":"staff_post",
"DefaultForum":2,
"MinifyTemplates":true,
"BuildSlugs":true,
"ServerCount":1,
"Noavatar":"https://api.adorable.io/avatars/{width}/{id}.png",
"ItemsPerPage":25
},
"Database": {
"Adapter": "` + adap.Name() + `",
"Host": "` + adap.DBHost() + `",
"Username": "` + adap.DBUsername() + `",
"Password": "` + adap.DBPassword() + `",
"Dbname": "` + adap.DBName() + `",
"Port": "` + adap.DBPort() + `",
"TestAdapter": "` + adap.Name() + `",
"TestHost": "",
"TestUsername": "",
"TestPassword": "",
"TestDbname": "",
"TestPort": ""
},
"Dev": {
"DebugMode":true,
"SuperDebug":false
}
"TestAdapter": "` + adap.Name() + `",
"TestHost": "",
"TestUsername": "",
"TestPassword": "",
"TestDbname": "",
"TestPort": ""
},
"Dev": {
"DebugMode":true,
"SuperDebug":false
}
}`)
fmt.Println("Opening the configuration file")
configFile, err := os.Create("./config/config.json")
if err != nil {
abortError(err)
return
}
fmt.Println("Opening the configuration file")
configFile, err := os.Create("./config/config.json")
if err != nil {
abortError(err)
return
}
fmt.Println("Writing to the configuration file...")
_, err = configFile.Write(configContents)
if err != nil {
abortError(err)
return
}
fmt.Println("Writing to the configuration file...")
_, err = configFile.Write(configContents)
if err != nil {
abortError(err)
return
}
configFile.Sync()
configFile.Close()
fmt.Println("Finished writing to the configuration file")
configFile.Sync()
configFile.Close()
fmt.Println("Finished writing to the configuration file")
fmt.Println("Yay, you have successfully installed Gosora!")
fmt.Println("Your name is Admin and you can login with the password 'password'. Don't forget to change it! Seriously. It's really insecure.")
pressAnyKey()
fmt.Println("Yay, you have successfully installed Gosora!")
fmt.Println("Your name is Admin and you can login with the password 'password'. Don't forget to change it! Seriously. It's really insecure.")
pressAnyKey()
}
func abortError(err error) {
fmt.Println(err)
fmt.Println("Aborting installation...")
pressAnyKey()
fmt.Println(err)
fmt.Println("Aborting installation...")
pressAnyKey()
}
func handleDatabaseDetails() (adap install.InstallAdapter, ok bool) {
var dbAdapter string
var dbHost string
var dbUsername string
var dbPassword string
var dbName string
// TODO: Let the admin set the database port?
//var dbPort string
var dbAdapter string
var dbHost string
var dbUsername string
var dbPassword string
var dbName string
// TODO: Let the admin set the database port?
//var dbPort string
for {
fmt.Println("Which database adapter do you wish to use? mysql or mssql? Default: mysql")
if !scanner.Scan() {
return nil, false
}
dbAdapter := strings.TrimSpace(scanner.Text())
if dbAdapter == "" {
dbAdapter = defaultAdapter
}
adap, ok = install.Lookup(dbAdapter)
if ok {
break
}
fmt.Println("That adapter doesn't exist")
}
fmt.Println("Set database adapter to " + dbAdapter)
for {
fmt.Println("Which database adapter do you wish to use? mysql or mssql? Default: mysql")
if !scanner.Scan() {
return nil, false
}
dbAdapter := strings.TrimSpace(scanner.Text())
if dbAdapter == "" {
dbAdapter = defaultAdapter
}
adap, ok = install.Lookup(dbAdapter)
if ok {
break
}
fmt.Println("That adapter doesn't exist")
}
fmt.Println("Set database adapter to " + dbAdapter)
fmt.Println("Database Host? Default: " + defaultHost)
if !scanner.Scan() {
return nil, false
}
dbHost = scanner.Text()
if dbHost == "" {
dbHost = defaultHost
}
fmt.Println("Set database host to " + dbHost)
fmt.Println("Database Host? Default: " + defaultHost)
if !scanner.Scan() {
return nil, false
}
dbHost = scanner.Text()
if dbHost == "" {
dbHost = defaultHost
}
fmt.Println("Set database host to " + dbHost)
fmt.Println("Database Username? Default: " + defaultUsername)
if !scanner.Scan() {
return nil, false
}
dbUsername = scanner.Text()
if dbUsername == "" {
dbUsername = defaultUsername
}
fmt.Println("Set database username to " + dbUsername)
fmt.Println("Database Username? Default: " + defaultUsername)
if !scanner.Scan() {
return nil, false
}
dbUsername = scanner.Text()
if dbUsername == "" {
dbUsername = defaultUsername
}
fmt.Println("Set database username to " + dbUsername)
fmt.Println("Database Password? Default: ''")
if !scanner.Scan() {
return nil, false
}
dbPassword = scanner.Text()
if len(dbPassword) == 0 {
fmt.Println("You didn't set a password for this user. This won't block the installation process, but it might create security issues in the future.")
fmt.Println("")
} else {
fmt.Println("Set password to " + obfuscatePassword(dbPassword))
}
fmt.Println("Database Password? Default: ''")
if !scanner.Scan() {
return nil, false
}
dbPassword = scanner.Text()
if len(dbPassword) == 0 {
fmt.Println("You didn't set a password for this user. This won't block the installation process, but it might create security issues in the future.")
fmt.Println("")
} else {
fmt.Println("Set password to " + obfuscatePassword(dbPassword))
}
fmt.Println("Database Name? Pick a name you like or one provided to you. Default: " + defaultDbname)
if !scanner.Scan() {
return nil, false
}
dbName = scanner.Text()
if dbName == "" {
dbName = defaultDbname
}
fmt.Println("Set database name to " + dbName)
fmt.Println("Database Name? Pick a name you like or one provided to you. Default: " + defaultDbname)
if !scanner.Scan() {
return nil, false
}
dbName = scanner.Text()
if dbName == "" {
dbName = defaultDbname
}
fmt.Println("Set database name to " + dbName)
adap.SetConfig(dbHost, dbUsername, dbPassword, dbName, adap.DefaultPort())
return adap, true
adap.SetConfig(dbHost, dbUsername, dbPassword, dbName, adap.DefaultPort())
return adap, true
}
func getSiteDetails() bool {
fmt.Println("Okay. We also need to know some actual information about your site!")
fmt.Println("What's your site's name? Default: " + defaultSiteName)
if !scanner.Scan() {
return false
}
siteName = scanner.Text()
if siteName == "" {
siteName = defaultSiteName
}
fmt.Println("Set the site name to " + siteName)
fmt.Println("Okay. We also need to know some actual information about your site!")
fmt.Println("What's your site's name? Default: " + defaultSiteName)
if !scanner.Scan() {
return false
}
siteName = scanner.Text()
if siteName == "" {
siteName = defaultSiteName
}
fmt.Println("Set the site name to " + siteName)
// ? - We could compute this based on the first letter of each word in the site's name, if it's name spans multiple words. I'm not sure how to do this for single word names.
fmt.Println("Can we have a short abbreviation for your site? Default: " + defaultSiteShortName)
if !scanner.Scan() {
return false
}
siteShortName = scanner.Text()
if siteShortName == "" {
siteShortName = defaultSiteShortName
}
fmt.Println("Set the short name to " + siteShortName)
// ? - We could compute this based on the first letter of each word in the site's name, if it's name spans multiple words. I'm not sure how to do this for single word names.
fmt.Println("Can we have a short abbreviation for your site? Default: " + defaultSiteShortName)
if !scanner.Scan() {
return false
}
siteShortName = scanner.Text()
if siteShortName == "" {
siteShortName = defaultSiteShortName
}
fmt.Println("Set the short name to " + siteShortName)
fmt.Println("What's your site's url? Default: " + defaultsiteURL)
if !scanner.Scan() {
return false
}
siteURL = scanner.Text()
if siteURL == "" {
siteURL = defaultsiteURL
}
fmt.Println("Set the site url to " + siteURL)
fmt.Println("What's your site's url? Default: " + defaultsiteURL)
if !scanner.Scan() {
return false
}
siteURL = scanner.Text()
if siteURL == "" {
siteURL = defaultsiteURL
}
fmt.Println("Set the site url to " + siteURL)
fmt.Println("What port do you want the server to listen on? If you don't know what this means, you should probably leave it on the default. Default: " + defaultServerPort)
if !scanner.Scan() {
return false
}
serverPort = scanner.Text()
if serverPort == "" {
serverPort = defaultServerPort
}
_, err := strconv.Atoi(serverPort)
if err != nil {
fmt.Println("That's not a valid number!")
return false
}
fmt.Println("Set the server port to " + serverPort)
return true
fmt.Println("What port do you want the server to listen on? If you don't know what this means, you should probably leave it on the default. Default: " + defaultServerPort)
if !scanner.Scan() {
return false
}
serverPort = scanner.Text()
if serverPort == "" {
serverPort = defaultServerPort
}
_, err := strconv.Atoi(serverPort)
if err != nil {
fmt.Println("That's not a valid number!")
return false
}
fmt.Println("Set the server port to " + serverPort)
return true
}
func obfuscatePassword(password string) (out string) {
for i := 0; i < len(password); i++ {
out += "*"
}
return out
for i := 0; i < len(password); i++ {
out += "*"
}
return out
}
func pressAnyKey() {
//fmt.Println("Press any key to exit...")
fmt.Println("Please press enter to exit...")
for scanner.Scan() {
_ = scanner.Text()
return
}
//fmt.Println("Press any key to exit...")
fmt.Println("Please press enter to exit...")
for scanner.Scan() {
_ = scanner.Text()
return
}
}

View File

@ -2,8 +2,8 @@
echo Building the query generator
go build -ldflags="-s -w"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
pause
exit /b %errorlevel%
)
echo The query generator was successfully built
pause

View File

@ -2,407 +2,407 @@
package main // import "github.com/Azareal/Gosora/query_gen"
import (
"encoding/json"
"fmt"
"log"
"os"
"runtime/debug"
"strconv"
"strings"
"encoding/json"
"fmt"
"log"
"os"
"runtime/debug"
"strconv"
"strings"
c "github.com/Azareal/Gosora/common"
qgen "github.com/Azareal/Gosora/query_gen"
c "github.com/Azareal/Gosora/common"
qgen "github.com/Azareal/Gosora/query_gen"
)
// TODO: Make sure all the errors in this file propagate upwards properly
func main() {
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
return
}
}()
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
debug.PrintStack()
return
}
}()
log.Println("Running the query generator")
for _, a := range qgen.Registry {
log.Printf("Building the queries for the %s adapter", a.GetName())
qgen.Install.SetAdapterInstance(a)
qgen.Install.AddPlugins(NewPrimaryKeySpitter()) // TODO: Do we really need to fill the spitter for every adapter?
log.Println("Running the query generator")
for _, a := range qgen.Registry {
log.Printf("Building the queries for the %s adapter", a.GetName())
qgen.Install.SetAdapterInstance(a)
qgen.Install.AddPlugins(NewPrimaryKeySpitter()) // TODO: Do we really need to fill the spitter for every adapter?
e := writeStatements(a)
if e != nil {
log.Print(e)
}
e = qgen.Install.Write()
if e != nil {
log.Print(e)
}
e = a.Write()
if e != nil {
log.Print(e)
}
}
e := writeStatements(a)
if e != nil {
log.Print(e)
}
e = qgen.Install.Write()
if e != nil {
log.Print(e)
}
e = a.Write()
if e != nil {
log.Print(e)
}
}
}
// nolint
func writeStatements(a qgen.Adapter) (err error) {
e := func(f func(qgen.Adapter) error) {
if err != nil {
return
}
err = f(a)
}
e(createTables)
e(seedTables)
e(writeSelects)
e(writeLeftJoins)
e(writeInnerJoins)
e(writeInserts)
e(writeUpdates)
e(writeDeletes)
e(writeSimpleCounts)
e(writeInsertSelects)
e(writeInsertLeftJoins)
e(writeInsertInnerJoins)
return err
e := func(f func(qgen.Adapter) error) {
if err != nil {
return
}
err = f(a)
}
e(createTables)
e(seedTables)
e(writeSelects)
e(writeLeftJoins)
e(writeInnerJoins)
e(writeInserts)
e(writeUpdates)
e(writeDeletes)
e(writeSimpleCounts)
e(writeInsertSelects)
e(writeInsertLeftJoins)
e(writeInsertInnerJoins)
return err
}
type si = map[string]interface{}
type tK = tblKey
func seedTables(a qgen.Adapter) error {
qgen.Install.AddIndex("topics", "parentID", "parentID")
qgen.Install.AddIndex("replies", "tid", "tid")
qgen.Install.AddIndex("polls", "parentID", "parentID")
qgen.Install.AddIndex("likes", "targetItem", "targetItem")
qgen.Install.AddIndex("emails", "uid", "uid")
qgen.Install.AddIndex("attachments", "originID", "originID")
qgen.Install.AddIndex("attachments", "path", "path")
qgen.Install.AddIndex("activity_stream_matches", "watcher", "watcher")
// TODO: Remove these keys to save space when Elasticsearch is active?
//qgen.Install.AddKey("topics", "title", tK{"title", "fulltext", "", false})
//qgen.Install.AddKey("topics", "content", tK{"content", "fulltext", "", false})
//qgen.Install.AddKey("topics", "title,content", tK{"title,content", "fulltext", "", false})
//qgen.Install.AddKey("replies", "content", tK{"content", "fulltext", "", false})
qgen.Install.AddIndex("topics", "parentID", "parentID")
qgen.Install.AddIndex("replies", "tid", "tid")
qgen.Install.AddIndex("polls", "parentID", "parentID")
qgen.Install.AddIndex("likes", "targetItem", "targetItem")
qgen.Install.AddIndex("emails", "uid", "uid")
qgen.Install.AddIndex("attachments", "originID", "originID")
qgen.Install.AddIndex("attachments", "path", "path")
qgen.Install.AddIndex("activity_stream_matches", "watcher", "watcher")
// TODO: Remove these keys to save space when Elasticsearch is active?
//qgen.Install.AddKey("topics", "title", tK{"title", "fulltext", "", false})
//qgen.Install.AddKey("topics", "content", tK{"content", "fulltext", "", false})
//qgen.Install.AddKey("topics", "title,content", tK{"title,content", "fulltext", "", false})
//qgen.Install.AddKey("replies", "content", tK{"content", "fulltext", "", false})
insert := func(tbl, cols, vals string) {
qgen.Install.SimpleInsert(tbl, cols, vals)
}
insert("sync", "last_update", "UTC_TIMESTAMP()")
addSetting := func(name, content, stype string, constraints ...string) {
if strings.Contains(name, "'") {
panic("name contains '")
}
if strings.Contains(stype, "'") {
panic("stype contains '")
}
// TODO: Add more field validators
cols := "name,content,type"
if len(constraints) > 0 {
cols += ",constraints"
}
q := func(s string) string {
return "'" + s + "'"
}
c := func() string {
if len(constraints) == 0 {
return ""
}
return "," + q(constraints[0])
}
insert("settings", cols, q(name)+","+q(content)+","+q(stype)+c())
}
addSetting("activation_type", "1", "list", "1-3")
addSetting("bigpost_min_words", "250", "int")
addSetting("megapost_min_words", "1000", "int")
addSetting("meta_desc", "", "html-attribute")
addSetting("rapid_loading", "1", "bool")
addSetting("google_site_verify", "", "html-attribute")
addSetting("avatar_visibility", "0", "list", "0-1")
insert("themes", "uname, default", "'cosora',1")
insert("emails", "email, uid, validated", "'admin@localhost',1,1") // ? - Use a different default email or let the admin input it during installation?
insert := func(tbl, cols, vals string) {
qgen.Install.SimpleInsert(tbl, cols, vals)
}
insert("sync", "last_update", "UTC_TIMESTAMP()")
addSetting := func(name, content, stype string, constraints ...string) {
if strings.Contains(name, "'") {
panic("name contains '")
}
if strings.Contains(stype, "'") {
panic("stype contains '")
}
// TODO: Add more field validators
cols := "name,content,type"
if len(constraints) > 0 {
cols += ",constraints"
}
q := func(s string) string {
return "'" + s + "'"
}
c := func() string {
if len(constraints) == 0 {
return ""
}
return "," + q(constraints[0])
}
insert("settings", cols, q(name)+","+q(content)+","+q(stype)+c())
}
addSetting("activation_type", "1", "list", "1-3")
addSetting("bigpost_min_words", "250", "int")
addSetting("megapost_min_words", "1000", "int")
addSetting("meta_desc", "", "html-attribute")
addSetting("rapid_loading", "1", "bool")
addSetting("google_site_verify", "", "html-attribute")
addSetting("avatar_visibility", "0", "list", "0-1")
insert("themes", "uname, default", "'cosora',1")
insert("emails", "email, uid, validated", "'admin@localhost',1,1") // ? - Use a different default email or let the admin input it during installation?
/*
The Permissions:
/*
The Permissions:
Global Permissions:
BanUsers
ActivateUsers
EditUser
EditUserEmail
EditUserPassword
EditUserGroup
EditUserGroupSuperMod
EditUserGroupAdmin
EditGroup
EditGroupLocalPerms
EditGroupGlobalPerms
EditGroupSuperMod
EditGroupAdmin
ManageForums
EditSettings
ManageThemes
ManagePlugins
ViewAdminLogs
ViewIPs
Global Permissions:
BanUsers
ActivateUsers
EditUser
EditUserEmail
EditUserPassword
EditUserGroup
EditUserGroupSuperMod
EditUserGroupAdmin
EditGroup
EditGroupLocalPerms
EditGroupGlobalPerms
EditGroupSuperMod
EditGroupAdmin
ManageForums
EditSettings
ManageThemes
ManagePlugins
ViewAdminLogs
ViewIPs
Non-staff Global Permissions:
UploadFiles
UploadAvatars
UseConvos
UseConvosOnlyWithMod
CreateProfileReply
AutoEmbed
AutoLink
// CreateConvo ?
// CreateConvoReply ?
Non-staff Global Permissions:
UploadFiles
UploadAvatars
UseConvos
UseConvosOnlyWithMod
CreateProfileReply
AutoEmbed
AutoLink
// CreateConvo ?
// CreateConvoReply ?
Forum Permissions:
ViewTopic
LikeItem
CreateTopic
EditTopic
DeleteTopic
CreateReply
EditReply
DeleteReply
PinTopic
CloseTopic
MoveTopic
*/
Forum Permissions:
ViewTopic
LikeItem
CreateTopic
EditTopic
DeleteTopic
CreateReply
EditReply
DeleteReply
PinTopic
CloseTopic
MoveTopic
*/
p := func(perms *c.Perms) string {
jBytes, err := json.Marshal(perms)
if err != nil {
panic(err)
}
return string(jBytes)
}
addGroup := func(name string, perms c.Perms, mod, admin, banned bool, tag string) {
mi, ai, bi := "0", "0", "0"
if mod {
mi = "1"
}
if admin {
ai = "1"
}
if banned {
bi = "1"
}
insert("users_groups", "name, permissions, plugin_perms, is_mod, is_admin, is_banned, tag", `'`+name+`','`+p(&perms)+`','{}',`+mi+`,`+ai+`,`+bi+`,"`+tag+`"`)
}
p := func(perms *c.Perms) string {
jBytes, err := json.Marshal(perms)
if err != nil {
panic(err)
}
return string(jBytes)
}
addGroup := func(name string, perms c.Perms, mod, admin, banned bool, tag string) {
mi, ai, bi := "0", "0", "0"
if mod {
mi = "1"
}
if admin {
ai = "1"
}
if banned {
bi = "1"
}
insert("users_groups", "name, permissions, plugin_perms, is_mod, is_admin, is_banned, tag", `'`+name+`','`+p(&perms)+`','{}',`+mi+`,`+ai+`,`+bi+`,"`+tag+`"`)
}
perms := c.AllPerms
perms.EditUserGroupAdmin = false
perms.EditGroupAdmin = false
addGroup("Administrator", perms, true, true, false, "Admin")
perms := c.AllPerms
perms.EditUserGroupAdmin = false
perms.EditGroupAdmin = false
addGroup("Administrator", perms, true, true, false, "Admin")
perms = c.Perms{BanUsers: true, ActivateUsers: true, EditUser: true, EditUserEmail: false, EditUserGroup: true, ViewIPs: true, UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, EditTopic: true, DeleteTopic: true, CreateReply: true, EditReply: true, DeleteReply: true, PinTopic: true, CloseTopic: true, MoveTopic: true}
addGroup("Moderator", perms, true, false, false, "Mod")
perms = c.Perms{BanUsers: true, ActivateUsers: true, EditUser: true, EditUserEmail: false, EditUserGroup: true, ViewIPs: true, UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, EditTopic: true, DeleteTopic: true, CreateReply: true, EditReply: true, DeleteReply: true, PinTopic: true, CloseTopic: true, MoveTopic: true}
addGroup("Moderator", perms, true, false, false, "Mod")
perms = c.Perms{UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, CreateReply: true}
addGroup("Member", perms, false, false, false, "")
perms = c.Perms{UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, CreateReply: true}
addGroup("Member", perms, false, false, false, "")
perms = c.Perms{ViewTopic: true}
addGroup("Banned", perms, false, false, true, "")
addGroup("Awaiting Activation", c.Perms{ViewTopic: true, UseConvosOnlyWithMod: true}, false, false, false, "")
addGroup("Not Loggedin", perms, false, false, false, "Guest")
perms = c.Perms{ViewTopic: true}
addGroup("Banned", perms, false, false, true, "")
addGroup("Awaiting Activation", c.Perms{ViewTopic: true, UseConvosOnlyWithMod: true}, false, false, false, "")
addGroup("Not Loggedin", perms, false, false, false, "Guest")
//
// TODO: Stop processFields() from stripping the spaces in the descriptions in the next commit
//
// TODO: Stop processFields() from stripping the spaces in the descriptions in the next commit
insert("forums", "name, active, desc, tmpl", "'Reports',0,'All the reports go here',''")
insert("forums", "name, lastTopicID, lastReplyerID, desc, tmpl", "'General',1,1,'A place for general discussions which don't fit elsewhere',''")
insert("forums", "name, active, desc, tmpl", "'Reports',0,'All the reports go here',''")
insert("forums", "name, lastTopicID, lastReplyerID, desc, tmpl", "'General',1,1,'A place for general discussions which don't fit elsewhere',''")
//
//
/*var addForumPerm = func(gid, fid int, permStr string) {
insert("forums_permissions", "gid, fid, permissions", strconv.Itoa(gid)+`,`+strconv.Itoa(fid)+`,'`+permStr+`'`)
}*/
/*var addForumPerm = func(gid, fid int, permStr string) {
insert("forums_permissions", "gid, fid, permissions", strconv.Itoa(gid)+`,`+strconv.Itoa(fid)+`,'`+permStr+`'`)
}*/
insert("forums_permissions", "gid, fid, permissions", `1,1,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"PinTopic":true,"CloseTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `2,1,'{"ViewTopic":true,"CreateReply":true,"CloseTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", "3,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", "4,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", "5,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", "6,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", `1,1,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"PinTopic":true,"CloseTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `2,1,'{"ViewTopic":true,"CreateReply":true,"CloseTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", "3,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", "4,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", "5,1,'{}'")
insert("forums_permissions", "gid, fid, permissions", "6,1,'{}'")
//
//
insert("forums_permissions", "gid, fid, permissions", `1,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `1,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `2,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `2,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `3,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true}'`)
insert("forums_permissions", "gid, fid, permissions", `3,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true}'`)
insert("forums_permissions", "gid, fid, permissions", `4,2,'{"ViewTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `4,2,'{"ViewTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `5,2,'{"ViewTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `5,2,'{"ViewTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `6,2,'{"ViewTopic":true}'`)
insert("forums_permissions", "gid, fid, permissions", `6,2,'{"ViewTopic":true}'`)
//
//
insert("topics", "title, content, parsed_content, createdAt, lastReplyAt, lastReplyBy, createdBy, parentID, ip", "'Test Topic','A topic automatically generated by the software.','A topic automatically generated by the software.',UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,1,2,''")
insert("topics", "title, content, parsed_content, createdAt, lastReplyAt, lastReplyBy, createdBy, parentID, ip", "'Test Topic','A topic automatically generated by the software.','A topic automatically generated by the software.',UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,1,2,''")
insert("replies", "tid, content, parsed_content, createdAt, createdBy, lastUpdated, lastEdit, lastEditBy, ip", "1,'A reply!','A reply!',UTC_TIMESTAMP(),1,UTC_TIMESTAMP(),0,0,''")
insert("replies", "tid, content, parsed_content, createdAt, createdBy, lastUpdated, lastEdit, lastEditBy, ip", "1,'A reply!','A reply!',UTC_TIMESTAMP(),1,UTC_TIMESTAMP(),0,0,''")
insert("menus", "", "")
insert("menus", "", "")
// Go maps have a random iteration order, so we have to do this, otherwise the schema files will become unstable and harder to audit
order := 0
mOrder := "mid, name, htmlID, cssClass, position, path, aria, tooltip, guestOnly, memberOnly, staffOnly, adminOnly"
addMenuItem := func(data map[string]interface{}) {
if data["mid"] == nil {
data["mid"] = 1
}
if data["position"] == nil {
data["position"] = "left"
}
cols, values := qgen.InterfaceMapToInsertStrings(data, mOrder)
insert("menu_items", cols+", order", values+","+strconv.Itoa(order))
order++
}
// Go maps have a random iteration order, so we have to do this, otherwise the schema files will become unstable and harder to audit
order := 0
mOrder := "mid, name, htmlID, cssClass, position, path, aria, tooltip, guestOnly, memberOnly, staffOnly, adminOnly"
addMenuItem := func(data map[string]interface{}) {
if data["mid"] == nil {
data["mid"] = 1
}
if data["position"] == nil {
data["position"] = "left"
}
cols, values := qgen.InterfaceMapToInsertStrings(data, mOrder)
insert("menu_items", cols+", order", values+","+strconv.Itoa(order))
order++
}
addMenuItem(si{"name": "{lang.menu_forums}", "htmlID": "menu_forums", "path": "/forums/", "aria": "{lang.menu_forums_aria}", "tooltip": "{lang.menu_forums_tooltip}"})
addMenuItem(si{"name": "{lang.menu_forums}", "htmlID": "menu_forums", "path": "/forums/", "aria": "{lang.menu_forums_aria}", "tooltip": "{lang.menu_forums_tooltip}"})
addMenuItem(si{"name": "{lang.menu_topics}", "htmlID": "menu_topics", "cssClass": "menu_topics", "path": "/topics/", "aria": "{lang.menu_topics_aria}", "tooltip": "{lang.menu_topics_tooltip}"})
addMenuItem(si{"name": "{lang.menu_topics}", "htmlID": "menu_topics", "cssClass": "menu_topics", "path": "/topics/", "aria": "{lang.menu_topics_aria}", "tooltip": "{lang.menu_topics_tooltip}"})
addMenuItem(si{"htmlID": "general_alerts", "cssClass": "menu_alerts", "position": "right", "tmplName": "menu_alerts"})
addMenuItem(si{"htmlID": "general_alerts", "cssClass": "menu_alerts", "position": "right", "tmplName": "menu_alerts"})
addMenuItem(si{"name": "{lang.menu_account}", "cssClass": "menu_account", "path": "/user/edit/", "aria": "{lang.menu_account_aria}", "tooltip": "{lang.menu_account_tooltip}", "memberOnly": true})
addMenuItem(si{"name": "{lang.menu_account}", "cssClass": "menu_account", "path": "/user/edit/", "aria": "{lang.menu_account_aria}", "tooltip": "{lang.menu_account_tooltip}", "memberOnly": true})
addMenuItem(si{"name": "{lang.menu_profile}", "cssClass": "menu_profile", "path": "{me.Link}", "aria": "{lang.menu_profile_aria}", "tooltip": "{lang.menu_profile_tooltip}", "memberOnly": true})
addMenuItem(si{"name": "{lang.menu_profile}", "cssClass": "menu_profile", "path": "{me.Link}", "aria": "{lang.menu_profile_aria}", "tooltip": "{lang.menu_profile_tooltip}", "memberOnly": true})
addMenuItem(si{"name": "{lang.menu_panel}", "cssClass": "menu_panel menu_account", "path": "/panel/", "aria": "{lang.menu_panel_aria}", "tooltip": "{lang.menu_panel_tooltip}", "memberOnly": true, "staffOnly": true})
addMenuItem(si{"name": "{lang.menu_panel}", "cssClass": "menu_panel menu_account", "path": "/panel/", "aria": "{lang.menu_panel_aria}", "tooltip": "{lang.menu_panel_tooltip}", "memberOnly": true, "staffOnly": true})
addMenuItem(si{"name": "{lang.menu_logout}", "cssClass": "menu_logout", "path": "/accounts/logout/?s={me.Session}", "aria": "{lang.menu_logout_aria}", "tooltip": "{lang.menu_logout_tooltip}", "memberOnly": true})
addMenuItem(si{"name": "{lang.menu_logout}", "cssClass": "menu_logout", "path": "/accounts/logout/?s={me.Session}", "aria": "{lang.menu_logout_aria}", "tooltip": "{lang.menu_logout_tooltip}", "memberOnly": true})
addMenuItem(si{"name": "{lang.menu_register}", "cssClass": "menu_register", "path": "/accounts/create/", "aria": "{lang.menu_register_aria}", "tooltip": "{lang.menu_register_tooltip}", "guestOnly": true})
addMenuItem(si{"name": "{lang.menu_register}", "cssClass": "menu_register", "path": "/accounts/create/", "aria": "{lang.menu_register_aria}", "tooltip": "{lang.menu_register_tooltip}", "guestOnly": true})
addMenuItem(si{"name": "{lang.menu_login}", "cssClass": "menu_login", "path": "/accounts/login/", "aria": "{lang.menu_login_aria}", "tooltip": "{lang.menu_login_tooltip}", "guestOnly": true})
addMenuItem(si{"name": "{lang.menu_login}", "cssClass": "menu_login", "path": "/accounts/login/", "aria": "{lang.menu_login_aria}", "tooltip": "{lang.menu_login_tooltip}", "guestOnly": true})
/*var fSet []string
for _, table := range tables {
fSet = append(fSet, "'"+table+"'")
}
qgen.Install.SimpleBulkInsert("tables", "name", fSet)*/
/*var fSet []string
for _, table := range tables {
fSet = append(fSet, "'"+table+"'")
}
qgen.Install.SimpleBulkInsert("tables", "name", fSet)*/
return nil
return nil
}
// ? - What is this for?
/*func copyInsertMap(in map[string]interface{}) (out map[string]interface{}) {
out = make(map[string]interface{})
for col, value := range in {
out[col] = value
}
return out
out = make(map[string]interface{})
for col, value := range in {
out[col] = value
}
return out
}*/
type LitStr string
func writeSelects(a qgen.Adapter) error {
b := a.Builder()
b := a.Builder()
// Looking for getTopic? Your statement is in another castle
// Looking for getTopic? Your statement is in another castle
//b.Select("isPluginInstalled").Table("plugins").Columns("installed").Where("uname = ?").Parse()
//b.Select("isPluginInstalled").Table("plugins").Columns("installed").Where("uname = ?").Parse()
b.Select("forumEntryExists").Table("forums").Columns("fid").Where("name = ''").Orderby("fid ASC").Limit("0,1").Parse()
b.Select("forumEntryExists").Table("forums").Columns("fid").Where("name = ''").Orderby("fid ASC").Limit("0,1").Parse()
b.Select("groupEntryExists").Table("users_groups").Columns("gid").Where("name = ''").Orderby("gid ASC").Limit("0,1").Parse()
b.Select("groupEntryExists").Table("users_groups").Columns("gid").Where("name = ''").Orderby("gid ASC").Limit("0,1").Parse()
return nil
return nil
}
func writeLeftJoins(a qgen.Adapter) error {
a.SimpleLeftJoin("getForumTopics", "topics", "users", "topics.tid, topics.title, topics.content, topics.createdBy, topics.is_closed, topics.sticky, topics.createdAt, topics.lastReplyAt, topics.parentID, users.name, users.avatar", "topics.createdBy = users.uid", "topics.parentID = ?", "topics.sticky DESC, topics.lastReplyAt DESC, topics.createdBy desc", "")
a.SimpleLeftJoin("getForumTopics", "topics", "users", "topics.tid, topics.title, topics.content, topics.createdBy, topics.is_closed, topics.sticky, topics.createdAt, topics.lastReplyAt, topics.parentID, users.name, users.avatar", "topics.createdBy = users.uid", "topics.parentID = ?", "topics.sticky DESC, topics.lastReplyAt DESC, topics.createdBy desc", "")
return nil
return nil
}
func writeInnerJoins(a qgen.Adapter) (err error) {
return nil
return nil
}
func writeInserts(a qgen.Adapter) error {
b := a.Builder()
b := a.Builder()
b.Insert("addForumPermsToForum").Table("forums_permissions").Columns("gid,fid,preset,permissions").Fields("?,?,?,?").Parse()
b.Insert("addForumPermsToForum").Table("forums_permissions").Columns("gid,fid,preset,permissions").Fields("?,?,?,?").Parse()
return nil
return nil
}
func writeUpdates(a qgen.Adapter) error {
b := a.Builder()
b := a.Builder()
b.Update("updateEmail").Table("emails").Set("email = ?, uid = ?, validated = ?, token = ?").Where("email = ?").Parse()
b.Update("updateEmail").Table("emails").Set("email = ?, uid = ?, validated = ?, token = ?").Where("email = ?").Parse()
b.Update("setTempGroup").Table("users").Set("temp_group = ?").Where("uid = ?").Parse()
b.Update("setTempGroup").Table("users").Set("temp_group = ?").Where("uid = ?").Parse()
b.Update("bumpSync").Table("sync").Set("last_update = UTC_TIMESTAMP()").Parse()
b.Update("bumpSync").Table("sync").Set("last_update = UTC_TIMESTAMP()").Parse()
return nil
return nil
}
func writeDeletes(a qgen.Adapter) error {
b := a.Builder()
b := a.Builder()
//b.Delete("deleteForumPermsByForum").Table("forums_permissions").Where("fid=?").Parse()
//b.Delete("deleteForumPermsByForum").Table("forums_permissions").Where("fid=?").Parse()
b.Delete("deleteActivityStreamMatch").Table("activity_stream_matches").Where("watcher=? AND asid=?").Parse()
//b.Delete("deleteActivityStreamMatchesByWatcher").Table("activity_stream_matches").Where("watcher=?").Parse()
b.Delete("deleteActivityStreamMatch").Table("activity_stream_matches").Where("watcher=? AND asid=?").Parse()
//b.Delete("deleteActivityStreamMatchesByWatcher").Table("activity_stream_matches").Where("watcher=?").Parse()
return nil
return nil
}
func writeSimpleCounts(a qgen.Adapter) error {
return nil
return nil
}
func writeInsertSelects(a qgen.Adapter) error {
/*a.SimpleInsertSelect("addForumPermsToForumAdmins",
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 1", "", ""},
)*/
/*a.SimpleInsertSelect("addForumPermsToForumAdmins",
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 1", "", ""},
)*/
/*a.SimpleInsertSelect("addForumPermsToForumStaff",
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 1", "", ""},
)*/
/*a.SimpleInsertSelect("addForumPermsToForumStaff",
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 1", "", ""},
)*/
/*a.SimpleInsertSelect("addForumPermsToForumMembers",
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 0 AND is_banned = 0", "", ""},
)*/
/*a.SimpleInsertSelect("addForumPermsToForumMembers",
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 0 AND is_banned = 0", "", ""},
)*/
return nil
return nil
}
// nolint
func writeInsertLeftJoins(a qgen.Adapter) error {
return nil
return nil
}
func writeInsertInnerJoins(a qgen.Adapter) error {
return nil
return nil
}
func writeFile(name, content string) (err error) {
f, err := os.Create(name)
if err != nil {
return err
}
_, err = f.WriteString(content)
if err != nil {
return err
}
err = f.Sync()
if err != nil {
return err
}
return f.Close()
f, err := os.Create(name)
if err != nil {
return err
}
_, err = f.WriteString(content)
if err != nil {
return err
}
err = f.Sync()
if err != nil {
return err
}
return f.Close()
}

View File

@ -2,8 +2,8 @@
echo Building the query generator
go build -ldflags="-s -w"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
pause
exit /b %errorlevel%
)
echo The query generator was successfully built
query_gen.exe

View File

@ -4,42 +4,42 @@ import "strings"
import "github.com/Azareal/Gosora/query_gen"
type PrimaryKeySpitter struct {
keys map[string]string
keys map[string]string
}
func NewPrimaryKeySpitter() *PrimaryKeySpitter {
return &PrimaryKeySpitter{make(map[string]string)}
return &PrimaryKeySpitter{make(map[string]string)}
}
func (spit *PrimaryKeySpitter) Hook(name string, args ...interface{}) error {
if name == "CreateTableStart" {
var found string
var table = args[0].(*qgen.DBInstallTable)
for _, key := range table.Keys {
if key.Type == "primary" {
expl := strings.Split(key.Columns, ",")
if len(expl) > 1 {
continue
}
found = key.Columns
}
if found != "" {
table := table.Name
spit.keys[table] = found
}
}
}
return nil
if name == "CreateTableStart" {
var found string
var table = args[0].(*qgen.DBInstallTable)
for _, key := range table.Keys {
if key.Type == "primary" {
expl := strings.Split(key.Columns, ",")
if len(expl) > 1 {
continue
}
found = key.Columns
}
if found != "" {
table := table.Name
spit.keys[table] = found
}
}
}
return nil
}
func (spit *PrimaryKeySpitter) Write() error {
out := `// Generated by Gosora's Query Generator. DO NOT EDIT.
out := `// Generated by Gosora's Query Generator. DO NOT EDIT.
package main
var dbTablePrimaryKeys = map[string]string{
`
for table, key := range spit.keys {
out += "\t\"" + table + "\":\"" + key + "\",\n"
}
return writeFile("./gen_tables.go", out+"}\n")
for table, key := range spit.keys {
out += "\t\"" + table + "\":\"" + key + "\",\n"
}
return writeFile("./gen_tables.go", out+"}\n")
}

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +0,0 @@
echo "Updating the dependencies"
./update-deps-linux
echo "Updating Gosora"
git stash
git pull origin master
git stash apply
echo "Patching Gosora"
go generate
go build -ldflags="-s -w" -o Patcher "./patcher"
./Patcher

View File

@ -1,4 +0,0 @@
echo "Building the patcher"
go generate
./update-deps-linux
go build -ldflags="-s -w" -o Patcher "./patcher"

View File

@ -1,32 +0,0 @@
@echo off
echo Updating the dependencies
go get
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
go get -u github.com/mailru/easyjson/...
echo Updating Gosora
git stash
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
git pull origin master
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
git stash apply
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Patching Gosora
go generate
go build -ldflags="-s -w" ./patcher
patcher.exe

View File

@ -11,80 +11,80 @@ import "github.com/Azareal/Gosora/common"
// nolint
type Stmts struct {
forumEntryExists *sql.Stmt
groupEntryExists *sql.Stmt
getForumTopics *sql.Stmt
addForumPermsToForum *sql.Stmt
updateEmail *sql.Stmt
setTempGroup *sql.Stmt
bumpSync *sql.Stmt
deleteActivityStreamMatch *sql.Stmt
forumEntryExists *sql.Stmt
groupEntryExists *sql.Stmt
getForumTopics *sql.Stmt
addForumPermsToForum *sql.Stmt
updateEmail *sql.Stmt
setTempGroup *sql.Stmt
bumpSync *sql.Stmt
deleteActivityStreamMatch *sql.Stmt
getActivityFeedByWatcher *sql.Stmt
getActivityCountByWatcher *sql.Stmt
getActivityFeedByWatcher *sql.Stmt
getActivityCountByWatcher *sql.Stmt
Mocks bool
Mocks bool
}
// nolint
func _gen_mysql() (err error) {
common.DebugLog("Building the generated statements")
common.DebugLog("Preparing forumEntryExists statement.")
stmts.forumEntryExists, err = db.Prepare("SELECT `fid` FROM `forums` WHERE `name` = '' ORDER BY `fid` ASC LIMIT 0,1")
if err != nil {
log.Print("Error in forumEntryExists statement.")
return err
}
common.DebugLog("Preparing groupEntryExists statement.")
stmts.groupEntryExists, err = db.Prepare("SELECT `gid` FROM `users_groups` WHERE `name` = '' ORDER BY `gid` ASC LIMIT 0,1")
if err != nil {
log.Print("Error in groupEntryExists statement.")
return err
}
common.DebugLog("Preparing getForumTopics statement.")
stmts.getForumTopics, err = db.Prepare("SELECT `topics`.`tid`, `topics`.`title`, `topics`.`content`, `topics`.`createdBy`, `topics`.`is_closed`, `topics`.`sticky`, `topics`.`createdAt`, `topics`.`lastReplyAt`, `topics`.`parentID`, `users`.`name`, `users`.`avatar` FROM `topics` LEFT JOIN `users` ON `topics`.`createdBy` = `users`.`uid` WHERE `topics`.`parentID` = ? ORDER BY `topics`.`sticky` DESC,`topics`.`lastReplyAt` DESC,`topics`.`createdBy` DESC")
if err != nil {
log.Print("Error in getForumTopics statement.")
return err
}
common.DebugLog("Preparing addForumPermsToForum statement.")
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO `forums_permissions`(`gid`,`fid`,`preset`,`permissions`) VALUES (?,?,?,?)")
if err != nil {
log.Print("Error in addForumPermsToForum statement.")
return err
}
common.DebugLog("Preparing updateEmail statement.")
stmts.updateEmail, err = db.Prepare("UPDATE `emails` SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
if err != nil {
log.Print("Error in updateEmail statement.")
return err
}
common.DebugLog("Preparing setTempGroup statement.")
stmts.setTempGroup, err = db.Prepare("UPDATE `users` SET `temp_group`= ? WHERE `uid` = ?")
if err != nil {
log.Print("Error in setTempGroup statement.")
return err
}
common.DebugLog("Preparing bumpSync statement.")
stmts.bumpSync, err = db.Prepare("UPDATE `sync` SET `last_update`= UTC_TIMESTAMP()")
if err != nil {
log.Print("Error in bumpSync statement.")
return err
}
common.DebugLog("Preparing deleteActivityStreamMatch statement.")
stmts.deleteActivityStreamMatch, err = db.Prepare("DELETE FROM `activity_stream_matches` WHERE `watcher` = ? AND `asid` = ?")
if err != nil {
log.Print("Error in deleteActivityStreamMatch statement.")
return err
}
return nil
common.DebugLog("Building the generated statements")
common.DebugLog("Preparing forumEntryExists statement.")
stmts.forumEntryExists, err = db.Prepare("SELECT `fid` FROM `forums` WHERE `name` = '' ORDER BY `fid` ASC LIMIT 0,1")
if err != nil {
log.Print("Error in forumEntryExists statement.")
return err
}
common.DebugLog("Preparing groupEntryExists statement.")
stmts.groupEntryExists, err = db.Prepare("SELECT `gid` FROM `users_groups` WHERE `name` = '' ORDER BY `gid` ASC LIMIT 0,1")
if err != nil {
log.Print("Error in groupEntryExists statement.")
return err
}
common.DebugLog("Preparing getForumTopics statement.")
stmts.getForumTopics, err = db.Prepare("SELECT `topics`.`tid`, `topics`.`title`, `topics`.`content`, `topics`.`createdBy`, `topics`.`is_closed`, `topics`.`sticky`, `topics`.`createdAt`, `topics`.`lastReplyAt`, `topics`.`parentID`, `users`.`name`, `users`.`avatar` FROM `topics` LEFT JOIN `users` ON `topics`.`createdBy` = `users`.`uid` WHERE `topics`.`parentID` = ? ORDER BY `topics`.`sticky` DESC,`topics`.`lastReplyAt` DESC,`topics`.`createdBy` DESC")
if err != nil {
log.Print("Error in getForumTopics statement.")
return err
}
common.DebugLog("Preparing addForumPermsToForum statement.")
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO `forums_permissions`(`gid`,`fid`,`preset`,`permissions`) VALUES (?,?,?,?)")
if err != nil {
log.Print("Error in addForumPermsToForum statement.")
return err
}
common.DebugLog("Preparing updateEmail statement.")
stmts.updateEmail, err = db.Prepare("UPDATE `emails` SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
if err != nil {
log.Print("Error in updateEmail statement.")
return err
}
common.DebugLog("Preparing setTempGroup statement.")
stmts.setTempGroup, err = db.Prepare("UPDATE `users` SET `temp_group`= ? WHERE `uid` = ?")
if err != nil {
log.Print("Error in setTempGroup statement.")
return err
}
common.DebugLog("Preparing bumpSync statement.")
stmts.bumpSync, err = db.Prepare("UPDATE `sync` SET `last_update`= UTC_TIMESTAMP()")
if err != nil {
log.Print("Error in bumpSync statement.")
return err
}
common.DebugLog("Preparing deleteActivityStreamMatch statement.")
stmts.deleteActivityStreamMatch, err = db.Prepare("DELETE FROM `activity_stream_matches` WHERE `watcher` = ? AND `asid` = ?")
if err != nil {
log.Print("Error in deleteActivityStreamMatch statement.")
return err
}
return nil
}

View File

@ -9,48 +9,48 @@ import "github.com/Azareal/Gosora/common"
// nolint
type Stmts struct {
addForumPermsToForum *sql.Stmt
updateEmail *sql.Stmt
setTempGroup *sql.Stmt
bumpSync *sql.Stmt
addForumPermsToForum *sql.Stmt
updateEmail *sql.Stmt
setTempGroup *sql.Stmt
bumpSync *sql.Stmt
getActivityFeedByWatcher *sql.Stmt
getActivityCountByWatcher *sql.Stmt
getActivityFeedByWatcher *sql.Stmt
getActivityCountByWatcher *sql.Stmt
Mocks bool
Mocks bool
}
// nolint
func _gen_pgsql() (err error) {
common.DebugLog("Building the generated statements")
common.DebugLog("Preparing addForumPermsToForum statement.")
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO \"forums_permissions\"(\"gid\",\"fid\",\"preset\",\"permissions\") VALUES (?,?,?,?)")
if err != nil {
log.Print("Error in addForumPermsToForum statement.")
return err
}
common.DebugLog("Preparing updateEmail statement.")
stmts.updateEmail, err = db.Prepare("UPDATE \"emails\" SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
if err != nil {
log.Print("Error in updateEmail statement.")
return err
}
common.DebugLog("Preparing setTempGroup statement.")
stmts.setTempGroup, err = db.Prepare("UPDATE \"users\" SET `temp_group`= ? WHERE `uid` = ?")
if err != nil {
log.Print("Error in setTempGroup statement.")
return err
}
common.DebugLog("Preparing bumpSync statement.")
stmts.bumpSync, err = db.Prepare("UPDATE \"sync\" SET `last_update`= LOCALTIMESTAMP()")
if err != nil {
log.Print("Error in bumpSync statement.")
return err
}
return nil
common.DebugLog("Building the generated statements")
common.DebugLog("Preparing addForumPermsToForum statement.")
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO \"forums_permissions\"(\"gid\",\"fid\",\"preset\",\"permissions\") VALUES (?,?,?,?)")
if err != nil {
log.Print("Error in addForumPermsToForum statement.")
return err
}
common.DebugLog("Preparing updateEmail statement.")
stmts.updateEmail, err = db.Prepare("UPDATE \"emails\" SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
if err != nil {
log.Print("Error in updateEmail statement.")
return err
}
common.DebugLog("Preparing setTempGroup statement.")
stmts.setTempGroup, err = db.Prepare("UPDATE \"users\" SET `temp_group`= ? WHERE `uid` = ?")
if err != nil {
log.Print("Error in setTempGroup statement.")
return err
}
common.DebugLog("Preparing bumpSync statement.")
stmts.bumpSync, err = db.Prepare("UPDATE \"sync\" SET `last_update`= LOCALTIMESTAMP()")
if err != nil {
log.Print("Error in bumpSync statement.")
return err
}
return nil
}

View File

@ -1,21 +0,0 @@
# An example systemd service file
[Unit]
Description=Gosora
[Service]
User=gosora
Group=www-data
Restart=on-failure
RestartSec=10
# Set these to the location of Gosora
WorkingDirectory=/home/gosora/src
AmbientCapabilities=CAP_NET_BIND_SERVICE
# Make sure you manually run pre-run-linux before you start the service
ExecStart=/home/gosora/src/Gosora
ProtectSystem=full
PrivateDevices=true
[Install]
WantedBy=multi-user.target

View File

@ -1,7 +0,0 @@
go get -u github.com/mailru/easyjson/...
easyjson -pkg common
go get
go build -ldflags="-s -w" -o Installer "./cmd/install"
./Installer --dbType=mysql --dbHost=localhost --dbUser=$MYSQL_USER --dbPassword=$MYSQL_PASSWORD --dbName=$MYSQL_DATABASE --shortSiteName=$SITE_SHORT_NAME --siteName=$SITE_NAME --siteURL=$SITE_URL --serverPort=$SERVER_PORT--secureServerPort=$SECURE_SERVER_PORT

View File

@ -1,8 +0,0 @@
echo "Installing the dependencies"
./update-deps-linux
echo "Building the installer"
go build -ldflags="-s -w" -o Installer "./cmd/install"
echo "Running the installer"
./Installer

View File

@ -1,29 +0,0 @@
@echo off
echo Installing the dependencies
go get -u github.com/mailru/easyjson/...
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
easyjson -pkg common
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
go get
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the installer
go generate
go build -ldflags="-s -w" "./cmd/install"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
install.exe

View File

@ -1,48 +1,48 @@
package install
import (
"fmt"
"fmt"
qgen "github.com/Azareal/Gosora/query_gen"
qgen "github.com/Azareal/Gosora/query_gen"
)
var adapters = make(map[string]InstallAdapter)
type InstallAdapter interface {
Name() string
DefaultPort() string
SetConfig(dbHost, dbUsername, dbPassword, dbName, dbPort string)
InitDatabase() error
TableDefs() error
InitialData() error
CreateAdmin() error
Name() string
DefaultPort() string
SetConfig(dbHost, dbUsername, dbPassword, dbName, dbPort string)
InitDatabase() error
TableDefs() error
InitialData() error
CreateAdmin() error
DBHost() string
DBUsername() string
DBPassword() string
DBName() string
DBPort() string
DBHost() string
DBUsername() string
DBPassword() string
DBName() string
DBPort() string
}
func Lookup(name string) (InstallAdapter, bool) {
adap, ok := adapters[name]
return adap, ok
adap, ok := adapters[name]
return adap, ok
}
func createAdmin() error {
fmt.Println("Creating the admin user")
hashedPassword, salt, e := BcryptGeneratePassword("password")
if e != nil {
return e
}
fmt.Println("Creating the admin user")
hashedPassword, salt, e := BcryptGeneratePassword("password")
if e != nil {
return e
}
// Build the admin user query
adminUserStmt, e := qgen.Builder.SimpleInsert("users", "name, password, salt, email, group, is_super_admin, active, createdAt, lastActiveAt, lastLiked, oldestItemLikedCreatedAt, message, last_ip", "'Admin',?,?,'admin@localhost',1,1,1,UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),'',''")
if e != nil {
return e
}
// Build the admin user query
adminUserStmt, e := qgen.Builder.SimpleInsert("users", "name, password, salt, email, group, is_super_admin, active, createdAt, lastActiveAt, lastLiked, oldestItemLikedCreatedAt, message, last_ip", "'Admin',?,?,'admin@localhost',1,1,1,UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),'',''")
if e != nil {
return e
}
// Run the admin user query
_, e = adminUserStmt.Exec(hashedPassword, salt)
return e
// Run the admin user query
_, e = adminUserStmt.Exec(hashedPassword, salt)
return e
}

View File

@ -7,165 +7,165 @@
package install
import (
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"log"
"net/url"
"path/filepath"
"strconv"
"strings"
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"log"
"net/url"
"path/filepath"
"strconv"
"strings"
"github.com/Azareal/Gosora/query_gen"
_ "github.com/denisenkom/go-mssqldb"
"github.com/Azareal/Gosora/query_gen"
_ "github.com/denisenkom/go-mssqldb"
)
func init() {
adapters["mssql"] = &MssqlInstaller{dbHost: ""}
adapters["mssql"] = &MssqlInstaller{dbHost: ""}
}
type MssqlInstaller struct {
db *sql.DB
dbHost string
dbUsername string
dbPassword string
dbName string
dbInstance string
dbPort string
db *sql.DB
dbHost string
dbUsername string
dbPassword string
dbName string
dbInstance string
dbPort string
}
func (ins *MssqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
ins.dbHost = dbHost
ins.dbUsername = dbUsername
ins.dbPassword = dbPassword
ins.dbName = dbName
ins.dbInstance = "" // You can't set this from the installer right now, it allows you to connect to a named instance instead of a port
ins.dbPort = dbPort
ins.dbHost = dbHost
ins.dbUsername = dbUsername
ins.dbPassword = dbPassword
ins.dbName = dbName
ins.dbInstance = "" // You can't set this from the installer right now, it allows you to connect to a named instance instead of a port
ins.dbPort = dbPort
}
func (ins *MssqlInstaller) Name() string {
return "mssql"
return "mssql"
}
func (ins *MssqlInstaller) DefaultPort() string {
return "1433"
return "1433"
}
func (ins *MssqlInstaller) InitDatabase() (err error) {
query := url.Values{}
query.Add("database", ins.dbName)
u := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword(ins.dbUsername, ins.dbPassword),
Host: ins.dbHost + ":" + ins.dbPort,
Path: ins.dbInstance,
RawQuery: query.Encode(),
}
log.Print("u.String() ", u.String())
query := url.Values{}
query.Add("database", ins.dbName)
u := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword(ins.dbUsername, ins.dbPassword),
Host: ins.dbHost + ":" + ins.dbPort,
Path: ins.dbInstance,
RawQuery: query.Encode(),
}
log.Print("u.String() ", u.String())
db, err := sql.Open("mssql", u.String())
if err != nil {
return err
}
db, err := sql.Open("mssql", u.String())
if err != nil {
return err
}
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// TODO: Create the database, if it doesn't exist
// TODO: Create the database, if it doesn't exist
// Ready the query builder
ins.db = db
qgen.Builder.SetConn(db)
return qgen.Builder.SetAdapter("mssql")
// Ready the query builder
ins.db = db
qgen.Builder.SetConn(db)
return qgen.Builder.SetAdapter("mssql")
}
func (ins *MssqlInstaller) TableDefs() (err error) {
//fmt.Println("Creating the tables")
files, _ := ioutil.ReadDir("./schema/mssql/")
for _, f := range files {
if !strings.HasPrefix(f.Name(), "query_") {
continue
}
//fmt.Println("Creating the tables")
files, _ := ioutil.ReadDir("./schema/mssql/")
for _, f := range files {
if !strings.HasPrefix(f.Name(), "query_") {
continue
}
var table, ext string
table = strings.TrimPrefix(f.Name(), "query_")
ext = filepath.Ext(table)
if ext != ".sql" {
continue
}
table = strings.TrimSuffix(table, ext)
var table, ext string
table = strings.TrimPrefix(f.Name(), "query_")
ext = filepath.Ext(table)
if ext != ".sql" {
continue
}
table = strings.TrimSuffix(table, ext)
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
_, err = ins.db.Exec("DROP TABLE IF EXISTS [" + table + "];")
if err != nil {
fmt.Println("Failed query:", "DROP TABLE IF EXISTS ["+table+"]")
return err
}
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
_, err = ins.db.Exec("DROP TABLE IF EXISTS [" + table + "];")
if err != nil {
fmt.Println("Failed query:", "DROP TABLE IF EXISTS ["+table+"]")
return err
}
fmt.Println("Creating table '" + table + "'")
data, err := ioutil.ReadFile("./schema/mssql/" + f.Name())
if err != nil {
return err
}
data = bytes.TrimSpace(data)
fmt.Println("Creating table '" + table + "'")
data, err := ioutil.ReadFile("./schema/mssql/" + f.Name())
if err != nil {
return err
}
data = bytes.TrimSpace(data)
_, err = ins.db.Exec(string(data))
if err != nil {
fmt.Println("Failed query:", string(data))
return err
}
}
return nil
_, err = ins.db.Exec(string(data))
if err != nil {
fmt.Println("Failed query:", string(data))
return err
}
}
return nil
}
func (ins *MssqlInstaller) InitialData() (err error) {
//fmt.Println("Seeding the tables")
data, err := ioutil.ReadFile("./schema/mssql/inserts.sql")
if err != nil {
return err
}
data = bytes.TrimSpace(data)
//fmt.Println("Seeding the tables")
data, err := ioutil.ReadFile("./schema/mssql/inserts.sql")
if err != nil {
return err
}
data = bytes.TrimSpace(data)
statements := bytes.Split(data, []byte(";"))
for key, statement := range statements {
if len(statement) == 0 {
continue
}
statements := bytes.Split(data, []byte(";"))
for key, statement := range statements {
if len(statement) == 0 {
continue
}
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + string(statement))
_, err = ins.db.Exec(string(statement))
if err != nil {
return err
}
}
return nil
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + string(statement))
_, err = ins.db.Exec(string(statement))
if err != nil {
return err
}
}
return nil
}
func (ins *MssqlInstaller) CreateAdmin() error {
return createAdmin()
return createAdmin()
}
func (ins *MssqlInstaller) DBHost() string {
return ins.dbHost
return ins.dbHost
}
func (ins *MssqlInstaller) DBUsername() string {
return ins.dbUsername
return ins.dbUsername
}
func (ins *MssqlInstaller) DBPassword() string {
return ins.dbPassword
return ins.dbPassword
}
func (ins *MssqlInstaller) DBName() string {
return ins.dbName
return ins.dbName
}
func (ins *MssqlInstaller) DBPort() string {
return ins.dbPort
return ins.dbPort
}

View File

@ -7,177 +7,177 @@
package install
import (
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/Azareal/Gosora/query_gen"
_ "github.com/go-sql-driver/mysql"
"github.com/Azareal/Gosora/query_gen"
_ "github.com/go-sql-driver/mysql"
)
//var dbCollation string = "utf8mb4_general_ci"
func init() {
adapters["mysql"] = &MysqlInstaller{dbHost: ""}
adapters["mysql"] = &MysqlInstaller{dbHost: ""}
}
type MysqlInstaller struct {
db *sql.DB
dbHost string
dbUsername string
dbPassword string
dbName string
dbPort string
db *sql.DB
dbHost string
dbUsername string
dbPassword string
dbName string
dbPort string
}
func (ins *MysqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
ins.dbHost = dbHost
ins.dbUsername = dbUsername
ins.dbPassword = dbPassword
ins.dbName = dbName
ins.dbPort = dbPort
ins.dbHost = dbHost
ins.dbUsername = dbUsername
ins.dbPassword = dbPassword
ins.dbName = dbName
ins.dbPort = dbPort
}
func (ins *MysqlInstaller) Name() string {
return "mysql"
return "mysql"
}
func (ins *MysqlInstaller) DefaultPort() string {
return "3306"
return "3306"
}
func (ins *MysqlInstaller) dbExists(dbName string) (bool, error) {
var waste string
err := ins.db.QueryRow("SHOW DATABASES LIKE '" + dbName + "'").Scan(&waste)
if err != nil && err != sql.ErrNoRows {
return false, err
} else if err == sql.ErrNoRows {
return false, nil
}
return true, nil
var waste string
err := ins.db.QueryRow("SHOW DATABASES LIKE '" + dbName + "'").Scan(&waste)
if err != nil && err != sql.ErrNoRows {
return false, err
} else if err == sql.ErrNoRows {
return false, nil
}
return true, nil
}
func (ins *MysqlInstaller) InitDatabase() (err error) {
_dbPassword := ins.dbPassword
if _dbPassword != "" {
_dbPassword = ":" + _dbPassword
}
db, err := sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/")
if err != nil {
return err
}
_dbPassword := ins.dbPassword
if _dbPassword != "" {
_dbPassword = ":" + _dbPassword
}
db, err := sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/")
if err != nil {
return err
}
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
ins.db = db
ok, err := ins.dbExists(ins.dbName)
if err != nil {
return err
}
ins.db = db
ok, err := ins.dbExists(ins.dbName)
if err != nil {
return err
}
if !ok {
fmt.Println("Unable to find the database. Attempting to create it")
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + ins.dbName)
if err != nil {
return err
}
fmt.Println("The database was successfully created")
}
if !ok {
fmt.Println("Unable to find the database. Attempting to create it")
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + ins.dbName)
if err != nil {
return err
}
fmt.Println("The database was successfully created")
}
/*fmt.Println("Switching to database ", ins.dbName)
_, err = db.Exec("USE " + ins.dbName)
if err != nil {
return err
}*/
db.Close()
/*fmt.Println("Switching to database ", ins.dbName)
_, err = db.Exec("USE " + ins.dbName)
if err != nil {
return err
}*/
db.Close()
db, err = sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/"+ins.dbName)
if err != nil {
return err
}
db, err = sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/"+ins.dbName)
if err != nil {
return err
}
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// Ready the query builder
ins.db = db
qgen.Builder.SetConn(db)
return qgen.Builder.SetAdapter("mysql")
// Ready the query builder
ins.db = db
qgen.Builder.SetConn(db)
return qgen.Builder.SetAdapter("mysql")
}
func (ins *MysqlInstaller) createTable(f os.FileInfo) error {
table := strings.TrimPrefix(f.Name(), "query_")
ext := filepath.Ext(table)
if ext != ".sql" {
return nil
}
table = strings.TrimSuffix(table, ext)
table := strings.TrimPrefix(f.Name(), "query_")
ext := filepath.Ext(table)
if ext != ".sql" {
return nil
}
table = strings.TrimSuffix(table, ext)
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
q := "DROP TABLE IF EXISTS `" + table + "`;"
_, err := ins.db.Exec(q)
if err != nil {
fmt.Println("Failed query:", q)
fmt.Println("e:", err)
return err
}
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
q := "DROP TABLE IF EXISTS `" + table + "`;"
_, err := ins.db.Exec(q)
if err != nil {
fmt.Println("Failed query:", q)
fmt.Println("e:", err)
return err
}
data, err := ioutil.ReadFile("./schema/mysql/" + f.Name())
if err != nil {
return err
}
data = bytes.TrimSpace(data)
data, err := ioutil.ReadFile("./schema/mysql/" + f.Name())
if err != nil {
return err
}
data = bytes.TrimSpace(data)
q = string(data)
_, err = ins.db.Exec(q)
if err != nil {
fmt.Println("Failed query:", q)
fmt.Println("e:", err)
return err
}
fmt.Printf("Created table '%s'\n", table)
q = string(data)
_, err = ins.db.Exec(q)
if err != nil {
fmt.Println("Failed query:", q)
fmt.Println("e:", err)
return err
}
fmt.Printf("Created table '%s'\n", table)
return nil
return nil
}
func (ins *MysqlInstaller) TableDefs() (err error) {
fmt.Println("Creating the tables")
files, err := ioutil.ReadDir("./schema/mysql/")
if err != nil {
return err
}
fmt.Println("Creating the tables")
files, err := ioutil.ReadDir("./schema/mysql/")
if err != nil {
return err
}
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 0;")
if err != nil {
return err
}
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 0;")
if err != nil {
return err
}
for _, f := range files {
if !strings.HasPrefix(f.Name(), "query_") {
continue
}
err := ins.createTable(f)
if err != nil {
return err
}
}
for _, f := range files {
if !strings.HasPrefix(f.Name(), "query_") {
continue
}
err := ins.createTable(f)
if err != nil {
return err
}
}
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 1;")
return err
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 1;")
return err
}
// ? - Moved this here since it was breaking the installer, we need to add this at some point
@ -185,50 +185,50 @@ func (ins *MysqlInstaller) TableDefs() (err error) {
/*INSERT INTO settings(`name`,`content`,`type`) VALUES ('meta_desc','','html-attribute');*/
func (ins *MysqlInstaller) InitialData() error {
fmt.Println("Seeding the tables")
data, err := ioutil.ReadFile("./schema/mysql/inserts.sql")
if err != nil {
return err
}
data = bytes.TrimSpace(data)
fmt.Println("Seeding the tables")
data, err := ioutil.ReadFile("./schema/mysql/inserts.sql")
if err != nil {
return err
}
data = bytes.TrimSpace(data)
statements := bytes.Split(data, []byte(";"))
for key, sBytes := range statements {
statement := string(sBytes)
if statement == "" {
continue
}
statement += ";"
statements := bytes.Split(data, []byte(";"))
for key, sBytes := range statements {
statement := string(sBytes)
if statement == "" {
continue
}
statement += ";"
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + statement)
_, err = ins.db.Exec(statement)
if err != nil {
return err
}
}
return nil
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + statement)
_, err = ins.db.Exec(statement)
if err != nil {
return err
}
}
return nil
}
func (ins *MysqlInstaller) CreateAdmin() error {
return createAdmin()
return createAdmin()
}
func (ins *MysqlInstaller) DBHost() string {
return ins.dbHost
return ins.dbHost
}
func (ins *MysqlInstaller) DBUsername() string {
return ins.dbUsername
return ins.dbUsername
}
func (ins *MysqlInstaller) DBPassword() string {
return ins.dbPassword
return ins.dbPassword
}
func (ins *MysqlInstaller) DBName() string {
return ins.dbName
return ins.dbName
}
func (ins *MysqlInstaller) DBPort() string {
return ins.dbPort
return ins.dbPort
}

View File

@ -8,105 +8,105 @@
package install
import (
"database/sql"
"errors"
"fmt"
"strings"
"database/sql"
"errors"
"fmt"
"strings"
"github.com/Azareal/Gosora/query_gen"
_ "github.com/go-sql-driver/mysql"
"github.com/Azareal/Gosora/query_gen"
_ "github.com/go-sql-driver/mysql"
)
// We don't need SSL to run an installer... Do we?
var dbSslmode = "disable"
func init() {
adapters["pgsql"] = &PgsqlInstaller{dbHost: ""}
adapters["pgsql"] = &PgsqlInstaller{dbHost: ""}
}
type PgsqlInstaller struct {
db *sql.DB
dbHost string
dbUsername string
dbPassword string
dbName string
dbPort string
db *sql.DB
dbHost string
dbUsername string
dbPassword string
dbName string
dbPort string
}
func (ins *PgsqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
ins.dbHost = dbHost
ins.dbUsername = dbUsername
ins.dbPassword = dbPassword
ins.dbName = dbName
ins.dbPort = dbPort
ins.dbHost = dbHost
ins.dbUsername = dbUsername
ins.dbPassword = dbPassword
ins.dbName = dbName
ins.dbPort = dbPort
}
func (ins *PgsqlInstaller) Name() string {
return "pgsql"
return "pgsql"
}
func (ins *PgsqlInstaller) DefaultPort() string {
return "5432"
return "5432"
}
func (ins *PgsqlInstaller) InitDatabase() (err error) {
_dbPassword := ins.dbPassword
if _dbPassword != "" {
_dbPassword = " password=" + pgEscapeBit(_dbPassword)
}
db, err := sql.Open("postgres", "host='"+pgEscapeBit(ins.dbHost)+"' port='"+pgEscapeBit(ins.dbPort)+"' user='"+pgEscapeBit(ins.dbUsername)+"' dbname='"+pgEscapeBit(ins.dbName)+"'"+_dbPassword+" sslmode='"+dbSslmode+"'")
if err != nil {
return err
}
_dbPassword := ins.dbPassword
if _dbPassword != "" {
_dbPassword = " password=" + pgEscapeBit(_dbPassword)
}
db, err := sql.Open("postgres", "host='"+pgEscapeBit(ins.dbHost)+"' port='"+pgEscapeBit(ins.dbPort)+"' user='"+pgEscapeBit(ins.dbUsername)+"' dbname='"+pgEscapeBit(ins.dbName)+"'"+_dbPassword+" sslmode='"+dbSslmode+"'")
if err != nil {
return err
}
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// Make sure that the connection is alive..
err = db.Ping()
if err != nil {
return err
}
fmt.Println("Successfully connected to the database")
// TODO: Create the database, if it doesn't exist
// TODO: Create the database, if it doesn't exist
// Ready the query builder
ins.db = db
qgen.Builder.SetConn(db)
return qgen.Builder.SetAdapter("pgsql")
// Ready the query builder
ins.db = db
qgen.Builder.SetConn(db)
return qgen.Builder.SetAdapter("pgsql")
}
func (ins *PgsqlInstaller) TableDefs() (err error) {
return errors.New("TableDefs() not implemented")
return errors.New("TableDefs() not implemented")
}
func (ins *PgsqlInstaller) InitialData() (err error) {
return errors.New("InitialData() not implemented")
return errors.New("InitialData() not implemented")
}
func (ins *PgsqlInstaller) CreateAdmin() error {
return createAdmin()
return createAdmin()
}
func (ins *PgsqlInstaller) DBHost() string {
return ins.dbHost
return ins.dbHost
}
func (ins *PgsqlInstaller) DBUsername() string {
return ins.dbUsername
return ins.dbUsername
}
func (ins *PgsqlInstaller) DBPassword() string {
return ins.dbPassword
return ins.dbPassword
}
func (ins *PgsqlInstaller) DBName() string {
return ins.dbName
return ins.dbName
}
func (ins *PgsqlInstaller) DBPort() string {
return ins.dbPort
return ins.dbPort
}
func pgEscapeBit(bit string) string {
// TODO: Write a custom parser, so that backslashes work properly in the sql.Open string. Do something similar for the database driver, if possible?
return strings.Replace(bit, "'", "\\'", -1)
// TODO: Write a custom parser, so that backslashes work properly in the sql.Open string. Do something similar for the database driver, if possible?
return strings.Replace(bit, "'", "\\'", -1)
}

View File

@ -8,20 +8,20 @@ const saltLength int = 32
// Generate a cryptographically secure set of random bytes..
func GenerateSafeString(length int) (string, error) {
rb := make([]byte, length)
_, err := rand.Read(rb)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(rb), nil
rb := make([]byte, length)
_, err := rand.Read(rb)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(rb), nil
}
// Generate a bcrypt hash
// Note: The salt is in the hash, therefore the salt value is blank
func BcryptGeneratePassword(password string) (hash string, salt string, err error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", "", err
}
return string(hashedPassword), salt, nil
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", "", err
}
return string(hashedPassword), salt, nil
}

View File

@ -1 +0,0 @@
0.1.0-dev

1314
main.go

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

110
mysql.go
View File

@ -2,81 +2,81 @@
/*
*
* Gosora MySQL Interface
* Copyright Azareal 2016 - 2020
* Gosora MySQL Interface
* Copyright Azareal 2016 - 2020
*
*/
package main
import (
"log"
"log"
c "github.com/Azareal/Gosora/common"
qgen "github.com/Azareal/Gosora/query_gen"
_ "github.com/go-sql-driver/mysql"
"github.com/pkg/errors"
c "github.com/Azareal/Gosora/common"
qgen "github.com/Azareal/Gosora/query_gen"
_ "github.com/go-sql-driver/mysql"
"github.com/pkg/errors"
)
var dbCollation = "utf8mb4_general_ci"
func init() {
dbAdapter = "mysql"
_initDatabase = initMySQL
dbAdapter = "mysql"
_initDatabase = initMySQL
}
func initMySQL() (err error) {
err = qgen.Builder.Init("mysql", map[string]string{
"host": c.DbConfig.Host,
"port": c.DbConfig.Port,
"name": c.DbConfig.Dbname,
"username": c.DbConfig.Username,
"password": c.DbConfig.Password,
"collation": dbCollation,
})
if err != nil {
return errors.WithStack(err)
}
err = qgen.Builder.Init("mysql", map[string]string{
"host": c.DbConfig.Host,
"port": c.DbConfig.Port,
"name": c.DbConfig.Dbname,
"username": c.DbConfig.Username,
"password": c.DbConfig.Password,
"collation": dbCollation,
})
if err != nil {
return errors.WithStack(err)
}
// Set the number of max open connections
db = qgen.Builder.GetConn()
db.SetMaxOpenConns(64)
db.SetMaxIdleConns(32)
//db.SetConnMaxLifetime(time.Second * 60 * 5) // Just in case we accumulate some bad connections due to the MySQL driver being stupid
// Set the number of max open connections
db = qgen.Builder.GetConn()
db.SetMaxOpenConns(64)
db.SetMaxIdleConns(32)
//db.SetConnMaxLifetime(time.Second * 60 * 5) // Just in case we accumulate some bad connections due to the MySQL driver being stupid
// Only hold connections open for five seconds to avoid accumulating a large number of stale connections
//db.SetConnMaxLifetime(5 * time.Second)
db.SetConnMaxLifetime(c.DBTimeout())
// Only hold connections open for five seconds to avoid accumulating a large number of stale connections
//db.SetConnMaxLifetime(5 * time.Second)
db.SetConnMaxLifetime(c.DBTimeout())
// Build the generated prepared statements, we are going to slowly move the queries over to the query generator rather than writing them all by hand, this'll make it easier for us to implement database adapters for other databases like PostgreSQL, MSSQL, SQlite, etc.
err = _gen_mysql()
if err != nil {
return errors.WithStack(err)
}
// Build the generated prepared statements, we are going to slowly move the queries over to the query generator rather than writing them all by hand, this'll make it easier for us to implement database adapters for other databases like PostgreSQL, MSSQL, SQlite, etc.
err = _gen_mysql()
if err != nil {
return errors.WithStack(err)
}
// TODO: Is there a less noisy way of doing this for tests?
/*log.Print("Preparing getActivityFeedByWatcher statement.")
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM `activity_stream_matches` INNER JOIN `activity_stream` ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE `watcher` = ? ORDER BY activity_stream.asid DESC LIMIT 16")
if err != nil {
return errors.WithStack(err)
}*/
// TODO: Is there a less noisy way of doing this for tests?
/*log.Print("Preparing getActivityFeedByWatcher statement.")
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM `activity_stream_matches` INNER JOIN `activity_stream` ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE `watcher` = ? ORDER BY activity_stream.asid DESC LIMIT 16")
if err != nil {
return errors.WithStack(err)
}*/
log.Print("Preparing getActivityFeedByWatcher statement.")
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? ORDER BY activity_stream.asid DESC LIMIT ?")
if err != nil {
return errors.WithStack(err)
}
log.Print("Preparing getActivityFeedByWatcher statement.")
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? ORDER BY activity_stream.asid DESC LIMIT ?")
if err != nil {
return errors.WithStack(err)
}
/*log.Print("Preparing getActivityFeedByWatcherAfter statement.")
stmts.getActivityFeedByWatcherAfter, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? AND asid => ? ORDER BY activity_stream.asid DESC LIMIT ?")
if err != nil {
return errors.WithStack(err)
}*/
/*log.Print("Preparing getActivityFeedByWatcherAfter statement.")
stmts.getActivityFeedByWatcherAfter, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? AND asid => ? ORDER BY activity_stream.asid DESC LIMIT ?")
if err != nil {
return errors.WithStack(err)
}*/
log.Print("Preparing getActivityCountByWatcher statement.")
stmts.getActivityCountByWatcher, err = db.Prepare("SELECT count(*) FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=?")
if err != nil {
return errors.WithStack(err)
}
log.Print("Preparing getActivityCountByWatcher statement.")
stmts.getActivityCountByWatcher, err = db.Prepare("SELECT count(*) FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=?")
if err != nil {
return errors.WithStack(err)
}
return nil
return nil
}

View File

@ -1,24 +1,24 @@
{
"strict": true,
"newcap": false,
"node": true,
"expr": true,
"supernew": true,
"laxbreak": true,
"white": true,
"globals": {
"define": true,
"test": true,
"expect": true,
"module": true,
"asyncTest": true,
"start": true,
"ok": true,
"equal": true,
"notEqual": true,
"deepEqual": true,
"window": true,
"document": true,
"performance": true
}
"strict": true,
"newcap": false,
"node": true,
"expr": true,
"supernew": true,
"laxbreak": true,
"white": true,
"globals": {
"define": true,
"test": true,
"expect": true,
"module": true,
"asyncTest": true,
"start": true,
"ok": true,
"equal": true,
"notEqual": true,
"deepEqual": true,
"window": true,
"document": true,
"performance": true
}
}

View File

@ -33,9 +33,9 @@ Demo: http://rubaxa.github.io/Sortable/
### Usage
```html
<ul id="items">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
```
@ -53,79 +53,79 @@ You can use any element for the list and its elements, not just `ul`/`li`. Here
### Options
```js
var sortable = new Sortable(el, {
group: "name", // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
sort: true, // sorting inside list
delay: 0, // time in milliseconds to define when the sorting should start
disabled: false, // Disables the sortable if set to true.
store: null, // @see Store
animation: 150, // ms, animation speed moving items when sorting, `0` — without animation
handle: ".my-handle", // Drag handle selector within list items
filter: ".ignore-elements", // Selectors that do not lead to dragging (String or Function)
draggable: ".item", // Specifies which items inside the element should be sortable
ghostClass: "sortable-ghost", // Class name for the drop placeholder
chosenClass: "sortable-chosen", // Class name for the chosen item
dataIdAttr: 'data-id',
forceFallback: false, // ignore the HTML5 DnD behaviour and force the fallback to kick in
fallbackClass: "sortable-fallback" // Class name for the cloned DOM Element when using forceFallback
fallbackOnBody: false // Appends the cloned DOM Element into the Document's Body
scroll: true, // or HTMLElement
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
scrollSpeed: 10, // px
setData: function (dataTransfer, dragEl) {
dataTransfer.setData('Text', dragEl.textContent);
},
group: "name", // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
sort: true, // sorting inside list
delay: 0, // time in milliseconds to define when the sorting should start
disabled: false, // Disables the sortable if set to true.
store: null, // @see Store
animation: 150, // ms, animation speed moving items when sorting, `0` — without animation
handle: ".my-handle", // Drag handle selector within list items
filter: ".ignore-elements", // Selectors that do not lead to dragging (String or Function)
draggable: ".item", // Specifies which items inside the element should be sortable
ghostClass: "sortable-ghost", // Class name for the drop placeholder
chosenClass: "sortable-chosen", // Class name for the chosen item
dataIdAttr: 'data-id',
forceFallback: false, // ignore the HTML5 DnD behaviour and force the fallback to kick in
fallbackClass: "sortable-fallback" // Class name for the cloned DOM Element when using forceFallback
fallbackOnBody: false // Appends the cloned DOM Element into the Document's Body
scroll: true, // or HTMLElement
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
scrollSpeed: 10, // px
setData: function (dataTransfer, dragEl) {
dataTransfer.setData('Text', dragEl.textContent);
},
// dragging started
onStart: function (/**Event*/evt) {
evt.oldIndex; // element index within parent
},
// dragging ended
onEnd: function (/**Event*/evt) {
evt.oldIndex; // element's old index within parent
evt.newIndex; // element's new index within parent
},
// dragging started
onStart: function (/**Event*/evt) {
evt.oldIndex; // element index within parent
},
// dragging ended
onEnd: function (/**Event*/evt) {
evt.oldIndex; // element's old index within parent
evt.newIndex; // element's new index within parent
},
// Element is dropped into the list from another list
onAdd: function (/**Event*/evt) {
var itemEl = evt.item; // dragged HTMLElement
evt.from; // previous list
// + indexes from onEnd
},
// Element is dropped into the list from another list
onAdd: function (/**Event*/evt) {
var itemEl = evt.item; // dragged HTMLElement
evt.from; // previous list
// + indexes from onEnd
},
// Changed sorting within list
onUpdate: function (/**Event*/evt) {
var itemEl = evt.item; // dragged HTMLElement
// + indexes from onEnd
},
// Changed sorting within list
onUpdate: function (/**Event*/evt) {
var itemEl = evt.item; // dragged HTMLElement
// + indexes from onEnd
},
// Called by any change to the list (add / update / remove)
onSort: function (/**Event*/evt) {
// same properties as onUpdate
},
// Called by any change to the list (add / update / remove)
onSort: function (/**Event*/evt) {
// same properties as onUpdate
},
// Element is removed from the list into another list
onRemove: function (/**Event*/evt) {
// same properties as onUpdate
},
// Element is removed from the list into another list
onRemove: function (/**Event*/evt) {
// same properties as onUpdate
},
// Attempt to drag a filtered element
onFilter: function (/**Event*/evt) {
var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
},
// Event when you move an item in the list or between lists
onMove: function (/**Event*/evt) {
// Example: http://jsbin.com/tuyafe/1/edit?js,output
evt.dragged; // dragged HTMLElement
evt.draggedRect; // TextRectangle {left, top, right и bottom}
evt.related; // HTMLElement on which have guided
evt.relatedRect; // TextRectangle
// return false; — for cancel
}
// Attempt to drag a filtered element
onFilter: function (/**Event*/evt) {
var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
},
// Event when you move an item in the list or between lists
onMove: function (/**Event*/evt) {
// Example: http://jsbin.com/tuyafe/1/edit?js,output
evt.dragged; // dragged HTMLElement
evt.draggedRect; // TextRectangle {left, top, right и bottom}
evt.related; // HTMLElement on which have guided
evt.relatedRect; // TextRectangle
// return false; — for cancel
}
});
```
@ -172,9 +172,9 @@ Demo: http://jsbin.com/xiloqu/1/edit?html,js,output
var sortable = Sortable.create(list);
document.getElementById("switcher").onclick = function () {
var state = sortable.option("disabled"); // get
var state = sortable.option("disabled"); // get
sortable.option("disabled", !state); // set
sortable.option("disabled", !state); // set
};
```
@ -191,21 +191,21 @@ Demo: http://jsbin.com/newize/1/edit?html,js,output
```js
Sortable.create(el, {
handle: ".my-handle"
handle: ".my-handle"
});
```
```html
<ul>
<li><span class="my-handle">::</span> list item text one
<li><span class="my-handle">::</span> list item text two
<li><span class="my-handle">::</span> list item text one
<li><span class="my-handle">::</span> list item text two
</ul>
```
```css
.my-handle {
cursor: move;
cursor: -webkit-grabbing;
cursor: move;
cursor: -webkit-grabbing;
}
```
@ -218,18 +218,18 @@ Sortable.create(el, {
```js
Sortable.create(list, {
filter: ".js-remove, .js-edit",
onFilter: function (evt) {
var item = evt.item,
ctrl = evt.target;
filter: ".js-remove, .js-edit",
onFilter: function (evt) {
var item = evt.item,
ctrl = evt.target;
if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button
item.parentNode.removeChild(item); // remove sortable item
}
else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link
// ...
}
}
if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button
item.parentNode.removeChild(item); // remove sortable item
}
else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link
// ...
}
}
})
```
@ -326,35 +326,35 @@ Demo: http://jsbin.com/naduvo/1/edit?html,js,output
```html
<div ng-app="myApp" ng-controller="demo">
<ul ng-sortable>
<li ng-repeat="item in items">{{item}}</li>
</ul>
<ul ng-sortable>
<li ng-repeat="item in items">{{item}}</li>
</ul>
<ul ng-sortable="{ group: 'foobar' }">
<li ng-repeat="item in foo">{{item}}</li>
</ul>
<ul ng-sortable="{ group: 'foobar' }">
<li ng-repeat="item in foo">{{item}}</li>
</ul>
<ul ng-sortable="barConfig">
<li ng-repeat="item in bar">{{item}}</li>
</ul>
<ul ng-sortable="barConfig">
<li ng-repeat="item in bar">{{item}}</li>
</ul>
</div>
```
```js
angular.module('myApp', ['ng-sortable'])
.controller('demo', ['$scope', function ($scope) {
$scope.items = ['item 1', 'item 2'];
$scope.foo = ['foo 1', '..'];
$scope.bar = ['bar 1', '..'];
$scope.barConfig = {
group: 'foobar',
animation: 150,
onSort: function (/** ngSortEvent */evt){
// @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24
}
};
}]);
.controller('demo', ['$scope', function ($scope) {
$scope.items = ['item 1', 'item 2'];
$scope.foo = ['foo 1', '..'];
$scope.bar = ['bar 1', '..'];
$scope.barConfig = {
group: 'foobar',
animation: 150,
onSort: function (/** ngSortEvent */evt){
// @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24
}
};
}]);
```
@ -369,23 +369,23 @@ See [more options](react-sortable-mixin.js#L26).
```jsx
var SortableList = React.createClass({
mixins: [SortableMixin],
mixins: [SortableMixin],
getInitialState: function() {
return {
items: ['Mixin', 'Sortable']
};
},
getInitialState: function() {
return {
items: ['Mixin', 'Sortable']
};
},
handleSort: function (/** Event */evt) { /*..*/ },
handleSort: function (/** Event */evt) { /*..*/ },
render: function() {
return <ul>{
this.state.items.map(function (text) {
return <li>{text}</li>
})
}</ul>
}
render: function() {
return <ul>{
this.state.items.map(function (text) {
return <li>{text}</li>
})
}</ul>
}
});
React.render(<SortableList />, document.body);
@ -395,51 +395,51 @@ React.render(<SortableList />, document.body);
// Groups
//
var AllUsers = React.createClass({
mixins: [SortableMixin],
mixins: [SortableMixin],
sortableOptions: {
ref: "user",
group: "shared",
model: "users"
},
sortableOptions: {
ref: "user",
group: "shared",
model: "users"
},
getInitialState: function() {
return { users: ['Abbi', 'Adela', 'Bud', 'Cate', 'Davis', 'Eric']; };
},
getInitialState: function() {
return { users: ['Abbi', 'Adela', 'Bud', 'Cate', 'Davis', 'Eric']; };
},
render: function() {
return (
<h1>Users</h1>
<ul ref="user">{
this.state.users.map(function (text) {
return <li>{text}</li>
})
}</ul>
);
}
render: function() {
return (
<h1>Users</h1>
<ul ref="user">{
this.state.users.map(function (text) {
return <li>{text}</li>
})
}</ul>
);
}
});
var ApprovedUsers = React.createClass({
mixins: [SortableMixin],
sortableOptions: { group: "shared" },
mixins: [SortableMixin],
sortableOptions: { group: "shared" },
getInitialState: function() {
return { items: ['Hal', 'Judy']; };
},
getInitialState: function() {
return { items: ['Hal', 'Judy']; };
},
render: function() {
return <ul>{
this.state.items.map(function (text) {
return <li>{text}</li>
})
}</ul>
}
render: function() {
return <ul>{
this.state.items.map(function (text) {
return <li>{text}</li>
})
}</ul>
}
});
React.render(<div>
<AllUsers/>
<hr/>
<ApprovedUsers/>
<AllUsers/>
<hr/>
<ApprovedUsers/>
</div>, document.body);
```
@ -453,11 +453,11 @@ Include [knockout-sortable.js](knockout-sortable.js)
```html
<div data-bind="sortable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
<!-- optional item template here -->
<!-- optional item template here -->
</div>
<div data-bind="draggable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
<!-- optional item template here -->
<!-- optional item template here -->
</div>
```
@ -466,8 +466,8 @@ Using this bindingHandler sorts the observableArray when the user sorts the HTML
The sortable/draggable bindingHandlers supports the same syntax as Knockouts built in [template](http://knockoutjs.com/documentation/template-binding.html) binding except for the `data` option, meaning that you could supply the name of a template or specify a separate templateEngine. The difference between the sortable and draggable handlers is that the draggable has the sortable `group` option set to `{pull:'clone',put: false}` and the `sort` option set to false by default (overridable).
Other attributes are:
* options: an object that contains settings for the underlaying sortable, ie `group`,`handle`, events etc.
* collection: if your `foreach` array is a computed then you would supply the underlaying observableArray that you would like to sort here.
* options: an object that contains settings for the underlaying sortable, ie `group`,`handle`, events etc.
* collection: if your `foreach` array is a computed then you would supply the underlaying observableArray that you would like to sort here.
---
@ -527,35 +527,35 @@ Saving and restoring of the sort.
```html
<ul>
<li data-id="1">order</li>
<li data-id="2">save</li>
<li data-id="3">restore</li>
<li data-id="1">order</li>
<li data-id="2">save</li>
<li data-id="3">restore</li>
</ul>
```
```js
Sortable.create(el, {
group: "localStorage-example",
store: {
/**
* Get the order of elements. Called once during initialization.
* @param {Sortable} sortable
* @returns {Array}
*/
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group);
return order ? order.split('|') : [];
},
group: "localStorage-example",
store: {
/**
* Get the order of elements. Called once during initialization.
* @param {Sortable} sortable
* @returns {Array}
*/
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group);
return order ? order.split('|') : [];
},
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* @param {Sortable} sortable
*/
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group, order.join('|'));
}
}
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* @param {Sortable} sortable
*/
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group, order.join('|'));
}
}
})
```
@ -578,11 +578,11 @@ Demo: http://jsbin.com/luxero/2/edit?html,js,output
<!-- Simple List -->
<ul id="simpleList" class="list-group">
<li class="list-group-item">This is <a href="http://rubaxa.github.io/Sortable/">Sortable</a></li>
<li class="list-group-item">It works with Bootstrap...</li>
<li class="list-group-item">...out of the box.</li>
<li class="list-group-item">It has support for touch devices.</li>
<li class="list-group-item">Just drag some elements around.</li>
<li class="list-group-item">This is <a href="http://rubaxa.github.io/Sortable/">Sortable</a></li>
<li class="list-group-item">It works with Bootstrap...</li>
<li class="list-group-item">...out of the box.</li>
<li class="list-group-item">It has support for touch devices.</li>
<li class="list-group-item">Just drag some elements around.</li>
</ul>
<script>

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
{
"name": "Sortable",
"main": [
"Sortable.js",
"ng-sortable.js",
"knockout-sortable.js",
"react-sortable-mixin.js"
"Sortable.js",
"ng-sortable.js",
"knockout-sortable.js",
"react-sortable-mixin.js"
],
"homepage": "http://rubaxa.github.io/Sortable/",
"authors": [
@ -20,7 +20,7 @@
"and",
"drop",
"dnd",
"web-components"
"web-components"
],
"license": "MIT",
"ignore": [
@ -31,5 +31,5 @@
],
"dependencies": {
"polymer": "Polymer/polymer#~1.1.4",
}
}
}

View File

@ -1,61 +1,61 @@
/**
* jQuery plugin for Sortable
* @author RubaXa <trash@rubaxa.org>
* @author RubaXa <trash@rubaxa.org>
* @license MIT
*/
(function (factory) {
"use strict";
"use strict";
if (typeof define === "function" && define.amd) {
define(["jquery"], factory);
}
else {
/* jshint sub:true */
factory(jQuery);
}
if (typeof define === "function" && define.amd) {
define(["jquery"], factory);
}
else {
/* jshint sub:true */
factory(jQuery);
}
})(function ($) {
"use strict";
"use strict";
/* CODE */
/* CODE */
/**
* jQuery plugin for Sortable
* @param {Object|String} options
* @param {..*} [args]
* @returns {jQuery|*}
*/
$.fn.sortable = function (options) {
var retVal,
args = arguments;
/**
* jQuery plugin for Sortable
* @param {Object|String} options
* @param {..*} [args]
* @returns {jQuery|*}
*/
$.fn.sortable = function (options) {
var retVal,
args = arguments;
this.each(function () {
var $el = $(this),
sortable = $el.data('sortable');
this.each(function () {
var $el = $(this),
sortable = $el.data('sortable');
if (!sortable && (options instanceof Object || !options)) {
sortable = new Sortable(this, options);
$el.data('sortable', sortable);
}
if (!sortable && (options instanceof Object || !options)) {
sortable = new Sortable(this, options);
$el.data('sortable', sortable);
}
if (sortable) {
if (options === 'widget') {
return sortable;
}
else if (options === 'destroy') {
sortable.destroy();
$el.removeData('sortable');
}
else if (typeof sortable[options] === 'function') {
retVal = sortable[options].apply(sortable, [].slice.call(args, 1));
}
else if (options in sortable.options) {
retVal = sortable.option.apply(sortable, args);
}
}
});
if (sortable) {
if (options === 'widget') {
return sortable;
}
else if (options === 'destroy') {
sortable.destroy();
$el.removeData('sortable');
}
else if (typeof sortable[options] === 'function') {
retVal = sortable[options].apply(sortable, [].slice.call(args, 1));
}
else if (options in sortable.options) {
retVal = sortable.option.apply(sortable, args);
}
}
});
return (retVal === void 0) ? this : retVal;
};
return (retVal === void 0) ? this : retVal;
};
});

View File

@ -2,8 +2,8 @@
(() => {
addInitHook("end_init", () => {
$("#dash_username input").click(()=>{
$("#dash_username button").show();
});
$("#dash_username input").click(()=>{
$("#dash_username button").show();
});
});
})()

View File

@ -1,74 +1,74 @@
function memStuff(window,document,Chartist) {
'use strict';
Chartist.plugins = Chartist.plugins || {};
Chartist.plugins.byteUnits = function(options) {
options = Chartist.extend({},{},options);
'use strict';
Chartist.plugins = Chartist.plugins || {};
Chartist.plugins.byteUnits = function(options) {
options = Chartist.extend({},{},options);
return function byteUnits(chart) {
if(!chart instanceof Chartist.Line) return;
chart.on('created', function() {
log("running created")
const vbits = document.getElementsByClassName("ct-vertical");
if(vbits==null) return;
if(!chart instanceof Chartist.Line) return;
chart.on('created', function() {
log("running created")
const vbits = document.getElementsByClassName("ct-vertical");
if(vbits==null) return;
let tbits = [];
for(let i=0; i<vbits.length; i++) {
tbits[i] = vbits[i].innerHTML;
}
log("tbits",tbits);
const calc = (places) => {
if(places==3) return;
const matcher = vbits[0].innerHTML;
let allMatch = true;
for(let i=0; i<tbits.length; i++) {
let val = convertByteUnit(tbits[i], places);
if(val!=matcher) allMatch = false;
vbits[i].innerHTML = val;
}
if(allMatch) calc(places + 1);
}
calc(0);
let tbits = [];
for(let i=0; i<vbits.length; i++) {
tbits[i] = vbits[i].innerHTML;
}
log("tbits",tbits);
const calc = (places) => {
if(places==3) return;
const matcher = vbits[0].innerHTML;
let allMatch = true;
for(let i=0; i<tbits.length; i++) {
let val = convertByteUnit(tbits[i], places);
if(val!=matcher) allMatch = false;
vbits[i].innerHTML = val;
}
if(allMatch) calc(places + 1);
}
calc(0);
});
};
};
}
function perfStuff(window,document,Chartist) {
'use strict';
Chartist.plugins = Chartist.plugins || {};
Chartist.plugins.perfUnits = function(options) {
options = Chartist.extend({},{},options);
'use strict';
Chartist.plugins = Chartist.plugins || {};
Chartist.plugins.perfUnits = function(options) {
options = Chartist.extend({},{},options);
return function perfUnits(chart) {
if(!chart instanceof Chartist.Line) return;
chart.on('created', function() {
log("running created")
const vbits = document.getElementsByClassName("ct-vertical");
if(vbits==null) return;
if(!chart instanceof Chartist.Line) return;
chart.on('created', function() {
log("running created")
const vbits = document.getElementsByClassName("ct-vertical");
if(vbits==null) return;
let tbits = [];
for(let i=0; i<vbits.length; i++) {
tbits[i] = vbits[i].innerHTML;
}
log("tbits:",tbits);
const calc = (places) => {
if(places==3) return;
const matcher = vbits[0].innerHTML;
let allMatch = true;
for(let i=0; i<tbits.length; i++) {
let val = convertPerfUnit(tbits[i], places);
if(val!=matcher) allMatch = false;
vbits[i].innerHTML = val;
}
if(allMatch) calc(places + 1);
}
calc(0);
let tbits = [];
for(let i=0; i<vbits.length; i++) {
tbits[i] = vbits[i].innerHTML;
}
log("tbits:",tbits);
const calc = (places) => {
if(places==3) return;
const matcher = vbits[0].innerHTML;
let allMatch = true;
for(let i=0; i<tbits.length; i++) {
let val = convertPerfUnit(tbits[i], places);
if(val!=matcher) allMatch = false;
vbits[i].innerHTML = val;
}
if(allMatch) calc(places + 1);
}
calc(0);
});
};
};
@ -81,19 +81,19 @@ const Terabyte = Gigabyte * 1024;
const Petabyte = Terabyte * 1024;
function convertByteUnit(bytes, places = 0) {
let o;
if(bytes >= Petabyte) o = [bytes / Petabyte, "PB"];
else if(bytes >= Terabyte) o = [bytes / Terabyte, "TB"];
else if(bytes >= Gigabyte) o = [bytes / Gigabyte, "GB"];
else if(bytes >= Megabyte) o = [bytes / Megabyte, "MB"];
else if(bytes >= Kilobyte) o = [bytes / Kilobyte, "KB"];
else o = [bytes,"b"];
let o;
if(bytes >= Petabyte) o = [bytes / Petabyte, "PB"];
else if(bytes >= Terabyte) o = [bytes / Terabyte, "TB"];
else if(bytes >= Gigabyte) o = [bytes / Gigabyte, "GB"];
else if(bytes >= Megabyte) o = [bytes / Megabyte, "MB"];
else if(bytes >= Kilobyte) o = [bytes / Kilobyte, "KB"];
else o = [bytes,"b"];
if(places==0) return Math.ceil(o[0]) + o[1];
else {
let ex = Math.pow(10, places);
return (Math.round(o[0], ex) / ex) + o[1];
}
if(places==0) return Math.ceil(o[0]) + o[1];
else {
let ex = Math.pow(10, places);
return (Math.round(o[0], ex) / ex) + o[1];
}
}
let ms = 1000;
@ -102,89 +102,89 @@ let min = sec * 60;
let hour = min * 60;
let day = hour * 24;
function convertPerfUnit(quan, places = 0) {
let o;
if(quan >= day) o = [quan / day, "d"];
else if(quan >= hour) o = [quan / hour, "h"];
else if(quan >= min) o = [quan / min, "m"];
else if(quan >= sec) o = [quan / sec, "s"];
else if(quan >= ms) o = [quan / ms, "ms"];
else o = [quan,"μs"];
let o;
if(quan >= day) o = [quan / day, "d"];
else if(quan >= hour) o = [quan / hour, "h"];
else if(quan >= min) o = [quan / min, "m"];
else if(quan >= sec) o = [quan / sec, "s"];
else if(quan >= ms) o = [quan / ms, "ms"];
else o = [quan,"μs"];
if(places==0) return Math.ceil(o[0]) + o[1];
else {
let ex = Math.pow(10, places);
return (Math.round(o[0], ex) / ex) + o[1];
}
if(places==0) return Math.ceil(o[0]) + o[1];
else {
let ex = Math.pow(10, places);
return (Math.round(o[0], ex) / ex) + o[1];
}
}
// TODO: Fully localise this
// TODO: Load rawLabels and seriesData dynamically rather than potentially fiddling with nonces for the CSP?
function buildStatsChart(rawLabels, seriesData, timeRange, legendNames, typ=0) {
log("buildStatsChart");
log("seriesData",seriesData);
let labels = [];
let aphrases = phraseBox["analytics"];
if(timeRange=="one-year") {
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.months_short"]];
for(let i = 2; i < 12; i++) {
labels.push(i + aphrases["analytics.months_short"]);
}
} else if(timeRange=="three-months") {
labels = [aphrases["analytics.now"],"3" + aphrases["analytics.days_short"]]
for(let i = 6; i < 90; i = i + 3) {
if (i%2==0) labels.push("");
else labels.push(i + aphrases["analytics.days_short"]);
}
} else if(timeRange=="one-month") {
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.days_short"]];
for(let i = 2; i < 30; i++) {
if (i%2==0) labels.push("");
else labels.push(i + aphrases["analytics.days_short"]);
}
} else if(timeRange=="one-week") {
labels = [aphrases["analytics.now"]];
for(let i = 2; i < 14; i++) {
if (i%2==0) labels.push("");
else labels.push(Math.floor(i/2) + aphrases["analytics.days"]);
}
} else if (timeRange=="two-days" || timeRange == "one-day" || timeRange == "twelve-hours") {
for(const i in rawLabels) {
if (i%2==0) {
labels.push("");
continue;
}
let date = new Date(rawLabels[i]*1000);
log("date",date);
let minutes = "0" + date.getMinutes();
let label = date.getHours() + ":" + minutes.substr(-2);
log("label",label);
labels.push(label);
}
} else {
for(const i in rawLabels) {
let date = new Date(rawLabels[i]*1000);
log("date",date);
let minutes = "0" + date.getMinutes();
let label = date.getHours() + ":" + minutes.substr(-2);
log("label",label);
labels.push(label);
}
}
labels = labels.reverse()
for(let i = 0; i < seriesData.length; i++) {
seriesData[i] = seriesData[i].reverse();
}
log("buildStatsChart");
log("seriesData",seriesData);
let labels = [];
let aphrases = phraseBox["analytics"];
if(timeRange=="one-year") {
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.months_short"]];
for(let i = 2; i < 12; i++) {
labels.push(i + aphrases["analytics.months_short"]);
}
} else if(timeRange=="three-months") {
labels = [aphrases["analytics.now"],"3" + aphrases["analytics.days_short"]]
for(let i = 6; i < 90; i = i + 3) {
if (i%2==0) labels.push("");
else labels.push(i + aphrases["analytics.days_short"]);
}
} else if(timeRange=="one-month") {
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.days_short"]];
for(let i = 2; i < 30; i++) {
if (i%2==0) labels.push("");
else labels.push(i + aphrases["analytics.days_short"]);
}
} else if(timeRange=="one-week") {
labels = [aphrases["analytics.now"]];
for(let i = 2; i < 14; i++) {
if (i%2==0) labels.push("");
else labels.push(Math.floor(i/2) + aphrases["analytics.days"]);
}
} else if (timeRange=="two-days" || timeRange == "one-day" || timeRange == "twelve-hours") {
for(const i in rawLabels) {
if (i%2==0) {
labels.push("");
continue;
}
let date = new Date(rawLabels[i]*1000);
log("date",date);
let minutes = "0" + date.getMinutes();
let label = date.getHours() + ":" + minutes.substr(-2);
log("label",label);
labels.push(label);
}
} else {
for(const i in rawLabels) {
let date = new Date(rawLabels[i]*1000);
log("date",date);
let minutes = "0" + date.getMinutes();
let label = date.getHours() + ":" + minutes.substr(-2);
log("label",label);
labels.push(label);
}
}
labels = labels.reverse()
for(let i = 0; i < seriesData.length; i++) {
seriesData[i] = seriesData[i].reverse();
}
let config = {height: '250px', plugins:[]};
if(legendNames.length > 0) config.plugins = [
Chartist.plugins.legend({legendNames: legendNames})
];
if(typ==1) config.plugins.push(Chartist.plugins.byteUnits());
else if(typ==2) config.plugins.push(Chartist.plugins.perfUnits());
Chartist.Line('.ct_chart', {
labels: labels,
series: seriesData,
}, config);
let config = {height: '250px', plugins:[]};
if(legendNames.length > 0) config.plugins = [
Chartist.plugins.legend({legendNames: legendNames})
];
if(typ==1) config.plugins.push(Chartist.plugins.byteUnits());
else if(typ==2) config.plugins.push(Chartist.plugins.perfUnits());
Chartist.Line('.ct_chart', {
labels: labels,
series: seriesData,
}, config);
}
runInitHook("analytics_loaded");

File diff suppressed because one or more lines are too long

View File

@ -1,12 +1,12 @@
(() => {
addInitHook("end_init", () => {
$(".create_convo_link").click((event) => {
event.preventDefault();
$(".convo_create_form").removeClass("auto_hide");
});
$(".convo_create_form .close_form").click((event) => {
event.preventDefault();
$(".convo_create_form").addClass("auto_hide");
});
});
addInitHook("end_init", () => {
$(".create_convo_link").click((event) => {
event.preventDefault();
$(".convo_create_form").removeClass("auto_hide");
});
$(".convo_create_form .close_form").click((event) => {
event.preventDefault();
$(".convo_create_form").addClass("auto_hide");
});
});
})();

File diff suppressed because it is too large Load Diff

View File

@ -1,66 +1,66 @@
.emoji-wysiwyg-editor {
border: 1px solid #d0d0d0;
overflow: auto;
outline: none;
border: 1px solid #d0d0d0;
overflow: auto;
outline: none;
}
.emoji-wysiwyg-editor img {
width: 20px;
height: 20px;
vertical-align: middle;
margin: -3px 0 0 0;
width: 20px;
height: 20px;
vertical-align: middle;
margin: -3px 0 0 0;
}
.emoji-menu {
position: absolute;
z-index: 999;
width: 180px;
margin-left: -100px;
padding: 0;
overflow: hidden;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
position: absolute;
z-index: 999;
width: 180px;
margin-left: -100px;
padding: 0;
overflow: hidden;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.emoji-menu > div {
max-height: 200px;
overflow: hidden;
background: #fff;
width: 200px;
-webkit-overflow-scrolling: touch;
overflow: auto;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
-moz-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
box-shadow: 0 1px 5px rgba(0,0,0,0.3);
padding-top: 40px;
max-height: 200px;
overflow: hidden;
background: #fff;
width: 200px;
-webkit-overflow-scrolling: touch;
overflow: auto;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
-moz-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
box-shadow: 0 1px 5px rgba(0,0,0,0.3);
padding-top: 40px;
}
.emoji-menu img {
width: 25px;
height: 25px;
vertical-align: middle;
border: 0 none;
width: 25px;
height: 25px;
vertical-align: middle;
border: 0 none;
}
.emoji-menu a {
margin: -1px 0 0 -1px;
border: 1px solid #f2f2f2;
padding: 5px;
display: block;
float: left;
margin: -1px 0 0 -1px;
border: 1px solid #f2f2f2;
padding: 5px;
display: block;
float: left;
}
.emoji-menu a:hover {
background-color: #fffae7;
background-color: #fffae7;
}
.emoji-menu:after {
content: ' ';
display: block;
clear: left;
content: ' ';
display: block;
clear: left;
}
.emoji-menu a .label {
display: none;
display: none;
}
.emoji-menu div {
@ -69,29 +69,29 @@
}
.emoji-menu .group-selector {
position: absolute;
list-style-type: none;
height: 40px;
top: 0;
left: 0;
width: 100%;
background-color: rgb(255,255,255);
background-color: rgba(255,255,255, .9);
position: absolute;
list-style-type: none;
height: 40px;
top: 0;
left: 0;
width: 100%;
background-color: rgb(255,255,255);
background-color: rgba(255,255,255, .9);
}
.emoji-menu .group-selector li {
height: 15px;
width: 17px;
padding: 5px;
height: 15px;
width: 17px;
padding: 5px;
}
.emoji-menu .group-selector a:last-child li {
width: 15px;
width: 15px;
}
.emoji-menu .group-selector a {
color: #EB7878;
text-decoration: none;
border: none;
background-color: transparent;
color: #EB7878;
text-decoration: none;
border: none;
background-color: transparent;
}
.emoji-menu .group-selector a:hover, .emoji-menu .group-selector a.active {
color:#000000;
color:#000000;
}

View File

@ -16,470 +16,470 @@
(function($, window, document) {
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var TAGS_BLOCK = ['p', 'div', 'pre', 'form'];
var KEY_ESC = 27;
var KEY_TAB = 9;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$.emojiarea = {
path: '',
icons: {},
defaults: {
button: null,
buttonLabel: 'Emojis',
buttonPosition: 'after'
}
};
$.fn.emojiarea = function(options) {
options = $.extend({}, $.emojiarea.defaults, options);
return this.each(function() {
var $textarea = $(this);
if ('contentEditable' in document.body && options.wysiwyg !== false) {
new EmojiArea_WYSIWYG($textarea, options);
} else {
new EmojiArea_Plain($textarea, options);
}
});
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var util = {};
util.restoreSelection = (function() {
if (window.getSelection) {
return function(savedSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSelection.length; i < len; ++i) {
sel.addRange(savedSelection[i]);
}
};
} else if (document.selection && document.selection.createRange) {
return function(savedSelection) {
if (savedSelection) {
savedSelection.select();
}
};
}
})();
util.saveSelection = (function() {
if (window.getSelection) {
return function() {
var sel = window.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
} else if (document.selection && document.selection.createRange) {
return function() {
var sel = document.selection;
return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null;
};
}
})();
util.replaceSelection = (function() {
if (window.getSelection) {
return function(content) {
var range, sel = window.getSelection();
var node = typeof content === 'string' ? document.createTextNode(content) : content;
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(' '));
range.insertNode(node);
range.setStart(node, 0);
window.setTimeout(function() {
range = document.createRange();
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}, 0);
}
}
} else if (document.selection && document.selection.createRange) {
return function(content) {
var range = document.selection.createRange();
if (typeof content === 'string') {
range.text = content;
} else {
range.pasteHTML(content.outerHTML);
}
}
}
})();
util.insertAtCursor = function(text, el) {
text = ' ' + text;
var val = el.value, endIndex, startIndex, range;
if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') {
startIndex = el.selectionStart;
endIndex = el.selectionEnd;
el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd);
el.selectionStart = el.selectionEnd = startIndex + text.length;
} else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') {
el.focus();
range = document.selection.createRange();
range.text = text;
range.select();
}
};
util.extend = function(a, b) {
if (typeof a === 'undefined' || !a) { a = {}; }
if (typeof b === 'object') {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
}
return a;
};
util.escapeRegex = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
util.htmlEntities = function(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var EmojiArea = function() {};
EmojiArea.prototype.setup = function() {
var self = this;
this.$editor.on('focus', function() { self.hasFocus = true; });
this.$editor.on('blur', function() { self.hasFocus = false; });
this.setupButton();
};
EmojiArea.prototype.setupButton = function() {
var self = this;
var $button;
if (this.options.button) {
$button = $(this.options.button);
} else if (this.options.button !== false) {
$button = $('<a href="javascript:void(0)">');
$button.html(this.options.buttonLabel);
$button.addClass('emoji-button');
$button.attr({title: this.options.buttonLabel});
this.$editor[this.options.buttonPosition]($button);
} else {
$button = $('');
}
$button.on('click', function(e) {
EmojiMenu.show(self);
e.stopPropagation();
});
this.$button = $button;
};
EmojiArea.createIcon = function(group, emoji) {
var filename = $.emojiarea.icons[group]['icons'][emoji];
var path = $.emojiarea.path || '';
if (path.length && path.charAt(path.length - 1) !== '/') {
path += '/';
}
return '<img src="' + path + filename + '" alt="' + util.htmlEntities(emoji) + '">';
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Editor (plain-text)
*
* @constructor
* @param {object} $textarea
* @param {object} options
*/
var EmojiArea_Plain = function($textarea, options) {
this.options = options;
this.$textarea = $textarea;
this.$editor = $textarea;
this.setup();
};
EmojiArea_Plain.prototype.insert = function(group, emoji) {
if (!$.emojiarea.icons[group]['icons'].hasOwnProperty(emoji)) return;
util.insertAtCursor(emoji, this.$textarea[0]);
this.$textarea.trigger('change');
};
EmojiArea_Plain.prototype.val = function() {
return this.$textarea.val();
};
util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Editor (rich)
*
* @constructor
* @param {object} $textarea
* @param {object} options
*/
var EmojiArea_WYSIWYG = function($textarea, options) {
var self = this;
this.options = options;
this.$textarea = $textarea;
this.$editor = $('<div>').addClass('emoji-wysiwyg-editor');
this.$editor.text($textarea.val());
this.$editor.attr({contenteditable: 'true'});
this.$editor.on('blur keyup paste', function() { return self.onChange.apply(self, arguments); });
this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); });
this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); });
var html = this.$editor.text();
var emojis = $.emojiarea.icons;
for (var group in emojis) {
for (var key in emojis[group]['icons']) {
if (emojis[group]['icons'].hasOwnProperty(key)) {
html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(group, key));
}
}
}
this.$editor.html(html);
$textarea.hide().after(this.$editor);
this.setup();
this.$button.on('mousedown', function() {
if (self.hasFocus) {
self.selection = util.saveSelection();
}
});
};
EmojiArea_WYSIWYG.prototype.onChange = function() {
this.$textarea.val(this.val()).trigger('change');
};
EmojiArea_WYSIWYG.prototype.insert = function(group, emoji) {
var content;
var $img = $(EmojiArea.createIcon(group, emoji));
if ($img[0].attachEvent) {
$img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false);
}
this.$editor.trigger('focus');
if (this.selection) {
util.restoreSelection(this.selection);
}
try { util.replaceSelection($img[0]); } catch (e) {}
this.onChange();
};
EmojiArea_WYSIWYG.prototype.val = function() {
var lines = [];
var line = [];
var flush = function() {
lines.push(line.join(''));
line = [];
};
var sanitizeNode = function(node) {
if (node.nodeType === TEXT_NODE) {
line.push(node.nodeValue);
} else if (node.nodeType === ELEMENT_NODE) {
var tagName = node.tagName.toLowerCase();
var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1;
if (isBlock && line.length) flush();
if (tagName === 'img') {
var alt = node.getAttribute('alt') || '';
if (alt) line.push(alt);
return;
} else if (tagName === 'br') {
flush();
}
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
sanitizeNode(children[i]);
}
if (isBlock && line.length) flush();
}
};
var children = this.$editor[0].childNodes;
for (var i = 0; i < children.length; i++) {
sanitizeNode(children[i]);
}
if (line.length) flush();
return lines.join('\n');
};
util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Emoji Dropdown Menu
*
* @constructor
* @param {object} emojiarea
*/
var EmojiMenu = function() {
var self = this;
var $body = $(document.body);
var $window = $(window);
this.visible = false;
this.emojiarea = null;
this.$menu = $('<div>');
this.$menu.addClass('emoji-menu');
this.$menu.hide();
this.$items = $('<div>').appendTo(this.$menu);
$body.append(this.$menu);
$body.on('keydown', function(e) {
if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) {
self.hide();
}
});
$body.on('mouseup', function() {
self.hide();
});
$window.on('resize', function() {
if (self.visible) self.reposition();
});
this.$menu.on('mouseup', 'a', function(e) {
e.stopPropagation();
return false;
});
this.$menu.on('click', 'a', function(e) {
var emoji = $('.label', $(this)).text();
var group = $('.label', $(this)).parent().parent().attr('group');
if(group && emoji !== ''){
window.setTimeout(function() {
self.onItemSelected.apply(self, [group, emoji]);
}, 0);
e.stopPropagation();
return false;
}
});
this.load();
};
EmojiMenu.prototype.onItemSelected = function(group, emoji) {
this.emojiarea.insert(group, emoji);
this.hide();
};
EmojiMenu.prototype.load = function() {
var html = [];
var groups = [];
var options = $.emojiarea.icons;
var path = $.emojiarea.path;
if (path.length && path.charAt(path.length - 1) !== '/') {
path += '/';
}
groups.push('<ul class="group-selector">');
for (var group in options) {
groups.push('<a href="#group_' + group + '" class="tab_switch"><li>' + options[group]['name'] + '</li></a>');
html.push('<div class="select_group" group="' + group + '" id="group_' + group + '">');
for (var key in options[group]['icons']) {
if (options[group]['icons'].hasOwnProperty(key)) {
var filename = options[key];
html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(group, key) + '<span class="label">' + util.htmlEntities(key) + '</span></a>');
}
}
html.push('</div>');
}
groups.push('</ul>');
this.$items.html(html.join(''));
this.$menu.prepend(groups.join(''));
this.$menu.find('.tab_switch').each(function(i) {
if (i != 0) {
var select = $(this).attr('href');
$(select).hide();
} else {
$(this).addClass('active');
}
$(this).click(function() {
$(this).addClass('active');
$(this).siblings().removeClass('active');
$('.select_group').hide();
var select = $(this).attr('href');
$(select).show();
});
});
};
EmojiMenu.prototype.reposition = function() {
var $button = this.emojiarea.$button;
var offset = $button.offset();
offset.top += $button.outerHeight();
offset.left += Math.round($button.outerWidth() / 2);
this.$menu.css({
top: offset.top,
left: offset.left
});
};
EmojiMenu.prototype.hide = function(callback) {
if (this.emojiarea) {
this.emojiarea.menu = null;
this.emojiarea.$button.removeClass('on');
this.emojiarea = null;
}
this.visible = false;
this.$menu.hide();
};
EmojiMenu.prototype.show = function(emojiarea) {
if (this.emojiarea && this.emojiarea === emojiarea) return;
this.emojiarea = emojiarea;
this.emojiarea.menu = this;
this.reposition();
this.$menu.show();
this.visible = true;
};
EmojiMenu.show = (function() {
var menu = null;
return function(emojiarea) {
menu = menu || new EmojiMenu();
menu.show(emojiarea);
};
})();
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var TAGS_BLOCK = ['p', 'div', 'pre', 'form'];
var KEY_ESC = 27;
var KEY_TAB = 9;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$.emojiarea = {
path: '',
icons: {},
defaults: {
button: null,
buttonLabel: 'Emojis',
buttonPosition: 'after'
}
};
$.fn.emojiarea = function(options) {
options = $.extend({}, $.emojiarea.defaults, options);
return this.each(function() {
var $textarea = $(this);
if ('contentEditable' in document.body && options.wysiwyg !== false) {
new EmojiArea_WYSIWYG($textarea, options);
} else {
new EmojiArea_Plain($textarea, options);
}
});
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var util = {};
util.restoreSelection = (function() {
if (window.getSelection) {
return function(savedSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSelection.length; i < len; ++i) {
sel.addRange(savedSelection[i]);
}
};
} else if (document.selection && document.selection.createRange) {
return function(savedSelection) {
if (savedSelection) {
savedSelection.select();
}
};
}
})();
util.saveSelection = (function() {
if (window.getSelection) {
return function() {
var sel = window.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
} else if (document.selection && document.selection.createRange) {
return function() {
var sel = document.selection;
return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null;
};
}
})();
util.replaceSelection = (function() {
if (window.getSelection) {
return function(content) {
var range, sel = window.getSelection();
var node = typeof content === 'string' ? document.createTextNode(content) : content;
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(' '));
range.insertNode(node);
range.setStart(node, 0);
window.setTimeout(function() {
range = document.createRange();
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}, 0);
}
}
} else if (document.selection && document.selection.createRange) {
return function(content) {
var range = document.selection.createRange();
if (typeof content === 'string') {
range.text = content;
} else {
range.pasteHTML(content.outerHTML);
}
}
}
})();
util.insertAtCursor = function(text, el) {
text = ' ' + text;
var val = el.value, endIndex, startIndex, range;
if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') {
startIndex = el.selectionStart;
endIndex = el.selectionEnd;
el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd);
el.selectionStart = el.selectionEnd = startIndex + text.length;
} else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') {
el.focus();
range = document.selection.createRange();
range.text = text;
range.select();
}
};
util.extend = function(a, b) {
if (typeof a === 'undefined' || !a) { a = {}; }
if (typeof b === 'object') {
for (var key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
}
return a;
};
util.escapeRegex = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
util.htmlEntities = function(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var EmojiArea = function() {};
EmojiArea.prototype.setup = function() {
var self = this;
this.$editor.on('focus', function() { self.hasFocus = true; });
this.$editor.on('blur', function() { self.hasFocus = false; });
this.setupButton();
};
EmojiArea.prototype.setupButton = function() {
var self = this;
var $button;
if (this.options.button) {
$button = $(this.options.button);
} else if (this.options.button !== false) {
$button = $('<a href="javascript:void(0)">');
$button.html(this.options.buttonLabel);
$button.addClass('emoji-button');
$button.attr({title: this.options.buttonLabel});
this.$editor[this.options.buttonPosition]($button);
} else {
$button = $('');
}
$button.on('click', function(e) {
EmojiMenu.show(self);
e.stopPropagation();
});
this.$button = $button;
};
EmojiArea.createIcon = function(group, emoji) {
var filename = $.emojiarea.icons[group]['icons'][emoji];
var path = $.emojiarea.path || '';
if (path.length && path.charAt(path.length - 1) !== '/') {
path += '/';
}
return '<img src="' + path + filename + '" alt="' + util.htmlEntities(emoji) + '">';
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Editor (plain-text)
*
* @constructor
* @param {object} $textarea
* @param {object} options
*/
var EmojiArea_Plain = function($textarea, options) {
this.options = options;
this.$textarea = $textarea;
this.$editor = $textarea;
this.setup();
};
EmojiArea_Plain.prototype.insert = function(group, emoji) {
if (!$.emojiarea.icons[group]['icons'].hasOwnProperty(emoji)) return;
util.insertAtCursor(emoji, this.$textarea[0]);
this.$textarea.trigger('change');
};
EmojiArea_Plain.prototype.val = function() {
return this.$textarea.val();
};
util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Editor (rich)
*
* @constructor
* @param {object} $textarea
* @param {object} options
*/
var EmojiArea_WYSIWYG = function($textarea, options) {
var self = this;
this.options = options;
this.$textarea = $textarea;
this.$editor = $('<div>').addClass('emoji-wysiwyg-editor');
this.$editor.text($textarea.val());
this.$editor.attr({contenteditable: 'true'});
this.$editor.on('blur keyup paste', function() { return self.onChange.apply(self, arguments); });
this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); });
this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); });
var html = this.$editor.text();
var emojis = $.emojiarea.icons;
for (var group in emojis) {
for (var key in emojis[group]['icons']) {
if (emojis[group]['icons'].hasOwnProperty(key)) {
html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(group, key));
}
}
}
this.$editor.html(html);
$textarea.hide().after(this.$editor);
this.setup();
this.$button.on('mousedown', function() {
if (self.hasFocus) {
self.selection = util.saveSelection();
}
});
};
EmojiArea_WYSIWYG.prototype.onChange = function() {
this.$textarea.val(this.val()).trigger('change');
};
EmojiArea_WYSIWYG.prototype.insert = function(group, emoji) {
var content;
var $img = $(EmojiArea.createIcon(group, emoji));
if ($img[0].attachEvent) {
$img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false);
}
this.$editor.trigger('focus');
if (this.selection) {
util.restoreSelection(this.selection);
}
try { util.replaceSelection($img[0]); } catch (e) {}
this.onChange();
};
EmojiArea_WYSIWYG.prototype.val = function() {
var lines = [];
var line = [];
var flush = function() {
lines.push(line.join(''));
line = [];
};
var sanitizeNode = function(node) {
if (node.nodeType === TEXT_NODE) {
line.push(node.nodeValue);
} else if (node.nodeType === ELEMENT_NODE) {
var tagName = node.tagName.toLowerCase();
var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1;
if (isBlock && line.length) flush();
if (tagName === 'img') {
var alt = node.getAttribute('alt') || '';
if (alt) line.push(alt);
return;
} else if (tagName === 'br') {
flush();
}
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
sanitizeNode(children[i]);
}
if (isBlock && line.length) flush();
}
};
var children = this.$editor[0].childNodes;
for (var i = 0; i < children.length; i++) {
sanitizeNode(children[i]);
}
if (line.length) flush();
return lines.join('\n');
};
util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Emoji Dropdown Menu
*
* @constructor
* @param {object} emojiarea
*/
var EmojiMenu = function() {
var self = this;
var $body = $(document.body);
var $window = $(window);
this.visible = false;
this.emojiarea = null;
this.$menu = $('<div>');
this.$menu.addClass('emoji-menu');
this.$menu.hide();
this.$items = $('<div>').appendTo(this.$menu);
$body.append(this.$menu);
$body.on('keydown', function(e) {
if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) {
self.hide();
}
});
$body.on('mouseup', function() {
self.hide();
});
$window.on('resize', function() {
if (self.visible) self.reposition();
});
this.$menu.on('mouseup', 'a', function(e) {
e.stopPropagation();
return false;
});
this.$menu.on('click', 'a', function(e) {
var emoji = $('.label', $(this)).text();
var group = $('.label', $(this)).parent().parent().attr('group');
if(group && emoji !== ''){
window.setTimeout(function() {
self.onItemSelected.apply(self, [group, emoji]);
}, 0);
e.stopPropagation();
return false;
}
});
this.load();
};
EmojiMenu.prototype.onItemSelected = function(group, emoji) {
this.emojiarea.insert(group, emoji);
this.hide();
};
EmojiMenu.prototype.load = function() {
var html = [];
var groups = [];
var options = $.emojiarea.icons;
var path = $.emojiarea.path;
if (path.length && path.charAt(path.length - 1) !== '/') {
path += '/';
}
groups.push('<ul class="group-selector">');
for (var group in options) {
groups.push('<a href="#group_' + group + '" class="tab_switch"><li>' + options[group]['name'] + '</li></a>');
html.push('<div class="select_group" group="' + group + '" id="group_' + group + '">');
for (var key in options[group]['icons']) {
if (options[group]['icons'].hasOwnProperty(key)) {
var filename = options[key];
html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(group, key) + '<span class="label">' + util.htmlEntities(key) + '</span></a>');
}
}
html.push('</div>');
}
groups.push('</ul>');
this.$items.html(html.join(''));
this.$menu.prepend(groups.join(''));
this.$menu.find('.tab_switch').each(function(i) {
if (i != 0) {
var select = $(this).attr('href');
$(select).hide();
} else {
$(this).addClass('active');
}
$(this).click(function() {
$(this).addClass('active');
$(this).siblings().removeClass('active');
$('.select_group').hide();
var select = $(this).attr('href');
$(select).show();
});
});
};
EmojiMenu.prototype.reposition = function() {
var $button = this.emojiarea.$button;
var offset = $button.offset();
offset.top += $button.outerHeight();
offset.left += Math.round($button.outerWidth() / 2);
this.$menu.css({
top: offset.top,
left: offset.left
});
};
EmojiMenu.prototype.hide = function(callback) {
if (this.emojiarea) {
this.emojiarea.menu = null;
this.emojiarea.$button.removeClass('on');
this.emojiarea = null;
}
this.visible = false;
this.$menu.hide();
};
EmojiMenu.prototype.show = function(emojiarea) {
if (this.emojiarea && this.emojiarea === emojiarea) return;
this.emojiarea = emojiarea;
this.emojiarea.menu = this;
this.reposition();
this.$menu.show();
this.visible = true;
};
EmojiMenu.show = (function() {
var menu = null;
return function(emojiarea) {
menu = menu || new EmojiMenu();
menu.show(emojiarea);
};
})();
})(jQuery, window, document);

View File

@ -2,356 +2,356 @@
var imageExts = ["png","jpg","jpe","jpeg","jif","jfi","jfif","svg","bmp","gif","tiff","tif","webp"];
(() => {
function copyToClipboard(str) {
const el=document.createElement('textarea');
el.value=str;
el.setAttribute('readonly','');
el.style.position='absolute';
el.style.left='-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
function copyToClipboard(str) {
const el=document.createElement('textarea');
el.value=str;
el.setAttribute('readonly','');
el.style.position='absolute';
el.style.left='-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
function uploadFileHandler(fileList, maxFiles=5, step1 = () => {}, step2 = () => {}) {
let files = [];
for(var i=0; i<fileList.length && i<5; i++) files[i] = fileList[i];
let totalSize = 0;
for(let i=0; i<files.length; i++) {
log("file "+i,files[i]);
totalSize += files[i]["size"];
}
if(totalSize > me.Site.MaxReqSize) throw("You can't upload this much at once, max: "+me.Site.MaxReqSize);
for(let i=0; i<files.length; i++) {
let fname = files[i]["name"];
let f = e => {
step1(e,fname)
let reader = new FileReader();
reader.onload = e2 => {
crypto.subtle.digest('SHA-256',e2.target.result)
.then(hash => {
const hashArray = Array.from(new Uint8Array(hash))
return hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
}).then(hash => step2(e,hash,fname));
}
reader.readAsArrayBuffer(files[i]);
};
let ext = getExt(fname);
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
let isImage = imageExts.includes(ext);
if(isImage) {
let reader = new FileReader();
reader.onload = f;
reader.readAsDataURL(files[i]);
} else f(null);
}
}
function uploadFileHandler(fileList, maxFiles=5, step1 = () => {}, step2 = () => {}) {
let files = [];
for(var i=0; i<fileList.length && i<5; i++) files[i] = fileList[i];
let totalSize = 0;
for(let i=0; i<files.length; i++) {
log("file "+i,files[i]);
totalSize += files[i]["size"];
}
if(totalSize > me.Site.MaxReqSize) throw("You can't upload this much at once, max: "+me.Site.MaxReqSize);
for(let i=0; i<files.length; i++) {
let fname = files[i]["name"];
let f = e => {
step1(e,fname)
let reader = new FileReader();
reader.onload = e2 => {
crypto.subtle.digest('SHA-256',e2.target.result)
.then(hash => {
const hashArray = Array.from(new Uint8Array(hash))
return hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
}).then(hash => step2(e,hash,fname));
}
reader.readAsArrayBuffer(files[i]);
};
let ext = getExt(fname);
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
let isImage = imageExts.includes(ext);
if(isImage) {
let reader = new FileReader();
reader.onload = f;
reader.readAsDataURL(files[i]);
} else f(null);
}
}
// Attachment Manager
function uploadAttachHandler2() {
let post = this.closest(".post_item");
let fileDock = this.closest(".attach_edit_bay");
try {
uploadFileHandler(this.files, 5, () => {},
(e,hash,fname) => {
log("hash",hash);
let formData = new FormData();
formData.append("s",me.User.S);
for(let i=0; i<this.files.length; i++) formData.append("upload_files",this.files[i]);
bindAttachManager();
// Attachment Manager
function uploadAttachHandler2() {
let post = this.closest(".post_item");
let fileDock = this.closest(".attach_edit_bay");
try {
uploadFileHandler(this.files, 5, () => {},
(e,hash,fname) => {
log("hash",hash);
let formData = new FormData();
formData.append("s",me.User.S);
for(let i=0; i<this.files.length; i++) formData.append("upload_files",this.files[i]);
bindAttachManager();
let req = new XMLHttpRequest();
req.addEventListener("load", () => {
let data = JSON.parse(req.responseText);
//log("rdata",data);
let fileItem = document.createElement("div");
let ext = getExt(fname);
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
let isImage = imageExts.includes(ext);
let c = "";
if(isImage) c = " attach_image_holder"
fileItem.className = "attach_item attach_item_item"+c;
fileItem.innerHTML = Tmpl_topic_c_attach_item({
ID: data.elems[hash+"."+ext],
ImgSrc: isImage ? e.target.result : "",
Path: hash+"."+ext,
FullPath: "//" + window.location.host + "/attachs/" + hash + "." + ext,
});
fileDock.insertBefore(fileItem,fileDock.querySelector(".attach_item_buttons"));
post.classList.add("has_attachs");
bindAttachItems();
});
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/add/submit/"+fileDock.getAttribute("id"));
req.send(formData);
});
} catch(e) {
// TODO: Use a notice instead
log("e",e);
alert(e);
}
}
let req = new XMLHttpRequest();
req.addEventListener("load", () => {
let data = JSON.parse(req.responseText);
//log("rdata",data);
let fileItem = document.createElement("div");
let ext = getExt(fname);
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
let isImage = imageExts.includes(ext);
let c = "";
if(isImage) c = " attach_image_holder"
fileItem.className = "attach_item attach_item_item"+c;
fileItem.innerHTML = Tmpl_topic_c_attach_item({
ID: data.elems[hash+"."+ext],
ImgSrc: isImage ? e.target.result : "",
Path: hash+"."+ext,
FullPath: "//" + window.location.host + "/attachs/" + hash + "." + ext,
});
fileDock.insertBefore(fileItem,fileDock.querySelector(".attach_item_buttons"));
post.classList.add("has_attachs");
bindAttachItems();
});
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/add/submit/"+fileDock.getAttribute("id"));
req.send(formData);
});
} catch(e) {
// TODO: Use a notice instead
log("e",e);
alert(e);
}
}
// Quick Topic / Quick Reply
function uploadAttachHandler() {
try {
uploadFileHandler(this.files,5,(e,fname) => {
// TODO: Use client templates here
let fileDock = document.getElementById("upload_file_dock");
let fileItem = document.createElement("label");
log("fileItem",fileItem);
// Quick Topic / Quick Reply
function uploadAttachHandler() {
try {
uploadFileHandler(this.files,5,(e,fname) => {
// TODO: Use client templates here
let fileDock = document.getElementById("upload_file_dock");
let fileItem = document.createElement("label");
log("fileItem",fileItem);
let ext = getExt(fname);
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
let isImage = imageExts.includes(ext);
fileItem.innerText = "."+ext;
fileItem.className = "formbutton uploadItem";
// TODO: Check if this is actually an image
if(isImage) fileItem.style.backgroundImage = "url("+e.target.result+")";
let ext = getExt(fname);
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
let isImage = imageExts.includes(ext);
fileItem.innerText = "."+ext;
fileItem.className = "formbutton uploadItem";
// TODO: Check if this is actually an image
if(isImage) fileItem.style.backgroundImage = "url("+e.target.result+")";
fileDock.appendChild(fileItem);
},(e,hash,fname) => {
log("hash",hash);
let ext = getExt(fname)
let con = document.getElementById("input_content")
log("con.value",con.value);
let attachItem;
if(con.value=="") attachItem = "//"+window.location.host+"/attachs/"+hash+"."+ext;
else attachItem = "\r\n//"+window.location.host+"/attachs/"+hash+"."+ext;
con.value = con.value + attachItem;
log("con.value",con.value);
// For custom / third party text editors
attachItemCallback(attachItem);
});
} catch(e) {
// TODO: Use a notice instead
log("e",e);
alert(e);
}
}
fileDock.appendChild(fileItem);
},(e,hash,fname) => {
log("hash",hash);
let ext = getExt(fname)
let con = document.getElementById("input_content")
log("con.value",con.value);
let attachItem;
if(con.value=="") attachItem = "//"+window.location.host+"/attachs/"+hash+"."+ext;
else attachItem = "\r\n//"+window.location.host+"/attachs/"+hash+"."+ext;
con.value = con.value + attachItem;
log("con.value",con.value);
// For custom / third party text editors
attachItemCallback(attachItem);
});
} catch(e) {
// TODO: Use a notice instead
log("e",e);
alert(e);
}
}
function bindAttachManager() {
let uploadFiles = document.getElementsByClassName("upload_files_post");
if(uploadFiles==null) return;
for(let i=0; i<uploadFiles.length; i++) {
let uploader = uploadFiles[i];
uploader.value = "";
uploader.removeEventListener("change", uploadAttachHandler2, false);
uploader.addEventListener("change", uploadAttachHandler2, false);
}
}
//addInitHook("before_init_bind_page", () => {
//log("in member.js before_init_bind_page")
addInitHook("end_bind_topic", () => {
log("in member.js end_bind_topic")
function bindAttachManager() {
let uploadFiles = document.getElementsByClassName("upload_files_post");
if(uploadFiles==null) return;
for(let i=0; i<uploadFiles.length; i++) {
let uploader = uploadFiles[i];
uploader.value = "";
uploader.removeEventListener("change", uploadAttachHandler2, false);
uploader.addEventListener("change", uploadAttachHandler2, false);
}
}
//addInitHook("before_init_bind_page", () => {
//log("in member.js before_init_bind_page")
addInitHook("end_bind_topic", () => {
log("in member.js end_bind_topic")
let changeListener = (files,h) => {
if(files!=null) {
files.removeEventListener("change", h, false);
files.addEventListener("change", h, false);
}
};
let uploadFiles = document.getElementById("upload_files");
changeListener(uploadFiles,uploadAttachHandler);
let uploadFilesOp = document.getElementById("upload_files_op");
changeListener(uploadFilesOp,uploadAttachHandler2);
bindAttachManager();
function bindAttachItems() {
$(".attach_item_select").unbind("click");
$(".attach_item_copy").unbind("click");
$(".attach_item_select").click(function(){
let hold = $(this).closest(".attach_item");
if(hold.hasClass("attach_item_selected")) hold.removeClass("attach_item_selected");
else hold.addClass("attach_item_selected");
});
$(".attach_item_copy").click(function(){
let hold = $(this).closest(".attach_item");
let pathNode = hold.find(".attach_item_path");
copyToClipboard(pathNode.attr("fullPath"));
});
}
bindAttachItems();
$(".attach_item_delete").unbind("click");
$(".attach_item_delete").click(function(){
let formData = new URLSearchParams();
formData.append("s",me.User.S);
let post = this.closest(".post_item");
let aidList = "";
let elems = post.getElementsByClassName("attach_item_selected");
if(elems==null) return;
for(let i = 0; i < elems.length; i++) {
let pathNode = elems[i].querySelector(".attach_item_path");
log("pathNode",pathNode);
aidList += pathNode.getAttribute("aid")+",";
elems[i].remove();
}
if(aidList.length > 0) aidList = aidList.slice(0, -1);
log("aidList",aidList)
formData.append("aids",aidList);
let ec = 0;
let e = post.getElementsByClassName("attach_item_item");
if(e!=null) ec = e.length;
if(ec==0) post.classList.remove("has_attachs");
let req = new XMLHttpRequest();
let fileDock = this.closest(".attach_edit_bay");
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/remove/submit/"+fileDock.getAttribute("id"),true);
req.send(formData);
bindAttachItems();
bindAttachManager();
});
function addPollInput() {
log("clicked on pollinputinput");
let dataPollInput = $(this).parent().attr("data-pollinput");
log("dataPollInput",dataPollInput);
if(dataPollInput==undefined) return;
if(dataPollInput!=(pollInputIndex-1)) return;
$(".poll_content_row .formitem").append(Tmpl_topic_c_poll_input({
Index: pollInputIndex,
Place: phraseBox["topic"]["topic.reply_add_poll_option"].replace("%d",pollInputIndex),
}));
pollInputIndex++;
log("new pollInputIndex",pollInputIndex);
$(".pollinputinput").off("click");
$(".pollinputinput").click(addPollInput);
}
let pollInputIndex = 1;
$("#add_poll_button").unbind("click");
$("#add_poll_button").click(ev => {
ev.preventDefault();
$(".poll_content_row").removeClass("auto_hide");
$("#has_poll_input").val("1");
$(".pollinputinput").click(addPollInput);
});
});
//});
function modCancel() {
log("enter modCancel");
if(!$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide")
$(".moderate_link").unbind("click");
$(".moderate_link").removeClass("moderate_open");
$(".pre_opt").addClass("auto_hide");
$(".mod_floater_submit").unbind("click");
$("#topicsItemList,#forumItemList").removeClass("topics_moderate");
$(".topic_selected").removeClass("topic_selected");
// ! Be careful not to trample bindings elsewhere
$(".topic_row").unbind("click");
$("#mod_topic_mover").addClass("auto_hide");
}
function modCancelBind() {
log("enter modCancelBind")
$(".moderate_link").unbind("click");
$(".moderate_open").click(ev => {
modCancel();
$(".moderate_open").unbind("click");
modLinkBind();
});
}
function modLinkBind() {
log("enter modLinkBind");
$(".moderate_link").click(ev => {
log("enter .moderate_link");
ev.preventDefault();
$(".pre_opt").removeClass("auto_hide");
$(".moderate_link").addClass("moderate_open");
selectedTopics=[];
modCancelBind();
$("#topicsItemList,#forumItemList").addClass("topics_moderate");
$(".topic_row").each(function(){
$(this).click(function(){
if(!this.classList.contains("can_mod")) return;
let tid = parseInt($(this).attr("data-tid"),10);
let sel = this.classList.contains("topic_selected");
if(sel) {
for(var i=0; i<selectedTopics.length; i++){
if(selectedTopics[i]===tid) selectedTopics.splice(i, 1);
}
} else selectedTopics.push(tid);
if(selectedTopics.length==1) {
var msg = phraseBox["topic_list"]["topic_list.what_to_do_single"];
} else {
var msg = "What do you want to do with these "+selectedTopics.length+" topics?";
}
$(".mod_floater_head span").html(msg);
if(!sel) {
$(this).addClass("topic_selected");
$(".mod_floater").removeClass("auto_hide");
} else {
$(this).removeClass("topic_selected");
}
if(selectedTopics.length==0 && !$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide");
});
});
let bulkActionSender = (action,selectedTopics,fragBit) => {
$.ajax({
url: "/topic/"+action+"/submit/"+fragBit+"?s="+me.User.S,
type: "POST",
data: JSON.stringify(selectedTopics),
contentType: "application/json",
error: ajaxError,
success: () => window.location.reload()
});
};
// TODO: Should we unbind this here to avoid binding multiple listeners to this accidentally?
$(".mod_floater_submit").click(function(ev){
ev.preventDefault();
let selectNode = this.form.querySelector(".mod_floater_options");
let optionNode = selectNode.options[selectNode.selectedIndex];
let action = optionNode.getAttribute("value");
// Handle these specially
switch(action) {
case "move":
log("move action");
let modTopicMover = $("#mod_topic_mover");
$("#mod_topic_mover").removeClass("auto_hide");
$("#mod_topic_mover .pane_row").unbind("click");
$("#mod_topic_mover .pane_row").click(function(){
modTopicMover.find(".pane_row").removeClass("pane_selected");
let fid = this.getAttribute("data-fid");
if(fid==null) return;
this.classList.add("pane_selected");
log("fid",fid);
forumToMoveTo = fid;
$("#mover_submit").unbind("click");
$("#mover_submit").click(ev => {
ev.preventDefault();
bulkActionSender("move",selectedTopics,forumToMoveTo);
});
});
return;
}
let changeListener = (files,h) => {
if(files!=null) {
files.removeEventListener("change", h, false);
files.addEventListener("change", h, false);
}
};
let uploadFiles = document.getElementById("upload_files");
changeListener(uploadFiles,uploadAttachHandler);
let uploadFilesOp = document.getElementById("upload_files_op");
changeListener(uploadFilesOp,uploadAttachHandler2);
bindAttachManager();
function bindAttachItems() {
$(".attach_item_select").unbind("click");
$(".attach_item_copy").unbind("click");
$(".attach_item_select").click(function(){
let hold = $(this).closest(".attach_item");
if(hold.hasClass("attach_item_selected")) hold.removeClass("attach_item_selected");
else hold.addClass("attach_item_selected");
});
$(".attach_item_copy").click(function(){
let hold = $(this).closest(".attach_item");
let pathNode = hold.find(".attach_item_path");
copyToClipboard(pathNode.attr("fullPath"));
});
}
bindAttachItems();
$(".attach_item_delete").unbind("click");
$(".attach_item_delete").click(function(){
let formData = new URLSearchParams();
formData.append("s",me.User.S);
let post = this.closest(".post_item");
let aidList = "";
let elems = post.getElementsByClassName("attach_item_selected");
if(elems==null) return;
for(let i = 0; i < elems.length; i++) {
let pathNode = elems[i].querySelector(".attach_item_path");
log("pathNode",pathNode);
aidList += pathNode.getAttribute("aid")+",";
elems[i].remove();
}
if(aidList.length > 0) aidList = aidList.slice(0, -1);
log("aidList",aidList)
formData.append("aids",aidList);
let ec = 0;
let e = post.getElementsByClassName("attach_item_item");
if(e!=null) ec = e.length;
if(ec==0) post.classList.remove("has_attachs");
let req = new XMLHttpRequest();
let fileDock = this.closest(".attach_edit_bay");
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/remove/submit/"+fileDock.getAttribute("id"),true);
req.send(formData);
bindAttachItems();
bindAttachManager();
});
function addPollInput() {
log("clicked on pollinputinput");
let dataPollInput = $(this).parent().attr("data-pollinput");
log("dataPollInput",dataPollInput);
if(dataPollInput==undefined) return;
if(dataPollInput!=(pollInputIndex-1)) return;
$(".poll_content_row .formitem").append(Tmpl_topic_c_poll_input({
Index: pollInputIndex,
Place: phraseBox["topic"]["topic.reply_add_poll_option"].replace("%d",pollInputIndex),
}));
pollInputIndex++;
log("new pollInputIndex",pollInputIndex);
$(".pollinputinput").off("click");
$(".pollinputinput").click(addPollInput);
}
let pollInputIndex = 1;
$("#add_poll_button").unbind("click");
$("#add_poll_button").click(ev => {
ev.preventDefault();
$(".poll_content_row").removeClass("auto_hide");
$("#has_poll_input").val("1");
$(".pollinputinput").click(addPollInput);
});
});
//});
function modCancel() {
log("enter modCancel");
if(!$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide")
$(".moderate_link").unbind("click");
$(".moderate_link").removeClass("moderate_open");
$(".pre_opt").addClass("auto_hide");
$(".mod_floater_submit").unbind("click");
$("#topicsItemList,#forumItemList").removeClass("topics_moderate");
$(".topic_selected").removeClass("topic_selected");
// ! Be careful not to trample bindings elsewhere
$(".topic_row").unbind("click");
$("#mod_topic_mover").addClass("auto_hide");
}
function modCancelBind() {
log("enter modCancelBind")
$(".moderate_link").unbind("click");
$(".moderate_open").click(ev => {
modCancel();
$(".moderate_open").unbind("click");
modLinkBind();
});
}
function modLinkBind() {
log("enter modLinkBind");
$(".moderate_link").click(ev => {
log("enter .moderate_link");
ev.preventDefault();
$(".pre_opt").removeClass("auto_hide");
$(".moderate_link").addClass("moderate_open");
selectedTopics=[];
modCancelBind();
$("#topicsItemList,#forumItemList").addClass("topics_moderate");
$(".topic_row").each(function(){
$(this).click(function(){
if(!this.classList.contains("can_mod")) return;
let tid = parseInt($(this).attr("data-tid"),10);
let sel = this.classList.contains("topic_selected");
if(sel) {
for(var i=0; i<selectedTopics.length; i++){
if(selectedTopics[i]===tid) selectedTopics.splice(i, 1);
}
} else selectedTopics.push(tid);
if(selectedTopics.length==1) {
var msg = phraseBox["topic_list"]["topic_list.what_to_do_single"];
} else {
var msg = "What do you want to do with these "+selectedTopics.length+" topics?";
}
$(".mod_floater_head span").html(msg);
if(!sel) {
$(this).addClass("topic_selected");
$(".mod_floater").removeClass("auto_hide");
} else {
$(this).removeClass("topic_selected");
}
if(selectedTopics.length==0 && !$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide");
});
});
let bulkActionSender = (action,selectedTopics,fragBit) => {
$.ajax({
url: "/topic/"+action+"/submit/"+fragBit+"?s="+me.User.S,
type: "POST",
data: JSON.stringify(selectedTopics),
contentType: "application/json",
error: ajaxError,
success: () => window.location.reload()
});
};
// TODO: Should we unbind this here to avoid binding multiple listeners to this accidentally?
$(".mod_floater_submit").click(function(ev){
ev.preventDefault();
let selectNode = this.form.querySelector(".mod_floater_options");
let optionNode = selectNode.options[selectNode.selectedIndex];
let action = optionNode.getAttribute("value");
// Handle these specially
switch(action) {
case "move":
log("move action");
let modTopicMover = $("#mod_topic_mover");
$("#mod_topic_mover").removeClass("auto_hide");
$("#mod_topic_mover .pane_row").unbind("click");
$("#mod_topic_mover .pane_row").click(function(){
modTopicMover.find(".pane_row").removeClass("pane_selected");
let fid = this.getAttribute("data-fid");
if(fid==null) return;
this.classList.add("pane_selected");
log("fid",fid);
forumToMoveTo = fid;
$("#mover_submit").unbind("click");
$("#mover_submit").click(ev => {
ev.preventDefault();
bulkActionSender("move",selectedTopics,forumToMoveTo);
});
});
return;
}
bulkActionSender(action,selectedTopics,"");
});
});
}
//addInitHook("after_init_bind_page", () => {
//addInitHook("before_init_bind_page", () => {
//log("in member.js before_init_bind_page 2")
addInitHook("end_bind_page", () => {
log("in member.js end_bind_page")
modCancel();
modLinkBind();
});
addInitHook("after_init_bind_page", () => addHook("end_unbind_page", () => modCancel()))
//});
bulkActionSender(action,selectedTopics,"");
});
});
}
//addInitHook("after_init_bind_page", () => {
//addInitHook("before_init_bind_page", () => {
//log("in member.js before_init_bind_page 2")
addInitHook("end_bind_page", () => {
log("in member.js end_bind_page")
modCancel();
modLinkBind();
});
addInitHook("after_init_bind_page", () => addHook("end_unbind_page", () => modCancel()))
//});
})()

View File

@ -1,5 +1,5 @@
(() => {
addInitHook("end_init", () => {
formVars = {'perm_preset': ['can_moderate','can_post','read_only','no_access','default','custom']};
});
addInitHook("end_init", () => {
formVars = {'perm_preset': ['can_moderate','can_post','read_only','no_access','default','custom']};
});
})();

View File

@ -2,8 +2,8 @@
addInitHook("end_init", () => {
formVars = {
'forum_active': ['Hide','Show'],
'forum_preset': ['all','announce','members','staff','admins','archive','custom']
'forum_active': ['Hide','Show'],
'forum_preset': ['all','announce','members','staff','admins','archive','custom']
};
var forums = {};
let items = document.getElementsByClassName("panel_forum_item");
@ -11,48 +11,48 @@ for(let i=0; item=items[i]; i++) forums[i] = item.getAttribute("data-fid");
log("forums",forums);
Sortable.create(document.getElementById("panel_forums"), {
sort: true,
onEnd: (evt) => {
log("pre forums",forums)
log("evt",evt)
let oldFid = forums[evt.newIndex];
forums[evt.oldIndex] = oldFid;
let newFid = evt.item.getAttribute("data-fid");
log("newFid",newFid);
forums[evt.newIndex] = newFid;
log("post forums",forums);
}
sort: true,
onEnd: (evt) => {
log("pre forums",forums)
log("evt",evt)
let oldFid = forums[evt.newIndex];
forums[evt.oldIndex] = oldFid;
let newFid = evt.item.getAttribute("data-fid");
log("newFid",newFid);
forums[evt.newIndex] = newFid;
log("post forums",forums);
}
});
document.getElementById("panel_forums_order_button").addEventListener("click", () => {
let req = new XMLHttpRequest();
if(!req) {
log("Failed to create request");
return false;
}
req.onreadystatechange = () => {
try {
if(req.readyState!==XMLHttpRequest.DONE) return;
// TODO: Signal the error with a notice
if(req.status!==200) return;
let resp = JSON.parse(req.responseText);
log("resp",resp);
// TODO: Should we move other notices into TmplPhrases like this one?
pushNotice(phraseBox["panel"]["panel.forums_order_updated"]);
if(resp.success==1) return;
} catch(e) {
console.error("e",e)
}
console.trace();
}
// ? - Is encodeURIComponent the right function for this?
req.open("POST","/panel/forums/order/edit/submit/?s=" + encodeURIComponent(me.User.S));
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
let items = "";
for(let i=0;item=forums[i];i++) items += item+",";
if(items.length > 0) items = items.slice(0,-1);
req.send("js=1&amp;items={"+items+"}");
let req = new XMLHttpRequest();
if(!req) {
log("Failed to create request");
return false;
}
req.onreadystatechange = () => {
try {
if(req.readyState!==XMLHttpRequest.DONE) return;
// TODO: Signal the error with a notice
if(req.status!==200) return;
let resp = JSON.parse(req.responseText);
log("resp",resp);
// TODO: Should we move other notices into TmplPhrases like this one?
pushNotice(phraseBox["panel"]["panel.forums_order_updated"]);
if(resp.success==1) return;
} catch(e) {
console.error("e",e)
}
console.trace();
}
// ? - Is encodeURIComponent the right function for this?
req.open("POST","/panel/forums/order/edit/submit/?s=" + encodeURIComponent(me.User.S));
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
let items = "";
for(let i=0;item=forums[i];i++) items += item+",";
if(items.length > 0) items = items.slice(0,-1);
req.send("js=1&amp;items={"+items+"}");
});
});

View File

@ -1,5 +1,5 @@
(() => {
addInitHook("end_init", () => {
addInitHook("end_init", () => {
// TODO: Move this into a JS file to reduce the number of possible problems
var menuItems = {};
@ -7,49 +7,49 @@ let items = document.getElementsByClassName("panel_menu_item");
for(let i=0; item=items[i]; i++) menuItems[i] = item.getAttribute("data-miid");
Sortable.create(document.getElementById("panel_menu_item_holder"), {
sort: true,
onEnd: evt => {
log("pre menuItems",menuItems)
log("evt",evt)
let oldMiid = menuItems[evt.newIndex];
menuItems[evt.oldIndex] = oldMiid;
let newMiid = evt.item.getAttribute("data-miid");
log("newMiid",newMiid);
menuItems[evt.newIndex] = newMiid;
log("post menuItems",menuItems);
}
sort: true,
onEnd: evt => {
log("pre menuItems",menuItems)
log("evt",evt)
let oldMiid = menuItems[evt.newIndex];
menuItems[evt.oldIndex] = oldMiid;
let newMiid = evt.item.getAttribute("data-miid");
log("newMiid",newMiid);
menuItems[evt.newIndex] = newMiid;
log("post menuItems",menuItems);
}
});
document.getElementById("panel_menu_items_order_button").addEventListener("click", () => {
let req = new XMLHttpRequest();
if(!req) {
log("Failed to create request");
return false;
}
req.onreadystatechange = () => {
try {
if(req.readyState!==XMLHttpRequest.DONE) return;
// TODO: Signal the error with a notice
if(req.status===200) {
let resp = JSON.parse(req.responseText);
log("resp",resp);
// TODO: Should we move other notices into TmplPhrases like this one?
pushNotice(phraseBox["panel"]["panel.themes_menus_items_order_updated"]);
if(resp.success==1) return;
}
} catch(e) {
console.error("e",e)
}
console.trace();
}
// ? - Is encodeURIComponent the right function for this?
let spl = document.location.pathname.split("/");
req.open("POST","/panel/themes/menus/item/order/edit/submit/"+parseInt(spl[spl.length-1],10)+"?s="+encodeURIComponent(me.User.S));
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
let items = "";
for(let i=0; item=menuItems[i];i++) items += item+",";
if(items.length > 0) items = items.slice(0,-1);
req.send("js=1&amp;items={"+items+"}");
let req = new XMLHttpRequest();
if(!req) {
log("Failed to create request");
return false;
}
req.onreadystatechange = () => {
try {
if(req.readyState!==XMLHttpRequest.DONE) return;
// TODO: Signal the error with a notice
if(req.status===200) {
let resp = JSON.parse(req.responseText);
log("resp",resp);
// TODO: Should we move other notices into TmplPhrases like this one?
pushNotice(phraseBox["panel"]["panel.themes_menus_items_order_updated"]);
if(resp.success==1) return;
}
} catch(e) {
console.error("e",e)
}
console.trace();
}
// ? - Is encodeURIComponent the right function for this?
let spl = document.location.pathname.split("/");
req.open("POST","/panel/themes/menus/item/order/edit/submit/"+parseInt(spl[spl.length-1],10)+"?s="+encodeURIComponent(me.User.S));
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
let items = "";
for(let i=0; item=menuItems[i];i++) items += item+",";
if(items.length > 0) items = items.slice(0,-1);
req.send("js=1&amp;items={"+items+"}");
});
});

View File

@ -1,23 +1,23 @@
function handle_profile_hashbit() {
var hash_class = "";
switch(window.location.hash.substr(1)) {
case "ban_user":
hash_class = "ban_user_hash";
break;
case "delete_posts":
hash_class = "delete_posts_hash";
break;
default:
log("Unknown hashbit");
return;
}
$(".hash_hide").hide();
$("." + hash_class).show();
var hash_class = "";
switch(window.location.hash.substr(1)) {
case "ban_user":
hash_class = "ban_user_hash";
break;
case "delete_posts":
hash_class = "delete_posts_hash";
break;
default:
log("Unknown hashbit");
return;
}
$(".hash_hide").hide();
$("." + hash_class).show();
}
(() => {
addInitHook("end_init", () => {
if(window.location.hash) handle_profile_hashbit();
window.addEventListener("hashchange", handle_profile_hashbit, false);
if(window.location.hash) handle_profile_hashbit();
window.addEventListener("hashchange", handle_profile_hashbit, false);
});
})();

View File

@ -1,14 +1,14 @@
(() => {
addInitHook("end_init", () => {
fetch("/api/watches/")
.then(resp => {
if(resp.status!==200) {
log("err");
log("resp",resp);
return;
}
resp.text().then(d => eval(d));
})
.catch(e => log("e",e));
});
addInitHook("end_init", () => {
fetch("/api/watches/")
.then(resp => {
if(resp.status!==200) {
log("err");
log("resp",resp);
return;
}
resp.text().then(d => eval(d));
})
.catch(e => log("e",e));
});
})()

View File

@ -1,64 +1,64 @@
"use strict";
$(document).ready(() => {
let clickHandle = function(ev){
log("in clickHandle")
ev.preventDefault();
let ep = $(this).closest(".editable_parent");
ep.find(".hide_on_block_edit").addClass("edit_opened");
ep.find(".show_on_block_edit").addClass("edit_opened");
ep.addClass("in_edit");
let clickHandle = function(ev){
log("in clickHandle")
ev.preventDefault();
let ep = $(this).closest(".editable_parent");
ep.find(".hide_on_block_edit").addClass("edit_opened");
ep.find(".show_on_block_edit").addClass("edit_opened");
ep.addClass("in_edit");
ep.find(".widget_save").click(() => {
ep.find(".hide_on_block_edit").removeClass("edit_opened");
ep.find(".show_on_block_edit").removeClass("edit_opened");
ep.removeClass("in_edit");
});
ep.find(".widget_save").click(() => {
ep.find(".hide_on_block_edit").removeClass("edit_opened");
ep.find(".show_on_block_edit").removeClass("edit_opened");
ep.removeClass("in_edit");
});
ep.find(".widget_delete").click(function(ev) {
ev.preventDefault();
ep.remove();
let formData = new URLSearchParams();
formData.append("s",me.User.S);
let req = new XMLHttpRequest();
let target = this.closest("a").getAttribute("href");
req.open("POST",target,true);
req.send(formData);
});
};
ep.find(".widget_delete").click(function(ev) {
ev.preventDefault();
ep.remove();
let formData = new URLSearchParams();
formData.append("s",me.User.S);
let req = new XMLHttpRequest();
let target = this.closest("a").getAttribute("href");
req.open("POST",target,true);
req.send(formData);
});
};
$(".widget_item a").click(clickHandle);
$(".widget_item a").click(clickHandle);
let changeHandle = function(ev){
let wtype = this.options[this.selectedIndex].value;
let typeBlock = this.closest(".widget_edit").querySelector(".wtypes");
typeBlock.className = "wtypes wtype_"+wtype;
};
$(".wtype_sel").change(changeHandle);
let changeHandle = function(ev){
let wtype = this.options[this.selectedIndex].value;
let typeBlock = this.closest(".widget_edit").querySelector(".wtypes");
typeBlock.className = "wtypes wtype_"+wtype;
};
$(".wtype_sel").change(changeHandle);
$(".widget_new a").click(function(ev){
log("clicked widget_new a")
let widgetList = this.closest(".panel_widgets");
let widgetNew = this.closest(".widget_new");
let widgetTmpl = document.getElementById("widgetTmpl").querySelector(".widget_item");
let n = widgetTmpl.cloneNode(true);
n.querySelector(".wside").value = this.getAttribute("data-dock");
widgetList.insertBefore(n,widgetNew);
$(".widget_item a").unbind("click");
$(".widget_item a").click(clickHandle);
$(".wtype_sel").unbind("change");
$(".wtype_sel").change(changeHandle);
});
$(".widget_new a").click(function(ev){
log("clicked widget_new a")
let widgetList = this.closest(".panel_widgets");
let widgetNew = this.closest(".widget_new");
let widgetTmpl = document.getElementById("widgetTmpl").querySelector(".widget_item");
let n = widgetTmpl.cloneNode(true);
n.querySelector(".wside").value = this.getAttribute("data-dock");
widgetList.insertBefore(n,widgetNew);
$(".widget_item a").unbind("click");
$(".widget_item a").click(clickHandle);
$(".wtype_sel").unbind("change");
$(".wtype_sel").change(changeHandle);
});
$(".widget_save").click(function(ev){
log("in .widget_save")
ev.preventDefault();
ev.stopPropagation();
let pform = this.closest("form");
let dat = new URLSearchParams();
for (const pair of new FormData(pform)) dat.append(pair[0], pair[1]);
dat.append("s",me.User.S);
var req = new XMLHttpRequest();
req.open("POST",pform.getAttribute("action"));
req.send(dat);
});
$(".widget_save").click(function(ev){
log("in .widget_save")
ev.preventDefault();
ev.stopPropagation();
let pform = this.closest("form");
let dat = new URLSearchParams();
for (const pair of new FormData(pform)) dat.append(pair[0], pair[1]);
dat.append("s",me.User.S);
var req = new XMLHttpRequest();
req.open("POST",pform.getAttribute("action"));
req.send(dat);
});
});

View File

@ -1,8 +0,0 @@
echo "Updating Gosora"
git stash
git pull origin master
git stash apply
echo "Patching Gosora"
go build -ldflags="-s -w" -o Patcher "./patcher"
./Patcher

494
router.go
View File

@ -2,214 +2,214 @@
package main
import (
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
c "github.com/Azareal/Gosora/common"
co "github.com/Azareal/Gosora/common/counters"
c "github.com/Azareal/Gosora/common"
co "github.com/Azareal/Gosora/common/counters"
)
// TODO: Stop spilling these into the package scope?
func init() {
_ = time.Now()
co.SetRouteMapEnum(routeMapEnum)
co.SetReverseRouteMapEnum(reverseRouteMapEnum)
co.SetAgentMapEnum(agentMapEnum)
co.SetReverseAgentMapEnum(reverseAgentMapEnum)
co.SetOSMapEnum(osMapEnum)
co.SetReverseOSMapEnum(reverseOSMapEnum)
_ = time.Now()
co.SetRouteMapEnum(routeMapEnum)
co.SetReverseRouteMapEnum(reverseRouteMapEnum)
co.SetAgentMapEnum(agentMapEnum)
co.SetReverseAgentMapEnum(reverseAgentMapEnum)
co.SetOSMapEnum(osMapEnum)
co.SetReverseOSMapEnum(reverseOSMapEnum)
g := func(n string) int {
a, ok := agentMapEnum[n]
if !ok {
panic("name not found in agentMapEnum")
}
return a
}
c.Chrome = g("chrome")
c.Firefox = g("firefox")
c.SimpleBots = []int{
g("semrush"),
g("ahrefs"),
g("python"),
//g("go"),
g("curl"),
}
g := func(n string) int {
a, ok := agentMapEnum[n]
if !ok {
panic("name not found in agentMapEnum")
}
return a
}
c.Chrome = g("chrome")
c.Firefox = g("firefox")
c.SimpleBots = []int{
g("semrush"),
g("ahrefs"),
g("python"),
//g("go"),
g("curl"),
}
}
type WriterIntercept struct {
http.ResponseWriter
http.ResponseWriter
}
func NewWriterIntercept(w http.ResponseWriter) *WriterIntercept {
return &WriterIntercept{w}
return &WriterIntercept{w}
}
var wiMaxAge = "max-age=" + strconv.Itoa(int(c.Day))
func (wi *WriterIntercept) WriteHeader(code int) {
if code == 200 {
h := wi.ResponseWriter.Header()
h.Set("Cache-Control", wiMaxAge)
h.Set("Vary", "Accept-Encoding")
}
wi.ResponseWriter.WriteHeader(code)
if code == 200 {
h := wi.ResponseWriter.Header()
h.Set("Cache-Control", wiMaxAge)
h.Set("Vary", "Accept-Encoding")
}
wi.ResponseWriter.WriteHeader(code)
}
type GenRouter struct {
UploadHandler func(http.ResponseWriter, *http.Request)
extraRoutes map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError
UploadHandler func(http.ResponseWriter, *http.Request)
extraRoutes map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError
reqLogger *log.Logger
reqLogger *log.Logger
reqLog2 *RouterLog
suspLog *RouterLog
reqLog2 *RouterLog
suspLog *RouterLog
sync.RWMutex
sync.RWMutex
}
type RouterLogLog struct {
File *os.File
Log *log.Logger
File *os.File
Log *log.Logger
}
type RouterLog struct {
FileVal atomic.Value
LogVal atomic.Value
FileVal atomic.Value
LogVal atomic.Value
sync.RWMutex
sync.RWMutex
}
func (r *GenRouter) DailyTick() error {
currentTime := time.Now()
rotateLog := func(l *RouterLog, name string) error {
l.Lock()
defer l.Unlock()
currentTime := time.Now()
rotateLog := func(l *RouterLog, name string) error {
l.Lock()
defer l.Unlock()
f := l.FileVal.Load().(*os.File)
stat, e := f.Stat()
if e != nil {
return nil
}
if (stat.Size() < int64(c.Megabyte)) && (currentTime.Sub(c.StartTime).Hours() >= (24 * 7)) {
return nil
}
if e = f.Close(); e != nil {
return e
}
f := l.FileVal.Load().(*os.File)
stat, e := f.Stat()
if e != nil {
return nil
}
if (stat.Size() < int64(c.Megabyte)) && (currentTime.Sub(c.StartTime).Hours() >= (24 * 7)) {
return nil
}
if e = f.Close(); e != nil {
return e
}
stimestr := strconv.FormatInt(currentTime.Unix(), 10)
f, e = os.OpenFile(c.Config.LogDir+name+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if e != nil {
return e
}
lval := log.New(f, "", log.LstdFlags)
l.FileVal.Store(f)
l.LogVal.Store(lval)
return nil
}
stimestr := strconv.FormatInt(currentTime.Unix(), 10)
f, e = os.OpenFile(c.Config.LogDir+name+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if e != nil {
return e
}
lval := log.New(f, "", log.LstdFlags)
l.FileVal.Store(f)
l.LogVal.Store(lval)
return nil
}
if !c.Config.DisableSuspLog {
err := rotateLog(r.suspLog, "reqs-susp-")
if err != nil {
return err
}
}
return rotateLog(r.reqLog2, "reqs-")
if !c.Config.DisableSuspLog {
err := rotateLog(r.suspLog, "reqs-susp-")
if err != nil {
return err
}
}
return rotateLog(r.reqLog2, "reqs-")
}
type RouterConfig struct {
Uploads http.Handler
DisableTick bool
Uploads http.Handler
DisableTick bool
}
func NewGenRouter(cfg *RouterConfig) (*GenRouter, error) {
stimestr := strconv.FormatInt(c.StartTime.Unix(), 10)
createLog := func(name, stimestr string) (*RouterLog, error) {
f, err := os.OpenFile(c.Config.LogDir+name+"-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
l := log.New(f, "", log.LstdFlags)
var aVal atomic.Value
var aVal2 atomic.Value
aVal.Store(f)
aVal2.Store(l)
return &RouterLog{FileVal: aVal, LogVal: aVal2}, nil
}
reqLog, err := createLog("reqs", stimestr)
if err != nil {
return nil, err
}
var suspReqLog *RouterLog
if !c.Config.DisableSuspLog {
suspReqLog, err = createLog("reqs-susp", stimestr)
if err != nil {
return nil, err
}
}
f3, err := os.OpenFile(c.Config.LogDir+"reqs-misc-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
reqMiscLog := log.New(f3, "", log.LstdFlags)
stimestr := strconv.FormatInt(c.StartTime.Unix(), 10)
createLog := func(name, stimestr string) (*RouterLog, error) {
f, err := os.OpenFile(c.Config.LogDir+name+"-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
l := log.New(f, "", log.LstdFlags)
var aVal atomic.Value
var aVal2 atomic.Value
aVal.Store(f)
aVal2.Store(l)
return &RouterLog{FileVal: aVal, LogVal: aVal2}, nil
}
reqLog, err := createLog("reqs", stimestr)
if err != nil {
return nil, err
}
var suspReqLog *RouterLog
if !c.Config.DisableSuspLog {
suspReqLog, err = createLog("reqs-susp", stimestr)
if err != nil {
return nil, err
}
}
f3, err := os.OpenFile(c.Config.LogDir+"reqs-misc-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
reqMiscLog := log.New(f3, "", log.LstdFlags)
ro := &GenRouter{
UploadHandler: func(w http.ResponseWriter, r *http.Request) {
writ := NewWriterIntercept(w)
http.StripPrefix("/uploads/", cfg.Uploads).ServeHTTP(writ, r)
},
extraRoutes: make(map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError),
ro := &GenRouter{
UploadHandler: func(w http.ResponseWriter, r *http.Request) {
writ := NewWriterIntercept(w)
http.StripPrefix("/uploads/", cfg.Uploads).ServeHTTP(writ, r)
},
extraRoutes: make(map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError),
reqLogger: reqMiscLog,
reqLog2: reqLog,
suspLog: suspReqLog,
}
if !cfg.DisableTick {
c.Tasks.Day.Add(ro.DailyTick)
}
return ro, nil
reqLogger: reqMiscLog,
reqLog2: reqLog,
suspLog: suspReqLog,
}
if !cfg.DisableTick {
c.Tasks.Day.Add(ro.DailyTick)
}
return ro, nil
}
func (r *GenRouter) handleError(err c.RouteError, w http.ResponseWriter, req *http.Request, u *c.User) {
if err.Handled() {
return
}
if err.Type() == "system" {
c.InternalErrorJSQ(err, w, req, err.JSON())
return
}
c.LocalErrorJSQ(err.Error(), w, req, u, err.JSON())
if err.Handled() {
return
}
if err.Type() == "system" {
c.InternalErrorJSQ(err, w, req, err.JSON())
return
}
c.LocalErrorJSQ(err.Error(), w, req, u, err.JSON())
}
func (r *GenRouter) Handle(_ string, _ http.Handler) {
}
func (r *GenRouter) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request, *c.User) c.RouteError) {
r.Lock()
defer r.Unlock()
r.extraRoutes[pattern] = h
r.Lock()
defer r.Unlock()
r.extraRoutes[pattern] = h
}
func (r *GenRouter) RemoveFunc(pattern string) error {
r.Lock()
defer r.Unlock()
_, ok := r.extraRoutes[pattern]
if !ok {
return ErrNoRoute
}
delete(r.extraRoutes, pattern)
return nil
r.Lock()
defer r.Unlock()
_, ok := r.extraRoutes[pattern]
if !ok {
return ErrNoRoute
}
delete(r.extraRoutes, pattern)
return nil
}
func (r *GenRouter) dumpRequest(req *http.Request, pre string, log *RouterLog) {
var sb strings.Builder
r.ddumpRequest(req, pre, log, &sb)
var sb strings.Builder
r.ddumpRequest(req, pre, log, &sb)
}
// TODO: Some of these sanitisations may be redundant
@ -217,115 +217,115 @@ var dumpReqLen = len("\nUA: \n Host: \nIP: \n") + 7
var dumpReqLen2 = len("\nHead : ") + 2
func (r *GenRouter) ddumpRequest(req *http.Request, pre string, l *RouterLog, sb *strings.Builder) {
nfield := func(label, val string) {
sb.WriteString(label)
sb.WriteString(val)
}
field := func(label, val string) {
nfield(label, c.SanitiseSingleLine(val))
}
ua := req.UserAgent()
nfield := func(label, val string) {
sb.WriteString(label)
sb.WriteString(val)
}
field := func(label, val string) {
nfield(label, c.SanitiseSingleLine(val))
}
ua := req.UserAgent()
sb.Grow(dumpReqLen + len(pre) + len(ua) + len(req.Method) + len(req.Host) + (dumpReqLen2 * len(req.Header)))
sb.WriteString(pre)
sb.WriteString("\n")
sb.WriteString(c.SanitiseSingleLine(req.Method))
sb.WriteRune(' ')
sb.WriteString(c.SanitiseSingleLine(req.URL.Path))
field("\nUA: ", ua)
sb.Grow(dumpReqLen + len(pre) + len(ua) + len(req.Method) + len(req.Host) + (dumpReqLen2 * len(req.Header)))
sb.WriteString(pre)
sb.WriteString("\n")
sb.WriteString(c.SanitiseSingleLine(req.Method))
sb.WriteRune(' ')
sb.WriteString(c.SanitiseSingleLine(req.URL.Path))
field("\nUA: ", ua)
for key, val := range req.Header {
// Avoid logging this for security reasons
if key == "Cookie" {
continue
}
for _, vvalue := range val {
sb.WriteString("\nHead ")
sb.WriteString(c.SanitiseSingleLine(key))
sb.WriteString(": ")
sb.WriteString(c.SanitiseSingleLine(vvalue))
}
}
field("\nHost: ", req.Host)
if rawQuery := req.URL.RawQuery; rawQuery != "" {
field("\nURL.RawQuery: ", rawQuery)
}
if ref := req.Referer(); ref != "" {
field("\nRef: ", ref)
}
nfield("\nIP: ", req.RemoteAddr)
sb.WriteString("\n")
for key, val := range req.Header {
// Avoid logging this for security reasons
if key == "Cookie" {
continue
}
for _, vvalue := range val {
sb.WriteString("\nHead ")
sb.WriteString(c.SanitiseSingleLine(key))
sb.WriteString(": ")
sb.WriteString(c.SanitiseSingleLine(vvalue))
}
}
field("\nHost: ", req.Host)
if rawQuery := req.URL.RawQuery; rawQuery != "" {
field("\nURL.RawQuery: ", rawQuery)
}
if ref := req.Referer(); ref != "" {
field("\nRef: ", ref)
}
nfield("\nIP: ", req.RemoteAddr)
sb.WriteString("\n")
str := sb.String()
l.RLock()
l.LogVal.Load().(*log.Logger).Print(str)
l.RUnlock()
str := sb.String()
l.RLock()
l.LogVal.Load().(*log.Logger).Print(str)
l.RUnlock()
}
func (r *GenRouter) DumpRequest(req *http.Request, pre string) {
r.dumpRequest(req, pre, r.reqLog2)
r.dumpRequest(req, pre, r.reqLog2)
}
func (r *GenRouter) unknownUA(req *http.Request) {
if c.Dev.DebugMode {
var presb strings.Builder
presb.WriteString("Unknown UA: ")
for _, ch := range req.UserAgent() {
presb.WriteString(strconv.Itoa(int(ch)))
presb.WriteRune(' ')
}
r.ddumpRequest(req, "", r.reqLog2, &presb)
} else {
r.reqLogger.Print("unknown ua: ", c.SanitiseSingleLine(req.UserAgent()))
}
if c.Dev.DebugMode {
var presb strings.Builder
presb.WriteString("Unknown UA: ")
for _, ch := range req.UserAgent() {
presb.WriteString(strconv.Itoa(int(ch)))
presb.WriteRune(' ')
}
r.ddumpRequest(req, "", r.reqLog2, &presb)
} else {
r.reqLogger.Print("unknown ua: ", c.SanitiseSingleLine(req.UserAgent()))
}
}
func (r *GenRouter) susp1(req *http.Request) bool {
if !strings.Contains(req.URL.Path, ".") {
return false
}
if strings.Contains(req.URL.Path, "..") /* || strings.Contains(req.URL.Path,"--")*/ {
return true
}
lp := strings.ToLower(req.URL.Path)
// TODO: Flag any requests which has a dot with anything but a number after that
// TODO: Use HasSuffix to avoid over-scanning?
return strings.Contains(lp, ".php") || strings.Contains(lp, ".asp") || strings.Contains(lp, ".cgi") || strings.Contains(lp, ".py") || strings.Contains(lp, ".sql") || strings.Contains(lp, ".act") //.action
if !strings.Contains(req.URL.Path, ".") {
return false
}
if strings.Contains(req.URL.Path, "..") /* || strings.Contains(req.URL.Path,"--")*/ {
return true
}
lp := strings.ToLower(req.URL.Path)
// TODO: Flag any requests which has a dot with anything but a number after that
// TODO: Use HasSuffix to avoid over-scanning?
return strings.Contains(lp, ".php") || strings.Contains(lp, ".asp") || strings.Contains(lp, ".cgi") || strings.Contains(lp, ".py") || strings.Contains(lp, ".sql") || strings.Contains(lp, ".act") //.action
}
func (r *GenRouter) suspScan(req *http.Request) {
if c.Config.DisableSuspLog {
if c.Dev.FullReqLog {
r.DumpRequest(req, "")
}
return
}
if c.Config.DisableSuspLog {
if c.Dev.FullReqLog {
r.DumpRequest(req, "")
}
return
}
// TODO: Cover more suspicious strings and at a lower layer than this
var ch rune
var susp bool
for _, ch = range req.URL.Path { //char
if ch != '&' && !(ch > 44 && ch < 58) && ch != '=' && ch != '?' && !(ch > 64 && ch < 91) && ch != '\\' && ch != '_' && !(ch > 96 && ch < 123) {
susp = true
break
}
}
// TODO: Cover more suspicious strings and at a lower layer than this
var ch rune
var susp bool
for _, ch = range req.URL.Path { //char
if ch != '&' && !(ch > 44 && ch < 58) && ch != '=' && ch != '?' && !(ch > 64 && ch < 91) && ch != '\\' && ch != '_' && !(ch > 96 && ch < 123) {
susp = true
break
}
}
// Avoid logging the same request multiple times
susp2 := r.susp1(req)
if susp && susp2 {
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path\nBad snippet in path")
} else if susp {
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path")
} else if susp2 {
r.SuspiciousRequest(req, "Bad snippet in path")
} else if c.Dev.FullReqLog {
r.DumpRequest(req, "")
}
// Avoid logging the same request multiple times
susp2 := r.susp1(req)
if susp && susp2 {
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path\nBad snippet in path")
} else if susp {
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path")
} else if susp2 {
r.SuspiciousRequest(req, "Bad snippet in path")
} else if c.Dev.FullReqLog {
r.DumpRequest(req, "")
}
}
func isLocalHost(h string) bool {
return h == "localhost" || h == "127.0.0.1" || h == "::1"
return h == "localhost" || h == "127.0.0.1" || h == "::1"
}
//var brPool = sync.Pool{}
@ -334,12 +334,12 @@ var gzipPool = sync.Pool{}
//var uaBufPool = sync.Pool{}
func (r *GenRouter) responseWriter(w http.ResponseWriter) http.ResponseWriter {
/*if bzw, ok := w.(c.BrResponseWriter); ok {
w = bzw.ResponseWriter
w.Header().Del("Content-Encoding")
} else */if gzw, ok := w.(c.GzipResponseWriter); ok {
w = gzw.ResponseWriter
w.Header().Del("Content-Encoding")
}
return w
/*if bzw, ok := w.(c.BrResponseWriter); ok {
w = bzw.ResponseWriter
w.Header().Del("Content-Encoding")
} else */if gzw, ok := w.(c.GzipResponseWriter); ok {
w = gzw.ResponseWriter
w.Header().Del("Content-Encoding")
}
return w
}

View File

@ -1,96 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the router generator
router_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook stub generator
hook_stub_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook generator
hook_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the query generator
query_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable
go build -ldflags="-s -w" -o gosora.exe -tags no_ws
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the templates
gosora.exe -build-templates
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable... again
go build -ldflags="-s -w" -o gosora.exe -tags no_ws
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running Gosora
gosora.exe
pause

98
run.bat
View File

@ -1,98 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the router generator
router_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook stub generator
hook_stub_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook generator
hook_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the query generator
query_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable
go build -ldflags="-s -w" -o gosora.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the templates
gosora.exe -build-templates
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable... again
go build -ldflags="-s -w" -gcflags="-d=ssa/check_bce/debug=1" -o gosora.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running Gosora
gosora.exe
rem Or you could redirect the output to a file
rem gosora.exe > ./logs/ops.log 2>&1
pause

View File

@ -1,96 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the router generator
router_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook stub generator
hook_stub_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook generator
hook_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the query generator
query_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable
go build -ldflags="-s -w" -o gosora.exe -tags mssql
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the templates
gosora.exe -build-templates
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable... again
go build -ldflags="-s -w" -o gosora.exe -tags mssql
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running Gosora
gosora.exe
pause

View File

@ -1,79 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the router generator
router_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook stub generator
hook_stub_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook generator
hook_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the query generator
query_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable
go test
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
pause

View File

@ -1,79 +0,0 @@
@echo off
rem TODO: Make these deletes a little less noisy
del "template_*.go"
del "tmpl_*.go"
del "gen_*.go"
del ".\tmpl_client\template_*"
del ".\tmpl_client\tmpl_*"
del ".\common\gen_extend.go"
del "gosora.exe"
echo Generating the dynamic code
go generate
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the router generator
go build -ldflags="-s -w" ./router_gen
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the router generator
router_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the hook stub generator
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook stub generator
hook_stub_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Generating the JSON handlers
easyjson -pkg common
echo Building the hook generator
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the hook generator
hook_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the query generator
go build -ldflags="-s -w" "./cmd/query_gen"
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Running the query generator
query_gen.exe
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
echo Building the executable
go test -tags mssql
if %errorlevel% neq 0 (
pause
exit /b %errorlevel%
)
pause

View File

@ -1,11 +1,11 @@
CREATE TABLE [activity_stream] (
[asid] int not null IDENTITY,
[actor] int not null,
[targetUser] int not null,
[event] nvarchar (50) not null,
[elementType] nvarchar (50) not null,
[elementID] int not null,
[createdAt] datetime not null,
[extra] nvarchar (200) DEFAULT '' not null,
primary key([asid])
[asid] int not null IDENTITY,
[actor] int not null,
[targetUser] int not null,
[event] nvarchar (50) not null,
[elementType] nvarchar (50) not null,
[elementID] int not null,
[createdAt] datetime not null,
[extra] nvarchar (200) DEFAULT '' not null,
primary key([asid])
);

View File

@ -1,5 +1,5 @@
CREATE TABLE [activity_stream_matches] (
[watcher] int not null,
[asid] int not null,
foreign key([asid],[asid])
[watcher] int not null,
[asid] int not null,
foreign key([asid],[asid])
);

View File

@ -1,6 +1,6 @@
CREATE TABLE [activity_subscriptions] (
[user] int not null,
[targetID] int not null,
[targetType] nvarchar (50) not null,
[level] int DEFAULT 0 not null
[user] int not null,
[targetID] int not null,
[targetType] nvarchar (50) not null,
[level] int DEFAULT 0 not null
);

View File

@ -1,9 +1,9 @@
CREATE TABLE [administration_logs] (
[action] nvarchar (100) not null,
[elementID] int not null,
[elementType] nvarchar (100) not null,
[ipaddress] nvarchar (200) not null,
[actorID] int not null,
[doneAt] datetime not null,
[extra] nvarchar (MAX) not null
[action] nvarchar (100) not null,
[elementID] int not null,
[elementType] nvarchar (100) not null,
[ipaddress] nvarchar (200) not null,
[actorID] int not null,
[doneAt] datetime not null,
[extra] nvarchar (MAX) not null
);

View File

@ -1,11 +1,11 @@
CREATE TABLE [attachments] (
[attachID] int not null IDENTITY,
[sectionID] int DEFAULT 0 not null,
[sectionTable] nvarchar (200) DEFAULT 'forums' not null,
[originID] int not null,
[originTable] nvarchar (200) DEFAULT 'replies' not null,
[uploadedBy] int not null,
[path] nvarchar (200) not null,
[extra] nvarchar (200) not null,
primary key([attachID])
[attachID] int not null IDENTITY,
[sectionID] int DEFAULT 0 not null,
[sectionTable] nvarchar (200) DEFAULT 'forums' not null,
[originID] int not null,
[originTable] nvarchar (200) DEFAULT 'replies' not null,
[uploadedBy] int not null,
[path] nvarchar (200) not null,
[extra] nvarchar (200) not null,
primary key([attachID])
);

View File

@ -1,8 +1,8 @@
CREATE TABLE [conversations] (
[cid] int not null IDENTITY,
[createdBy] int not null,
[createdAt] datetime not null,
[lastReplyAt] datetime not null,
[lastReplyBy] int not null,
primary key([cid])
[cid] int not null IDENTITY,
[createdBy] int not null,
[createdAt] datetime not null,
[lastReplyAt] datetime not null,
[lastReplyBy] int not null,
primary key([cid])
);

View File

@ -1,4 +1,4 @@
CREATE TABLE [conversations_participants] (
[uid] int not null,
[cid] int not null
[uid] int not null,
[cid] int not null
);

View File

@ -1,8 +1,8 @@
CREATE TABLE [conversations_posts] (
[pid] int not null IDENTITY,
[cid] int not null,
[createdBy] int not null,
[body] nvarchar (50) not null,
[post] nvarchar (50) DEFAULT '' not null,
primary key([pid])
[pid] int not null IDENTITY,
[cid] int not null,
[createdBy] int not null,
[body] nvarchar (50) not null,
[post] nvarchar (50) DEFAULT '' not null,
primary key([pid])
);

View File

@ -1,6 +1,6 @@
CREATE TABLE [emails] (
[email] nvarchar (200) not null,
[uid] int not null,
[validated] bit DEFAULT 0 not null,
[token] nvarchar (200) DEFAULT '' not null
[email] nvarchar (200) not null,
[uid] int not null,
[validated] bit DEFAULT 0 not null,
[token] nvarchar (200) DEFAULT '' not null
);

View File

@ -1,15 +1,15 @@
CREATE TABLE [forums] (
[fid] int not null IDENTITY,
[name] nvarchar (100) not null,
[desc] nvarchar (200) not null,
[tmpl] nvarchar (200) DEFAULT '' not null,
[active] bit DEFAULT 1 not null,
[order] int DEFAULT 0 not null,
[topicCount] int DEFAULT 0 not null,
[preset] nvarchar (100) DEFAULT '' not null,
[parentID] int DEFAULT 0 not null,
[parentType] nvarchar (50) DEFAULT '' not null,
[lastTopicID] int DEFAULT 0 not null,
[lastReplyerID] int DEFAULT 0 not null,
primary key([fid])
[fid] int not null IDENTITY,
[name] nvarchar (100) not null,
[desc] nvarchar (200) not null,
[tmpl] nvarchar (200) DEFAULT '' not null,
[active] bit DEFAULT 1 not null,
[order] int DEFAULT 0 not null,
[topicCount] int DEFAULT 0 not null,
[preset] nvarchar (100) DEFAULT '' not null,
[parentID] int DEFAULT 0 not null,
[parentType] nvarchar (50) DEFAULT '' not null,
[lastTopicID] int DEFAULT 0 not null,
[lastReplyerID] int DEFAULT 0 not null,
primary key([fid])
);

View File

@ -1,10 +1,10 @@
CREATE TABLE [forums_actions] (
[faid] int not null IDENTITY,
[fid] int not null,
[runOnTopicCreation] bit DEFAULT 0 not null,
[runDaysAfterTopicCreation] int DEFAULT 0 not null,
[runDaysAfterTopicLastReply] int DEFAULT 0 not null,
[action] nvarchar (50) not null,
[extra] nvarchar (200) DEFAULT '' not null,
primary key([faid])
[faid] int not null IDENTITY,
[fid] int not null,
[runOnTopicCreation] bit DEFAULT 0 not null,
[runDaysAfterTopicCreation] int DEFAULT 0 not null,
[runDaysAfterTopicLastReply] int DEFAULT 0 not null,
[action] nvarchar (50) not null,
[extra] nvarchar (200) DEFAULT '' not null,
primary key([faid])
);

View File

@ -1,7 +1,7 @@
CREATE TABLE [forums_permissions] (
[fid] int not null,
[gid] int not null,
[preset] nvarchar (100) DEFAULT '' not null,
[permissions] nvarchar (MAX) not null,
primary key([fid],[gid])
[fid] int not null,
[gid] int not null,
[preset] nvarchar (100) DEFAULT '' not null,
[permissions] nvarchar (MAX) not null,
primary key([fid],[gid])
);

View File

@ -1,8 +1,8 @@
CREATE TABLE [likes] (
[weight] tinyint DEFAULT 1 not null,
[targetItem] int not null,
[targetType] nvarchar (50) DEFAULT 'replies' not null,
[sentBy] int not null,
[createdAt] datetime not null,
[recalc] tinyint DEFAULT 0 not null
[weight] tinyint DEFAULT 1 not null,
[targetItem] int not null,
[targetType] nvarchar (50) DEFAULT 'replies' not null,
[sentBy] int not null,
[createdAt] datetime not null,
[recalc] tinyint DEFAULT 0 not null
);

View File

@ -1,8 +1,8 @@
CREATE TABLE [login_logs] (
[lid] int not null IDENTITY,
[uid] int not null,
[success] bool DEFAULT 0 not null,
[ipaddress] nvarchar (200) not null,
[doneAt] datetime not null,
primary key([lid])
[lid] int not null IDENTITY,
[uid] int not null,
[success] bool DEFAULT 0 not null,
[ipaddress] nvarchar (200) not null,
[doneAt] datetime not null,
primary key([lid])
);

View File

@ -1,6 +1,6 @@
CREATE TABLE [memchunks] (
[count] int DEFAULT 0 not null,
[stack] int DEFAULT 0 not null,
[heap] int DEFAULT 0 not null,
[createdAt] datetime not null
[count] int DEFAULT 0 not null,
[stack] int DEFAULT 0 not null,
[heap] int DEFAULT 0 not null,
[createdAt] datetime not null
);

View File

@ -1,18 +1,18 @@
CREATE TABLE [menu_items] (
[miid] int not null IDENTITY,
[mid] int not null,
[name] nvarchar (200) DEFAULT '' not null,
[htmlID] nvarchar (200) DEFAULT '' not null,
[cssClass] nvarchar (200) DEFAULT '' not null,
[position] nvarchar (100) not null,
[path] nvarchar (200) DEFAULT '' not null,
[aria] nvarchar (200) DEFAULT '' not null,
[tooltip] nvarchar (200) DEFAULT '' not null,
[tmplName] nvarchar (200) DEFAULT '' not null,
[order] int DEFAULT 0 not null,
[guestOnly] bit DEFAULT 0 not null,
[memberOnly] bit DEFAULT 0 not null,
[staffOnly] bit DEFAULT 0 not null,
[adminOnly] bit DEFAULT 0 not null,
primary key([miid])
[miid] int not null IDENTITY,
[mid] int not null,
[name] nvarchar (200) DEFAULT '' not null,
[htmlID] nvarchar (200) DEFAULT '' not null,
[cssClass] nvarchar (200) DEFAULT '' not null,
[position] nvarchar (100) not null,
[path] nvarchar (200) DEFAULT '' not null,
[aria] nvarchar (200) DEFAULT '' not null,
[tooltip] nvarchar (200) DEFAULT '' not null,
[tmplName] nvarchar (200) DEFAULT '' not null,
[order] int DEFAULT 0 not null,
[guestOnly] bit DEFAULT 0 not null,
[memberOnly] bit DEFAULT 0 not null,
[staffOnly] bit DEFAULT 0 not null,
[adminOnly] bit DEFAULT 0 not null,
primary key([miid])
);

View File

@ -1,4 +1,4 @@
CREATE TABLE [menus] (
[mid] int not null IDENTITY,
primary key([mid])
[mid] int not null IDENTITY,
primary key([mid])
);

View File

@ -1,4 +1,4 @@
CREATE TABLE [meta] (
[name] nvarchar (200) not null,
[value] nvarchar (200) not null
[name] nvarchar (200) not null,
[value] nvarchar (200) not null
);

View File

@ -1,9 +1,9 @@
CREATE TABLE [moderation_logs] (
[action] nvarchar (100) not null,
[elementID] int not null,
[elementType] nvarchar (100) not null,
[ipaddress] nvarchar (200) not null,
[actorID] int not null,
[doneAt] datetime not null,
[extra] nvarchar (MAX) not null
[action] nvarchar (100) not null,
[elementID] int not null,
[elementType] nvarchar (100) not null,
[ipaddress] nvarchar (200) not null,
[actorID] int not null,
[doneAt] datetime not null,
[extra] nvarchar (MAX) not null
);

View File

@ -1,9 +1,9 @@
CREATE TABLE [pages] (
[pid] int not null IDENTITY,
[name] nvarchar (200) not null,
[title] nvarchar (200) not null,
[body] nvarchar (MAX) not null,
[allowedGroups] nvarchar (MAX) not null,
[menuID] int DEFAULT -1 not null,
primary key([pid])
[pid] int not null IDENTITY,
[name] nvarchar (200) not null,
[title] nvarchar (200) not null,
[body] nvarchar (MAX) not null,
[allowedGroups] nvarchar (MAX) not null,
[menuID] int DEFAULT -1 not null,
primary key([pid])
);

View File

@ -1,7 +1,7 @@
CREATE TABLE [password_resets] (
[email] nvarchar (200) not null,
[uid] int not null,
[validated] nvarchar (200) not null,
[token] nvarchar (200) not null,
[createdAt] datetime not null
[email] nvarchar (200) not null,
[uid] int not null,
[validated] nvarchar (200) not null,
[token] nvarchar (200) not null,
[createdAt] datetime not null
);

View File

@ -1,6 +1,6 @@
CREATE TABLE [perfchunks] (
[low] int DEFAULT 0 not null,
[high] int DEFAULT 0 not null,
[avg] int DEFAULT 0 not null,
[createdAt] datetime not null
[low] int DEFAULT 0 not null,
[high] int DEFAULT 0 not null,
[avg] int DEFAULT 0 not null,
[createdAt] datetime not null
);

View File

@ -1,6 +1,6 @@
CREATE TABLE [plugins] (
[uname] nvarchar (180) not null,
[active] bit DEFAULT 0 not null,
[installed] bit DEFAULT 0 not null,
unique([uname])
[uname] nvarchar (180) not null,
[active] bit DEFAULT 0 not null,
[installed] bit DEFAULT 0 not null,
unique([uname])
);

View File

@ -1,9 +1,9 @@
CREATE TABLE [polls] (
[pollID] int not null IDENTITY,
[parentID] int DEFAULT 0 not null,
[parentTable] nvarchar (100) DEFAULT 'topics' not null,
[type] int DEFAULT 0 not null,
[options] nvarchar (MAX) not null,
[votes] int DEFAULT 0 not null,
primary key([pollID])
[pollID] int not null IDENTITY,
[parentID] int DEFAULT 0 not null,
[parentTable] nvarchar (100) DEFAULT 'topics' not null,
[type] int DEFAULT 0 not null,
[options] nvarchar (MAX) not null,
[votes] int DEFAULT 0 not null,
primary key([pollID])
);

View File

@ -1,5 +1,5 @@
CREATE TABLE [polls_options] (
[pollID] int not null,
[option] int DEFAULT 0 not null,
[votes] int DEFAULT 0 not null
[pollID] int not null,
[option] int DEFAULT 0 not null,
[votes] int DEFAULT 0 not null
);

View File

@ -1,5 +1,5 @@
CREATE TABLE [polls_voters] (
[pollID] int not null,
[uid] int not null,
[option] int DEFAULT 0 not null
[pollID] int not null,
[uid] int not null,
[option] int DEFAULT 0 not null
);

View File

@ -1,7 +1,7 @@
CREATE TABLE [polls_votes] (
[pollID] int not null,
[uid] int not null,
[option] int DEFAULT 0 not null,
[castAt] datetime not null,
[ip] nvarchar (200) DEFAULT '' not null
[pollID] int not null,
[uid] int not null,
[option] int DEFAULT 0 not null,
[castAt] datetime not null,
[ip] nvarchar (200) DEFAULT '' not null
);

View File

@ -1,4 +1,4 @@
CREATE TABLE [postchunks] (
[count] int DEFAULT 0 not null,
[createdAt] datetime not null
[count] int DEFAULT 0 not null,
[createdAt] datetime not null
);

View File

@ -1,10 +1,10 @@
CREATE TABLE [registration_logs] (
[rlid] int not null IDENTITY,
[username] nvarchar (100) not null,
[email] nvarchar (100) not null,
[failureReason] nvarchar (100) not null,
[success] bool DEFAULT 0 not null,
[ipaddress] nvarchar (200) not null,
[doneAt] datetime not null,
primary key([rlid])
[rlid] int not null IDENTITY,
[username] nvarchar (100) not null,
[email] nvarchar (100) not null,
[failureReason] nvarchar (100) not null,
[success] bool DEFAULT 0 not null,
[ipaddress] nvarchar (200) not null,
[doneAt] datetime not null,
primary key([rlid])
);

View File

@ -1,19 +1,19 @@
CREATE TABLE [replies] (
[rid] int not null IDENTITY,
[tid] int not null,
[content] nvarchar (MAX) not null,
[parsed_content] nvarchar (MAX) not null,
[createdAt] datetime not null,
[createdBy] int not null,
[lastEdit] int DEFAULT 0 not null,
[lastEditBy] int DEFAULT 0 not null,
[lastUpdated] datetime not null,
[ip] nvarchar (200) DEFAULT '' not null,
[likeCount] int DEFAULT 0 not null,
[attachCount] int DEFAULT 0 not null,
[words] int DEFAULT 1 not null,
[actionType] nvarchar (20) DEFAULT '' not null,
[poll] int DEFAULT 0 not null,
primary key([rid]),
fulltext key([content])
[rid] int not null IDENTITY,
[tid] int not null,
[content] nvarchar (MAX) not null,
[parsed_content] nvarchar (MAX) not null,
[createdAt] datetime not null,
[createdBy] int not null,
[lastEdit] int DEFAULT 0 not null,
[lastEditBy] int DEFAULT 0 not null,
[lastUpdated] datetime not null,
[ip] nvarchar (200) DEFAULT '' not null,
[likeCount] int DEFAULT 0 not null,
[attachCount] int DEFAULT 0 not null,
[words] int DEFAULT 1 not null,
[actionType] nvarchar (20) DEFAULT '' not null,
[poll] int DEFAULT 0 not null,
primary key([rid]),
fulltext key([content])
);

View File

@ -1,8 +1,8 @@
CREATE TABLE [revisions] (
[reviseID] int not null IDENTITY,
[content] nvarchar (MAX) not null,
[contentID] int not null,
[contentType] nvarchar (100) DEFAULT 'replies' not null,
[createdAt] datetime not null,
primary key([reviseID])
[reviseID] int not null IDENTITY,
[content] nvarchar (MAX) not null,
[contentID] int not null,
[contentType] nvarchar (100) DEFAULT 'replies' not null,
[createdAt] datetime not null,
primary key([reviseID])
);

View File

@ -1,7 +1,7 @@
CREATE TABLE [settings] (
[name] nvarchar (180) not null,
[content] nvarchar (250) not null,
[type] nvarchar (50) not null,
[constraints] nvarchar (200) DEFAULT '' not null,
unique([name])
[name] nvarchar (180) not null,
[content] nvarchar (250) not null,
[type] nvarchar (50) not null,
[constraints] nvarchar (200) DEFAULT '' not null,
unique([name])
);

View File

@ -1,3 +1,3 @@
CREATE TABLE [sync] (
[last_update] datetime not null
[last_update] datetime not null
);

View File

@ -1,5 +1,5 @@
CREATE TABLE [themes] (
[uname] nvarchar (180) not null,
[default] bit DEFAULT 0 not null,
unique([uname])
[uname] nvarchar (180) not null,
[default] bit DEFAULT 0 not null,
unique([uname])
);

View File

@ -1,4 +1,4 @@
CREATE TABLE [topicchunks] (
[count] int DEFAULT 0 not null,
[createdAt] datetime not null
[count] int DEFAULT 0 not null,
[createdAt] datetime not null
);

View File

@ -1,28 +1,28 @@
CREATE TABLE [topics] (
[tid] int not null IDENTITY,
[title] nvarchar (100) not null,
[content] nvarchar (MAX) not null,
[parsed_content] nvarchar (MAX) not null,
[createdAt] datetime not null,
[lastReplyAt] datetime not null,
[lastReplyBy] int not null,
[lastReplyID] int DEFAULT 0 not null,
[createdBy] int not null,
[is_closed] bit DEFAULT 0 not null,
[sticky] bit DEFAULT 0 not null,
[parentID] int DEFAULT 2 not null,
[ip] nvarchar (200) DEFAULT '' not null,
[postCount] int DEFAULT 1 not null,
[likeCount] int DEFAULT 0 not null,
[attachCount] int DEFAULT 0 not null,
[words] int DEFAULT 0 not null,
[views] int DEFAULT 0 not null,
[weekEvenViews] int DEFAULT 0 not null,
[weekOddViews] int DEFAULT 0 not null,
[css_class] nvarchar (100) DEFAULT '' not null,
[poll] int DEFAULT 0 not null,
[data] nvarchar (200) DEFAULT '' not null,
primary key([tid]),
fulltext key([title]),
fulltext key([content])
[tid] int not null IDENTITY,
[title] nvarchar (100) not null,
[content] nvarchar (MAX) not null,
[parsed_content] nvarchar (MAX) not null,
[createdAt] datetime not null,
[lastReplyAt] datetime not null,
[lastReplyBy] int not null,
[lastReplyID] int DEFAULT 0 not null,
[createdBy] int not null,
[is_closed] bit DEFAULT 0 not null,
[sticky] bit DEFAULT 0 not null,
[parentID] int DEFAULT 2 not null,
[ip] nvarchar (200) DEFAULT '' not null,
[postCount] int DEFAULT 1 not null,
[likeCount] int DEFAULT 0 not null,
[attachCount] int DEFAULT 0 not null,
[words] int DEFAULT 0 not null,
[views] int DEFAULT 0 not null,
[weekEvenViews] int DEFAULT 0 not null,
[weekOddViews] int DEFAULT 0 not null,
[css_class] nvarchar (100) DEFAULT '' not null,
[poll] int DEFAULT 0 not null,
[data] nvarchar (200) DEFAULT '' not null,
primary key([tid]),
fulltext key([title]),
fulltext key([content])
);

View File

@ -1,3 +1,3 @@
CREATE TABLE [updates] (
[dbVersion] int DEFAULT 0 not null
[dbVersion] int DEFAULT 0 not null
);

Some files were not shown because too many files have changed in this diff Show More