forked from GithubBackups/vichan
Compare commits
1 Commits
master
...
bumplock_i
Author | SHA1 | Date | |
---|---|---|---|
|
9e77f7b7c4 |
@ -1,4 +0,0 @@
|
||||
**/.git
|
||||
**/.gitignore
|
||||
/local-instances
|
||||
**/.gitkeep
|
69
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
69
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,69 +0,0 @@
|
||||
name: Bug Report
|
||||
description: File a bug report for Vichan
|
||||
title: "[BUG] "
|
||||
labels: ["bug"]
|
||||
assignees: []
|
||||
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**Thank you for reporting a bug! Please provide as much detail as possible.**
|
||||
|
||||
Before submitting, check the [Vichan Wiki](https://vichan.info) to see if there's already a solution to your problem.
|
||||
|
||||
- type: textarea
|
||||
id: bug_description
|
||||
attributes:
|
||||
label: "Describe the bug"
|
||||
description: "A clear and concise description of what the bug is."
|
||||
placeholder: "Posting doesn't go through and displays a collation error. The exact error message given is the text below and I've attached a screenshot..."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps_to_reproduce
|
||||
attributes:
|
||||
label: "Steps to Reproduce"
|
||||
description: "Provide step-by-step instructions to reproduce the issue. If you're unsure on how, that is alright, just try and explain as well as you can."
|
||||
placeholder: |
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
render: markdown
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected_behavior
|
||||
attributes:
|
||||
label: "Expected Behavior"
|
||||
description: "What did you expect to happen?"
|
||||
placeholder: "Expected behavior here..."
|
||||
render: markdown
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: server_specs
|
||||
attributes:
|
||||
label: "Server Specifications"
|
||||
description: "Provide details about your server environment. If you're unsure about any of this, you might be using shared hosting (Hostinger, HostGator, Serv00, etc). If so, put the name of your hosting provider here."
|
||||
placeholder: |
|
||||
- OS: (Ubuntu, CentOS, Windows Server 2025, etc.)
|
||||
- PHP Version: (e.g., 7.4, 8.0, 8.4)
|
||||
- Web Server: (Apache, NGINX, etc.)
|
||||
- Database: (MySQL, MariaDB, etc.)
|
||||
- Vichan Version: (5.2.0, 5.3.0 (dev branch), etc)
|
||||
render: markdown
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additional_context
|
||||
attributes:
|
||||
label: "Additional Context"
|
||||
description: "Any other details we should know?"
|
||||
placeholder: "Add any additional context here..."
|
||||
render: markdown
|
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -44,6 +44,5 @@ Thumbs.db
|
||||
#vichan custom
|
||||
favicon.ico
|
||||
/static/spoiler.png
|
||||
/local-instances
|
||||
|
||||
/vendor/
|
||||
|
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -7,6 +7,3 @@
|
||||
path = inc/lib/parsedown
|
||||
url = https://github.com/vichan-devel/parsedown.git
|
||||
branch = master
|
||||
[submodule "js/twemoji"]
|
||||
path = js/twemoji
|
||||
url = https://github.com/basedgentoo/twemoji
|
||||
|
43
README.md
43
README.md
@ -1,15 +1,22 @@
|
||||
vichan - A lightweight and full featured PHP imageboard.
|
||||
========================================================
|
||||
|
||||
**Please do not contact Fredrick Brennan in regards to vichan issues.**
|
||||
**Vichan has next to no active development<!--, however you can still pay for support. Basic support costs $40/hr, and is only payable in BTC. New features depend on what you want. Email COPYPASTE <AT> KITTENS <DOT> PH if you're interested—Vichan forks such as OpenIB are included in this offer-->.**
|
||||
|
||||
As of 29 August 2022 it supports PHP8.1.
|
||||
As of 29 August 2022, though, it supports PHP8.1.
|
||||
|
||||
About
|
||||
------------
|
||||
vichan is a free light-weight, fast, highly configurable and user-friendly
|
||||
imageboard software package. It is written in PHP and has few dependencies.
|
||||
|
||||
*Security problems can be reported to the development team: DEVELOPMENT \<AT\> VICHAN \<DOT\> NET.*
|
||||
|
||||
While there is currently no active development besides fixing security problems, we don't exclude the possibility to refactor the code in order to meet today's standards and continue our work from the point where [@czaks](https://github.com/czaks) retired in 2017.
|
||||
Before this milestone is achieved though, we strongly urge you to consider other imageboard packages. It is the opinion of the vichan development team that no new vichan imageboards should be deployed at the moment, and other imageboard packages used instead.
|
||||
|
||||
For support, feel free to join our [IRC channel](https://webchat.6an.org/?channels=vichan-dev) at irc.6an.org.
|
||||
|
||||
Some documentation may be found on our [wiki](https://github.com/vichan-devel/vichan/wiki). (feel free to contribute)
|
||||
|
||||
History
|
||||
@ -18,21 +25,18 @@ vichan is a fork of (now defunc'd) [Tinyboard](http://github.com/savetheinternet
|
||||
a great imageboard package, actively building on it and adding a lot of features and other
|
||||
improvements.
|
||||
|
||||

|
||||
|
||||
### Maintainer timeline
|
||||
1. [@perdedora](https://github.com/perdedora) and [@RealAngeleno](https://github.com/RealAngeleno) - 2023-Present.
|
||||
2. Development Commission lead by [@basedgentoo](https://github.com/basedgentoo), [@kuz-sysadmin](https://github.com/kuz-sysadmin), and [@RealAngeleno](https://github.com/RealAngeleno). (2023 - 2023)
|
||||
3. [@h00j](https://github.com/h00j) (2021 - ???)
|
||||
4. [@ctrlcctrlv](https://github.com/ctrlcctrlv) (2017 - 2021)
|
||||
5. [@czaks](https://github.com/czaks) (2014 - 2017) (The author of vichan fork)
|
||||
6. [@savetheinternet](https://github.com/savetheinternet) (2010 - 2014) (The creator of Tinyboard)
|
||||
1. [@h00j](https://github.com/h00j) (2021 - present)
|
||||
2. [@ctrlcctrlv](https://github.com/ctrlcctrlv) (2017 - 2021)
|
||||
3. [@czaks](https://github.com/czaks) (2014 - 2017) (The author of vichan fork)
|
||||
4. [@savetheinternet](https://github.com/savetheinternet) (2010 - 2014) (The creator of Tinyboard)
|
||||
|
||||
Requirements
|
||||
------------
|
||||
1. PHP >= 7.4
|
||||
1. PHP >= 5.4 (we still try to keep compatibility with php 5.3 as much as possible)
|
||||
PHP 7.0 is explicitly supported. PHP 7.2 works as well, but may cause as yet unreported bugs.
|
||||
2. MySQL/MariaDB server
|
||||
3. [mbstring](http://www.php.net/manual/en/mbstring.installation.php)
|
||||
3. [mbstring](http://www.php.net/manual/en/mbstring.installation.php)
|
||||
4. [PHP GD](http://www.php.net/manual/en/intro.image.php)
|
||||
5. [PHP PDO](http://www.php.net/manual/en/intro.pdo.php)
|
||||
6. A Unix-like OS, preferrably FreeBSD or GNU/Linux
|
||||
@ -42,7 +46,9 @@ We try to make sure vichan is compatible with all major web servers. vichan does
|
||||
### Recommended
|
||||
1. MySQL/MariaDB server >= 5.5.3
|
||||
2. ImageMagick (command-line ImageMagick or GraphicsMagick preferred).
|
||||
3. [APCu (Alternative PHP Cache)](http://php.net/manual/en/book.apcu.php),
|
||||
3. ~~[APC (Alternative PHP Cache)](http://php.net/manual/en/book.apc.php)~~,
|
||||
[APCu (Alternative PHP Cache)](http://php.net/manual/en/book.apcu.php),
|
||||
[XCache](http://xcache.lighttpd.net/),
|
||||
[Memcached](http://www.php.net/manual/en/intro.memcached.php) or
|
||||
[Redis](https://redis.io/docs/about/)
|
||||
|
||||
@ -55,11 +61,12 @@ You can contribute to vichan by:
|
||||
|
||||
Installation
|
||||
-------------
|
||||
1. Get the latest development version with:
|
||||
1. Download and extract vichan to your web directory or get the latest
|
||||
development version with:
|
||||
|
||||
git clone git://github.com/vichan-devel/vichan.git
|
||||
|
||||
2. run ```composer install``` inside the directory
|
||||
2. run ```composer install``` inside the directory
|
||||
3. Navigate to ```install.php``` in your web browser and follow the
|
||||
prompts.
|
||||
4. vichan should now be installed. Log in to ```mod.php``` with the
|
||||
@ -119,11 +126,6 @@ WebM support
|
||||
------------
|
||||
Read `inc/lib/webm/README.md` for information about enabling webm.
|
||||
|
||||
Docker
|
||||
------------
|
||||
Vichan comes with a Dockerfile and docker-compose configuration, the latter aimed primarily at development and testing.
|
||||
See the `docker/doc.md` file for more information.
|
||||
|
||||
vichan API
|
||||
----------
|
||||
vichan provides by default a 4chan-compatible JSON API. For documentation on this, see:
|
||||
@ -132,3 +134,4 @@ https://github.com/vichan-devel/vichan-API/ .
|
||||
License
|
||||
--------
|
||||
See [LICENSE.md](http://github.com/vichan-devel/vichan/blob/master/LICENSE.md).
|
||||
|
||||
|
21
b.php
21
b.php
@ -1,8 +1,19 @@
|
||||
<?php
|
||||
$dir = "static/banners/";
|
||||
$files = scandir($dir);
|
||||
$images = array_diff($files, array('.', '..'));
|
||||
$name = $images[array_rand($images)];
|
||||
// open the file in a binary mode
|
||||
$fp = fopen($dir . $name, 'rb');
|
||||
|
||||
$files = scandir('static/banners/', SCANDIR_SORT_NONE);
|
||||
$files = array_diff($files, ['.', '..']);
|
||||
// send the right headers
|
||||
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1
|
||||
header('Pragma: no-cache'); // HTTP 1.0
|
||||
header('Expires: 0'); // Proxies
|
||||
header('Content-Type: ' . $fp['type']);
|
||||
header('Content-Length: ' . $fp['bytes']);
|
||||
|
||||
$name = $files[array_rand($files)];
|
||||
header("Location: /static/banners/$name", true, 307);
|
||||
header('Cache-Control: no-cache');
|
||||
// dump the picture and stop the script
|
||||
fpassthru($fp);
|
||||
exit;
|
||||
?>
|
||||
|
@ -1,4 +1,6 @@
|
||||
<?php
|
||||
require_once 'inc/functions.php';
|
||||
require_once 'inc/bans.php';
|
||||
require_once 'inc/bootstrap.php';
|
||||
checkBan();
|
||||
|
||||
|
40
compose.yml
40
compose.yml
@ -1,40 +0,0 @@
|
||||
services:
|
||||
#nginx webserver + php 8.x
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ./docker/nginx/Dockerfile
|
||||
ports:
|
||||
- "9090:80"
|
||||
depends_on:
|
||||
- db
|
||||
volumes:
|
||||
- ./local-instances/${INSTANCE:-0}/www:/var/www/html
|
||||
- ./docker/nginx/vichan.conf:/etc/nginx/conf.d/default.conf
|
||||
- ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
|
||||
- ./docker/nginx/proxy.conf:/etc/nginx/conf.d/proxy.conf
|
||||
links:
|
||||
- php
|
||||
|
||||
php:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ./docker/php/Dockerfile
|
||||
volumes:
|
||||
- ./local-instances/${INSTANCE:-0}/www:/var/www
|
||||
- ./docker/php/www.conf:/usr/local/etc/php-fpm.d/www.conf
|
||||
- ./docker/php/jit.ini:/usr/local/etc/php/conf.d/jit.ini
|
||||
|
||||
#MySQL Service
|
||||
db:
|
||||
image: mysql:8.0.35
|
||||
container_name: db
|
||||
restart: unless-stopped
|
||||
tty: true
|
||||
ports:
|
||||
- "3306:3306"
|
||||
environment:
|
||||
MYSQL_DATABASE: vichan
|
||||
MYSQL_ROOT_PASSWORD: password
|
||||
volumes:
|
||||
- ./local-instances/${INSTANCE:-0}/mysql:/var/lib/mysql
|
@ -2,24 +2,16 @@
|
||||
"name": "vichan-devel/vichan",
|
||||
"description": "vichan imageboard",
|
||||
"type": "project",
|
||||
"config": {
|
||||
"platform": {
|
||||
"php": "7.4"
|
||||
}
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.4",
|
||||
"ext-mbstring": ">=7.4",
|
||||
"ext-gd": ">=7.4",
|
||||
"ext-pdo": ">=7.4",
|
||||
"twig/twig": "^2.9",
|
||||
"phpmyadmin/twig-i18n-extension": "^4.0",
|
||||
"ext-mbstring": ">=5.4",
|
||||
"ext-gd": ">=5.4",
|
||||
"ext-pdo": ">=5.4",
|
||||
"twig/twig": "^1.44.2",
|
||||
"lifo/ip": "^1.0",
|
||||
"gettext/gettext": "^5.5",
|
||||
"gettext/gettext": "^1.0",
|
||||
"mrclay/minify": "^2.1.6",
|
||||
"geoip/geoip": "^1.17",
|
||||
"dapphp/securimage": "^4.0",
|
||||
"erusev/parsedown": "^1.7.4"
|
||||
"dapphp/securimage": "^4.0"
|
||||
},
|
||||
"autoload": {
|
||||
"classmap": ["inc/"],
|
||||
@ -33,14 +25,8 @@
|
||||
"inc/mod/auth.php",
|
||||
"inc/lock.php",
|
||||
"inc/queue.php",
|
||||
"inc/functions.php",
|
||||
"inc/functions/dice.php",
|
||||
"inc/functions/format.php",
|
||||
"inc/functions/net.php",
|
||||
"inc/functions/num.php",
|
||||
"inc/functions/theme.php",
|
||||
"inc/service/captcha-queries.php",
|
||||
"inc/context.php"
|
||||
"inc/polyfill.php",
|
||||
"inc/functions.php"
|
||||
]
|
||||
},
|
||||
"license": "Tinyboard + vichan",
|
||||
|
416
composer.lock
generated
416
composer.lock
generated
@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "72e79f203581eea6e6b0455147b25878",
|
||||
"content-hash": "1e3723687369c82eea457d2dded76b74",
|
||||
"packages": [
|
||||
{
|
||||
"name": "dapphp/securimage",
|
||||
@ -31,12 +31,12 @@
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Securimage\\": "./"
|
||||
},
|
||||
"classmap": [
|
||||
"securimage.php"
|
||||
]
|
||||
],
|
||||
"psr-4": {
|
||||
"Securimage\\": "./"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
@ -114,43 +114,37 @@
|
||||
"issues": "https://github.com/maxmind/geoip-api-php/issues",
|
||||
"source": "https://github.com/maxmind/geoip-api-php/tree/master"
|
||||
},
|
||||
"abandoned": "geoip2/geoip2",
|
||||
"time": "2016-05-16T19:06:50+00:00"
|
||||
},
|
||||
{
|
||||
"name": "gettext/gettext",
|
||||
"version": "v5.7.0",
|
||||
"version": "v1.1.5",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-gettext/Gettext.git",
|
||||
"reference": "8657e580747bb3baacccdcebe69cac094661e404"
|
||||
"reference": "1bdf755a1b49f0614d6fc29f446df567eb62cd5c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-gettext/Gettext/zipball/8657e580747bb3baacccdcebe69cac094661e404",
|
||||
"reference": "8657e580747bb3baacccdcebe69cac094661e404",
|
||||
"url": "https://api.github.com/repos/php-gettext/Gettext/zipball/1bdf755a1b49f0614d6fc29f446df567eb62cd5c",
|
||||
"reference": "1bdf755a1b49f0614d6fc29f446df567eb62cd5c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"gettext/languages": "^2.3",
|
||||
"php": "^7.2|^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"brick/varexporter": "^0.3.5",
|
||||
"friendsofphp/php-cs-fixer": "^3.2",
|
||||
"oscarotero/php-cs-fixer-config": "^2.0",
|
||||
"phpunit/phpunit": "^8.0|^9.0",
|
||||
"squizlabs/php_codesniffer": "^3.0"
|
||||
"php": ">=5.3.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Gettext\\": "src"
|
||||
}
|
||||
"psr-0": {
|
||||
"Gettext": ""
|
||||
},
|
||||
"files": [
|
||||
"Gettext/translator_functions.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
"AGPL-3.0"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
@ -160,123 +154,33 @@
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "PHP gettext manager",
|
||||
"homepage": "https://github.com/php-gettext/Gettext",
|
||||
"description": "PHP - JS gettext conversor",
|
||||
"homepage": "https://github.com/oscarotero/Gettext",
|
||||
"keywords": [
|
||||
"JS",
|
||||
"gettext",
|
||||
"i18n",
|
||||
"mo",
|
||||
"po",
|
||||
"translation"
|
||||
],
|
||||
"support": {
|
||||
"email": "oom@oscarotero.com",
|
||||
"issues": "https://github.com/php-gettext/Gettext/issues",
|
||||
"source": "https://github.com/php-gettext/Gettext/tree/v5.7.0"
|
||||
"issues": "https://github.com/oscarotero/Gettext/issues",
|
||||
"source": "https://github.com/php-gettext/Gettext/tree/v1.1.5"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://paypal.me/oscarotero",
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/oscarotero",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://www.patreon.com/misteroom",
|
||||
"type": "patreon"
|
||||
}
|
||||
],
|
||||
"time": "2022-07-27T19:54:55+00:00"
|
||||
},
|
||||
{
|
||||
"name": "gettext/languages",
|
||||
"version": "2.10.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/php-gettext/Languages.git",
|
||||
"reference": "4d61d67fe83a2ad85959fe6133d6d9ba7dddd1ab"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/php-gettext/Languages/zipball/4d61d67fe83a2ad85959fe6133d6d9ba7dddd1ab",
|
||||
"reference": "4d61d67fe83a2ad85959fe6133d6d9ba7dddd1ab",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.3"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^4.8 || ^5.7 || ^6.5 || ^7.5 || ^8.4"
|
||||
},
|
||||
"bin": [
|
||||
"bin/export-plural-rules"
|
||||
],
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Gettext\\Languages\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Michele Locati",
|
||||
"email": "mlocati@gmail.com",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "gettext languages with plural rules",
|
||||
"homepage": "https://github.com/php-gettext/Languages",
|
||||
"keywords": [
|
||||
"cldr",
|
||||
"i18n",
|
||||
"internationalization",
|
||||
"l10n",
|
||||
"language",
|
||||
"languages",
|
||||
"localization",
|
||||
"php",
|
||||
"plural",
|
||||
"plural rules",
|
||||
"plurals",
|
||||
"translate",
|
||||
"translations",
|
||||
"unicode"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/php-gettext/Languages/issues",
|
||||
"source": "https://github.com/php-gettext/Languages/tree/2.10.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://paypal.me/mlocati",
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/mlocati",
|
||||
"type": "github"
|
||||
}
|
||||
],
|
||||
"time": "2022-10-18T15:00:10+00:00"
|
||||
"time": "2014-10-22T15:53:45+00:00"
|
||||
},
|
||||
{
|
||||
"name": "lifo/ip",
|
||||
"version": "v1.1.1",
|
||||
"version": "v1.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/lifo101/ip.git",
|
||||
"reference": "4c4cf5b554884be93f1d0422eaec8d6426993229"
|
||||
"reference": "b6a36dab288d7aea155698808bfc6649799fe413"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/lifo101/ip/zipball/4c4cf5b554884be93f1d0422eaec8d6426993229",
|
||||
"reference": "4c4cf5b554884be93f1d0422eaec8d6426993229",
|
||||
"url": "https://api.github.com/repos/lifo101/ip/zipball/b6a36dab288d7aea155698808bfc6649799fe413",
|
||||
"reference": "b6a36dab288d7aea155698808bfc6649799fe413",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@ -308,9 +212,9 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/lifo101/ip/issues",
|
||||
"source": "https://github.com/lifo101/ip/tree/v1.1.1"
|
||||
"source": "https://github.com/lifo101/ip/tree/master"
|
||||
},
|
||||
"time": "2022-07-12T15:45:54+00:00"
|
||||
"time": "2020-04-02T11:09:10+00:00"
|
||||
},
|
||||
{
|
||||
"name": "mrclay/minify",
|
||||
@ -363,89 +267,30 @@
|
||||
},
|
||||
"time": "2017-11-03T21:04:01+00:00"
|
||||
},
|
||||
{
|
||||
"name": "phpmyadmin/twig-i18n-extension",
|
||||
"version": "v4.0.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/phpmyadmin/twig-i18n-extension.git",
|
||||
"reference": "c0d0dd171cd1c7733bf152fd44b61055843df052"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/phpmyadmin/twig-i18n-extension/zipball/c0d0dd171cd1c7733bf152fd44b61055843df052",
|
||||
"reference": "c0d0dd171cd1c7733bf152fd44b61055843df052",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.1 || ^8.0",
|
||||
"twig/twig": "^1.42.3|^2.0|^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpmyadmin/coding-standard": "^3.0.0",
|
||||
"phpmyadmin/motranslator": "^5.2",
|
||||
"phpstan/phpstan": "^0.12.66",
|
||||
"phpunit/phpunit": "^7 || ^8 || ^9"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"PhpMyAdmin\\Twig\\Extensions\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Fabien Potencier",
|
||||
"email": "fabien@symfony.com"
|
||||
},
|
||||
{
|
||||
"name": "The phpMyAdmin Team",
|
||||
"email": "developers@phpmyadmin.net",
|
||||
"homepage": "https://www.phpmyadmin.net/team/"
|
||||
}
|
||||
],
|
||||
"description": "Internationalization support for Twig via the gettext library",
|
||||
"keywords": [
|
||||
"gettext",
|
||||
"i18n"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/phpmyadmin/twig-i18n-extension/issues",
|
||||
"source": "https://github.com/phpmyadmin/twig-i18n-extension"
|
||||
},
|
||||
"time": "2021-06-10T15:53:38+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-ctype",
|
||||
"version": "v1.27.0",
|
||||
"version": "v1.23.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-ctype.git",
|
||||
"reference": "5bbc823adecdae860bb64756d639ecfec17b050a"
|
||||
"reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/5bbc823adecdae860bb64756d639ecfec17b050a",
|
||||
"reference": "5bbc823adecdae860bb64756d639ecfec17b050a",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/46cd95797e9df938fdd2b03693b5fca5e64b01ce",
|
||||
"reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.1"
|
||||
},
|
||||
"provide": {
|
||||
"ext-ctype": "*"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-ctype": "For best performance"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.27-dev"
|
||||
"dev-main": "1.23-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@ -453,12 +298,12 @@
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"bootstrap.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"Symfony\\Polyfill\\Ctype\\": ""
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"bootstrap.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
@ -483,7 +328,7 @@
|
||||
"portable"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.27.0"
|
||||
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.23.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@ -499,195 +344,34 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-mbstring",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-mbstring.git",
|
||||
"reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/8ad114f6b39e2c98a8b0e3bd907732c207c2b534",
|
||||
"reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.1"
|
||||
},
|
||||
"provide": {
|
||||
"ext-mbstring": "*"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-mbstring": "For best performance"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
"url": "https://github.com/symfony/polyfill"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"bootstrap.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"Symfony\\Polyfill\\Mbstring\\": ""
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicolas Grekas",
|
||||
"email": "p@tchwork.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"description": "Symfony polyfill for the Mbstring extension",
|
||||
"homepage": "https://symfony.com",
|
||||
"keywords": [
|
||||
"compatibility",
|
||||
"mbstring",
|
||||
"polyfill",
|
||||
"portable",
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://symfony.com/sponsor",
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/fabpot",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-php72",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-php72.git",
|
||||
"reference": "869329b1e9894268a8a61dabb69153029b7a8c97"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/869329b1e9894268a8a61dabb69153029b7a8c97",
|
||||
"reference": "869329b1e9894268a8a61dabb69153029b7a8c97",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.1"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
"url": "https://github.com/symfony/polyfill"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"bootstrap.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"Symfony\\Polyfill\\Php72\\": ""
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicolas Grekas",
|
||||
"email": "p@tchwork.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions",
|
||||
"homepage": "https://symfony.com",
|
||||
"keywords": [
|
||||
"compatibility",
|
||||
"polyfill",
|
||||
"portable",
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-php72/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://symfony.com/sponsor",
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/fabpot",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
"time": "2021-02-19T12:13:01+00:00"
|
||||
},
|
||||
{
|
||||
"name": "twig/twig",
|
||||
"version": "v2.15.4",
|
||||
"version": "v1.44.5",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/twigphp/Twig.git",
|
||||
"reference": "3e059001d6d597dd50ea7c74dd2464b4adea48d3"
|
||||
"reference": "dd4353357c5a116322e92a00d16043a31881a81e"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/twigphp/Twig/zipball/3e059001d6d597dd50ea7c74dd2464b4adea48d3",
|
||||
"reference": "3e059001d6d597dd50ea7c74dd2464b4adea48d3",
|
||||
"url": "https://api.github.com/repos/twigphp/Twig/zipball/dd4353357c5a116322e92a00d16043a31881a81e",
|
||||
"reference": "dd4353357c5a116322e92a00d16043a31881a81e",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.1.3",
|
||||
"symfony/polyfill-ctype": "^1.8",
|
||||
"symfony/polyfill-mbstring": "^1.3",
|
||||
"symfony/polyfill-php72": "^1.8"
|
||||
"php": ">=7.2.5",
|
||||
"symfony/polyfill-ctype": "^1.8"
|
||||
},
|
||||
"require-dev": {
|
||||
"psr/container": "^1.0",
|
||||
"symfony/phpunit-bridge": "^4.4.9|^5.0.9|^6.0"
|
||||
"symfony/phpunit-bridge": "^4.4.9|^5.0.9"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "2.15-dev"
|
||||
"dev-master": "1.44-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@ -726,7 +410,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/twigphp/Twig/issues",
|
||||
"source": "https://github.com/twigphp/Twig/tree/v2.15.4"
|
||||
"source": "https://github.com/twigphp/Twig/tree/v1.44.5"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@ -738,7 +422,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-12-27T12:26:20+00:00"
|
||||
"time": "2021-09-17T08:35:19+00:00"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
@ -753,5 +437,5 @@
|
||||
"ext-pdo": ">=5.4"
|
||||
},
|
||||
"platform-dev": [],
|
||||
"plugin-api-version": "2.3.0"
|
||||
"plugin-api-version": "2.0.0"
|
||||
}
|
||||
|
@ -1,20 +0,0 @@
|
||||
The `php-fpm` process runs containerized.
|
||||
The php application always uses `/var/www` as it's work directory and home folder, and if `/var/www` is bind mounted it
|
||||
is necessary to adjust the path passed via FastCGI to `php-fpm` by changing the root directory to `/var/www`.
|
||||
This can achieved in nginx by setting the `fastcgi_param SCRIPT_FILENAME` to `/var/www/$fastcgi_script_name;`
|
||||
|
||||
The default docker compose settings are intended for development and testing purposes.
|
||||
The folder structure expected by compose is as follows
|
||||
|
||||
```
|
||||
<vichan-project>
|
||||
└── local-instances
|
||||
└── 1
|
||||
├── mysql
|
||||
└── www
|
||||
```
|
||||
The vichan container is by itself much less rigid.
|
||||
|
||||
|
||||
Use `docker compose up --build` to start the docker compose.
|
||||
Use `docker compose up --build -d php` to rebuild just the vichan container while the compose is running. Useful for development.
|
@ -1,8 +0,0 @@
|
||||
FROM nginx:1.25.3-alpine
|
||||
|
||||
COPY . /code
|
||||
RUN adduser --system www-data \
|
||||
&& adduser www-data www-data
|
||||
|
||||
CMD [ "nginx", "-g", "daemon off;" ]
|
||||
EXPOSE 80
|
@ -1,34 +0,0 @@
|
||||
# This and proxy.conf are based on
|
||||
# https://github.com/dead-guru/devichan/blob/master/nginx/nginx.conf
|
||||
|
||||
user www-data;
|
||||
worker_processes auto;
|
||||
|
||||
error_log /dev/stdout warn;
|
||||
pid /var/run/nginx.pid;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
# Switch logging to console out to view via Docker
|
||||
access_log /dev/stdout;
|
||||
error_log /dev/stdout warn;
|
||||
sendfile on;
|
||||
keepalive_timeout 5;
|
||||
|
||||
gzip on;
|
||||
gzip_http_version 1.0;
|
||||
gzip_vary on;
|
||||
gzip_comp_level 6;
|
||||
gzip_types text/xml text/plain text/css application/xhtml+xml application/xml application/rss+xml application/atom_xml application/x-javascript application/x-httpd-php;
|
||||
gzip_disable "MSIE [1-6]\.";
|
||||
|
||||
|
||||
include /etc/nginx/conf.d/*.conf;
|
||||
include /etc/nginx/sites-available/*.conf;
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=czone:4m max_size=50m inactive=120m;
|
||||
proxy_temp_path /var/tmp/nginx;
|
||||
proxy_cache_key "$scheme://$host$request_uri";
|
||||
|
||||
|
||||
map $http_forwarded_request_id $x_request_id {
|
||||
"" $request_id;
|
||||
default $http_forwarded_request_id;
|
||||
}
|
||||
|
||||
map $http_forwarded_forwarded_host $forwardedhost {
|
||||
"" $host;
|
||||
default $http_forwarded_forwarded_host;
|
||||
}
|
||||
|
||||
|
||||
map $http_x_forwarded_proto $fcgi_https {
|
||||
default "";
|
||||
https on;
|
||||
}
|
||||
|
||||
map $http_x_forwarded_proto $real_scheme {
|
||||
default $scheme;
|
||||
https https;
|
||||
}
|
||||
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Server $host;
|
||||
|
||||
real_ip_header X-Forwarded-For;
|
||||
|
||||
set_real_ip_from 10.0.0.0/8;
|
||||
set_real_ip_from 172.16.0.0/12;
|
||||
set_real_ip_from 172.18.0.0;
|
||||
set_real_ip_from 192.168.0.0/24;
|
||||
set_real_ip_from 127.0.0.0/8;
|
||||
|
||||
real_ip_recursive on;
|
@ -1,66 +0,0 @@
|
||||
upstream php-upstream {
|
||||
server php:9000;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80 default_server;
|
||||
listen [::]:80 default_server ipv6only=on;
|
||||
server_name vichan;
|
||||
root /var/www/html;
|
||||
add_header X-Frame-Options "SAMEORIGIN";
|
||||
add_header X-Content-Type-Options "nosniff";
|
||||
|
||||
index index.html index.php;
|
||||
|
||||
charset utf-8;
|
||||
|
||||
location ~ ^([^.\?]*[^\/])$ {
|
||||
try_files $uri @addslash;
|
||||
}
|
||||
|
||||
# Expire rules for static content
|
||||
# Media: images, icons, video, audio, HTC
|
||||
location ~* \.(?:jpg|jpeg|gif|png|webp|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
|
||||
expires 1M;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
# CSS and Javascript
|
||||
location ~* \.(?:css|js)$ {
|
||||
expires 1y;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
|
||||
location ~* \.(html)$ {
|
||||
expires -1;
|
||||
}
|
||||
|
||||
location @addslash {
|
||||
return 301 $uri/;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.php$is_args$args;
|
||||
}
|
||||
|
||||
client_max_body_size 2G;
|
||||
|
||||
location ~ \.php$ {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Request-Id $x_request_id;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header Forwarded-Request-Id $x_request_id;
|
||||
fastcgi_pass php-upstream;
|
||||
fastcgi_index index.php;
|
||||
fastcgi_param SCRIPT_FILENAME /var/www/$fastcgi_script_name;
|
||||
fastcgi_read_timeout 600;
|
||||
include fastcgi_params;
|
||||
}
|
||||
|
||||
location = /favicon.ico { access_log off; log_not_found off; }
|
||||
location = /robots.txt { access_log off; log_not_found off; }
|
||||
}
|
@ -1,88 +0,0 @@
|
||||
# Based on https://github.com/dead-guru/devichan/blob/master/php-fpm/Dockerfile
|
||||
|
||||
FROM composer:lts AS composer
|
||||
FROM php:8.1-fpm-alpine
|
||||
|
||||
RUN apk add --no-cache \
|
||||
zlib \
|
||||
zlib-dev \
|
||||
libpng \
|
||||
libpng-dev \
|
||||
libjpeg-turbo \
|
||||
libjpeg-turbo-dev \
|
||||
libwebp \
|
||||
libwebp-dev \
|
||||
libcurl \
|
||||
curl-dev \
|
||||
imagemagick \
|
||||
graphicsmagick \
|
||||
gifsicle \
|
||||
ffmpeg \
|
||||
bind-tools \
|
||||
gettext \
|
||||
gettext-dev \
|
||||
icu-dev \
|
||||
oniguruma \
|
||||
oniguruma-dev \
|
||||
libmcrypt \
|
||||
libmcrypt-dev \
|
||||
lz4-libs \
|
||||
lz4-dev \
|
||||
imagemagick-dev \
|
||||
pcre-dev \
|
||||
$PHPIZE_DEPS \
|
||||
&& docker-php-ext-configure gd \
|
||||
--with-webp=/usr/include/webp \
|
||||
--with-jpeg=/usr/include \
|
||||
&& docker-php-ext-install -j$(nproc) \
|
||||
gd \
|
||||
curl \
|
||||
bcmath \
|
||||
opcache \
|
||||
pdo_mysql \
|
||||
gettext \
|
||||
intl \
|
||||
mbstring \
|
||||
&& pecl update-channels \
|
||||
&& pecl install -o -f igbinary \
|
||||
&& pecl install redis \
|
||||
&& pecl install imagick \
|
||||
$$ docker-php-ext-enable \
|
||||
igbinary \
|
||||
redis \
|
||||
imagick \
|
||||
&& apk del \
|
||||
zlib-dev \
|
||||
libpng-dev \
|
||||
libjpeg-turbo-dev \
|
||||
libwebp-dev \
|
||||
curl-dev \
|
||||
gettext-dev \
|
||||
oniguruma-dev \
|
||||
libmcrypt-dev \
|
||||
lz4-dev \
|
||||
imagemagick-dev \
|
||||
pcre-dev \
|
||||
$PHPIZE_DEPS \
|
||||
&& rm -rf /var/cache/* \
|
||||
&& rm -rf /tmp/pear
|
||||
RUN rmdir /var/www/html \
|
||||
&& install -d -m 744 -o www-data -g www-data /var/www \
|
||||
&& install -d -m 700 -o www-data -g www-data /var/tmp/vichan \
|
||||
&& install -d -m 700 -o www-data -g www-data /var/cache/gen-cache \
|
||||
&& install -d -m 700 -o www-data -g www-data /var/cache/template-cache
|
||||
|
||||
# Copy the bootstrap script.
|
||||
COPY ./docker/php/bootstrap.sh /usr/local/bin/bootstrap.sh
|
||||
|
||||
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
|
||||
|
||||
# Copy the actual project (use .dockerignore to exclude stuff).
|
||||
COPY . /code
|
||||
|
||||
# Install the compose depedencies.
|
||||
RUN cd /code && composer install
|
||||
|
||||
WORKDIR "/var/www"
|
||||
CMD [ "bootstrap.sh" ]
|
||||
EXPOSE 9000
|
@ -1,16 +0,0 @@
|
||||
# syntax = devthefuture/dockerfile-x
|
||||
INCLUDE ./docker/php/Dockerfile
|
||||
|
||||
RUN apk add --no-cache \
|
||||
linux-headers \
|
||||
$PHPIZE_DEPS \
|
||||
&& pecl update-channels \
|
||||
&& pecl install xdebug \
|
||||
&& docker-php-ext-enable xdebug \
|
||||
&& apk del \
|
||||
linux-headers \
|
||||
$PHPIZE_DEPS \
|
||||
&& rm -rf /var/cache/*
|
||||
|
||||
ENV XDEBUG_OUT_DIR=/var/www/xdebug_out
|
||||
CMD [ "bootstrap.sh" ]
|
@ -1,87 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
function set_cfg() {
|
||||
if [ -L "/var/www/inc/$1" ]; then
|
||||
echo "INFO: Resetting $1"
|
||||
rm "/var/www/inc/$1"
|
||||
cp "/code/inc/$1" "/var/www/inc/$1"
|
||||
chown www-data "/var/www/inc/$1"
|
||||
chgrp www-data "/var/www/inc/$1"
|
||||
chmod 600 "/var/www/inc/$1"
|
||||
else
|
||||
echo "INFO: Using existing $1"
|
||||
fi
|
||||
}
|
||||
|
||||
if ! mountpoint -q /var/www; then
|
||||
echo "WARNING: '/var/www' is not a mountpoint. All the data will remain inside the container!"
|
||||
fi
|
||||
|
||||
if [ ! -w /var/www ] ; then
|
||||
echo "ERROR: '/var/www' is not writable. Closing."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${XDEBUG_OUT_DIR:-''}" ] ; then
|
||||
echo "INFO: Initializing xdebug out directory at $XDEBUG_OUT_DIR"
|
||||
mkdir -p "$XDEBUG_OUT_DIR"
|
||||
chown www-data "$XDEBUG_OUT_DIR"
|
||||
chgrp www-data "$XDEBUG_OUT_DIR"
|
||||
chmod 755 "$XDEBUG_OUT_DIR"
|
||||
fi
|
||||
|
||||
# Link the entrypoints from the exposed directory.
|
||||
ln -nfs \
|
||||
/code/tools/ \
|
||||
/code/*.php \
|
||||
/code/LICENSE.* \
|
||||
/code/install.sql \
|
||||
/var/www/
|
||||
# Static files accessible from the webserver must be copied.
|
||||
cp -ur /code/static /var/www/
|
||||
cp -ur /code/stylesheets /var/www/
|
||||
|
||||
# Ensure correct permissions are set, since this might be bind mount.
|
||||
chown www-data /var/www
|
||||
chgrp www-data /var/www
|
||||
|
||||
# Initialize an empty robots.txt with the default if it doesn't exist.
|
||||
touch /var/www/robots.txt
|
||||
|
||||
# Link the cache and tmp files directory.
|
||||
ln -nfs /var/tmp/vichan /var/www/tmp
|
||||
|
||||
# Link the javascript directory.
|
||||
ln -nfs /code/js /var/www/
|
||||
|
||||
# Link the html templates directory and it's cache.
|
||||
ln -nfs /code/templates /var/www/
|
||||
ln -nfs -T /var/cache/template-cache /var/www/templates/cache
|
||||
chown -h www-data /var/www/templates/cache
|
||||
chgrp -h www-data /var/www/templates/cache
|
||||
|
||||
# Link the generic cache.
|
||||
ln -nfs -T /var/cache/gen-cache /var/www/tmp/cache
|
||||
chown -h www-data /var/www/tmp/cache
|
||||
chgrp -h www-data /var/www/tmp/cache
|
||||
|
||||
# Create the included files directory and link them
|
||||
install -d -m 700 -o www-data -g www-data /var/www/inc
|
||||
for file in /code/inc/*; do
|
||||
file="${file##*/}"
|
||||
if [ ! -e /var/www/inc/$file ]; then
|
||||
ln -s /code/inc/$file /var/www/inc/
|
||||
fi
|
||||
done
|
||||
|
||||
# Copy an empty instance configuration if the file is a link (it was linked because it did not exist before).
|
||||
set_cfg 'instance-config.php'
|
||||
set_cfg 'secrets.php'
|
||||
|
||||
# Link the composer dependencies.
|
||||
ln -nfs /code/vendor /var/www/
|
||||
|
||||
# Start the php-fpm server.
|
||||
exec php-fpm
|
@ -1,2 +0,0 @@
|
||||
opcache.jit_buffer_size=192M
|
||||
opcache.jit=tracing
|
@ -1,13 +0,0 @@
|
||||
[www]
|
||||
access.log = /proc/self/fd/2
|
||||
|
||||
; Ensure worker stdout and stderr are sent to the main error log.
|
||||
catch_workers_output = yes
|
||||
decorate_workers_output = no
|
||||
|
||||
user = www-data
|
||||
group = www-data
|
||||
|
||||
listen = 127.0.0.1:9000
|
||||
pm = static
|
||||
pm.max_children = 16
|
@ -1,7 +0,0 @@
|
||||
zend_extension=xdebug
|
||||
|
||||
[xdebug]
|
||||
xdebug.mode = profile
|
||||
xdebug.start_with_request = start
|
||||
error_reporting = E_ALL
|
||||
xdebug.output_dir = /var/www/xdebug_out
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class ApcuCacheDriver implements CacheDriver {
|
||||
public function get(string $key): mixed {
|
||||
$success = false;
|
||||
$ret = \apcu_fetch($key, $success);
|
||||
if ($success === false) {
|
||||
return null;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value, mixed $expires = false): void {
|
||||
\apcu_store($key, $value, (int)$expires);
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
\apcu_delete($key);
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
\apcu_clear_cache();
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
/**
|
||||
* A simple process-wide PHP array.
|
||||
*/
|
||||
class ArrayCacheDriver implements CacheDriver {
|
||||
private static $inner = [];
|
||||
|
||||
public function get(string $key) {
|
||||
return isset(self::$inner[$key]) ? self::$inner[$key] : null;
|
||||
}
|
||||
|
||||
public function set(string $key, $value, $expires = false): void {
|
||||
self::$inner[$key] = $value;
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
unset(self::$inner[$key]);
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
self::$inner = [];
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
interface CacheDriver {
|
||||
/**
|
||||
* Get the value of associated with the key.
|
||||
*
|
||||
* @param string $key The key of the value.
|
||||
* @return mixed|null The value associated with the key, or null if there is none.
|
||||
*/
|
||||
public function get(string $key);
|
||||
|
||||
/**
|
||||
* Set a key-value pair.
|
||||
*
|
||||
* @param string $key The key.
|
||||
* @param mixed $value The value.
|
||||
* @param int|false $expires After how many seconds the pair will expire. Use false or ignore this parameter to keep
|
||||
* the value until it gets evicted to make space for more items. Some drivers will always
|
||||
* ignore this parameter and store the pair until it's removed.
|
||||
*/
|
||||
public function set(string $key, $value, $expires = false);
|
||||
|
||||
/**
|
||||
* Delete a key-value pair.
|
||||
*
|
||||
* @param string $key The key.
|
||||
*/
|
||||
public function delete(string $key);
|
||||
|
||||
/**
|
||||
* Delete all the key-value pairs.
|
||||
*/
|
||||
public function flush();
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
/**
|
||||
* Log via the php function error_log.
|
||||
*/
|
||||
class ErrorLogLogDriver implements LogDriver {
|
||||
use LogTrait;
|
||||
|
||||
private string $name;
|
||||
private int $level;
|
||||
|
||||
public function __construct(string $name, int $level) {
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
$lv = $this->levelToString($level);
|
||||
$line = "{$this->name} $lv: $message";
|
||||
\error_log($line, 0, null, null);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,61 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
/**
|
||||
* Log to a file.
|
||||
*/
|
||||
class FileLogDriver implements LogDriver {
|
||||
use LogTrait;
|
||||
|
||||
private string $name;
|
||||
private int $level;
|
||||
private mixed $fd;
|
||||
|
||||
public function __construct(string $name, int $level, string $file_path) {
|
||||
/*
|
||||
* error_log is slow as hell in it's 3rd mode, so use fopen + file locking instead.
|
||||
* https://grobmeier.solutions/performance-ofnonblocking-write-to-files-via-php-21082009.html
|
||||
*
|
||||
* Whatever file appending is atomic is contentious:
|
||||
* - There are no POSIX guarantees: https://stackoverflow.com/a/7237901
|
||||
* - But linus suggested they are on linux, on some filesystems: https://web.archive.org/web/20151201111541/http://article.gmane.org/gmane.linux.kernel/43445
|
||||
* - But it doesn't seem to be always the case: https://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/
|
||||
*
|
||||
* So we just use file locking to be sure.
|
||||
*/
|
||||
|
||||
$this->fd = \fopen($file_path, 'a');
|
||||
if ($this->fd === false) {
|
||||
throw new \RuntimeException("Unable to open log file at $file_path");
|
||||
}
|
||||
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
|
||||
// In some cases PHP does not run the destructor.
|
||||
\register_shutdown_function([$this, 'close']);
|
||||
}
|
||||
|
||||
public function __destruct() {
|
||||
$this->close();
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
$lv = $this->levelToString($level);
|
||||
$line = "{$this->name} $lv: $message\n";
|
||||
\flock($this->fd, LOCK_EX);
|
||||
\fwrite($this->fd, $line);
|
||||
\fflush($this->fd);
|
||||
\flock($this->fd, LOCK_UN);
|
||||
}
|
||||
}
|
||||
|
||||
public function close() {
|
||||
\flock($this->fd, LOCK_UN);
|
||||
\fclose($this->fd);
|
||||
}
|
||||
}
|
@ -1,155 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class FsCacheDriver implements CacheDriver {
|
||||
private string $prefix;
|
||||
private string $base_path;
|
||||
private mixed $lock_fd;
|
||||
private int|false $collect_chance_den;
|
||||
|
||||
|
||||
private function prepareKey(string $key): string {
|
||||
$key = \str_replace('/', '::', $key);
|
||||
$key = \str_replace("\0", '', $key);
|
||||
return $this->prefix . $key;
|
||||
}
|
||||
|
||||
private function sharedLockCache(): void {
|
||||
\flock($this->lock_fd, LOCK_SH);
|
||||
}
|
||||
|
||||
private function exclusiveLockCache(): void {
|
||||
\flock($this->lock_fd, LOCK_EX);
|
||||
}
|
||||
|
||||
private function unlockCache(): void {
|
||||
\flock($this->lock_fd, LOCK_UN);
|
||||
}
|
||||
|
||||
private function collectImpl(): int {
|
||||
/*
|
||||
* A read lock is ok, since it's alright if we delete expired items from under the feet of other processes, and
|
||||
* no other process add new cache items or refresh existing ones.
|
||||
*/
|
||||
$files = \glob($this->base_path . $this->prefix . '*', \GLOB_NOSORT);
|
||||
$count = 0;
|
||||
foreach ($files as $file) {
|
||||
$data = \file_get_contents($file);
|
||||
$wrapped = \json_decode($data, true, 512, \JSON_THROW_ON_ERROR);
|
||||
if ($wrapped['expires'] !== false && $wrapped['expires'] <= \time()) {
|
||||
if (@\unlink($file)) {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $count;
|
||||
}
|
||||
|
||||
private function maybeCollect(): void {
|
||||
if ($this->collect_chance_den !== false && \mt_rand(0, $this->collect_chance_den - 1) === 0) {
|
||||
$this->collect_chance_den = false; // Collect only once per instance (aka process).
|
||||
$this->collectImpl();
|
||||
}
|
||||
}
|
||||
|
||||
public function __construct(string $prefix, string $base_path, string $lock_file, int|false $collect_chance_den) {
|
||||
if ($base_path[\strlen($base_path) - 1] !== '/') {
|
||||
$base_path = "$base_path/";
|
||||
}
|
||||
|
||||
if (!\is_dir($base_path)) {
|
||||
throw new \RuntimeException("$base_path is not a directory!");
|
||||
}
|
||||
|
||||
if (!\is_writable($base_path)) {
|
||||
throw new \RuntimeException("$base_path is not writable!");
|
||||
}
|
||||
|
||||
$this->lock_fd = \fopen($base_path . $lock_file, 'w');
|
||||
if ($this->lock_fd === false) {
|
||||
throw new \RuntimeException('Unable to open the lock file!');
|
||||
}
|
||||
|
||||
$this->prefix = $prefix;
|
||||
$this->base_path = $base_path;
|
||||
$this->collect_chance_den = $collect_chance_den;
|
||||
}
|
||||
|
||||
public function __destruct() {
|
||||
$this->close();
|
||||
}
|
||||
|
||||
public function get(string $key): mixed {
|
||||
$key = $this->prepareKey($key);
|
||||
|
||||
$this->sharedLockCache();
|
||||
|
||||
// Collect expired items first so if the target key is expired we shortcut to failure in the next lines.
|
||||
$this->maybeCollect();
|
||||
|
||||
$fd = \fopen($this->base_path . $key, 'r');
|
||||
if ($fd === false) {
|
||||
$this->unlockCache();
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = \stream_get_contents($fd);
|
||||
\fclose($fd);
|
||||
$this->unlockCache();
|
||||
$wrapped = \json_decode($data, true, 512, \JSON_THROW_ON_ERROR);
|
||||
|
||||
if ($wrapped['expires'] !== false && $wrapped['expires'] <= \time()) {
|
||||
// Already expired, leave it there since we already released the lock and pretend it doesn't exist.
|
||||
return null;
|
||||
} else {
|
||||
return $wrapped['inner'];
|
||||
}
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value, mixed $expires = false): void {
|
||||
$key = $this->prepareKey($key);
|
||||
|
||||
$wrapped = [
|
||||
'expires' => $expires ? \time() + $expires : false,
|
||||
'inner' => $value
|
||||
];
|
||||
|
||||
$data = \json_encode($wrapped);
|
||||
$this->exclusiveLockCache();
|
||||
$this->maybeCollect();
|
||||
\file_put_contents($this->base_path . $key, $data);
|
||||
$this->unlockCache();
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
$key = $this->prepareKey($key);
|
||||
|
||||
$this->exclusiveLockCache();
|
||||
@\unlink($this->base_path . $key);
|
||||
$this->maybeCollect();
|
||||
$this->unlockCache();
|
||||
}
|
||||
|
||||
public function collect(): int {
|
||||
$this->sharedLockCache();
|
||||
$count = $this->collectImpl();
|
||||
$this->unlockCache();
|
||||
return $count;
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
$this->exclusiveLockCache();
|
||||
$files = \glob($this->base_path . $this->prefix . '*', \GLOB_NOSORT);
|
||||
foreach ($files as $file) {
|
||||
@\unlink($file);
|
||||
}
|
||||
$this->unlockCache();
|
||||
}
|
||||
|
||||
public function close(): void {
|
||||
\fclose($this->lock_fd);
|
||||
}
|
||||
}
|
@ -1,131 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
/**
|
||||
* Honestly this is just a wrapper for cURL. Still useful to mock it and have an OOP API on PHP 7.
|
||||
*/
|
||||
class HttpDriver {
|
||||
private $inner;
|
||||
private int $timeout;
|
||||
private int $max_file_size;
|
||||
|
||||
|
||||
private function resetTowards(string $url, int $timeout): void {
|
||||
\curl_reset($this->inner);
|
||||
\curl_setopt_array($this->inner, [
|
||||
\CURLOPT_URL => $url,
|
||||
\CURLOPT_TIMEOUT => $timeout,
|
||||
\CURLOPT_USERAGENT => 'Tinyboard',
|
||||
\CURLOPT_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS,
|
||||
]);
|
||||
}
|
||||
|
||||
public function __construct(int $timeout, int $max_file_size) {
|
||||
$this->inner = \curl_init();
|
||||
$this->timeout = $timeout;
|
||||
$this->max_file_size = $max_file_size;
|
||||
}
|
||||
|
||||
public function __destruct() {
|
||||
\curl_close($this->inner);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a GET request.
|
||||
*
|
||||
* @param string $endpoint Uri endpoint.
|
||||
* @param ?array $data Optional GET parameters.
|
||||
* @param int $timeout Optional request timeout in seconds. Use the default timeout if 0.
|
||||
* @return string Returns the body of the response.
|
||||
* @throws RuntimeException Throws on IO error.
|
||||
*/
|
||||
public function requestGet(string $endpoint, ?array $data, int $timeout = 0): string {
|
||||
if (!empty($data)) {
|
||||
$endpoint .= '?' . \http_build_query($data);
|
||||
}
|
||||
if ($timeout == 0) {
|
||||
$timeout = $this->timeout;
|
||||
}
|
||||
|
||||
$this->resetTowards($endpoint, $timeout);
|
||||
\curl_setopt($this->inner, \CURLOPT_RETURNTRANSFER, true);
|
||||
$ret = \curl_exec($this->inner);
|
||||
|
||||
if ($ret === false) {
|
||||
throw new \RuntimeException(\curl_error($this->inner));
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a POST request.
|
||||
*
|
||||
* @param string $endpoint Uri endpoint.
|
||||
* @param ?array $data Optional POST parameters.
|
||||
* @param int $timeout Optional request timeout in seconds. Use the default timeout if 0.
|
||||
* @return string Returns the body of the response.
|
||||
* @throws RuntimeException Throws on IO error.
|
||||
*/
|
||||
public function requestPost(string $endpoint, ?array $data, int $timeout = 0): string {
|
||||
if ($timeout == 0) {
|
||||
$timeout = $this->timeout;
|
||||
}
|
||||
|
||||
$this->resetTowards($endpoint, $timeout);
|
||||
\curl_setopt($this->inner, \CURLOPT_POST, true);
|
||||
if (!empty($data)) {
|
||||
\curl_setopt($this->inner, \CURLOPT_POSTFIELDS, \http_build_query($data));
|
||||
}
|
||||
\curl_setopt($this->inner, \CURLOPT_RETURNTRANSFER, true);
|
||||
$ret = \curl_exec($this->inner);
|
||||
|
||||
if ($ret === false) {
|
||||
throw new \RuntimeException(\curl_error($this->inner));
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the url's target with curl.
|
||||
*
|
||||
* @param string $url Url to the file to download.
|
||||
* @param ?array $data Optional GET parameters.
|
||||
* @param resource $fd File descriptor to save the content to.
|
||||
* @param int $timeout Optional request timeout in seconds. Use the default timeout if 0.
|
||||
* @return bool Returns true on success, false if the file was too large.
|
||||
* @throws RuntimeException Throws on IO error.
|
||||
*/
|
||||
public function requestGetInto(string $endpoint, ?array $data, $fd, int $timeout = 0): bool {
|
||||
if (!empty($data)) {
|
||||
$endpoint .= '?' . \http_build_query($data);
|
||||
}
|
||||
if ($timeout == 0) {
|
||||
$timeout = $this->timeout;
|
||||
}
|
||||
|
||||
$this->resetTowards($endpoint, $timeout);
|
||||
// Adapted from: https://stackoverflow.com/a/17642638
|
||||
$opt = (\PHP_MAJOR_VERSION >= 8 && \PHP_MINOR_VERSION >= 2) ? \CURLOPT_XFERINFOFUNCTION : \CURLOPT_PROGRESSFUNCTION;
|
||||
\curl_setopt_array($this->inner, [
|
||||
\CURLOPT_NOPROGRESS => false,
|
||||
$opt => fn($res, $next_dl, $dl, $next_up, $up) => (int)($dl <= $this->max_file_size),
|
||||
\CURLOPT_FAILONERROR => true,
|
||||
\CURLOPT_FOLLOWLOCATION => false,
|
||||
\CURLOPT_FILE => $fd,
|
||||
\CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
|
||||
]);
|
||||
$ret = \curl_exec($this->inner);
|
||||
|
||||
if ($ret === false) {
|
||||
if (\curl_errno($this->inner) === CURLE_ABORTED_BY_CALLBACK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new \RuntimeException(\curl_error($this->inner));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
interface LogDriver {
|
||||
public const EMERG = \LOG_EMERG;
|
||||
public const ERROR = \LOG_ERR;
|
||||
public const WARNING = \LOG_WARNING;
|
||||
public const NOTICE = \LOG_NOTICE;
|
||||
public const INFO = \LOG_INFO;
|
||||
public const DEBUG = \LOG_DEBUG;
|
||||
|
||||
/**
|
||||
* Log a message if the level of relevancy is at least the minimum.
|
||||
*
|
||||
* @param int $level Message level. Use Log interface constants.
|
||||
* @param string $message The message to log.
|
||||
*/
|
||||
public function log(int $level, string $message): void;
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
trait LogTrait {
|
||||
public static function levelToString(int $level): string {
|
||||
switch ($level) {
|
||||
case LogDriver::EMERG:
|
||||
return 'EMERG';
|
||||
case LogDriver::ERROR:
|
||||
return 'ERROR';
|
||||
case LogDriver::WARNING:
|
||||
return 'WARNING';
|
||||
case LogDriver::NOTICE:
|
||||
return 'NOTICE';
|
||||
case LogDriver::INFO:
|
||||
return 'INFO';
|
||||
case LogDriver::DEBUG:
|
||||
return 'DEBUG';
|
||||
default:
|
||||
throw new \InvalidArgumentException('Not a logging level');
|
||||
}
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class MemcachedCacheDriver implements CacheDriver {
|
||||
private \Memcached $inner;
|
||||
|
||||
public function __construct(string $prefix, string $memcached_server) {
|
||||
$this->inner = new \Memcached();
|
||||
if (!$this->inner->setOption(\Memcached::OPT_BINARY_PROTOCOL, true)) {
|
||||
throw new \RuntimeException('Unable to set the memcached protocol!');
|
||||
}
|
||||
if (!$this->inner->setOption(\Memcached::OPT_PREFIX_KEY, $prefix)) {
|
||||
throw new \RuntimeException('Unable to set the memcached prefix!');
|
||||
}
|
||||
if (!$this->inner->addServers($memcached_server)) {
|
||||
throw new \RuntimeException('Unable to add the memcached server!');
|
||||
}
|
||||
}
|
||||
|
||||
public function get(string $key): mixed {
|
||||
$ret = $this->inner->get($key);
|
||||
// If the returned value is false but the retrival was a success, then the value stored was a boolean false.
|
||||
if ($ret === false && $this->inner->getResultCode() !== \Memcached::RES_SUCCESS) {
|
||||
return null;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value, mixed $expires = false): void {
|
||||
$this->inner->set($key, $value, (int)$expires);
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
$this->inner->delete($key);
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
$this->inner->flush();
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
/**
|
||||
* No-op cache. Useful for testing.
|
||||
*/
|
||||
class NoneCacheDriver implements CacheDriver {
|
||||
public function get(string $key): mixed {
|
||||
return null;
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value, mixed $expires = false): void {
|
||||
// No-op.
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
// No-op.
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
// No-op.
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class RedisCacheDriver implements CacheDriver {
|
||||
private string $prefix;
|
||||
private \Redis $inner;
|
||||
|
||||
public function __construct(string $prefix, string $host, int $port, ?string $password, string $database) {
|
||||
$this->inner = new \Redis();
|
||||
$this->inner->connect($host, $port);
|
||||
if ($password) {
|
||||
$this->inner->auth($password);
|
||||
}
|
||||
if (!$this->inner->select($database)) {
|
||||
throw new \RuntimeException('Unable to connect to Redis!');
|
||||
}
|
||||
|
||||
$$this->prefix = $prefix;
|
||||
}
|
||||
|
||||
public function get(string $key): mixed {
|
||||
$ret = $this->inner->get($this->prefix . $key);
|
||||
if ($ret === false) {
|
||||
return null;
|
||||
}
|
||||
return \json_decode($ret, true);
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value, mixed $expires = false): void {
|
||||
if ($expires === false) {
|
||||
$this->inner->set($this->prefix . $key, \json_encode($value));
|
||||
} else {
|
||||
$expires = $expires * 1000; // Seconds to milliseconds.
|
||||
$this->inner->setex($this->prefix . $key, $expires, \json_encode($value));
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
$this->inner->del($this->prefix . $key);
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
$this->inner->flushDB();
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
/**
|
||||
* Log to php's standard error file stream.
|
||||
*/
|
||||
class StderrLogDriver implements LogDriver {
|
||||
use LogTrait;
|
||||
|
||||
private string $name;
|
||||
private int $level;
|
||||
|
||||
public function __construct(string $name, int $level) {
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
$lv = $this->levelToString($level);
|
||||
\fwrite(\STDERR, "{$this->name} $lv: $message\n");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Data\Driver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
/**
|
||||
* Log to syslog.
|
||||
*/
|
||||
class SyslogLogDriver implements LogDriver {
|
||||
private int $level;
|
||||
|
||||
public function __construct(string $name, int $level, bool $print_stderr) {
|
||||
$flags = \LOG_ODELAY;
|
||||
if ($print_stderr) {
|
||||
$flags |= \LOG_PERROR;
|
||||
}
|
||||
|
||||
if (!\openlog($name, $flags, \LOG_USER)) {
|
||||
throw new \RuntimeException('Unable to open syslog');
|
||||
}
|
||||
|
||||
$this->level = $level;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
if (isset($_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])) {
|
||||
// CGI
|
||||
\syslog($level, "$message - client: {$_SERVER['REMOTE_ADDR']}, request: \"{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']}\"");
|
||||
} else {
|
||||
\syslog($level, $message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
188
inc/anti-bot.php
188
inc/anti-bot.php
@ -1,5 +1,191 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Anti-bot.php has been deprecated and removed due to its functions not being necessary and being easily bypassable, by both customized and uncustomized spambots.
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
$hidden_inputs_twig = array();
|
||||
|
||||
class AntiBot {
|
||||
public $salt, $inputs = array(), $index = 0;
|
||||
|
||||
public static function randomString($length, $uppercase = false, $special_chars = false, $unicode_chars = false) {
|
||||
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
||||
if ($uppercase)
|
||||
$chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
if ($special_chars)
|
||||
$chars .= ' ~!@#$%^&*()_+,./;\'[]\\{}|:<>?=-` ';
|
||||
if ($unicode_chars) {
|
||||
$len = strlen($chars) / 10;
|
||||
for ($n = 0; $n < $len; $n++)
|
||||
$chars .= mb_convert_encoding('&#' . mt_rand(0x2600, 0x26FF) . ';', 'UTF-8', 'HTML-ENTITIES');
|
||||
}
|
||||
|
||||
$chars = preg_split('//u', $chars, -1, PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
$ch = array();
|
||||
|
||||
// fill up $ch until we reach $length
|
||||
while (count($ch) < $length) {
|
||||
$n = $length - count($ch);
|
||||
$keys = array_rand($chars, $n > count($chars) ? count($chars) : $n);
|
||||
if ($n == 1) {
|
||||
$ch[] = $chars[$keys];
|
||||
break;
|
||||
}
|
||||
shuffle($keys);
|
||||
foreach ($keys as $key)
|
||||
$ch[] = $chars[$key];
|
||||
}
|
||||
|
||||
$chars = $ch;
|
||||
|
||||
return implode('', $chars);
|
||||
}
|
||||
|
||||
public static function make_confusing($string) {
|
||||
$chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
foreach ($chars as &$c) {
|
||||
if (mt_rand(0, 3) != 0)
|
||||
$c = utf8tohtml($c);
|
||||
else
|
||||
$c = mb_encode_numericentity($c, array(0, 0xffff, 0, 0xffff), 'UTF-8');
|
||||
}
|
||||
|
||||
return implode('', $chars);
|
||||
}
|
||||
|
||||
public function __construct(array $salt = array()) {
|
||||
global $config;
|
||||
|
||||
if (!empty($salt)) {
|
||||
// create a salted hash of the "extra salt"
|
||||
$this->salt = implode(':', $salt);
|
||||
} else {
|
||||
$this->salt = '';
|
||||
}
|
||||
|
||||
shuffle($config['spam']['hidden_input_names']);
|
||||
|
||||
$input_count = mt_rand($config['spam']['hidden_inputs_min'], $config['spam']['hidden_inputs_max']);
|
||||
$hidden_input_names_x = 0;
|
||||
|
||||
for ($x = 0; $x < $input_count ; $x++) {
|
||||
if ($hidden_input_names_x === false || mt_rand(0, 2) == 0) {
|
||||
// Use an obscure name
|
||||
$name = $this->randomString(mt_rand(10, 40), false, false, $config['spam']['unicode']);
|
||||
} else {
|
||||
// Use a pre-defined confusing name
|
||||
$name = $config['spam']['hidden_input_names'][$hidden_input_names_x++];
|
||||
if ($hidden_input_names_x >= count($config['spam']['hidden_input_names']))
|
||||
$hidden_input_names_x = false;
|
||||
}
|
||||
|
||||
if (mt_rand(0, 2) == 0) {
|
||||
// Value must be null
|
||||
$this->inputs[$name] = '';
|
||||
} elseif (mt_rand(0, 4) == 0) {
|
||||
// Numeric value
|
||||
$this->inputs[$name] = (string)mt_rand(0, 100000);
|
||||
} else {
|
||||
// Obscure value
|
||||
$this->inputs[$name] = $this->randomString(mt_rand(5, 100), true, true, $config['spam']['unicode']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function space() {
|
||||
if (mt_rand(0, 3) != 0)
|
||||
return ' ';
|
||||
return str_repeat(' ', mt_rand(1, 3));
|
||||
}
|
||||
|
||||
public function html($count = false) {
|
||||
global $config;
|
||||
|
||||
$elements = array(
|
||||
'<input type="hidden" name="%name%" value="%value%">',
|
||||
'<input type="hidden" value="%value%" name="%name%">',
|
||||
'<input name="%name%" value="%value%" type="hidden">',
|
||||
'<input value="%value%" name="%name%" type="hidden">',
|
||||
'<input style="display:none" type="text" name="%name%" value="%value%">',
|
||||
'<input style="display:none" type="text" value="%value%" name="%name%">',
|
||||
'<span style="display:none"><input type="text" name="%name%" value="%value%"></span>',
|
||||
'<div style="display:none"><input type="text" name="%name%" value="%value%"></div>',
|
||||
'<div style="display:none"><input type="text" name="%name%" value="%value%"></div>',
|
||||
'<textarea style="display:none" name="%name%">%value%</textarea>',
|
||||
'<textarea name="%name%" style="display:none">%value%</textarea>'
|
||||
);
|
||||
|
||||
$html = '';
|
||||
|
||||
if ($count === false) {
|
||||
$count = mt_rand(1, abs(count($this->inputs) / 15) + 1);
|
||||
}
|
||||
|
||||
if ($count === true) {
|
||||
// all elements
|
||||
$inputs = array_slice($this->inputs, $this->index);
|
||||
} else {
|
||||
$inputs = array_slice($this->inputs, $this->index, $count);
|
||||
}
|
||||
$this->index += count($inputs);
|
||||
|
||||
foreach ($inputs as $name => $value) {
|
||||
$element = false;
|
||||
while (!$element) {
|
||||
$element = $elements[array_rand($elements)];
|
||||
$element = str_replace(' ', self::space(), $element);
|
||||
if (mt_rand(0, 5) == 0)
|
||||
$element = str_replace('>', self::space() . '>', $element);
|
||||
if (strpos($element, 'textarea') !== false && $value == '') {
|
||||
// There have been some issues with mobile web browsers and empty <textarea>'s.
|
||||
$element = false;
|
||||
}
|
||||
}
|
||||
|
||||
$element = str_replace('%name%', utf8tohtml($name), $element);
|
||||
|
||||
if (mt_rand(0, 2) == 0)
|
||||
$value = $this->make_confusing($value);
|
||||
else
|
||||
$value = utf8tohtml($value);
|
||||
|
||||
if (strpos($element, 'textarea') === false)
|
||||
$value = str_replace('"', '"', $value);
|
||||
|
||||
$element = str_replace('%value%', $value, $element);
|
||||
|
||||
$html .= $element;
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
public function reset() {
|
||||
$this->index = 0;
|
||||
}
|
||||
|
||||
public function hash() {
|
||||
global $config;
|
||||
|
||||
// This is the tricky part: create a hash to validate it after
|
||||
// First, sort the keys in alphabetical order (A-Z)
|
||||
$inputs = $this->inputs;
|
||||
ksort($inputs);
|
||||
|
||||
$hash = '';
|
||||
// Iterate through each input
|
||||
foreach ($inputs as $name => $value) {
|
||||
$hash .= $name . '=' . $value;
|
||||
}
|
||||
// Add a salt to the hash
|
||||
$hash .= $config['cookies']['salt'];
|
||||
|
||||
// Use SHA1 for the hash
|
||||
return sha1($hash . $this->salt);
|
||||
}
|
||||
}
|
||||
|
148
inc/api.php
148
inc/api.php
@ -9,49 +9,14 @@ defined('TINYBOARD') or exit;
|
||||
* Class for generating json API compatible with 4chan API
|
||||
*/
|
||||
class Api {
|
||||
private bool $show_filename;
|
||||
private bool $hide_email;
|
||||
private bool $country_flags;
|
||||
private array $postFields;
|
||||
function __construct(){
|
||||
global $config;
|
||||
/**
|
||||
* Translation from local fields to fields in 4chan-style API
|
||||
*/
|
||||
$this->config = $config;
|
||||
|
||||
private const INTS = [
|
||||
'no' => 1,
|
||||
'resto' => 1,
|
||||
'time' => 1,
|
||||
'tn_w' => 1,
|
||||
'tn_h' => 1,
|
||||
'w' => 1,
|
||||
'h' => 1,
|
||||
'fsize' => 1,
|
||||
'omitted_posts' => 1,
|
||||
'omitted_images' => 1,
|
||||
'replies' => 1,
|
||||
'images' => 1,
|
||||
'sticky' => 1,
|
||||
'locked' => 1,
|
||||
'last_modified' => 1
|
||||
];
|
||||
|
||||
private const THREADS_PAGE_FIELDS = [
|
||||
'id' => 'no',
|
||||
'bump' => 'last_modified'
|
||||
];
|
||||
|
||||
private const FILE_FIELDS = [
|
||||
'thumbheight' => 'tn_h',
|
||||
'thumbwidth' => 'tn_w',
|
||||
'height' => 'h',
|
||||
'width' => 'w',
|
||||
'size' => 'fsize'
|
||||
];
|
||||
|
||||
public function __construct(bool $show_filename, bool $hide_email, bool $country_flags) {
|
||||
// Translation from local fields to fields in 4chan-style API
|
||||
$this->show_filename = $show_filename;
|
||||
$this->hide_email = $hide_email;
|
||||
$this->country_flags = $country_flags;
|
||||
|
||||
$this->postFields = [
|
||||
$this->postFields = array(
|
||||
'id' => 'no',
|
||||
'thread' => 'resto',
|
||||
'subject' => 'sub',
|
||||
@ -70,65 +35,83 @@ class Api {
|
||||
'cycle' => 'cyclical',
|
||||
'bump' => 'last_modified',
|
||||
'embed' => 'embed',
|
||||
];
|
||||
);
|
||||
|
||||
$this->threadsPageFields = array(
|
||||
'id' => 'no',
|
||||
'bump' => 'last_modified'
|
||||
);
|
||||
|
||||
$this->fileFields = array(
|
||||
'thumbheight' => 'tn_h',
|
||||
'thumbwidth' => 'tn_w',
|
||||
'height' => 'h',
|
||||
'width' => 'w',
|
||||
'size' => 'fsize',
|
||||
);
|
||||
|
||||
if (isset($config['api']['extra_fields']) && gettype($config['api']['extra_fields']) == 'array'){
|
||||
$this->postFields = array_merge($this->postFields, $config['api']['extra_fields']);
|
||||
}
|
||||
}
|
||||
|
||||
private static $ints = array(
|
||||
'no' => 1,
|
||||
'resto' => 1,
|
||||
'time' => 1,
|
||||
'tn_w' => 1,
|
||||
'tn_h' => 1,
|
||||
'w' => 1,
|
||||
'h' => 1,
|
||||
'fsize' => 1,
|
||||
'omitted_posts' => 1,
|
||||
'omitted_images' => 1,
|
||||
'replies' => 1,
|
||||
'images' => 1,
|
||||
'sticky' => 1,
|
||||
'locked' => 1,
|
||||
'last_modified' => 1
|
||||
);
|
||||
|
||||
private function translateFields($fields, $object, &$apiPost) {
|
||||
foreach ($fields as $local => $translated) {
|
||||
if (!isset($object->$local)) {
|
||||
if (!isset($object->$local))
|
||||
continue;
|
||||
}
|
||||
|
||||
$toInt = isset(self::INTS[$translated]);
|
||||
$toInt = isset(self::$ints[$translated]);
|
||||
$val = $object->$local;
|
||||
if ($this->hide_email && $local === 'email') {
|
||||
$val = '';
|
||||
}
|
||||
if ($val !== null && $val !== '') {
|
||||
$apiPost[$translated] = $toInt ? (int) $val : $val;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private function translateFile($file, $post, &$apiPost) {
|
||||
$this->translateFields(self::FILE_FIELDS, $file, $apiPost);
|
||||
$this->translateFields($this->fileFields, $file, $apiPost);
|
||||
$apiPost['filename'] = @substr($file->name, 0, strrpos($file->name, '.'));
|
||||
$dotPos = strrpos($file->file, '.');
|
||||
$apiPost['ext'] = substr($file->file, $dotPos);
|
||||
$apiPost['tim'] = substr($file->file, 0, $dotPos);
|
||||
|
||||
if ($this->show_filename) {
|
||||
$apiPost['filename'] = @substr($file->name, 0, strrpos($file->name, '.'));
|
||||
} else {
|
||||
$apiPost['filename'] = substr($file->file, 0, $dotPos);
|
||||
}
|
||||
if (isset ($file->hash) && $file->hash) {
|
||||
$apiPost['md5'] = base64_encode(hex2bin($file->hash));
|
||||
} elseif (isset ($post->filehash) && $post->filehash) {
|
||||
}
|
||||
else if (isset ($post->filehash) && $post->filehash) {
|
||||
$apiPost['md5'] = base64_encode(hex2bin($post->filehash));
|
||||
}
|
||||
}
|
||||
|
||||
private function translatePost($post, bool $threadsPage = false) {
|
||||
private function translatePost($post, $threadsPage = false) {
|
||||
global $config, $board;
|
||||
|
||||
$apiPost = [];
|
||||
$fields = $threadsPage ? self::THREADS_PAGE_FIELDS : $this->postFields;
|
||||
$apiPost = array();
|
||||
$fields = $threadsPage ? $this->threadsPageFields : $this->postFields;
|
||||
$this->translateFields($fields, $post, $apiPost);
|
||||
|
||||
|
||||
if (isset($config['poster_ids']) && $config['poster_ids']) {
|
||||
$apiPost['id'] = poster_id($post->ip, $post->thread ?? $post->id);
|
||||
}
|
||||
if ($threadsPage) {
|
||||
return $apiPost;
|
||||
}
|
||||
if (isset($config['poster_ids']) && $config['poster_ids']) $apiPost['id'] = poster_id($post->ip, $post->thread, $board['uri']);
|
||||
if ($threadsPage) return $apiPost;
|
||||
|
||||
// Handle country field
|
||||
if (isset($post->body_nomarkup) && $this->country_flags) {
|
||||
if (isset($post->body_nomarkup) && $this->config['country_flags']) {
|
||||
$modifiers = extract_modifiers($post->body_nomarkup);
|
||||
if (isset($modifiers['flag']) && isset($modifiers['flag alt']) && preg_match('/^[a-z]{2}$/', $modifiers['flag'])) {
|
||||
$country = strtoupper($modifiers['flag']);
|
||||
@ -148,15 +131,12 @@ class Api {
|
||||
if (isset($post->files) && $post->files && !$threadsPage) {
|
||||
$file = $post->files[0];
|
||||
$this->translateFile($file, $post, $apiPost);
|
||||
|
||||
if (sizeof($post->files) > 1) {
|
||||
$extra_files = [];
|
||||
$extra_files = array();
|
||||
foreach ($post->files as $i => $f) {
|
||||
if ($i == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$extra_file = [];
|
||||
if ($i == 0) continue;
|
||||
|
||||
$extra_file = array();
|
||||
$this->translateFile($f, $post, $extra_file);
|
||||
|
||||
$extra_files[] = $extra_file;
|
||||
@ -168,8 +148,8 @@ class Api {
|
||||
return $apiPost;
|
||||
}
|
||||
|
||||
public function translateThread(Thread $thread, bool $threadsPage = false) {
|
||||
$apiPosts = [];
|
||||
function translateThread(Thread $thread, $threadsPage = false) {
|
||||
$apiPosts = array();
|
||||
$op = $this->translatePost($thread, $threadsPage);
|
||||
if (!$threadsPage) $op['resto'] = 0;
|
||||
$apiPosts['posts'][] = $op;
|
||||
@ -181,16 +161,16 @@ class Api {
|
||||
return $apiPosts;
|
||||
}
|
||||
|
||||
public function translatePage(array $threads) {
|
||||
$apiPage = [];
|
||||
function translatePage(array $threads) {
|
||||
$apiPage = array();
|
||||
foreach ($threads as $thread) {
|
||||
$apiPage['threads'][] = $this->translateThread($thread);
|
||||
}
|
||||
return $apiPage;
|
||||
}
|
||||
|
||||
public function translateCatalogPage(array $threads, bool $threadsPage = false) {
|
||||
$apiPage = [];
|
||||
function translateCatalogPage(array $threads, $threadsPage = false) {
|
||||
$apiPage = array();
|
||||
foreach ($threads as $thread) {
|
||||
$ts = $this->translateThread($thread, $threadsPage);
|
||||
$apiPage['threads'][] = current($ts['posts']);
|
||||
@ -198,8 +178,8 @@ class Api {
|
||||
return $apiPage;
|
||||
}
|
||||
|
||||
public function translateCatalog($catalog, bool $threadsPage = false) {
|
||||
$apiCatalog = [];
|
||||
function translateCatalog($catalog, $threadsPage = false) {
|
||||
$apiCatalog = array();
|
||||
foreach ($catalog as $page => $threads) {
|
||||
$apiPage = $this->translateCatalogPage($threads, $threadsPage);
|
||||
$apiPage['page'] = $page;
|
||||
|
333
inc/bans.php
333
inc/bans.php
@ -1,201 +1,46 @@
|
||||
<?php
|
||||
|
||||
use Vichan\Functions\Format;
|
||||
use Lifo\IP\CIDR;
|
||||
|
||||
class Bans {
|
||||
static private function shouldDelete(array $ban, bool $require_ban_view) {
|
||||
return $ban['expires'] && ($ban['seen'] || !$require_ban_view) && $ban['expires'] < time();
|
||||
}
|
||||
|
||||
static private function deleteBans(array $ban_ids) {
|
||||
$len = count($ban_ids);
|
||||
if ($len === 1) {
|
||||
$query = prepare('DELETE FROM ``bans`` WHERE `id` = :id');
|
||||
$query->bindValue(':id', $ban_ids[0], PDO::PARAM_INT);
|
||||
$query->execute() or error(db_error());
|
||||
|
||||
Vichan\Functions\Theme\rebuild_themes('bans');
|
||||
} elseif ($len >= 1) {
|
||||
// Build the query.
|
||||
$query = 'DELETE FROM ``bans`` WHERE `id` IN (';
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$query .= ":id{$i},";
|
||||
}
|
||||
// Substitute the last comma with a parenthesis.
|
||||
substr_replace($query, ')', strlen($query) - 1);
|
||||
|
||||
// Bind the params
|
||||
$query = prepare($query);
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$query->bindValue(":id{$i}", (int)$ban_ids[$i], PDO::PARAM_INT);
|
||||
}
|
||||
|
||||
$query->execute() or error(db_error());
|
||||
|
||||
Vichan\Functions\Theme\rebuild_themes('bans');
|
||||
}
|
||||
}
|
||||
|
||||
static private function findSingleAutoGc(string $ip, int $ban_id, bool $require_ban_view) {
|
||||
// Use OR in the query to also garbage collect bans.
|
||||
$query = prepare(
|
||||
'SELECT ``bans``.* FROM ``bans``
|
||||
WHERE ((`ipstart` = :ip OR (:ip >= `ipstart` AND :ip <= `ipend`)) OR (``bans``.id = :id))
|
||||
ORDER BY `expires` IS NULL, `expires` DESC'
|
||||
);
|
||||
|
||||
$query->bindValue(':id', $ban_id);
|
||||
$query->bindValue(':ip', inet_pton($ip));
|
||||
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$found_ban = null;
|
||||
$to_delete_list = [];
|
||||
|
||||
while ($ban = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
if (self::shouldDelete($ban, $require_ban_view)) {
|
||||
$to_delete_list[] = $ban['id'];
|
||||
} elseif ($ban['id'] === $ban_id) {
|
||||
if ($ban['post']) {
|
||||
$ban['post'] = json_decode($ban['post'], true);
|
||||
}
|
||||
$ban['mask'] = self::range_to_string([$ban['ipstart'], $ban['ipend']]);
|
||||
$found_ban = $ban;
|
||||
}
|
||||
}
|
||||
|
||||
self::deleteBans($to_delete_list);
|
||||
|
||||
return $found_ban;
|
||||
}
|
||||
|
||||
static private function findSingleNoGc(int $ban_id) {
|
||||
$query = prepare(
|
||||
'SELECT ``bans``.* FROM ``bans``
|
||||
WHERE ``bans``.id = :id
|
||||
ORDER BY `expires` IS NULL, `expires` DESC
|
||||
LIMIT 1'
|
||||
);
|
||||
|
||||
$query->bindValue(':id', $ban_id);
|
||||
|
||||
$query->execute() or error(db_error($query));
|
||||
$ret = $query->fetch(PDO::FETCH_ASSOC);
|
||||
if ($query->rowCount() == 0) {
|
||||
return null;
|
||||
} else {
|
||||
if ($ret['post']) {
|
||||
$ret['post'] = json_decode($ret['post'], true);
|
||||
}
|
||||
$ret['mask'] = self::range_to_string([$ret['ipstart'], $ret['ipend']]);
|
||||
|
||||
return $ret;
|
||||
}
|
||||
}
|
||||
|
||||
static private function findAutoGc(?string $ip, $board, bool $get_mod_info, bool $require_ban_view, ?int $ban_id): array {
|
||||
$query = prepare('SELECT ``bans``.*' . ($get_mod_info ? ', `username`' : '') . ' FROM ``bans``
|
||||
' . ($get_mod_info ? 'LEFT JOIN ``mods`` ON ``mods``.`id` = `creator`' : '') . '
|
||||
WHERE
|
||||
(' . ($board !== false ? '(`board` IS NULL OR `board` = :board) AND' : '') . '
|
||||
(`ipstart` = :ip OR (:ip >= `ipstart` AND :ip <= `ipend`)) OR (``bans``.id = :id))
|
||||
ORDER BY `expires` IS NULL, `expires` DESC');
|
||||
|
||||
if ($board !== false) {
|
||||
$query->bindValue(':board', $board, PDO::PARAM_STR);
|
||||
}
|
||||
|
||||
$query->bindValue(':id', $ban_id);
|
||||
$query->bindValue(':ip', inet_pton($ip));
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$ban_list = [];
|
||||
$to_delete_list = [];
|
||||
|
||||
while ($ban = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
if (self::shouldDelete($ban, $require_ban_view)) {
|
||||
$to_delete_list[] = $ban['id'];
|
||||
} else {
|
||||
if ($ban['post']) {
|
||||
$ban['post'] = json_decode($ban['post'], true);
|
||||
}
|
||||
$ban['mask'] = self::range_to_string([$ban['ipstart'], $ban['ipend']]);
|
||||
$ban_list[] = $ban;
|
||||
}
|
||||
}
|
||||
|
||||
self::deleteBans($to_delete_list);
|
||||
|
||||
return $ban_list;
|
||||
}
|
||||
|
||||
static private function findNoGc(?string $ip, string $board, bool $get_mod_info, ?int $ban_id): array {
|
||||
$query = prepare('SELECT ``bans``.*' . ($get_mod_info ? ', `username`' : '') . ' FROM ``bans``
|
||||
' . ($get_mod_info ? 'LEFT JOIN ``mods`` ON ``mods``.`id` = `creator`' : '') . '
|
||||
WHERE
|
||||
(' . ($board !== false ? '(`board` IS NULL OR `board` = :board) AND' : '') . '
|
||||
(`ipstart` = :ip OR (:ip >= `ipstart` AND :ip <= `ipend`)) OR (``bans``.id = :id))
|
||||
AND (`expires` IS NULL OR `expires` >= :curr_time)
|
||||
ORDER BY `expires` IS NULL, `expires` DESC');
|
||||
|
||||
if ($board !== false) {
|
||||
$query->bindValue(':board', $board, PDO::PARAM_STR);
|
||||
}
|
||||
|
||||
$query->bindValue(':id', $ban_id);
|
||||
$query->bindValue(':ip', inet_pton($ip));
|
||||
$query->bindValue(':curr_time', time());
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$ban_list = $query->fetchAll(PDO::FETCH_ASSOC);
|
||||
array_walk($ban_list, function (&$ban, $_index) {
|
||||
if ($ban['post']) {
|
||||
$ban['post'] = json_decode($ban['post'], true);
|
||||
}
|
||||
$ban['mask'] = self::range_to_string([$ban['ipstart'], $ban['ipend']]);
|
||||
});
|
||||
return $ban_list;
|
||||
}
|
||||
|
||||
static public function range_to_string($mask) {
|
||||
list($ipstart, $ipend) = $mask;
|
||||
|
||||
|
||||
if (!isset($ipend) || $ipend === false) {
|
||||
// Not a range. Single IP address.
|
||||
$ipstr = inet_ntop($ipstart);
|
||||
return $ipstr;
|
||||
}
|
||||
|
||||
|
||||
if (strlen($ipstart) != strlen($ipend))
|
||||
return '???'; // What the fuck are you doing, son?
|
||||
|
||||
|
||||
$range = CIDR::range_to_cidr(inet_ntop($ipstart), inet_ntop($ipend));
|
||||
if ($range !== false)
|
||||
return $range;
|
||||
|
||||
|
||||
return '???';
|
||||
}
|
||||
|
||||
|
||||
private static function calc_cidr($mask) {
|
||||
$cidr = new CIDR($mask);
|
||||
$range = $cidr->getRange();
|
||||
|
||||
return [ inet_pton($range[0]), inet_pton($range[1]) ];
|
||||
|
||||
return array(inet_pton($range[0]), inet_pton($range[1]));
|
||||
}
|
||||
|
||||
|
||||
public static function parse_time($str) {
|
||||
if (empty($str))
|
||||
return false;
|
||||
|
||||
|
||||
if (($time = @strtotime($str)) !== false)
|
||||
return $time;
|
||||
|
||||
|
||||
if (!preg_match('/^((\d+)\s?ye?a?r?s?)?\s?+((\d+)\s?mon?t?h?s?)?\s?+((\d+)\s?we?e?k?s?)?\s?+((\d+)\s?da?y?s?)?((\d+)\s?ho?u?r?s?)?\s?+((\d+)\s?mi?n?u?t?e?s?)?\s?+((\d+)\s?se?c?o?n?d?s?)?$/', $str, $matches))
|
||||
return false;
|
||||
|
||||
|
||||
$expire = 0;
|
||||
|
||||
|
||||
if (isset($matches[2])) {
|
||||
// Years
|
||||
$expire += (int)$matches[2]*60*60*24*365;
|
||||
@ -224,14 +69,14 @@ class Bans {
|
||||
// Seconds
|
||||
$expire += (int)$matches[14];
|
||||
}
|
||||
|
||||
|
||||
return time() + $expire;
|
||||
}
|
||||
|
||||
|
||||
static public function parse_range($mask) {
|
||||
$ipstart = false;
|
||||
$ipend = false;
|
||||
|
||||
|
||||
if (preg_match('@^(\d{1,3}\.){1,3}([\d*]{1,3})?$@', $mask) && substr_count($mask, '*') == 1) {
|
||||
// IPv4 wildcard mask
|
||||
$parts = explode('.', $mask);
|
||||
@ -252,38 +97,53 @@ class Bans {
|
||||
list($ipv4, $bits) = explode('/', $mask);
|
||||
if ($bits > 32)
|
||||
return false;
|
||||
|
||||
|
||||
list($ipstart, $ipend) = self::calc_cidr($mask);
|
||||
} elseif (preg_match('@^[:a-z\d]+/\d+$@i', $mask)) {
|
||||
list($ipv6, $bits) = explode('/', $mask);
|
||||
if ($bits > 128)
|
||||
return false;
|
||||
|
||||
|
||||
list($ipstart, $ipend) = self::calc_cidr($mask);
|
||||
} else {
|
||||
if (($ipstart = @inet_pton($mask)) === false)
|
||||
return false;
|
||||
}
|
||||
|
||||
return [$ipstart, $ipend];
|
||||
|
||||
return array($ipstart, $ipend);
|
||||
}
|
||||
|
||||
static public function findSingle(string $ip, int $ban_id, bool $require_ban_view, bool $auto_gc) {
|
||||
if ($auto_gc) {
|
||||
return self::findSingleAutoGc($ip, $ban_id, $require_ban_view);
|
||||
} else {
|
||||
return self::findSingleNoGc($ban_id);
|
||||
}
|
||||
}
|
||||
|
||||
static public function find(?string $ip, $board = false, bool $get_mod_info = false, ?int $ban_id = null, bool $auto_gc = true) {
|
||||
|
||||
static public function find($ip, $board = false, $get_mod_info = false) {
|
||||
global $config;
|
||||
|
||||
if ($auto_gc) {
|
||||
return self::findAutoGc($ip, $board, $get_mod_info, $config['require_ban_view'], $ban_id);
|
||||
} else {
|
||||
return self::findNoGc($ip, $board, $get_mod_info, $ban_id);
|
||||
|
||||
$query = prepare('SELECT ``bans``.*' . ($get_mod_info ? ', `username`' : '') . ' FROM ``bans``
|
||||
' . ($get_mod_info ? 'LEFT JOIN ``mods`` ON ``mods``.`id` = `creator`' : '') . '
|
||||
WHERE
|
||||
(' . ($board !== false ? '(`board` IS NULL OR `board` = :board) AND' : '') . '
|
||||
(`ipstart` = :ip OR (:ip >= `ipstart` AND :ip <= `ipend`)))
|
||||
ORDER BY `expires` IS NULL, `expires` DESC');
|
||||
|
||||
if ($board !== false)
|
||||
$query->bindValue(':board', $board, PDO::PARAM_STR);
|
||||
|
||||
$query->bindValue(':ip', inet_pton($ip));
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$ban_list = array();
|
||||
|
||||
while ($ban = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
if ($ban['expires'] && ($ban['seen'] || !$config['require_ban_view']) && $ban['expires'] < time()) {
|
||||
self::delete($ban['id']);
|
||||
} else {
|
||||
if ($ban['post'])
|
||||
$ban['post'] = json_decode($ban['post'], true);
|
||||
$ban['mask'] = self::range_to_string(array($ban['ipstart'], $ban['ipend']));
|
||||
$ban['cmask'] = cloak_mask($ban['mask']);
|
||||
$ban_list[] = $ban;
|
||||
}
|
||||
}
|
||||
|
||||
return $ban_list;
|
||||
}
|
||||
|
||||
static public function stream_json($out = false, $filter_ips = false, $filter_staff = false, $board_access = false) {
|
||||
@ -299,7 +159,8 @@ class Bans {
|
||||
$end = end($bans);
|
||||
|
||||
foreach ($bans as &$ban) {
|
||||
$ban['mask'] = self::range_to_string([$ban['ipstart'], $ban['ipend']]);
|
||||
$uncloaked_mask = self::range_to_string(array($ban['ipstart'], $ban['ipend']));
|
||||
$ban['mask'] = cloak_mask($uncloaked_mask);
|
||||
|
||||
if ($ban['post']) {
|
||||
$post = json_decode($ban['post']);
|
||||
@ -340,29 +201,17 @@ class Bans {
|
||||
$out ? fputs($out, "]") : print("]");
|
||||
|
||||
}
|
||||
|
||||
|
||||
static public function seen($ban_id) {
|
||||
$query = query("UPDATE ``bans`` SET `seen` = 1 WHERE `id` = " . (int)$ban_id) or error(db_error());
|
||||
Vichan\Functions\Theme\rebuild_themes('bans');
|
||||
rebuildThemes('bans');
|
||||
}
|
||||
|
||||
static public function purge($require_seen, $moratorium) {
|
||||
if ($require_seen) {
|
||||
$query = prepare("DELETE FROM ``bans`` WHERE `expires` IS NOT NULL AND `expires` + :moratorium < :curr_time AND `seen` = 1");
|
||||
} else {
|
||||
$query = prepare("DELETE FROM ``bans`` WHERE `expires` IS NOT NULL AND `expires` + :moratorium < :curr_time");
|
||||
}
|
||||
$query->bindValue(':moratorium', $moratorium);
|
||||
$query->bindValue(':curr_time', time());
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$affected = $query->rowCount();
|
||||
if ($affected > 0) {
|
||||
Vichan\Functions\Theme\rebuild_themes('bans');
|
||||
}
|
||||
return $affected;
|
||||
|
||||
static public function purge() {
|
||||
$query = query("DELETE FROM ``bans`` WHERE `expires` IS NOT NULL AND `expires` < " . time() . " AND `seen` = 1") or error(db_error());
|
||||
rebuildThemes('bans');
|
||||
}
|
||||
|
||||
|
||||
static public function delete($ban_id, $modlog = false, $boards = false, $dont_rebuild = false) {
|
||||
global $config;
|
||||
|
||||
@ -377,51 +226,52 @@ class Bans {
|
||||
|
||||
if ($boards !== false && !in_array($ban['board'], $boards))
|
||||
error($config['error']['noaccess']);
|
||||
|
||||
$mask = self::range_to_string([$ban['ipstart'], $ban['ipend']]);
|
||||
|
||||
|
||||
$mask = self::range_to_string(array($ban['ipstart'], $ban['ipend']));
|
||||
$cloaked_mask = cloak_mask($mask);
|
||||
|
||||
modLog("Removed ban #{$ban_id} for " .
|
||||
(filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$cloaked_mask\">$cloaked_mask</a>" : $cloaked_mask));
|
||||
}
|
||||
|
||||
|
||||
query("DELETE FROM ``bans`` WHERE `id` = " . (int)$ban_id) or error(db_error());
|
||||
|
||||
if (!$dont_rebuild) Vichan\Functions\Theme\rebuild_themes('bans');
|
||||
|
||||
if (!$dont_rebuild) rebuildThemes('bans');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
static public function new_ban($cloaked_mask, $reason, $length = false, $ban_board = false, $mod_id = false, $post = false) {
|
||||
$mask = uncloak_mask($cloaked_mask);
|
||||
|
||||
global $mod, $pdo, $board;
|
||||
|
||||
|
||||
if ($mod_id === false) {
|
||||
$mod_id = isset($mod['id']) ? $mod['id'] : -1;
|
||||
}
|
||||
|
||||
|
||||
$range = self::parse_range($mask);
|
||||
$mask = self::range_to_string($range);
|
||||
$cloaked_mask = cloak_mask($mask);
|
||||
|
||||
|
||||
$query = prepare("INSERT INTO ``bans`` VALUES (NULL, :ipstart, :ipend, :time, :expires, :board, :mod, :reason, 0, :post)");
|
||||
|
||||
|
||||
$query->bindValue(':ipstart', $range[0]);
|
||||
if ($range[1] !== false && $range[1] != $range[0])
|
||||
$query->bindValue(':ipend', $range[1]);
|
||||
else
|
||||
$query->bindValue(':ipend', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
$query->bindValue(':mod', $mod_id);
|
||||
$query->bindValue(':time', time());
|
||||
|
||||
|
||||
if ($reason !== '') {
|
||||
$reason = escape_markup_modifiers($reason);
|
||||
markup($reason);
|
||||
$query->bindValue(':reason', $reason);
|
||||
} else
|
||||
$query->bindValue(':reason', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
if ($length) {
|
||||
if (is_int($length) || ctype_digit($length)) {
|
||||
$length = time() + $length;
|
||||
@ -432,40 +282,31 @@ class Bans {
|
||||
} else {
|
||||
$query->bindValue(':expires', null, PDO::PARAM_NULL);
|
||||
}
|
||||
|
||||
|
||||
if ($ban_board)
|
||||
$query->bindValue(':board', $ban_board);
|
||||
else
|
||||
$query->bindValue(':board', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
if ($post) {
|
||||
if (!isset($board['uri']))
|
||||
openBoard($post['board']);
|
||||
|
||||
$post['board'] = $board['uri'];
|
||||
/*
|
||||
* The body can be so long to make the json longer than 64KBs, causing the query to fail.
|
||||
* Truncate it to a safe length (32KBs). It could probably be longer, but if the deleted body is THAT big
|
||||
* already, the likelihood of it being just assorted spam/garbage is about 101%.
|
||||
*/
|
||||
// We're on UTF-8 only, right...?
|
||||
$post['body'] = mb_strcut($post['body'], 0, 32768);
|
||||
|
||||
$query->bindValue(':post', json_encode($post));
|
||||
} else
|
||||
$query->bindValue(':post', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
$query->execute() or error(db_error($query));
|
||||
if (isset($mod['id']) && $mod['id'] == $mod_id) {
|
||||
modLog('Created a new ' .
|
||||
($length > 0 ? preg_replace('/^(\d+) (\w+?)s?$/', '$1-$2', until($length)) : 'permanent') .
|
||||
' ban on ' .
|
||||
($ban_board ? '/' . $ban_board . '/' : 'all boards') .
|
||||
' for ' .
|
||||
(filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$cloaked_mask\">$cloaked_mask</a>" : $cloaked_mask) .
|
||||
' (<small>#' . $pdo->lastInsertId() . '</small>)' .
|
||||
' with ' . ($reason ? 'reason: ' . utf8tohtml($reason) . '' : 'no reason'));
|
||||
}
|
||||
|
||||
$ban_len = $length > 0 ? preg_replace('/^(\d+) (\w+?)s?$/', '$1-$2', Format\until($length)) : 'permanent';
|
||||
$ban_board = $ban_board ? "/$ban_board/" : 'all boards';
|
||||
$ban_ip = filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$cloaked_mask\">$cloaked_mask</a>" : $cloaked_mask;
|
||||
$ban_id = $pdo->lastInsertId();
|
||||
$ban_reason = $reason ? 'reason: ' . utf8tohtml($reason) : 'no reason';
|
||||
|
||||
modLog("Created a new $ban_len ban on $ban_board for $ban_ip (<small># $ban_id </small>) with $ban_reason");
|
||||
|
||||
Vichan\Functions\Theme\rebuild_themes('bans');
|
||||
rebuildThemes('bans');
|
||||
|
||||
return $pdo->lastInsertId();
|
||||
}
|
||||
|
214
inc/cache.php
214
inc/cache.php
@ -4,89 +4,185 @@
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
use Vichan\Data\Driver\{CacheDriver, ApcuCacheDriver, ArrayCacheDriver, FsCacheDriver, MemcachedCacheDriver, NoneCacheDriver, RedisCacheDriver};
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class Cache {
|
||||
private static function buildCache(): CacheDriver {
|
||||
private static $cache;
|
||||
public static function init() {
|
||||
global $config;
|
||||
|
||||
|
||||
switch ($config['cache']['enabled']) {
|
||||
case 'memcached':
|
||||
return new MemcachedCacheDriver(
|
||||
$config['cache']['prefix'],
|
||||
$config['cache']['memcached']
|
||||
);
|
||||
self::$cache = new Memcached();
|
||||
self::$cache->addServers($config['cache']['memcached']);
|
||||
break;
|
||||
case 'redis':
|
||||
return new RedisCacheDriver(
|
||||
$config['cache']['prefix'],
|
||||
$config['cache']['redis'][0],
|
||||
$config['cache']['redis'][1],
|
||||
$config['cache']['redis'][2],
|
||||
$config['cache']['redis'][3]
|
||||
);
|
||||
case 'apcu':
|
||||
return new ApcuCacheDriver;
|
||||
case 'fs':
|
||||
return new FsCacheDriver(
|
||||
$config['cache']['prefix'],
|
||||
"tmp/cache/{$config['cache']['prefix']}",
|
||||
'.lock',
|
||||
$config['auto_maintenance'] ? 1000 : false
|
||||
);
|
||||
case 'none':
|
||||
return new NoneCacheDriver();
|
||||
self::$cache = new Redis();
|
||||
self::$cache->connect($config['cache']['redis'][0], $config['cache']['redis'][1]);
|
||||
if ($config['cache']['redis'][2]) {
|
||||
self::$cache->auth($config['cache']['redis'][2]);
|
||||
}
|
||||
self::$cache->select($config['cache']['redis'][3]) or die('cache select failure');
|
||||
break;
|
||||
case 'php':
|
||||
default:
|
||||
return new ArrayCacheDriver();
|
||||
self::$cache = array();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public static function getCache(): CacheDriver {
|
||||
static $cache;
|
||||
return $cache ??= self::buildCache();
|
||||
}
|
||||
|
||||
public static function get($key) {
|
||||
global $config, $debug;
|
||||
|
||||
$ret = self::getCache()->get($key);
|
||||
if ($ret === null) {
|
||||
$ret = false;
|
||||
|
||||
$key = $config['cache']['prefix'] . $key;
|
||||
|
||||
$data = false;
|
||||
switch ($config['cache']['enabled']) {
|
||||
case 'memcached':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
$data = self::$cache->get($key);
|
||||
break;
|
||||
case 'apc':
|
||||
$data = apc_fetch($key);
|
||||
break;
|
||||
case 'apcu':
|
||||
$data = apcu_fetch($key);
|
||||
break;
|
||||
case 'xcache':
|
||||
$data = xcache_get($key);
|
||||
break;
|
||||
case 'php':
|
||||
$data = isset(self::$cache[$key]) ? self::$cache[$key] : false;
|
||||
break;
|
||||
case 'fs':
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
if (!file_exists('tmp/cache/'.$key)) {
|
||||
$data = false;
|
||||
}
|
||||
else {
|
||||
$data = file_get_contents('tmp/cache/'.$key);
|
||||
$data = json_decode($data, true);
|
||||
}
|
||||
break;
|
||||
case 'redis':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
$data = json_decode(self::$cache->get($key), true);
|
||||
break;
|
||||
}
|
||||
|
||||
if ($config['debug']) {
|
||||
$debug['cached'][] = $config['cache']['prefix'] . $key . ($ret === false ? ' (miss)' : ' (hit)');
|
||||
}
|
||||
|
||||
return $ret;
|
||||
|
||||
if ($config['debug'])
|
||||
$debug['cached'][] = $key . ($data === false ? ' (miss)' : ' (hit)');
|
||||
|
||||
return $data;
|
||||
}
|
||||
public static function set($key, $value, $expires = false) {
|
||||
global $config, $debug;
|
||||
|
||||
if (!$expires) {
|
||||
|
||||
$key = $config['cache']['prefix'] . $key;
|
||||
|
||||
if (!$expires)
|
||||
$expires = $config['cache']['timeout'];
|
||||
|
||||
switch ($config['cache']['enabled']) {
|
||||
case 'memcached':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
self::$cache->set($key, $value, $expires);
|
||||
break;
|
||||
case 'redis':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
self::$cache->setex($key, $expires, json_encode($value));
|
||||
break;
|
||||
case 'apc':
|
||||
apc_store($key, $value, $expires);
|
||||
break;
|
||||
case 'apcu':
|
||||
apcu_store($key, $value, $expires);
|
||||
break;
|
||||
case 'xcache':
|
||||
xcache_set($key, $value, $expires);
|
||||
break;
|
||||
case 'fs':
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
file_put_contents('tmp/cache/'.$key, json_encode($value));
|
||||
break;
|
||||
case 'php':
|
||||
self::$cache[$key] = $value;
|
||||
break;
|
||||
}
|
||||
|
||||
self::getCache()->set($key, $value, $expires);
|
||||
|
||||
if ($config['debug']) {
|
||||
$debug['cached'][] = $config['cache']['prefix'] . $key . ' (set)';
|
||||
}
|
||||
|
||||
if ($config['debug'])
|
||||
$debug['cached'][] = $key . ' (set)';
|
||||
}
|
||||
public static function delete($key) {
|
||||
global $config, $debug;
|
||||
|
||||
self::getCache()->delete($key);
|
||||
|
||||
if ($config['debug']) {
|
||||
$debug['cached'][] = $config['cache']['prefix'] . $key . ' (deleted)';
|
||||
|
||||
$key = $config['cache']['prefix'] . $key;
|
||||
|
||||
switch ($config['cache']['enabled']) {
|
||||
case 'memcached':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
self::$cache->delete($key);
|
||||
break;
|
||||
case 'redis':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
self::$cache->del($key);
|
||||
break;
|
||||
case 'apc':
|
||||
apc_delete($key);
|
||||
break;
|
||||
case 'apcu':
|
||||
apcu_delete($key);
|
||||
break;
|
||||
case 'xcache':
|
||||
xcache_unset($key);
|
||||
break;
|
||||
case 'fs':
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
@unlink('tmp/cache/'.$key);
|
||||
break;
|
||||
case 'php':
|
||||
unset(self::$cache[$key]);
|
||||
break;
|
||||
}
|
||||
|
||||
if ($config['debug'])
|
||||
$debug['cached'][] = $key . ' (deleted)';
|
||||
}
|
||||
public static function flush() {
|
||||
self::getCache()->flush();
|
||||
global $config;
|
||||
|
||||
switch ($config['cache']['enabled']) {
|
||||
case 'memcached':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
return self::$cache->flush();
|
||||
case 'apc':
|
||||
return apc_clear_cache('user');
|
||||
case 'apcu':
|
||||
return apcu_clear_cache('user');
|
||||
case 'php':
|
||||
self::$cache = array();
|
||||
break;
|
||||
case 'fs':
|
||||
$files = glob('tmp/cache/*');
|
||||
foreach ($files as $file) {
|
||||
unlink($file);
|
||||
}
|
||||
break;
|
||||
case 'redis':
|
||||
if (!self::$cache)
|
||||
self::init();
|
||||
return self::$cache->flushDB();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -41,7 +41,7 @@ class CzaksCaptcha {
|
||||
function mutate_sizes() {
|
||||
foreach ($this->content as &$v) {
|
||||
if (!isset ($v['font-size']))
|
||||
$v['font-size'] = rand(intval($this->height/3) - 4, intval($this->height/3) + 8);
|
||||
$v['font-size'] = rand($this->height/3 - 4, $this->height/3 + 8);
|
||||
}
|
||||
}
|
||||
function mutate_positions() {
|
||||
|
9
inc/captcha/dbschema.sql
Normal file
9
inc/captcha/dbschema.sql
Normal file
@ -0,0 +1,9 @@
|
||||
SET NAMES utf8;
|
||||
|
||||
CREATE TABLE `captchas` (
|
||||
`cookie` VARCHAR(50),
|
||||
`extra` VARCHAR(200),
|
||||
`text` VARCHAR(255),
|
||||
`created_at` INT(11),
|
||||
PRIMARY KEY (cookie, extra)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
@ -1,8 +1,10 @@
|
||||
I integrated this from: https://github.com/ctrlcctrlv/infinity/commit/62a6dac022cb338f7b719d0c35a64ab3efc64658
|
||||
|
||||
<strike>First import the captcha/dbschema.sql in your database</strike> it is no longer required.
|
||||
|
||||
In inc/captcha/config.php change the database_name database_user database_password to your own settings.
|
||||
|
||||
Add js/captcha.js in your secrets.php or config.php
|
||||
Add js/captcha.js in your secrets.php or config.php
|
||||
|
||||
Go to Line 305 in the /inc/config file and copy the settings in instance config, while changing the url to your website.
|
||||
Go to the line beneath it if you only want to enable it when posting a new thread.
|
||||
|
915
inc/config.php
915
inc/config.php
File diff suppressed because it is too large
Load Diff
@ -1,91 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan;
|
||||
|
||||
use Vichan\Data\Driver\{CacheDriver, HttpDriver, ErrorLogLogDriver, FileLogDriver, LogDriver, StderrLogDriver, SyslogLogDriver};
|
||||
use Vichan\Service\HCaptchaQuery;
|
||||
use Vichan\Service\NativeCaptchaQuery;
|
||||
use Vichan\Service\ReCaptchaQuery;
|
||||
use Vichan\Service\RemoteCaptchaQuery;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
class Context {
|
||||
private array $definitions;
|
||||
|
||||
public function __construct(array $definitions) {
|
||||
$this->definitions = $definitions;
|
||||
}
|
||||
|
||||
public function get(string $name){
|
||||
if (!isset($this->definitions[$name])) {
|
||||
throw new \RuntimeException("Could not find a dependency named $name");
|
||||
}
|
||||
|
||||
$ret = $this->definitions[$name];
|
||||
if (is_callable($ret) && !is_string($ret) && !is_array($ret)) {
|
||||
$ret = $ret($this);
|
||||
$this->definitions[$name] = $ret;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
}
|
||||
|
||||
function build_context(array $config): Context {
|
||||
return new Context([
|
||||
'config' => $config,
|
||||
LogDriver::class => function($c) {
|
||||
$config = $c->get('config');
|
||||
|
||||
$name = $config['log_system']['name'];
|
||||
$level = $config['debug'] ? LogDriver::DEBUG : LogDriver::NOTICE;
|
||||
$backend = $config['log_system']['type'];
|
||||
|
||||
// Check 'syslog' for backwards compatibility.
|
||||
if ((isset($config['syslog']) && $config['syslog']) || $backend === 'syslog') {
|
||||
return new SyslogLogDriver($name, $level, $this->config['log_system']['syslog_stderr']);
|
||||
} elseif ($backend === 'file') {
|
||||
return new FileLogDriver($name, $level, $this->config['log_system']['file_path']);
|
||||
} elseif ($backend === 'stderr') {
|
||||
return new StderrLogDriver($name, $level);
|
||||
} else {
|
||||
return new ErrorLogLogDriver($name, $level);
|
||||
}
|
||||
},
|
||||
HttpDriver::class => function($c) {
|
||||
$config = $c->get('config');
|
||||
return new HttpDriver($config['upload_by_url_timeout'], $config['max_filesize']);
|
||||
},
|
||||
RemoteCaptchaQuery::class => function($c) {
|
||||
$config = $c->get('config');
|
||||
$http = $c->get(HttpDriver::class);
|
||||
switch ($config['captcha']['provider']) {
|
||||
case 'recaptcha':
|
||||
return new ReCaptchaQuery($http, $config['captcha']['recaptcha']['secret']);
|
||||
case 'hcaptcha':
|
||||
return new HCaptchaQuery(
|
||||
$http,
|
||||
$config['captcha']['hcaptcha']['secret'],
|
||||
$config['captcha']['hcaptcha']['sitekey']
|
||||
);
|
||||
default:
|
||||
throw new \RuntimeException('No remote captcha service available');
|
||||
}
|
||||
},
|
||||
NativeCaptchaQuery::class => function($c) {
|
||||
$config = $c->get('config');
|
||||
if ($config['captcha']['provider'] !== 'native') {
|
||||
throw new \RuntimeException('No native captcha service available');
|
||||
}
|
||||
return new NativeCaptchaQuery(
|
||||
$c->get(HttpDriver::class),
|
||||
$config['domain'],
|
||||
$config['captcha']['native']['provider_check'],
|
||||
$config['captcha']['native']['extra']
|
||||
);
|
||||
},
|
||||
CacheDriver::class => function($c) {
|
||||
// Use the global for backwards compatibility.
|
||||
return \cache::getCache();
|
||||
}
|
||||
]);
|
||||
}
|
@ -85,24 +85,24 @@ function sb_api($b) { global $config, $build_pages;
|
||||
}
|
||||
|
||||
function sb_ukko() {
|
||||
Vichan\Functions\Theme\rebuild_theme("ukko", "post-thread");
|
||||
rebuildTheme("ukko", "post-thread");
|
||||
return true;
|
||||
}
|
||||
|
||||
function sb_catalog($b) {
|
||||
if (!openBoard($b)) return false;
|
||||
|
||||
Vichan\Functions\Theme\rebuild_theme("catalog", "post-thread", $b);
|
||||
rebuildTheme("catalog", "post-thread", $b);
|
||||
return true;
|
||||
}
|
||||
|
||||
function sb_recent() {
|
||||
Vichan\Functions\Theme\rebuild_theme("recent", "post-thread");
|
||||
rebuildTheme("recent", "post-thread");
|
||||
return true;
|
||||
}
|
||||
|
||||
function sb_sitemap() {
|
||||
Vichan\Functions\Theme\rebuild_theme("sitemap", "all");
|
||||
rebuildTheme("sitemap", "all");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
194
inc/display.php
194
inc/display.php
@ -9,7 +9,7 @@ if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/*
|
||||
/*
|
||||
joaoptm78@gmail.com
|
||||
http://www.php.net/manual/en/function.filesize.php#100097
|
||||
*/
|
||||
@ -21,7 +21,7 @@ function format_bytes($size) {
|
||||
|
||||
function doBoardListPart($list, $root, &$boards) {
|
||||
global $config;
|
||||
|
||||
|
||||
$body = '';
|
||||
foreach ($list as $key => $board) {
|
||||
if (is_array($board))
|
||||
@ -34,21 +34,21 @@ function doBoardListPart($list, $root, &$boards) {
|
||||
if (isset ($boards[$board])) {
|
||||
$title = ' title="'.$boards[$board].'"';
|
||||
}
|
||||
|
||||
|
||||
$body .= ' <a href="' . $root . $board . '/' . $config['file_index'] . '"'.$title.'>' . $board . '</a> /';
|
||||
}
|
||||
}
|
||||
}
|
||||
$body = preg_replace('/\/$/', '', $body);
|
||||
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
function createBoardlist($mod=false) {
|
||||
global $config;
|
||||
|
||||
|
||||
if (!isset($config['boards'])) return array('top'=>'','bottom'=>'');
|
||||
|
||||
|
||||
$xboards = listBoards();
|
||||
$boards = array();
|
||||
foreach ($xboards as $val) {
|
||||
@ -59,26 +59,26 @@ function createBoardlist($mod=false) {
|
||||
|
||||
if ($config['boardlist_wrap_bracket'] && !preg_match('/\] $/', $body))
|
||||
$body = '[' . $body . ']';
|
||||
|
||||
|
||||
$body = trim($body);
|
||||
|
||||
// Message compact-boardlist.js faster, so that page looks less ugly during loading
|
||||
$top = "<script type='text/javascript'>if (typeof do_boardlist != 'undefined') do_boardlist();</script>";
|
||||
|
||||
|
||||
return array(
|
||||
'top' => '<div class="boardlist">' . $body . '</div>' . $top,
|
||||
'bottom' => '<div class="boardlist bottom">' . $body . '</div>'
|
||||
);
|
||||
}
|
||||
|
||||
function error($message, $priority = true, $debug_stuff = []) {
|
||||
function error($message, $priority = true, $debug_stuff = false) {
|
||||
global $board, $mod, $config, $db_error;
|
||||
|
||||
|
||||
if ($config['syslog'] && $priority !== false) {
|
||||
// Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant.
|
||||
_syslog($priority !== true ? $priority : LOG_NOTICE, $message);
|
||||
}
|
||||
|
||||
|
||||
if (defined('STDIN')) {
|
||||
// Running from CLI
|
||||
echo('Error: ' . $message . "\n");
|
||||
@ -113,7 +113,7 @@ function error($message, $priority = true, $debug_stuff = []) {
|
||||
};
|
||||
|
||||
|
||||
if ($debug_stuff)
|
||||
if ($debug_stuff)
|
||||
$debug_stuff = array_filter($debug_stuff, $debug_callback);
|
||||
|
||||
die(Element($config['file_page_template'], array(
|
||||
@ -132,7 +132,7 @@ function error($message, $priority = true, $debug_stuff = []) {
|
||||
|
||||
function loginForm($error=false, $username=false, $redirect=false) {
|
||||
global $config;
|
||||
|
||||
|
||||
die(Element($config['file_page_template'], array(
|
||||
'index' => $config['root'],
|
||||
'title' => _('Login'),
|
||||
@ -149,34 +149,34 @@ function loginForm($error=false, $username=false, $redirect=false) {
|
||||
|
||||
function pm_snippet($body, $len=null) {
|
||||
global $config;
|
||||
|
||||
|
||||
if (!isset($len))
|
||||
$len = &$config['mod']['snippet_length'];
|
||||
|
||||
|
||||
// Replace line breaks with some whitespace
|
||||
$body = preg_replace('@<br/?>@i', ' ', $body);
|
||||
|
||||
|
||||
// Strip tags
|
||||
$body = strip_tags($body);
|
||||
|
||||
|
||||
// Unescape HTML characters, to avoid splitting them in half
|
||||
$body = html_entity_decode($body, ENT_COMPAT, 'UTF-8');
|
||||
|
||||
|
||||
// calculate strlen() so we can add "..." after if needed
|
||||
$strlen = mb_strlen($body);
|
||||
|
||||
|
||||
$body = mb_substr($body, 0, $len);
|
||||
|
||||
|
||||
// Re-escape the characters.
|
||||
return '<em>' . utf8tohtml($body) . ($strlen > $len ? '…' : '') . '</em>';
|
||||
}
|
||||
|
||||
function capcode($cap) {
|
||||
global $config;
|
||||
|
||||
|
||||
if (!$cap)
|
||||
return false;
|
||||
|
||||
|
||||
$capcode = array();
|
||||
if (isset($config['custom_capcode'][$cap])) {
|
||||
if (is_array($config['custom_capcode'][$cap])) {
|
||||
@ -191,59 +191,59 @@ function capcode($cap) {
|
||||
} else {
|
||||
$capcode['cap'] = sprintf($config['capcode'], $cap);
|
||||
}
|
||||
|
||||
|
||||
return $capcode;
|
||||
}
|
||||
|
||||
function truncate($body, $url, $max_lines = false, $max_chars = false) {
|
||||
global $config;
|
||||
|
||||
|
||||
if ($max_lines === false)
|
||||
$max_lines = $config['body_truncate'];
|
||||
if ($max_chars === false)
|
||||
$max_chars = $config['body_truncate_char'];
|
||||
|
||||
|
||||
// We don't want to risk truncating in the middle of an HTML comment.
|
||||
// It's easiest just to remove them all first.
|
||||
$body = preg_replace('/<!--.*?-->/s', '', $body);
|
||||
|
||||
|
||||
$original_body = $body;
|
||||
|
||||
|
||||
$lines = substr_count($body, '<br/>');
|
||||
|
||||
|
||||
// Limit line count
|
||||
if ($lines > $max_lines) {
|
||||
if (preg_match('/(((.*?)<br\/>){' . $max_lines . '})/', $body, $m))
|
||||
$body = $m[0];
|
||||
}
|
||||
|
||||
|
||||
$body = mb_substr($body, 0, $max_chars);
|
||||
|
||||
|
||||
if ($body != $original_body) {
|
||||
// Remove any corrupt tags at the end
|
||||
$body = preg_replace('/<([\w]+)?([^>]*)?$/', '', $body);
|
||||
|
||||
|
||||
// Open tags
|
||||
if (preg_match_all('/<([\w]+)[^>]*>/', $body, $open_tags)) {
|
||||
|
||||
|
||||
$tags = array();
|
||||
for ($x=0;$x<count($open_tags[0]);$x++) {
|
||||
if (!preg_match('/\/(\s+)?>$/', $open_tags[0][$x]))
|
||||
$tags[] = $open_tags[1][$x];
|
||||
}
|
||||
|
||||
|
||||
// List successfully closed tags
|
||||
if (preg_match_all('/(<\/([\w]+))>/', $body, $closed_tags)) {
|
||||
for ($x=0;$x<count($closed_tags[0]);$x++) {
|
||||
unset($tags[array_search($closed_tags[2][$x], $tags)]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// remove broken HTML entity at the end (if existent)
|
||||
$body = preg_replace('/&[^;]+$/', '', $body);
|
||||
|
||||
|
||||
$tags_no_close_needed = array("colgroup", "dd", "dt", "li", "optgroup", "option", "p", "tbody", "td", "tfoot", "th", "thead", "tr", "br", "img");
|
||||
|
||||
|
||||
// Close any open tags
|
||||
foreach ($tags as &$tag) {
|
||||
if (!in_array($tag, $tags_no_close_needed))
|
||||
@ -253,10 +253,10 @@ function truncate($body, $url, $max_lines = false, $max_chars = false) {
|
||||
// remove broken HTML entity at the end (if existent)
|
||||
$body = preg_replace('/&[^;]*$/', '', $body);
|
||||
}
|
||||
|
||||
|
||||
$body .= '<span class="toolong">'.sprintf(_('Post too long. Click <a href="%s">here</a> to view the full text.'), $url).'</span>';
|
||||
}
|
||||
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
@ -266,21 +266,21 @@ function bidi_cleanup($data) {
|
||||
|
||||
$explicits = '\xE2\x80\xAA|\xE2\x80\xAB|\xE2\x80\xAD|\xE2\x80\xAE';
|
||||
$pdf = '\xE2\x80\xAC';
|
||||
|
||||
|
||||
preg_match_all("!$explicits!", $data, $m1, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
|
||||
preg_match_all("!$pdf!", $data, $m2, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
|
||||
|
||||
|
||||
if (count($m1) || count($m2)){
|
||||
|
||||
|
||||
$p = array();
|
||||
foreach ($m1 as $m){ $p[$m[0][1]] = 'push'; }
|
||||
foreach ($m2 as $m){ $p[$m[0][1]] = 'pop'; }
|
||||
ksort($p);
|
||||
|
||||
|
||||
$offset = 0;
|
||||
$stack = 0;
|
||||
foreach ($p as $pos => $type){
|
||||
|
||||
|
||||
if ($type == 'push'){
|
||||
$stack++;
|
||||
}else{
|
||||
@ -294,15 +294,15 @@ function bidi_cleanup($data) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# now add some pops if your stack is bigger than 0
|
||||
for ($i=0; $i<$stack; $i++){
|
||||
$data .= "\xE2\x80\xAC";
|
||||
}
|
||||
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
@ -317,24 +317,24 @@ function secure_link($href) {
|
||||
|
||||
function embed_html($link) {
|
||||
global $config;
|
||||
|
||||
|
||||
foreach ($config['embedding'] as $embed) {
|
||||
if ($html = preg_replace($embed[0], $embed[1], $link)) {
|
||||
if ($html == $link)
|
||||
continue; // Nope
|
||||
|
||||
|
||||
$html = str_replace('%%tb_width%%', $config['embed_width'], $html);
|
||||
$html = str_replace('%%tb_height%%', $config['embed_height'], $html);
|
||||
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if ($link[0] == '<') {
|
||||
// Prior to v0.9.6-dev-8, HTML code for embedding was stored in the database instead of the link.
|
||||
return $link;
|
||||
}
|
||||
|
||||
|
||||
return 'Embedding error.';
|
||||
}
|
||||
|
||||
@ -343,46 +343,29 @@ class Post {
|
||||
global $config;
|
||||
if (!isset($root))
|
||||
$root = &$config['root'];
|
||||
|
||||
|
||||
foreach ($post as $key => $value) {
|
||||
$this->{$key} = $value;
|
||||
}
|
||||
|
||||
if (isset($this->files) && $this->files) {
|
||||
$this->files = is_string($this->files) ? json_decode($this->files) : $this->files;
|
||||
// Compatibility for posts before individual file hashing
|
||||
foreach ($this->files as $i => &$file) {
|
||||
if (empty($file)) {
|
||||
unset($this->files[$i]);
|
||||
continue;
|
||||
}
|
||||
if (is_array($file)) {
|
||||
if (!isset($file['hash'])) {
|
||||
$file['hash'] = $this->filehash;
|
||||
}
|
||||
} else if (is_object($file)) {
|
||||
if (!isset($file->hash)) {
|
||||
$file->hash = $this->filehash;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($this->files) && $this->files)
|
||||
$this->files = @json_decode($this->files);
|
||||
|
||||
$this->subject = utf8tohtml($this->subject);
|
||||
$this->name = utf8tohtml($this->name);
|
||||
$this->mod = $mod;
|
||||
$this->root = $root;
|
||||
|
||||
|
||||
if ($this->embed)
|
||||
$this->embed = embed_html($this->embed);
|
||||
|
||||
|
||||
$this->modifiers = extract_modifiers($this->body_nomarkup);
|
||||
|
||||
|
||||
if ($config['always_regenerate_markup']) {
|
||||
$this->body = $this->body_nomarkup;
|
||||
markup($this->body);
|
||||
}
|
||||
|
||||
|
||||
if ($this->mod)
|
||||
// Fix internal links
|
||||
// Very complicated regex
|
||||
@ -394,25 +377,14 @@ class Post {
|
||||
}
|
||||
public function link($pre = '', $page = false) {
|
||||
global $config, $board;
|
||||
|
||||
|
||||
return $this->root . $board['dir'] . $config['dir']['res'] . link_for((array)$this, $page == '50') . '#' . $pre . $this->id;
|
||||
}
|
||||
|
||||
|
||||
public function build($index=false) {
|
||||
global $board, $config;
|
||||
|
||||
$options = [
|
||||
'config' => $config,
|
||||
'board' => $board,
|
||||
'post' => &$this,
|
||||
'index' => $index,
|
||||
'mod' => $this->mod
|
||||
];
|
||||
if ($this->mod) {
|
||||
$options['pm'] = create_pm_header();
|
||||
}
|
||||
|
||||
return Element($config['file_post_reply'], $options);
|
||||
|
||||
return Element($config['file_post_reply'], array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index, 'mod' => $this->mod));
|
||||
}
|
||||
};
|
||||
|
||||
@ -421,14 +393,14 @@ class Thread {
|
||||
global $config;
|
||||
if (!isset($root))
|
||||
$root = &$config['root'];
|
||||
|
||||
|
||||
foreach ($post as $key => $value) {
|
||||
$this->{$key} = $value;
|
||||
}
|
||||
|
||||
|
||||
if (isset($this->files))
|
||||
$this->files = is_string($this->files) ? json_decode($this->files) : $this->files;
|
||||
|
||||
$this->files = @json_decode($this->files);
|
||||
|
||||
$this->subject = utf8tohtml($this->subject);
|
||||
$this->name = utf8tohtml($this->name);
|
||||
$this->mod = $mod;
|
||||
@ -438,17 +410,17 @@ class Thread {
|
||||
$this->posts = array();
|
||||
$this->omitted = 0;
|
||||
$this->omitted_images = 0;
|
||||
|
||||
|
||||
if ($this->embed)
|
||||
$this->embed = embed_html($this->embed);
|
||||
|
||||
|
||||
$this->modifiers = extract_modifiers($this->body_nomarkup);
|
||||
|
||||
|
||||
if ($config['always_regenerate_markup']) {
|
||||
$this->body = $this->body_nomarkup;
|
||||
markup($this->body);
|
||||
}
|
||||
|
||||
|
||||
if ($this->mod)
|
||||
// Fix internal links
|
||||
// Very complicated regex
|
||||
@ -460,7 +432,7 @@ class Thread {
|
||||
}
|
||||
public function link($pre = '', $page = false) {
|
||||
global $config, $board;
|
||||
|
||||
|
||||
return $this->root . $board['dir'] . $config['dir']['res'] . link_for((array)$this, $page == '50') . '#' . $pre . $this->id;
|
||||
}
|
||||
public function add(Post $post) {
|
||||
@ -471,27 +443,15 @@ class Thread {
|
||||
}
|
||||
public function build($index=false, $isnoko50=false) {
|
||||
global $board, $config, $debug;
|
||||
|
||||
|
||||
$hasnoko50 = $this->postCount() >= $config['noko50_min'];
|
||||
|
||||
|
||||
event('show-thread', $this);
|
||||
|
||||
$options = [
|
||||
'config' => $config,
|
||||
'board' => $board,
|
||||
'post' => &$this,
|
||||
'index' => $index,
|
||||
'hasnoko50' => $hasnoko50,
|
||||
'isnoko50' => $isnoko50,
|
||||
'mod' => $this->mod
|
||||
];
|
||||
if ($this->mod) {
|
||||
$options['pm'] = create_pm_header();
|
||||
}
|
||||
|
||||
$file = ($index && $config['file_board']) ? $config['file_post_thread_fileboard'] : $config['file_post_thread'];
|
||||
$built = Element($file, $options);
|
||||
|
||||
$built = Element($file, array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index, 'hasnoko50' => $hasnoko50, 'isnoko50' => $isnoko50, 'mod' => $this->mod));
|
||||
|
||||
return $built;
|
||||
}
|
||||
};
|
||||
|
||||
|
165
inc/filters.php
165
inc/filters.php
@ -10,63 +10,54 @@ class Filter {
|
||||
public $flood_check;
|
||||
private $condition;
|
||||
private $post;
|
||||
|
||||
|
||||
|
||||
public function __construct(array $arr) {
|
||||
foreach ($arr as $key => $value) {
|
||||
$this->$key = $value;
|
||||
}
|
||||
foreach ($arr as $key => $value)
|
||||
$this->$key = $value;
|
||||
}
|
||||
|
||||
|
||||
public function match($condition, $match) {
|
||||
$condition = strtolower($condition);
|
||||
$post = &$this->post;
|
||||
|
||||
$post = &$this->post;
|
||||
|
||||
switch($condition) {
|
||||
case 'custom':
|
||||
if (!is_callable($match)) {
|
||||
if (!is_callable($match))
|
||||
error('Custom condition for filter is not callable!');
|
||||
}
|
||||
return $match($post);
|
||||
case 'flood-match':
|
||||
if (!is_array($match)) {
|
||||
if (!is_array($match))
|
||||
error('Filter condition "flood-match" must be an array.');
|
||||
}
|
||||
|
||||
|
||||
// Filter out "flood" table entries which do not match this filter.
|
||||
|
||||
|
||||
$flood_check_matched = array();
|
||||
|
||||
|
||||
foreach ($this->flood_check as $flood_post) {
|
||||
foreach ($match as $flood_match_arg) {
|
||||
switch ($flood_match_arg) {
|
||||
case 'ip':
|
||||
if ($flood_post['ip'] != $_SERVER['REMOTE_ADDR']) {
|
||||
if ($flood_post['ip'] != $_SERVER['REMOTE_ADDR'])
|
||||
continue 3;
|
||||
}
|
||||
break;
|
||||
case 'body':
|
||||
if ($flood_post['posthash'] != make_comment_hex($post['body_nomarkup'])) {
|
||||
if ($flood_post['posthash'] != make_comment_hex($post['body_nomarkup']))
|
||||
continue 3;
|
||||
}
|
||||
break;
|
||||
case 'file':
|
||||
if (!isset($post['filehash'])) {
|
||||
if (!isset($post['filehash']))
|
||||
return false;
|
||||
}
|
||||
if ($flood_post['filehash'] != $post['filehash']) {
|
||||
if ($flood_post['filehash'] != $post['filehash'])
|
||||
continue 3;
|
||||
}
|
||||
break;
|
||||
case 'board':
|
||||
if ($flood_post['board'] != $post['board']) {
|
||||
if ($flood_post['board'] != $post['board'])
|
||||
continue 3;
|
||||
}
|
||||
break;
|
||||
case 'isreply':
|
||||
if ($flood_post['isreply'] == $post['op']) {
|
||||
if ($flood_post['isreply'] == $post['op'])
|
||||
continue 3;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
error('Invalid filter flood condition: ' . $flood_match_arg);
|
||||
@ -74,8 +65,9 @@ class Filter {
|
||||
}
|
||||
$flood_check_matched[] = $flood_post;
|
||||
}
|
||||
|
||||
|
||||
$this->flood_check = $flood_check_matched;
|
||||
|
||||
return !empty($this->flood_check);
|
||||
case 'flood-time':
|
||||
foreach ($this->flood_check as $flood_post) {
|
||||
@ -105,9 +97,8 @@ class Filter {
|
||||
case 'filehash':
|
||||
return $match === $post['filehash'];
|
||||
case 'filename':
|
||||
if (!$post['files']) {
|
||||
if (!$post['files'])
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($post['files'] as $file) {
|
||||
if (preg_match($match, $file['filename'])) {
|
||||
@ -116,9 +107,8 @@ class Filter {
|
||||
}
|
||||
return false;
|
||||
case 'extension':
|
||||
if (!$post['files']) {
|
||||
if (!$post['files'])
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($post['files'] as $file) {
|
||||
if (preg_match($match, $file['extension'])) {
|
||||
@ -136,75 +126,60 @@ class Filter {
|
||||
return $post['board'] == $match;
|
||||
case 'password':
|
||||
return $post['password'] == $match;
|
||||
case 'unshorten':
|
||||
$extracted_urls = get_urls($post['body_nomarkup']);
|
||||
foreach ($extracted_urls as $url) {
|
||||
if (preg_match($match, trace_url($url))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
default:
|
||||
error('Unknown filter condition: ' . $condition);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function action() {
|
||||
global $board;
|
||||
|
||||
$this->add_note = isset($this->add_note) ? $this->add_note : false;
|
||||
if ($this->add_note) {
|
||||
$query = prepare('INSERT INTO ``ip_notes`` VALUES (NULL, :ip, :mod, :time, :body)');
|
||||
$query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
|
||||
$query->bindValue(':mod', -1);
|
||||
$query->bindValue(':time', time());
|
||||
$query->bindValue(':body', "Autoban message: ".$this->post['body']);
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
if (isset($this->action)) {
|
||||
switch($this->action) {
|
||||
case 'reject':
|
||||
error(isset($this->message) ? $this->message : 'Posting throttled by filter.');
|
||||
case 'ban':
|
||||
if (!isset($this->reason)) {
|
||||
error('The ban action requires a reason.');
|
||||
}
|
||||
$query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
|
||||
$query->bindValue(':mod', -1);
|
||||
$query->bindValue(':time', time());
|
||||
$query->bindValue(':body', "Autoban message: ".$this->post['body']);
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
if (isset ($this->action)) switch($this->action) {
|
||||
case 'reject':
|
||||
error(isset($this->message) ? $this->message : 'Posting throttled by filter.');
|
||||
case 'ban':
|
||||
if (!isset($this->reason))
|
||||
error('The ban action requires a reason.');
|
||||
|
||||
$this->expires = isset($this->expires) ? $this->expires : false;
|
||||
$this->reject = isset($this->reject) ? $this->reject : true;
|
||||
$this->all_boards = isset($this->all_boards) ? $this->all_boards : false;
|
||||
|
||||
Bans::new_ban($_SERVER['REMOTE_ADDR'], $this->reason, $this->expires, $this->all_boards ? false : $board['uri'], -1);
|
||||
|
||||
$this->expires = isset($this->expires) ? $this->expires : false;
|
||||
$this->reject = isset($this->reject) ? $this->reject : true;
|
||||
$this->all_boards = isset($this->all_boards) ? $this->all_boards : false;
|
||||
|
||||
Bans::new_ban($_SERVER['REMOTE_ADDR'], $this->reason, $this->expires, $this->all_boards ? false : $board['uri'], -1);
|
||||
|
||||
if ($this->reject) {
|
||||
if (isset($this->message)) {
|
||||
error($message);
|
||||
}
|
||||
|
||||
checkBan($board['uri']);
|
||||
exit;
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
error('Unknown filter action: ' . $this->action);
|
||||
}
|
||||
if ($this->reject) {
|
||||
if (isset($this->message))
|
||||
error($message);
|
||||
|
||||
checkBan($board['uri']);
|
||||
exit;
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
error('Unknown filter action: ' . $this->action);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function check(array $post) {
|
||||
$this->post = $post;
|
||||
foreach ($this->condition as $condition => $value) {
|
||||
if ($condition[0] == '!') {
|
||||
$NOT = true;
|
||||
$condition = substr($condition, 1);
|
||||
} else {
|
||||
$NOT = false;
|
||||
}
|
||||
|
||||
if ($this->match($condition, $value) == $NOT) {
|
||||
} else $NOT = false;
|
||||
|
||||
if ($this->match($condition, $value) == $NOT)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -212,41 +187,39 @@ class Filter {
|
||||
|
||||
function purge_flood_table() {
|
||||
global $config;
|
||||
|
||||
|
||||
// Determine how long we need to keep a cache of posts for flood prevention. Unfortunately, it is not
|
||||
// aware of flood filters in other board configurations. You can solve this problem by settings the
|
||||
// config variable $config['flood_cache'] (seconds).
|
||||
|
||||
if ($config['flood_cache'] != -1) {
|
||||
|
||||
if (isset($config['flood_cache'])) {
|
||||
$max_time = &$config['flood_cache'];
|
||||
} else {
|
||||
$max_time = 0;
|
||||
foreach ($config['filters'] as $filter) {
|
||||
if (isset($filter['condition']['flood-time'])) {
|
||||
if (isset($filter['condition']['flood-time']))
|
||||
$max_time = max($max_time, $filter['condition']['flood-time']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$time = time() - $max_time;
|
||||
|
||||
|
||||
query("DELETE FROM ``flood`` WHERE `time` < $time") or error(db_error());
|
||||
}
|
||||
|
||||
function do_filters(array $post) {
|
||||
global $config;
|
||||
|
||||
if (!isset($config['filters']) || empty($config['filters'])) {
|
||||
|
||||
if (!isset($config['filters']) || empty($config['filters']))
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
foreach ($config['filters'] as $filter) {
|
||||
if (isset($filter['condition']['flood-match'])) {
|
||||
$has_flood = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (isset($has_flood)) {
|
||||
if ($post['has_file']) {
|
||||
$query = prepare("SELECT * FROM ``flood`` WHERE `ip` = :ip OR `posthash` = :posthash OR `filehash` = :filehash");
|
||||
@ -263,14 +236,14 @@ function do_filters(array $post) {
|
||||
} else {
|
||||
$flood_check = false;
|
||||
}
|
||||
|
||||
|
||||
foreach ($config['filters'] as $filter_array) {
|
||||
$filter = new Filter($filter_array);
|
||||
$filter->flood_check = $flood_check;
|
||||
if ($filter->check($post)) {
|
||||
if ($filter->check($post))
|
||||
$filter->action();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
purge_flood_table();
|
||||
}
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,114 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Dice;
|
||||
|
||||
function _get_or_default_int(array $arr, int $index, int $default) {
|
||||
return (isset($arr[$index]) && is_numeric($arr[$index])) ? (int)$arr[$index] : $default;
|
||||
}
|
||||
|
||||
|
||||
/* Die rolling:
|
||||
* If "dice XdY+/-Z" is in the email field (where X or +/-Z may be
|
||||
* missing), X Y-sided dice are rolled and summed, with the modifier Z
|
||||
* added on. The result is displayed at the top of the post.
|
||||
*/
|
||||
function email_dice_roll($post) {
|
||||
global $config;
|
||||
if(strpos(strtolower($post->email), 'dice%20') === 0) {
|
||||
$dicestr = str_split(substr($post->email, strlen('dice%20')));
|
||||
|
||||
// Get params
|
||||
$diceX = '';
|
||||
$diceY = '';
|
||||
$diceZ = '';
|
||||
|
||||
$curd = 'diceX';
|
||||
for($i = 0; $i < count($dicestr); $i ++) {
|
||||
if(is_numeric($dicestr[$i])) {
|
||||
$$curd .= $dicestr[$i];
|
||||
} else if($dicestr[$i] == 'd') {
|
||||
$curd = 'diceY';
|
||||
} else if($dicestr[$i] == '-' || $dicestr[$i] == '+') {
|
||||
$curd = 'diceZ';
|
||||
$$curd = $dicestr[$i];
|
||||
}
|
||||
}
|
||||
|
||||
// Default values for X and Z
|
||||
if($diceX == '') {
|
||||
$diceX = '1';
|
||||
}
|
||||
|
||||
if($diceZ == '') {
|
||||
$diceZ = '+0';
|
||||
}
|
||||
|
||||
// Intify them
|
||||
$diceX = intval($diceX);
|
||||
$diceY = intval($diceY);
|
||||
$diceZ = intval($diceZ);
|
||||
|
||||
// Continue only if we have valid values
|
||||
if($diceX > 0 && $diceY > 0) {
|
||||
$dicerolls = array();
|
||||
$dicesum = $diceZ;
|
||||
for($i = 0; $i < $diceX; $i++) {
|
||||
$roll = rand(1, $diceY);
|
||||
$dicerolls[] = $roll;
|
||||
$dicesum += $roll;
|
||||
}
|
||||
|
||||
// Prepend the result to the post body
|
||||
$modifier = ($diceZ != 0) ? ((($diceZ < 0) ? ' - ' : ' + ') . abs($diceZ)) : '';
|
||||
$dicesum = ($diceX > 1) ? ' = ' . $dicesum : '';
|
||||
$post->body = '<table class="diceroll"><tr><td><img src="'.$config['dir']['static'].'d10.svg" alt="Dice roll" width="24"></td><td>Rolled ' . implode(', ', $dicerolls) . $modifier . $dicesum . '</td></tr></table><br/>' . $post->body;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls a dice and generates the appropriate html from the markup.
|
||||
* @param array $matches The array of the matches according to the default configuration.
|
||||
* 1 -> The number of dices to roll.
|
||||
* 3 -> The number faces of the dices.
|
||||
* 4 -> The offset to apply to the dice.
|
||||
* @param string $img_path Path to the image to use relative to the root. Null if none.
|
||||
* @return string The html to replace the original markup with.
|
||||
*/
|
||||
function inline_dice_roll_markup(array $matches, ?string $img_path): string {
|
||||
global $config;
|
||||
|
||||
$dice_count = _get_or_default_int($matches, 1, 1);
|
||||
$dice_faces = _get_or_default_int($matches, 3, 6);
|
||||
$dice_offset = _get_or_default_int($matches, 4, 0);
|
||||
|
||||
// Clamp between 1 and max_roll_count.
|
||||
$dice_count = max(min($dice_count, $config['max_roll_count']), 1);
|
||||
// Must be at least 2.
|
||||
if ($dice_faces < 2) {
|
||||
$dice_faces = 6;
|
||||
}
|
||||
|
||||
$tot = 0;
|
||||
for ($i = 0; $i < $dice_count; $i++) {
|
||||
$tot += mt_rand(1, $dice_faces);
|
||||
}
|
||||
// Ensure that final result is at least an integer.
|
||||
$tot = abs((int)($dice_offset + $tot));
|
||||
|
||||
|
||||
if ($img_path !== null) {
|
||||
$img_text = "<img src='{$config['root']}{$img_path}' alt='dice' title='dice' class=\"inline-dice\"/>";
|
||||
} else {
|
||||
$img_text = '';
|
||||
}
|
||||
|
||||
if ($dice_offset === 0) {
|
||||
$dice_offset_text = '';
|
||||
} elseif ($dice_offset > 0) {
|
||||
$dice_offset_text = "+{$dice_offset}";
|
||||
} else {
|
||||
$dice_offset_text = (string)$dice_offset;
|
||||
}
|
||||
|
||||
return "<span>$img_text {$dice_count}d{$dice_faces}{$dice_offset_text} = <b>$tot</b></span>";
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Format;
|
||||
|
||||
|
||||
function format_timestamp(int $delta): string {
|
||||
switch (true) {
|
||||
case $delta < 60:
|
||||
return $delta . ' ' . ngettext('second', 'seconds', $delta);
|
||||
case $delta < 3600: //60*60 = 3600
|
||||
return ($num = round($delta/ 60)) . ' ' . ngettext('minute', 'minutes', $num);
|
||||
case $delta < 86400: //60*60*24 = 86400
|
||||
return ($num = round($delta / 3600)) . ' ' . ngettext('hour', 'hours', $num);
|
||||
case $delta < 604800: //60*60*24*7 = 604800
|
||||
return ($num = round($delta / 86400)) . ' ' . ngettext('day', 'days', $num);
|
||||
case $delta < 31536000: //60*60*24*365 = 31536000
|
||||
return ($num = round($delta / 604800)) . ' ' . ngettext('week', 'weeks', $num);
|
||||
default:
|
||||
return ($num = round($delta / 31536000)) . ' ' . ngettext('year', 'years', $num);
|
||||
}
|
||||
}
|
||||
|
||||
function until(int $timestamp): string {
|
||||
return format_timestamp($timestamp - time());
|
||||
}
|
||||
|
||||
function ago(int $timestamp): string {
|
||||
return format_timestamp(time() - $timestamp);
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Net;
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $trust_headers. If true, trust the `HTTP_X_FORWARDED_PROTO` header to check if the connection is HTTPS.
|
||||
* @return bool Returns if the client-server connection is an encrypted one (HTTPS).
|
||||
*/
|
||||
function is_connection_secure(bool $trust_headers): bool {
|
||||
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
|
||||
return true;
|
||||
} elseif ($trust_headers && isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Num;
|
||||
|
||||
// Highest common factor
|
||||
function hcf($a, $b){
|
||||
$gcd = 1;
|
||||
|
||||
if ($a > $b) {
|
||||
$a = $a+$b;
|
||||
$b = $a-$b;
|
||||
$a = $a-$b;
|
||||
}
|
||||
if ($b == (round($b / $a)) * $a) {
|
||||
$gcd = $a;
|
||||
} else {
|
||||
for ($i = round($a / 2); $i; $i--) {
|
||||
if ($a == round($a / $i) * $i && $b == round($b / $i) * $i) {
|
||||
$gcd = $i;
|
||||
$i = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $gcd;
|
||||
}
|
||||
|
||||
function fraction($numerator, $denominator, $sep) {
|
||||
$gcf = hcf($numerator, $denominator);
|
||||
$numerator = $numerator / $gcf;
|
||||
$denominator = $denominator / $gcf;
|
||||
|
||||
return "{$numerator}{$sep}{$denominator}";
|
||||
}
|
@ -1,98 +0,0 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Theme;
|
||||
|
||||
|
||||
function rebuild_themes(string $action, $boardname = false): void {
|
||||
global $config, $board, $current_locale;
|
||||
|
||||
// Save the global variables
|
||||
$_config = $config;
|
||||
$_board = $board;
|
||||
|
||||
// List themes
|
||||
if ($themes = \Cache::get("themes")) {
|
||||
// OK, we already have themes loaded
|
||||
} else {
|
||||
$query = query("SELECT `theme` FROM ``theme_settings`` WHERE `name` IS NULL AND `value` IS NULL") or error(db_error());
|
||||
$themes = $query->fetchAll(\PDO::FETCH_NUM);
|
||||
|
||||
\Cache::set("themes", $themes);
|
||||
}
|
||||
|
||||
foreach ($themes as $theme) {
|
||||
// Restore them
|
||||
$config = $_config;
|
||||
$board = $_board;
|
||||
|
||||
// Reload the locale
|
||||
if ($config['locale'] != $current_locale) {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale']);
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli') {
|
||||
echo "Rebuilding theme ".$theme[0]."... ";
|
||||
}
|
||||
|
||||
rebuild_theme($theme[0], $action, $boardname);
|
||||
|
||||
if (PHP_SAPI === 'cli') {
|
||||
echo "done\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Restore them again
|
||||
$config = $_config;
|
||||
$board = $_board;
|
||||
|
||||
// Reload the locale
|
||||
if ($config['locale'] != $current_locale) {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale']);
|
||||
}
|
||||
}
|
||||
|
||||
function load_theme_config($_theme) {
|
||||
global $config;
|
||||
|
||||
if (!file_exists($config['dir']['themes'] . '/' . $_theme . '/info.php')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Load theme information into $theme
|
||||
include $config['dir']['themes'] . '/' . $_theme . '/info.php';
|
||||
|
||||
return $theme;
|
||||
}
|
||||
|
||||
function rebuild_theme($theme, string $action, $board = false) {
|
||||
global $config, $_theme;
|
||||
$_theme = $theme;
|
||||
|
||||
$theme = load_theme_config($_theme);
|
||||
|
||||
if (file_exists($config['dir']['themes'] . '/' . $_theme . '/theme.php')) {
|
||||
require_once $config['dir']['themes'] . '/' . $_theme . '/theme.php';
|
||||
|
||||
$theme['build_function']($action, theme_settings($_theme), $board);
|
||||
}
|
||||
}
|
||||
|
||||
function theme_settings($theme): array {
|
||||
if ($settings = \Cache::get("theme_settings_" . $theme)) {
|
||||
return $settings;
|
||||
}
|
||||
|
||||
$query = prepare("SELECT `name`, `value` FROM ``theme_settings`` WHERE `theme` = :theme AND `name` IS NOT NULL");
|
||||
$query->bindValue(':theme', $theme);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$settings = [];
|
||||
while ($s = $query->fetch(\PDO::FETCH_ASSOC)) {
|
||||
$settings[$s['name']] = $s['value'];
|
||||
}
|
||||
|
||||
\Cache::set("theme_settings_".$theme, $settings);
|
||||
|
||||
return $settings;
|
||||
}
|
159
inc/image.php
159
inc/image.php
@ -10,7 +10,7 @@ class Image {
|
||||
public $src, $format, $image, $size;
|
||||
public function __construct($src, $format = false, $size = false) {
|
||||
global $config;
|
||||
|
||||
|
||||
$this->src = $src;
|
||||
$this->format = $format;
|
||||
|
||||
@ -24,21 +24,21 @@ class Image {
|
||||
error(_('Unsupported file format: ') . $this->format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$this->image = new $classname($this, $size);
|
||||
|
||||
if (!$this->image->valid()) {
|
||||
$this->delete();
|
||||
error($config['error']['invalidimg']);
|
||||
}
|
||||
|
||||
|
||||
$this->size = (object)array('width' => $this->image->_width(), 'height' => $this->image->_height());
|
||||
if ($this->size->width < 1 || $this->size->height < 1) {
|
||||
$this->delete();
|
||||
error($config['error']['invalidimg']);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function resize($extension, $max_width, $max_height) {
|
||||
global $config;
|
||||
|
||||
@ -62,16 +62,16 @@ class Image {
|
||||
error(_('Unsupported file format: ') . $extension);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$thumb = new $classname(false);
|
||||
$thumb->src = $this->src;
|
||||
$thumb->format = $this->format;
|
||||
$thumb->original_width = $this->size->width;
|
||||
$thumb->original_height = $this->size->height;
|
||||
|
||||
|
||||
$x_ratio = $max_width / $this->size->width;
|
||||
$y_ratio = $max_height / $this->size->height;
|
||||
|
||||
|
||||
if (($this->size->width <= $max_width) && ($this->size->height <= $max_height)) {
|
||||
$width = $this->size->width;
|
||||
$height = $this->size->height;
|
||||
@ -82,16 +82,16 @@ class Image {
|
||||
$width = ceil($y_ratio * $this->size->width);
|
||||
$height = $max_height;
|
||||
}
|
||||
|
||||
|
||||
$thumb->_resize($this->image->image, $width, $height);
|
||||
|
||||
|
||||
return $thumb;
|
||||
}
|
||||
|
||||
|
||||
public function to($dst) {
|
||||
$this->image->to($dst);
|
||||
}
|
||||
|
||||
|
||||
public function delete() {
|
||||
file_unlink($this->src);
|
||||
}
|
||||
@ -114,26 +114,26 @@ class ImageGD {
|
||||
}
|
||||
|
||||
class ImageBase extends ImageGD {
|
||||
public $image, $src, $original, $original_width, $original_height, $width, $height;
|
||||
public $image, $src, $original, $original_width, $original_height, $width, $height;
|
||||
public function valid() {
|
||||
return (bool)$this->image;
|
||||
}
|
||||
|
||||
|
||||
public function __construct($img, $size = false) {
|
||||
if (method_exists($this, 'init'))
|
||||
$this->init();
|
||||
|
||||
|
||||
if ($size && $size[0] > 0 && $size[1] > 0) {
|
||||
$this->width = $size[0];
|
||||
$this->height = $size[1];
|
||||
}
|
||||
|
||||
|
||||
if ($img !== false) {
|
||||
$this->src = $img->src;
|
||||
$this->from();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function _width() {
|
||||
if (method_exists($this, 'width'))
|
||||
return $this->width();
|
||||
@ -156,7 +156,7 @@ class ImageBase extends ImageGD {
|
||||
$this->original = &$original;
|
||||
$this->width = $width;
|
||||
$this->height = $height;
|
||||
|
||||
|
||||
if (method_exists($this, 'resize'))
|
||||
$this->resize();
|
||||
else
|
||||
@ -199,31 +199,31 @@ class ImageImagick extends ImageBase {
|
||||
}
|
||||
public function resize() {
|
||||
global $config;
|
||||
|
||||
|
||||
if ($this->format == 'gif' && ($config['thumb_ext'] == 'gif' || $config['thumb_ext'] == '')) {
|
||||
$this->image = new Imagick();
|
||||
$this->image->setFormat('gif');
|
||||
|
||||
|
||||
$keep_frames = array();
|
||||
for ($i = 0; $i < $this->original->getNumberImages(); $i += floor($this->original->getNumberImages() / $config['thumb_keep_animation_frames']))
|
||||
$keep_frames[] = $i;
|
||||
|
||||
|
||||
$i = 0;
|
||||
$delay = 0;
|
||||
foreach ($this->original as $frame) {
|
||||
$delay += $frame->getImageDelay();
|
||||
|
||||
|
||||
if (in_array($i, $keep_frames)) {
|
||||
// $frame->scaleImage($this->width, $this->height, false);
|
||||
$frame->sampleImage($this->width, $this->height);
|
||||
$frame->setImagePage($this->width, $this->height, 0, 0);
|
||||
$frame->setImageDelay($delay);
|
||||
$delay = 0;
|
||||
|
||||
|
||||
$this->image->addImage($frame->getImage());
|
||||
}
|
||||
$i++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$this->image = clone $this->original;
|
||||
$this->image->scaleImage($this->width, $this->height, false);
|
||||
@ -234,15 +234,15 @@ class ImageImagick extends ImageBase {
|
||||
|
||||
class ImageConvert extends ImageBase {
|
||||
public $width, $height, $temp, $gm = false, $gifsicle = false;
|
||||
|
||||
|
||||
public function init() {
|
||||
global $config;
|
||||
|
||||
|
||||
if ($config['thumb_method'] == 'gm' || $config['thumb_method'] == 'gm+gifsicle')
|
||||
$this->gm = true;
|
||||
if ($config['thumb_method'] == 'convert+gifsicle' || $config['thumb_method'] == 'gm+gifsicle')
|
||||
$this->gifsicle = true;
|
||||
|
||||
|
||||
$this->temp = false;
|
||||
}
|
||||
public function get_size($src, $try_gd_first = true) {
|
||||
@ -264,7 +264,7 @@ class ImageConvert extends ImageBase {
|
||||
if ($size) {
|
||||
$this->width = $size[0];
|
||||
$this->height = $size[1];
|
||||
|
||||
|
||||
$this->image = true;
|
||||
} else {
|
||||
// mark as invalid
|
||||
@ -273,7 +273,7 @@ class ImageConvert extends ImageBase {
|
||||
}
|
||||
public function to($src) {
|
||||
global $config;
|
||||
|
||||
|
||||
if (!$this->temp) {
|
||||
if ($config['strip_exif']) {
|
||||
if($error = shell_exec_error(($this->gm ? 'gm ' : '') . 'convert ' .
|
||||
@ -291,7 +291,6 @@ class ImageConvert extends ImageBase {
|
||||
} else {
|
||||
rename($this->temp, $src);
|
||||
chmod($src, 0664);
|
||||
$this->temp = false;
|
||||
}
|
||||
}
|
||||
public function width() {
|
||||
@ -301,23 +300,21 @@ class ImageConvert extends ImageBase {
|
||||
return $this->height;
|
||||
}
|
||||
public function destroy() {
|
||||
if ($this->temp !== false) {
|
||||
@unlink($this->temp);
|
||||
$this->temp = false;
|
||||
}
|
||||
@unlink($this->temp);
|
||||
$this->temp = false;
|
||||
}
|
||||
public function resize() {
|
||||
global $config;
|
||||
|
||||
|
||||
if ($this->temp) {
|
||||
// remove old
|
||||
$this->destroy();
|
||||
}
|
||||
|
||||
|
||||
$this->temp = tempnam($config['tmp'], 'convert') . ($config['thumb_ext'] == '' ? '' : '.' . $config['thumb_ext']);
|
||||
|
||||
|
||||
$config['thumb_keep_animation_frames'] = (int)$config['thumb_keep_animation_frames'];
|
||||
|
||||
|
||||
if ($this->format == 'gif' && ($config['thumb_ext'] == 'gif' || $config['thumb_ext'] == '') && $config['thumb_keep_animation_frames'] > 1) {
|
||||
if ($this->gifsicle) {
|
||||
if (($error = shell_exec("gifsicle -w --unoptimize -O2 --resize {$this->width}x{$this->height} < " .
|
||||
@ -327,7 +324,12 @@ class ImageConvert extends ImageBase {
|
||||
error(_('Failed to resize image!'), null, $error);
|
||||
}
|
||||
} else {
|
||||
$convert_args = &$config['convert_args'];
|
||||
if ($config['convert_manual_orient'] && ($this->format == 'jpg' || $this->format == 'jpeg'))
|
||||
$convert_args = str_replace('-auto-orient', ImageConvert::jpeg_exif_orientation($this->src), $config['convert_args']);
|
||||
elseif ($config['convert_manual_orient'])
|
||||
$convert_args = str_replace('-auto-orient', '', $config['convert_args']);
|
||||
else
|
||||
$convert_args = &$config['convert_args'];
|
||||
|
||||
if (($error = shell_exec_error(($this->gm ? 'gm ' : '') . 'convert ' .
|
||||
sprintf($convert_args,
|
||||
@ -346,8 +348,12 @@ class ImageConvert extends ImageBase {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$convert_args = &$config['convert_args'];
|
||||
|
||||
if ($config['convert_manual_orient'] && ($this->format == 'jpg' || $this->format == 'jpeg'))
|
||||
$convert_args = str_replace('-auto-orient', ImageConvert::jpeg_exif_orientation($this->src), $config['convert_args']);
|
||||
elseif ($config['convert_manual_orient'])
|
||||
$convert_args = str_replace('-auto-orient', '', $config['convert_args']);
|
||||
else
|
||||
$convert_args = &$config['convert_args'];
|
||||
if (($error = shell_exec_error(($this->gm ? 'gm ' : '') . 'convert ' .
|
||||
sprintf($convert_args,
|
||||
$this->width,
|
||||
@ -374,6 +380,69 @@ class ImageConvert extends ImageBase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For when -auto-orient doesn't exist (older versions)
|
||||
static public function jpeg_exif_orientation($src, $exif = false) {
|
||||
if (!$exif) {
|
||||
$exif = @exif_read_data($src);
|
||||
if (!isset($exif['Orientation']))
|
||||
return false;
|
||||
}
|
||||
switch($exif['Orientation']) {
|
||||
case 1:
|
||||
// Normal
|
||||
return false;
|
||||
case 2:
|
||||
// 888888
|
||||
// 88
|
||||
// 8888
|
||||
// 88
|
||||
// 88
|
||||
|
||||
return '-flop';
|
||||
case 3:
|
||||
|
||||
// 88
|
||||
// 88
|
||||
// 8888
|
||||
// 88
|
||||
// 888888
|
||||
|
||||
return '-flip -flop';
|
||||
case 4:
|
||||
// 88
|
||||
// 88
|
||||
// 8888
|
||||
// 88
|
||||
// 888888
|
||||
|
||||
return '-flip';
|
||||
case 5:
|
||||
// 8888888888
|
||||
// 88 88
|
||||
// 88
|
||||
|
||||
return '-rotate 90 -flop';
|
||||
case 6:
|
||||
// 88
|
||||
// 88 88
|
||||
// 8888888888
|
||||
|
||||
return '-rotate 90';
|
||||
case 7:
|
||||
// 88
|
||||
// 88 88
|
||||
// 8888888888
|
||||
|
||||
return '-rotate "-90" -flop';
|
||||
case 8:
|
||||
// 8888888888
|
||||
// 88 88
|
||||
// 88
|
||||
|
||||
return '-rotate "-90"';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ImagePNG extends ImageBase {
|
||||
@ -428,11 +497,7 @@ class ImageBMP extends ImageBase {
|
||||
}
|
||||
}
|
||||
|
||||
class ImageWEBP extends ImageBase {
|
||||
public function from() {
|
||||
$this->image = @imagecreatefromwebp($this->src);
|
||||
}
|
||||
public function to($src) {
|
||||
imagewebp($this->image, $src);
|
||||
}
|
||||
|
||||
if (PHP_MAJOR_VERSION <= 7 && PHP_MINOR_VERSION < 2) {
|
||||
include 'inc/image/bmp.php';
|
||||
}
|
||||
|
186
inc/image/bmp.php
Normal file
186
inc/image/bmp.php
Normal file
@ -0,0 +1,186 @@
|
||||
<?php
|
||||
/*
|
||||
* These functions provide a polyfill for old versions of PHP.
|
||||
* PHP >= 7.2.0 provides these functions by default.
|
||||
*
|
||||
* These functions were submitted by user DHKold to the PHP manual in 2005.
|
||||
* http://php.net/manual/en/function.imagecreate.php#53879
|
||||
*
|
||||
* As per http://php.net/manual/en/about.notes.php ("About user notes", PHP
|
||||
* Manual), all PHP User Contributed Notes are "...considered part of the PHP
|
||||
* manual, and are therefore covered by the same license that covers this
|
||||
* documentation."
|
||||
*
|
||||
* Therefore, as per http://php.net/manual/en/copyright.php ("Copyright", PHP
|
||||
* Manual), the code below is licensed under the terms of the Creative Commons
|
||||
* Attribution 3.0 license, AKA CC-BY 3.0.
|
||||
* http://creativecommons.org/licenses/by/3.0/
|
||||
*/
|
||||
|
||||
/*********************************************/
|
||||
/* Function: imagecreatefrombmp */
|
||||
/* Author: DHKold */
|
||||
/* Contact: admin@dhkold.com */
|
||||
/* Date: The 15th of June 2005 */
|
||||
/* Version: 2.0B */
|
||||
/*********************************************/
|
||||
function imagecreatefrombmp($filename) {
|
||||
if (! $f1 = fopen($filename,"rb")) return FALSE;
|
||||
$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
|
||||
if ($FILE['file_type'] != 19778) return FALSE;
|
||||
$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
|
||||
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
|
||||
'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
|
||||
$BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
|
||||
if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
|
||||
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
|
||||
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
|
||||
$BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
|
||||
$BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
|
||||
$BMP['decal'] = 4-(4*$BMP['decal']);
|
||||
if ($BMP['decal'] == 4) $BMP['decal'] = 0;
|
||||
|
||||
$PALETTE = array();
|
||||
if ($BMP['colors'] < 16777216)
|
||||
{
|
||||
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
|
||||
}
|
||||
|
||||
$IMG = fread($f1,$BMP['size_bitmap']);
|
||||
$VIDE = chr(0);
|
||||
|
||||
$res = imagecreatetruecolor($BMP['width'],$BMP['height']);
|
||||
$P = 0;
|
||||
$Y = $BMP['height']-1;
|
||||
while ($Y >= 0)
|
||||
{
|
||||
$X=0;
|
||||
while ($X < $BMP['width'])
|
||||
{
|
||||
if ($BMP['bits_per_pixel'] == 24)
|
||||
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
|
||||
elseif ($BMP['bits_per_pixel'] == 16)
|
||||
{
|
||||
$COLOR = unpack("n",substr($IMG,$P,2));
|
||||
$COLOR[1] = $PALETTE[$COLOR[1]+1];
|
||||
}
|
||||
elseif ($BMP['bits_per_pixel'] == 8)
|
||||
{
|
||||
$COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
|
||||
$COLOR[1] = $PALETTE[$COLOR[1]+1];
|
||||
}
|
||||
elseif ($BMP['bits_per_pixel'] == 4)
|
||||
{
|
||||
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
|
||||
if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
|
||||
$COLOR[1] = $PALETTE[$COLOR[1]+1];
|
||||
}
|
||||
elseif ($BMP['bits_per_pixel'] == 1)
|
||||
{
|
||||
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
|
||||
if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7;
|
||||
elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
|
||||
elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
|
||||
elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
|
||||
elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
|
||||
elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
|
||||
elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
|
||||
elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
|
||||
$COLOR[1] = $PALETTE[$COLOR[1]+1];
|
||||
}
|
||||
else
|
||||
return FALSE;
|
||||
imagesetpixel($res,$X,$Y,$COLOR[1]);
|
||||
$X++;
|
||||
$P += $BMP['bytes_per_pixel'];
|
||||
}
|
||||
$Y--;
|
||||
$P+=$BMP['decal'];
|
||||
}
|
||||
fclose($f1);
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
function imagebmp(&$img, $filename='') {
|
||||
$widthOrig = imagesx($img);
|
||||
$widthFloor = ((floor($widthOrig/16))*16);
|
||||
$widthCeil = ((ceil($widthOrig/16))*16);
|
||||
$height = imagesy($img);
|
||||
|
||||
$size = ($widthCeil*$height*3)+54;
|
||||
|
||||
// Bitmap File Header
|
||||
$result = 'BM'; // header (2b)
|
||||
$result .= int_to_dword($size); // size of file (4b)
|
||||
$result .= int_to_dword(0); // reserved (4b)
|
||||
$result .= int_to_dword(54); // byte location in the file which is first byte of IMAGE (4b)
|
||||
// Bitmap Info Header
|
||||
$result .= int_to_dword(40); // Size of BITMAPINFOHEADER (4b)
|
||||
$result .= int_to_dword($widthCeil); // width of bitmap (4b)
|
||||
$result .= int_to_dword($height); // height of bitmap (4b)
|
||||
$result .= int_to_word(1); // biPlanes = 1 (2b)
|
||||
$result .= int_to_word(24); // biBitCount = {1 (mono) or 4 (16 clr ) or 8 (256 clr) or 24 (16 Mil)} (2b
|
||||
$result .= int_to_dword(0); // RLE COMPRESSION (4b)
|
||||
$result .= int_to_dword(0); // width x height (4b)
|
||||
$result .= int_to_dword(0); // biXPelsPerMeter (4b)
|
||||
$result .= int_to_dword(0); // biYPelsPerMeter (4b)
|
||||
$result .= int_to_dword(0); // Number of palettes used (4b)
|
||||
$result .= int_to_dword(0); // Number of important colour (4b)
|
||||
|
||||
// is faster than chr()
|
||||
$arrChr = array();
|
||||
for ($i=0; $i<256; $i++){
|
||||
$arrChr[$i] = chr($i);
|
||||
}
|
||||
|
||||
// creates image data
|
||||
$bgfillcolor = array('red'=>0, 'green'=>0, 'blue'=>0);
|
||||
|
||||
// bottom to top - left to right - attention blue green red !!!
|
||||
$y=$height-1;
|
||||
for ($y2=0; $y2<$height; $y2++) {
|
||||
for ($x=0; $x<$widthFloor; ) {
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
$rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y));
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
}
|
||||
for ($x=$widthFloor; $x<$widthCeil; $x++) {
|
||||
$rgb = ($x<$widthOrig) ? imagecolorsforindex($img, imagecolorat($img, $x, $y)) : $bgfillcolor;
|
||||
$result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']];
|
||||
}
|
||||
$y--;
|
||||
}
|
||||
|
||||
// see imagegif
|
||||
if ($filename == '') {
|
||||
echo $result;
|
||||
} else {
|
||||
$file = fopen($filename, 'wb');
|
||||
fwrite($file, $result);
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
|
||||
// imagebmp helpers
|
||||
function int_to_dword($n) {
|
||||
return chr($n & 255).chr(($n >> 8) & 255).chr(($n >> 16) & 255).chr(($n >> 24) & 255);
|
||||
}
|
||||
|
||||
function int_to_word($n) {
|
||||
return chr($n & 255).chr(($n >> 8) & 255);
|
||||
}
|
||||
?>
|
45
inc/lib/twig/extensions/Extension/I18n.php
Normal file
45
inc/lib/twig/extensions/Extension/I18n.php
Normal file
@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) 2010 Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
class Twig_Extensions_Extension_I18n extends Twig_Extension
|
||||
{
|
||||
/**
|
||||
* Returns the token parser instances to add to the existing list.
|
||||
*
|
||||
* @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
|
||||
*/
|
||||
public function getTokenParsers()
|
||||
{
|
||||
return array(new Twig_Extensions_TokenParser_Trans());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of filters to add to the existing list.
|
||||
*
|
||||
* @return array An array of filters
|
||||
*/
|
||||
public function getFilters()
|
||||
{
|
||||
return array(
|
||||
new Twig_SimpleFilter('trans', 'gettext'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the extension.
|
||||
*
|
||||
* @return string The extension name
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return 'i18n';
|
||||
}
|
||||
}
|
||||
|
137
inc/lib/twig/extensions/Extension/Tinyboard.php
Normal file
137
inc/lib/twig/extensions/Extension/Tinyboard.php
Normal file
@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
class Twig_Extensions_Extension_Tinyboard extends Twig_Extension
|
||||
{
|
||||
/**
|
||||
* Returns a list of filters to add to the existing list.
|
||||
*
|
||||
* @return array An array of filters
|
||||
*/
|
||||
public function getFilters()
|
||||
{
|
||||
return array(
|
||||
new Twig_SimpleFilter('filesize', 'format_bytes'),
|
||||
new Twig_SimpleFilter('truncate', 'twig_truncate_filter'),
|
||||
new Twig_SimpleFilter('truncate_body', 'truncate'),
|
||||
new Twig_SimpleFilter('truncate_filename', 'twig_filename_truncate_filter'),
|
||||
new Twig_SimpleFilter('extension', 'twig_extension_filter'),
|
||||
new Twig_SimpleFilter('sprintf', 'sprintf'),
|
||||
new Twig_SimpleFilter('capcode', 'capcode'),
|
||||
new Twig_SimpleFilter('remove_modifiers', 'remove_modifiers'),
|
||||
new Twig_SimpleFilter('hasPermission', 'twig_hasPermission_filter'),
|
||||
new Twig_SimpleFilter('date', 'twig_date_filter'),
|
||||
new Twig_SimpleFilter('poster_id', 'poster_id'),
|
||||
new Twig_SimpleFilter('remove_whitespace', 'twig_remove_whitespace_filter'),
|
||||
new Twig_SimpleFilter('count', 'count'),
|
||||
new Twig_SimpleFilter('ago', 'ago'),
|
||||
new Twig_SimpleFilter('until', 'until'),
|
||||
new Twig_SimpleFilter('push', 'twig_push_filter'),
|
||||
new Twig_SimpleFilter('bidi_cleanup', 'bidi_cleanup'),
|
||||
new Twig_SimpleFilter('addslashes', 'addslashes'),
|
||||
new Twig_SimpleFilter('cloak_ip', 'cloak_ip'),
|
||||
new Twig_SimpleFilter('cloak_mask', 'cloak_mask'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of functions to add to the existing list.
|
||||
*
|
||||
* @return array An array of filters
|
||||
*/
|
||||
public function getFunctions()
|
||||
{
|
||||
return array(
|
||||
new Twig_SimpleFunction('time', 'time'),
|
||||
new Twig_SimpleFunction('floor', 'floor'),
|
||||
new Twig_SimpleFunction('timezone', 'twig_timezone_function'),
|
||||
new Twig_SimpleFunction('hiddenInputs', 'hiddenInputs'),
|
||||
new Twig_SimpleFunction('hiddenInputsHash', 'hiddenInputsHash'),
|
||||
new Twig_SimpleFunction('ratio', 'twig_ratio_function'),
|
||||
new Twig_SimpleFunction('secure_link_confirm', 'twig_secure_link_confirm'),
|
||||
new Twig_SimpleFunction('secure_link', 'twig_secure_link'),
|
||||
new Twig_SimpleFunction('link_for', 'link_for')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the extension.
|
||||
*
|
||||
* @return string The extension name
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return 'tinyboard';
|
||||
}
|
||||
}
|
||||
|
||||
function twig_timezone_function() {
|
||||
return 'Z';
|
||||
}
|
||||
|
||||
function twig_push_filter($array, $value) {
|
||||
array_push($array, $value);
|
||||
return $array;
|
||||
}
|
||||
|
||||
function twig_remove_whitespace_filter($data) {
|
||||
return preg_replace('/[\t\r\n]/', '', $data);
|
||||
}
|
||||
|
||||
function twig_date_filter($date, $format) {
|
||||
return gmstrftime($format, $date);
|
||||
}
|
||||
|
||||
function twig_hasPermission_filter($mod, $permission, $board = null) {
|
||||
return hasPermission($permission, $board, $mod);
|
||||
}
|
||||
|
||||
function twig_extension_filter($value, $case_insensitive = true) {
|
||||
$ext = mb_substr($value, mb_strrpos($value, '.') + 1);
|
||||
if($case_insensitive)
|
||||
$ext = mb_strtolower($ext);
|
||||
return $ext;
|
||||
}
|
||||
|
||||
function twig_sprintf_filter( $value, $var) {
|
||||
return sprintf($value, $var);
|
||||
}
|
||||
|
||||
function twig_truncate_filter($value, $length = 30, $preserve = false, $separator = '…') {
|
||||
if (mb_strlen($value) > $length) {
|
||||
if ($preserve) {
|
||||
if (false !== ($breakpoint = mb_strpos($value, ' ', $length))) {
|
||||
$length = $breakpoint;
|
||||
}
|
||||
}
|
||||
return mb_substr($value, 0, $length) . $separator;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function twig_filename_truncate_filter($value, $length = 30, $separator = '…') {
|
||||
if (mb_strlen($value) > $length) {
|
||||
$value = strrev($value);
|
||||
$array = array_reverse(explode(".", $value, 2));
|
||||
$array = array_map("strrev", $array);
|
||||
|
||||
$filename = &$array[0];
|
||||
$extension = isset($array[1]) ? $array[1] : false;
|
||||
|
||||
$filename = mb_substr($filename, 0, $length - ($extension ? mb_strlen($extension) + 1 : 0)) . $separator;
|
||||
|
||||
return implode(".", $array);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function twig_ratio_function($w, $h) {
|
||||
return fraction($w, $h, ':');
|
||||
}
|
||||
function twig_secure_link_confirm($text, $title, $confirm_message, $href) {
|
||||
global $config;
|
||||
|
||||
return '<a onclick="if (event.which==2) return true;if (confirm(\'' . htmlentities(addslashes($confirm_message)) . '\')) document.location=\'?/' . htmlspecialchars(addslashes($href . '/' . make_secure_link_token($href))) . '\';return false;" title="' . htmlentities($title) . '" href="?/' . $href . '">' . $text . '</a>';
|
||||
}
|
||||
function twig_secure_link($href) {
|
||||
return $href . '/' . make_secure_link_token($href);
|
||||
}
|
133
inc/lib/twig/extensions/Node/Trans.php
Normal file
133
inc/lib/twig/extensions/Node/Trans.php
Normal file
@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) 2010 Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Represents a trans node.
|
||||
*
|
||||
* @package twig
|
||||
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
|
||||
*/
|
||||
class Twig_Extensions_Node_Trans extends Twig_Node
|
||||
{
|
||||
public function __construct(Twig_NodeInterface $body, Twig_NodeInterface $plural = null, Twig_Node_Expression $count = null, $lineno, $tag = null)
|
||||
{
|
||||
parent::__construct(array('count' => $count, 'body' => $body, 'plural' => $plural), array(), $lineno, $tag);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles the node to PHP.
|
||||
*
|
||||
* @param Twig_Compiler A Twig_Compiler instance
|
||||
*/
|
||||
public function compile(Twig_Compiler $compiler)
|
||||
{
|
||||
$compiler->addDebugInfo($this);
|
||||
|
||||
list($msg, $vars) = $this->compileString($this->getNode('body'));
|
||||
|
||||
if (null !== $this->getNode('plural')) {
|
||||
list($msg1, $vars1) = $this->compileString($this->getNode('plural'));
|
||||
|
||||
$vars = array_merge($vars, $vars1);
|
||||
}
|
||||
|
||||
$function = null === $this->getNode('plural') ? 'gettext' : 'ngettext';
|
||||
|
||||
if ($vars) {
|
||||
$compiler
|
||||
->write('echo strtr('.$function.'(')
|
||||
->subcompile($msg)
|
||||
;
|
||||
|
||||
if (null !== $this->getNode('plural')) {
|
||||
$compiler
|
||||
->raw(', ')
|
||||
->subcompile($msg1)
|
||||
->raw(', abs(')
|
||||
->subcompile($this->getNode('count'))
|
||||
->raw(')')
|
||||
;
|
||||
}
|
||||
|
||||
$compiler->raw('), array(');
|
||||
|
||||
foreach ($vars as $var) {
|
||||
if ('count' === $var->getAttribute('name')) {
|
||||
$compiler
|
||||
->string('%count%')
|
||||
->raw(' => abs(')
|
||||
->subcompile($this->getNode('count'))
|
||||
->raw('), ')
|
||||
;
|
||||
} else {
|
||||
$compiler
|
||||
->string('%'.$var->getAttribute('name').'%')
|
||||
->raw(' => ')
|
||||
->subcompile($var)
|
||||
->raw(', ')
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
$compiler->raw("));\n");
|
||||
} else {
|
||||
$compiler
|
||||
->write('echo '.$function.'(')
|
||||
->subcompile($msg)
|
||||
;
|
||||
|
||||
if (null !== $this->getNode('plural')) {
|
||||
$compiler
|
||||
->raw(', ')
|
||||
->subcompile($msg1)
|
||||
->raw(', abs(')
|
||||
->subcompile($this->getNode('count'))
|
||||
->raw(')')
|
||||
;
|
||||
}
|
||||
|
||||
$compiler->raw(");\n");
|
||||
}
|
||||
}
|
||||
|
||||
protected function compileString(Twig_NodeInterface $body)
|
||||
{
|
||||
if ($body instanceof Twig_Node_Expression_Name || $body instanceof Twig_Node_Expression_Constant || $body instanceof Twig_Node_Expression_TempName) {
|
||||
return array($body, array());
|
||||
}
|
||||
|
||||
$vars = array();
|
||||
if (count($body)) {
|
||||
$msg = '';
|
||||
|
||||
foreach ($body as $node) {
|
||||
if (get_class($node) === 'Twig_Node' && $node->getNode(0) instanceof Twig_Node_SetTemp) {
|
||||
$node = $node->getNode(1);
|
||||
}
|
||||
|
||||
if ($node instanceof Twig_Node_Print) {
|
||||
$n = $node->getNode('expr');
|
||||
while ($n instanceof Twig_Node_Expression_Filter) {
|
||||
$n = $n->getNode('node');
|
||||
}
|
||||
$msg .= sprintf('%%%s%%', $n->getAttribute('name'));
|
||||
$vars[] = new Twig_Node_Expression_Name($n->getAttribute('name'), $n->getLine());
|
||||
} else {
|
||||
$msg .= $node->getAttribute('data');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$msg = $body->getAttribute('data');
|
||||
}
|
||||
|
||||
return array(new Twig_Node(array(new Twig_Node_Expression_Constant(trim($msg), $body->getLine()))), $vars);
|
||||
}
|
||||
}
|
80
inc/lib/twig/extensions/TokenParser/Trans.php
Normal file
80
inc/lib/twig/extensions/TokenParser/Trans.php
Normal file
@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) 2010 Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
class Twig_Extensions_TokenParser_Trans extends Twig_TokenParser
|
||||
{
|
||||
/**
|
||||
* Parses a token and returns a node.
|
||||
*
|
||||
* @param Twig_Token $token A Twig_Token instance
|
||||
*
|
||||
* @return Twig_NodeInterface A Twig_NodeInterface instance
|
||||
*/
|
||||
public function parse(Twig_Token $token)
|
||||
{
|
||||
$lineno = $token->getLine();
|
||||
$stream = $this->parser->getStream();
|
||||
$count = null;
|
||||
$plural = null;
|
||||
|
||||
if (!$stream->test(Twig_Token::BLOCK_END_TYPE)) {
|
||||
$body = $this->parser->getExpressionParser()->parseExpression();
|
||||
} else {
|
||||
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
||||
$body = $this->parser->subparse(array($this, 'decideForFork'));
|
||||
if ('plural' === $stream->next()->getValue()) {
|
||||
$count = $this->parser->getExpressionParser()->parseExpression();
|
||||
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
||||
$plural = $this->parser->subparse(array($this, 'decideForEnd'), true);
|
||||
}
|
||||
}
|
||||
|
||||
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
||||
|
||||
$this->checkTransString($body, $lineno);
|
||||
|
||||
return new Twig_Extensions_Node_Trans($body, $plural, $count, $lineno, $this->getTag());
|
||||
}
|
||||
|
||||
public function decideForFork(Twig_Token $token)
|
||||
{
|
||||
return $token->test(array('plural', 'endtrans'));
|
||||
}
|
||||
|
||||
public function decideForEnd(Twig_Token $token)
|
||||
{
|
||||
return $token->test('endtrans');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the tag name associated with this token parser.
|
||||
*
|
||||
* @param string The tag name
|
||||
*/
|
||||
public function getTag()
|
||||
{
|
||||
return 'trans';
|
||||
}
|
||||
|
||||
protected function checkTransString(Twig_NodeInterface $body, $lineno)
|
||||
{
|
||||
foreach ($body as $i => $node) {
|
||||
if (
|
||||
$node instanceof Twig_Node_Text
|
||||
||
|
||||
($node instanceof Twig_Node_Print && $node->getNode('expr') instanceof Twig_Node_Expression_Name)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Twig_Error_Syntax(sprintf('The text to be translated with "trans" can only contain references to simple variables'), $lineno);
|
||||
}
|
||||
}
|
||||
}
|
@ -2287,6 +2287,8 @@ msgstr "usuń"
|
||||
msgid "New note"
|
||||
msgstr "Nowa notka"
|
||||
|
||||
msgid "New telegram"
|
||||
msgstr "Nowa depesza"
|
||||
|
||||
#. line 94
|
||||
#. line 7
|
||||
|
99
inc/lock.php
99
inc/lock.php
@ -1,76 +1,39 @@
|
||||
<?php
|
||||
class Locks {
|
||||
private static function filesystem(string $key) {
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
class Lock {
|
||||
function __construct($key) { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
|
||||
$fd = fopen("tmp/locks/$key", "w");
|
||||
if ($fd === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return new class($fd) implements Lock {
|
||||
// Resources have no type in PHP.
|
||||
private $f;
|
||||
|
||||
public function __construct($fd) {
|
||||
$this->f = $fd;
|
||||
}
|
||||
|
||||
public function get(bool $nonblock = false) {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_SH | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) {
|
||||
return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_ex(bool $nonblock = false) {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_EX | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) {
|
||||
return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function free() {
|
||||
flock($this->f, LOCK_UN);
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
$this->f = fopen("tmp/locks/$key", "w");
|
||||
}
|
||||
}
|
||||
|
||||
public static function none() {
|
||||
return new class() implements Lock {
|
||||
public function get(bool $nonblock = false) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_ex(bool $nonblock = false) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function free() {
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
// Get a shared lock
|
||||
function get($nonblock = false) { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_SH | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public static function get_lock(array $config, string $key) {
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
return self::filesystem($key);
|
||||
} else {
|
||||
return self::none();
|
||||
}
|
||||
// Get an exclusive lock
|
||||
function get_ex($nonblock = false) { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_EX | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface Lock {
|
||||
public function get(bool $nonblock = false);
|
||||
|
||||
public function get_ex(bool $nonblock = false);
|
||||
|
||||
public function free();
|
||||
return $this;
|
||||
}
|
||||
|
||||
// Free a lock
|
||||
function free() { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
flock($this->f, LOCK_UN);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
207
inc/mod/auth.php
207
inc/mod/auth.php
@ -4,22 +4,19 @@
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
use Vichan\Context;
|
||||
use Vichan\Functions\Net;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
// create a hash/salt pair for validate logins
|
||||
function mkhash(string $username, $password = null, $salt = false) {
|
||||
function mkhash($username, $password, $salt = false) {
|
||||
global $config;
|
||||
|
||||
|
||||
if (!$salt) {
|
||||
// create some sort of salt for the hash
|
||||
$salt = substr(base64_encode(sha1(rand() . time(), true) . $config['cookies']['salt']), 0, 15);
|
||||
|
||||
|
||||
$generated_salt = true;
|
||||
}
|
||||
|
||||
|
||||
// generate hash (method is not important as long as it's strong)
|
||||
$hash = substr(
|
||||
base64_encode(
|
||||
@ -33,59 +30,62 @@ function mkhash(string $username, $password = null, $salt = false) {
|
||||
)
|
||||
), 0, 20
|
||||
);
|
||||
|
||||
if (isset($generated_salt)) {
|
||||
return [ $hash, $salt ];
|
||||
} else {
|
||||
|
||||
if (isset($generated_salt))
|
||||
return array($hash, $salt);
|
||||
else
|
||||
return $hash;
|
||||
}
|
||||
}
|
||||
|
||||
function crypt_password(string $password): array {
|
||||
function crypt_password_old($password) {
|
||||
$salt = generate_salt();
|
||||
$password = hash('sha256', $salt . sha1($password));
|
||||
return array($salt, $password);
|
||||
}
|
||||
|
||||
function crypt_password($password) {
|
||||
global $config;
|
||||
// `salt` database field is reused as a version value. We don't want it to be 0.
|
||||
$version = $config['password_crypt_version'] ? $config['password_crypt_version'] : 1;
|
||||
$new_salt = generate_salt();
|
||||
$password = crypt($password, $config['password_crypt'] . $new_salt . "$");
|
||||
return [ $version, $password ];
|
||||
return array($version, $password);
|
||||
}
|
||||
|
||||
function test_password(string $password, string $salt, string $test): array {
|
||||
function test_password($password, $salt, $test) {
|
||||
global $config;
|
||||
|
||||
// Version = 0 denotes an old password hashing schema. In the same column, the
|
||||
// password hash was kept previously
|
||||
$version = strlen($salt) <= 8 ? (int)$salt : 0;
|
||||
$version = (strlen($salt) <= 8) ? (int) $salt : 0;
|
||||
|
||||
if ($version == 0) {
|
||||
$comp = hash('sha256', $salt . sha1($test));
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
$comp = crypt($test, $password);
|
||||
}
|
||||
return [ $version, hash_equals($password, $comp) ];
|
||||
return array($version, hash_equals($password, $comp));
|
||||
}
|
||||
|
||||
function generate_salt(): string {
|
||||
function generate_salt() {
|
||||
// mcrypt_create_iv() was deprecated in PHP 7.1.0, only use it if we're below that version number.
|
||||
if (PHP_VERSION_ID < 70100) {
|
||||
// 128 bits of entropy
|
||||
return strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
|
||||
}
|
||||
|
||||
// Otherwise, use random_bytes()
|
||||
return strtr(base64_encode(random_bytes(16)), '+', '.');
|
||||
}
|
||||
|
||||
function calc_cookie_name(bool $is_https, bool $is_path_jailed, string $base_name): string {
|
||||
if ($is_https) {
|
||||
if ($is_path_jailed) {
|
||||
return "__Host-$base_name";
|
||||
} else {
|
||||
return "__Secure-$base_name";
|
||||
}
|
||||
} else {
|
||||
return $base_name;
|
||||
}
|
||||
}
|
||||
|
||||
function login(string $username, string $password) {
|
||||
function login($username, $password) {
|
||||
global $mod, $config;
|
||||
|
||||
|
||||
$query = prepare("SELECT `id`, `type`, `boards`, `password`, `version` FROM ``mods`` WHERE BINARY `username` = :username");
|
||||
$query->bindValue(':username', $username);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
|
||||
if ($user = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
list($version, $ok) = test_password($user['password'], $user['version'], $password);
|
||||
|
||||
@ -100,83 +100,40 @@ function login(string $username, string $password) {
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
|
||||
return $mod = [
|
||||
return $mod = array(
|
||||
'id' => $user['id'],
|
||||
'type' => $user['type'],
|
||||
'username' => $username,
|
||||
'hash' => mkhash($username, $user['password']),
|
||||
'boards' => explode(',', $user['boards'])
|
||||
];
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function setCookies(): void {
|
||||
function setCookies() {
|
||||
global $mod, $config;
|
||||
if (!$mod) {
|
||||
if (!$mod)
|
||||
error('setCookies() was called for a non-moderator!');
|
||||
}
|
||||
|
||||
$is_https = Net\is_connection_secure($config['cookies']['secure_login_only'] === 1);
|
||||
$is_path_jailed = $config['cookies']['jail'];
|
||||
$name = calc_cookie_name($is_https, $is_path_jailed, $config['cookies']['mod']);
|
||||
|
||||
// <username>:<password>:<salt>
|
||||
$value = "{$mod['username']}:{$mod['hash'][0]}:{$mod['hash'][1]}";
|
||||
|
||||
$options = [
|
||||
'expires' => time() + $config['cookies']['expire'],
|
||||
'path' => $is_path_jailed ? $config['cookies']['path'] : '/',
|
||||
'secure' => $is_https,
|
||||
'httponly' => $config['cookies']['httponly'],
|
||||
'samesite' => 'Strict'
|
||||
];
|
||||
|
||||
setcookie($name, $value, $options);
|
||||
|
||||
setcookie($config['cookies']['mod'],
|
||||
$mod['username'] . // username
|
||||
':' .
|
||||
$mod['hash'][0] . // password
|
||||
':' .
|
||||
$mod['hash'][1], // salt
|
||||
time() + $config['cookies']['expire'], $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', $config['cookies']['httponly']);
|
||||
}
|
||||
|
||||
function destroyCookies(): void {
|
||||
function destroyCookies() {
|
||||
global $config;
|
||||
$base_name = $config['cookies']['mod'];
|
||||
$del_time = time() - 60 * 60 * 24 * 365; // 1 year.
|
||||
$jailed_path = $config['cookies']['jail'] ? $config['cookies']['path'] : '/';
|
||||
$http_only = $config['cookies']['httponly'];
|
||||
|
||||
$options_multi = [
|
||||
$base_name => [
|
||||
'expires' => $del_time,
|
||||
'path' => $jailed_path ,
|
||||
'secure' => false,
|
||||
'httponly' => $http_only,
|
||||
'samesite' => 'Strict'
|
||||
],
|
||||
"__Host-$base_name" => [
|
||||
'expires' => $del_time,
|
||||
'path' => $jailed_path,
|
||||
'secure' => true,
|
||||
'httponly' => $http_only,
|
||||
'samesite' => 'Strict'
|
||||
],
|
||||
"__Secure-$base_name" => [
|
||||
'expires' => $del_time,
|
||||
'path' => '/',
|
||||
'secure' => true,
|
||||
'httponly' => $http_only,
|
||||
'samesite' => 'Strict'
|
||||
]
|
||||
];
|
||||
|
||||
foreach ($options_multi as $name => $options) {
|
||||
if (isset($_COOKIE[$name])) {
|
||||
setcookie($name, 'deleted', $options);
|
||||
unset($_COOKIE[$name]);
|
||||
}
|
||||
}
|
||||
// Delete the cookies
|
||||
setcookie($config['cookies']['mod'], 'deleted', time() - $config['cookies']['expire'], $config['cookies']['jail']?$config['cookies']['path'] : '/', null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true);
|
||||
}
|
||||
|
||||
function modLog(string $action, ?string $_board = null): void {
|
||||
function modLog($action, $_board=null) {
|
||||
global $mod, $board, $config;
|
||||
$query = prepare("INSERT INTO ``modlogs`` VALUES (:id, :ip, :board, :time, :text)");
|
||||
$query->bindValue(':id', (isset($mod['id']) ? $mod['id'] : -1), PDO::PARAM_INT);
|
||||
@ -190,84 +147,70 @@ function modLog(string $action, ?string $_board = null): void {
|
||||
else
|
||||
$query->bindValue(':board', null, PDO::PARAM_NULL);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
if ($config['syslog']) {
|
||||
|
||||
if ($config['syslog'])
|
||||
_syslog(LOG_INFO, '[mod/' . $mod['username'] . ']: ' . $action);
|
||||
}
|
||||
}
|
||||
|
||||
function create_pm_header() {
|
||||
global $mod, $config;
|
||||
|
||||
|
||||
if ($config['cache']['enabled'] && ($header = cache::get('pm_unread_' . $mod['id'])) != false) {
|
||||
if ($header === true) {
|
||||
if ($header === true)
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return $header;
|
||||
}
|
||||
|
||||
|
||||
$query = prepare("SELECT `id` FROM ``pms`` WHERE `to` = :id AND `unread` = 1");
|
||||
$query->bindValue(':id', $mod['id'], PDO::PARAM_INT);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
if ($pm = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
$header = [ 'id' => $pm['id'], 'waiting' => $query->rowCount() - 1 ];
|
||||
} else {
|
||||
|
||||
if ($pm = $query->fetch(PDO::FETCH_ASSOC))
|
||||
$header = array('id' => $pm['id'], 'waiting' => $query->rowCount() - 1);
|
||||
else
|
||||
$header = true;
|
||||
}
|
||||
|
||||
if ($config['cache']['enabled']) {
|
||||
|
||||
if ($config['cache']['enabled'])
|
||||
cache::set('pm_unread_' . $mod['id'], $header);
|
||||
}
|
||||
|
||||
if ($header === true) {
|
||||
|
||||
if ($header === true)
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return $header;
|
||||
}
|
||||
|
||||
function make_secure_link_token(string $uri): string {
|
||||
function make_secure_link_token($uri) {
|
||||
global $mod, $config;
|
||||
return substr(sha1($config['cookies']['salt'] . '-' . $uri . '-' . $mod['id']), 0, 8);
|
||||
}
|
||||
|
||||
function check_login(Context $ctx, bool $prompt = false): void {
|
||||
function check_login($prompt = false) {
|
||||
global $config, $mod;
|
||||
|
||||
$is_https = Net\is_connection_secure($config['cookies']['secure_login_only'] === 1);
|
||||
$is_path_jailed = $config['cookies']['jail'];
|
||||
$expected_cookie_name = calc_cookie_name($is_https, $is_path_jailed, $config['cookies']['mod']);
|
||||
|
||||
// Validate session
|
||||
if (isset($_COOKIE[$expected_cookie_name])) {
|
||||
if (isset($_COOKIE[$config['cookies']['mod']])) {
|
||||
// Should be username:hash:salt
|
||||
$cookie = explode(':', $_COOKIE[$expected_cookie_name]);
|
||||
$cookie = explode(':', $_COOKIE[$config['cookies']['mod']]);
|
||||
if (count($cookie) != 3) {
|
||||
// Malformed cookies
|
||||
destroyCookies();
|
||||
if ($prompt) {
|
||||
mod_login($ctx);
|
||||
}
|
||||
if ($prompt) mod_login();
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
$query = prepare("SELECT `id`, `type`, `boards`, `password` FROM ``mods`` WHERE `username` = :username");
|
||||
$query->bindValue(':username', $cookie[0]);
|
||||
$query->execute() or error(db_error($query));
|
||||
$user = $query->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
// validate password hash
|
||||
if ($cookie[1] !== mkhash($cookie[0], $user['password'], $cookie[2])) {
|
||||
// Malformed cookies
|
||||
destroyCookies();
|
||||
if ($prompt) {
|
||||
mod_login($ctx);
|
||||
}
|
||||
if ($prompt) mod_login();
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
$mod = array(
|
||||
'id' => (int)$user['id'],
|
||||
'type' => (int)$user['type'],
|
||||
|
10
inc/mod/ban.php
Normal file
10
inc/mod/ban.php
Normal file
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
// This file is no longer used.
|
@ -64,10 +64,6 @@ function config_vars() {
|
||||
$var['comment'][] = $temp_comment;
|
||||
$temp_comment = false;
|
||||
}
|
||||
|
||||
if (preg_match('!^\s*\$config\[(\'log_system\'|\'captcha\')\]!', $line)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('!^\s*// ([^$].*)$!', $line, $matches)) {
|
||||
if ($var['default'] !== false) {
|
||||
|
2076
inc/mod/pages.php
2076
inc/mod/pages.php
File diff suppressed because it is too large
Load Diff
28
inc/polyfill.php
Normal file
28
inc/polyfill.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
// PHP 5.4
|
||||
|
||||
if (!function_exists('hex2bin')) {
|
||||
function hex2bin($data) {
|
||||
return pack("H*" , $hex_string);
|
||||
}
|
||||
}
|
||||
|
||||
// PHP 5.6
|
||||
|
||||
if (!function_exists('hash_equals')) {
|
||||
function hash_equals($ours, $theirs) {
|
||||
$ours = (string)$ours;
|
||||
$theirs = (string)$theirs;
|
||||
|
||||
$tlen = strlen($theirs);
|
||||
$olen = strlen($ours);
|
||||
|
||||
$answer = 0;
|
||||
for ($i = 0; $i < $tlen; $i++) {
|
||||
$answer |= ord($ours[$olen > $i ? $i : 0]) ^ ord($theirs[$i]);
|
||||
}
|
||||
|
||||
return $answer === 0 && $olen === $tlen;
|
||||
}
|
||||
}
|
131
inc/queue.php
131
inc/queue.php
@ -1,98 +1,49 @@
|
||||
<?php
|
||||
|
||||
class Queues {
|
||||
private static $queues = array();
|
||||
class Queue {
|
||||
function __construct($key) { global $config;
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$this->lock = new Lock($key);
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
$this->key = "tmp/queue/$key/";
|
||||
}
|
||||
}
|
||||
|
||||
function push($str) { global $config;
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$this->lock->get_ex();
|
||||
file_put_contents($this->key.microtime(true), $str);
|
||||
$this->lock->free();
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* This queue implementation isn't actually ordered, so it works more as a "bag".
|
||||
*/
|
||||
private static function filesystem(string $key, Lock $lock): Queue {
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
$key = "tmp/queue/$key/";
|
||||
|
||||
return new class($key, $lock) implements Queue {
|
||||
private Lock $lock;
|
||||
private string $key;
|
||||
|
||||
|
||||
function __construct(string $key, Lock $lock) {
|
||||
$this->lock = $lock;
|
||||
$this->key = $key;
|
||||
}
|
||||
|
||||
public function push(string $str): bool {
|
||||
$this->lock->get_ex();
|
||||
$ret = file_put_contents($this->key . microtime(true), $str);
|
||||
$this->lock->free();
|
||||
return $ret !== false;
|
||||
}
|
||||
|
||||
public function pop(int $n = 1): array {
|
||||
$this->lock->get_ex();
|
||||
$dir = opendir($this->key);
|
||||
$paths = array();
|
||||
|
||||
while ($n > 0) {
|
||||
$path = readdir($dir);
|
||||
if ($path === false) {
|
||||
break;
|
||||
} elseif ($path == '.' || $path == '..') {
|
||||
continue;
|
||||
} else {
|
||||
$paths[] = $path;
|
||||
$n--;
|
||||
}
|
||||
}
|
||||
|
||||
$out = array();
|
||||
foreach ($paths as $v) {
|
||||
$out[] = file_get_contents($this->key . $v);
|
||||
unlink($this->key . $v);
|
||||
}
|
||||
|
||||
$this->lock->free();
|
||||
return $out;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op. Can be used for mocking.
|
||||
*/
|
||||
public static function none(): Queue {
|
||||
return new class() implements Queue {
|
||||
public function push(string $str): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function pop(int $n = 1): array {
|
||||
return array();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static function get_queue(array $config, string $name) {
|
||||
if (!isset(self::$queues[$name])) {
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$lock = Locks::get_lock($config, $name);
|
||||
if ($lock === false) {
|
||||
return false;
|
||||
}
|
||||
self::$queues[$name] = self::filesystem($name, $lock);
|
||||
} else {
|
||||
self::$queues[$name] = self::none();
|
||||
}
|
||||
}
|
||||
return self::$queues[$name];
|
||||
}
|
||||
function pop($n = 1) { global $config;
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$this->lock->get_ex();
|
||||
$dir = opendir($this->key);
|
||||
$paths = array();
|
||||
while ($n > 0) {
|
||||
$path = readdir($dir);
|
||||
if ($path === FALSE) break;
|
||||
elseif ($path == '.' || $path == '..') continue;
|
||||
else { $paths[] = $path; $n--; }
|
||||
}
|
||||
$out = array();
|
||||
foreach ($paths as $v) {
|
||||
$out []= file_get_contents($this->key.$v);
|
||||
unlink($this->key.$v);
|
||||
}
|
||||
$this->lock->free();
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface Queue {
|
||||
// Push a string in the queue.
|
||||
public function push(string $str): bool;
|
||||
// Don't use the constructor. Use the get_queue function.
|
||||
$queues = array();
|
||||
|
||||
// Get a string from the queue.
|
||||
public function pop(int $n = 1): array;
|
||||
function get_queue($name) { global $queues;
|
||||
return $queues[$name] = isset ($queues[$name]) ? $queues[$name] : new Queue($name);
|
||||
}
|
||||
|
64
inc/remote.php
Normal file
64
inc/remote.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
class Remote {
|
||||
public function __construct($config) {
|
||||
foreach ($config as $name => $value) {
|
||||
$this->{$name} = $value;
|
||||
}
|
||||
|
||||
$methods = array();
|
||||
|
||||
if (!isset($this->auth['method']))
|
||||
error('Unspecified authentication method.');
|
||||
|
||||
// Connect
|
||||
$this->connection = ssh2_connect($this->host, isset($this->port) ? $this->port : 22, $methods);
|
||||
|
||||
switch ($this->auth['method']) {
|
||||
case 'pubkey':
|
||||
|
||||
if (!isset($this->auth['public']))
|
||||
error('Public key filename not specified.');
|
||||
if (!isset($this->auth['private']))
|
||||
error('Private key filename not specified.');
|
||||
|
||||
if (!ssh2_auth_pubkey_file($this->connection, $this->auth['username'], $this->auth['public'], $this->auth['private'], isset($this->auth['passphrase']) ? $this->auth['passphrase']: null))
|
||||
error('Public key authentication failed.');
|
||||
break;
|
||||
case 'plain':
|
||||
if (!ssh2_auth_password($this->connection, $this->auth['username'], $this->auth['password']))
|
||||
error('Plain-text authentication failed.');
|
||||
break;
|
||||
default:
|
||||
error('Unknown authentication method: "' . $this->auth['method'] . '".');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function write($data, $remote_path) {
|
||||
global $config;
|
||||
|
||||
switch ($this->type) {
|
||||
case 'sftp':
|
||||
$sftp = ssh2_sftp($this->connection);
|
||||
file_write('ssh2.sftp://' . $sftp . $remote_path, $data, true);
|
||||
break;
|
||||
case 'scp':
|
||||
$file = tempnam($config['tmp'], 'tinyboard-scp');
|
||||
// Write to temp file
|
||||
file_write($file, $data);
|
||||
|
||||
ssh2_scp_send($this->connection, $file, $remote_path, 0755);
|
||||
break;
|
||||
default:
|
||||
error('Unknown send method.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -1 +0,0 @@
|
||||
<?php
|
@ -1,143 +0,0 @@
|
||||
<?php // Verify captchas server side.
|
||||
namespace Vichan\Service;
|
||||
|
||||
use Vichan\Data\Driver\HttpDriver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class ReCaptchaQuery implements RemoteCaptchaQuery {
|
||||
private HttpDriver $http;
|
||||
private string $secret;
|
||||
|
||||
/**
|
||||
* Creates a new ReCaptchaQuery using the google recaptcha service.
|
||||
*
|
||||
* @param HttpDriver $http The http client.
|
||||
* @param string $secret Server side secret.
|
||||
* @return ReCaptchaQuery A new ReCaptchaQuery query instance.
|
||||
*/
|
||||
public function __construct(HttpDriver $http, string $secret) {
|
||||
$this->http = $http;
|
||||
$this->secret = $secret;
|
||||
}
|
||||
|
||||
public function responseField(): string {
|
||||
return 'g-recaptcha-response';
|
||||
}
|
||||
|
||||
public function verify(string $response, ?string $remote_ip): bool {
|
||||
$data = [
|
||||
'secret' => $this->secret,
|
||||
'response' => $response
|
||||
];
|
||||
|
||||
if ($remote_ip !== null) {
|
||||
$data['remoteip'] = $remote_ip;
|
||||
}
|
||||
|
||||
$ret = $this->http->requestGet('https://www.google.com/recaptcha/api/siteverify', $data);
|
||||
$resp = json_decode($ret, true, 16, JSON_THROW_ON_ERROR);
|
||||
|
||||
return isset($resp['success']) && $resp['success'];
|
||||
}
|
||||
}
|
||||
|
||||
class HCaptchaQuery implements RemoteCaptchaQuery {
|
||||
private HttpDriver $http;
|
||||
private string $secret;
|
||||
private string $sitekey;
|
||||
|
||||
/**
|
||||
* Creates a new HCaptchaQuery using the hCaptcha service.
|
||||
*
|
||||
* @param HttpDriver $http The http client.
|
||||
* @param string $secret Server side secret.
|
||||
* @return HCaptchaQuery A new hCaptcha query instance.
|
||||
*/
|
||||
public function __construct(HttpDriver $http, string $secret, string $sitekey) {
|
||||
$this->http = $http;
|
||||
$this->secret = $secret;
|
||||
$this->sitekey = $sitekey;
|
||||
}
|
||||
|
||||
public function responseField(): string {
|
||||
return 'h-captcha-response';
|
||||
}
|
||||
|
||||
public function verify(string $response, ?string $remote_ip): bool {
|
||||
$data = [
|
||||
'secret' => $this->secret,
|
||||
'response' => $response,
|
||||
'sitekey' => $this->sitekey
|
||||
];
|
||||
|
||||
if ($remote_ip !== null) {
|
||||
$data['remoteip'] = $remote_ip;
|
||||
}
|
||||
|
||||
$ret = $this->http->requestGet('https://hcaptcha.com/siteverify', $data);
|
||||
$resp = json_decode($ret, true, 16, JSON_THROW_ON_ERROR);
|
||||
|
||||
return isset($resp['success']) && $resp['success'];
|
||||
}
|
||||
}
|
||||
|
||||
interface RemoteCaptchaQuery {
|
||||
/**
|
||||
* Name of the response field in the form data expected by the implementation.
|
||||
*
|
||||
* @return string The name of the field.
|
||||
*/
|
||||
public function responseField(): string;
|
||||
|
||||
/**
|
||||
* Checks if the user at the remote ip passed the captcha.
|
||||
*
|
||||
* @param string $response User provided response.
|
||||
* @param ?string $remote_ip User ip. Leave to null to only check the response value.
|
||||
* @return bool Returns true if the user passed the captcha.
|
||||
* @throws RuntimeException|JsonException Throws on IO errors or if it fails to decode the answer.
|
||||
*/
|
||||
public function verify(string $response, ?string $remote_ip): bool;
|
||||
}
|
||||
|
||||
class NativeCaptchaQuery {
|
||||
private HttpDriver $http;
|
||||
private string $domain;
|
||||
private string $provider_check;
|
||||
private string $extra;
|
||||
|
||||
/**
|
||||
* @param HttpDriver $http The http client.
|
||||
* @param string $domain The server's domain.
|
||||
* @param string $provider_check Path to the endpoint.
|
||||
* @param string $extra Extra http parameters.
|
||||
*/
|
||||
function __construct(HttpDriver $http, string $domain, string $provider_check, string $extra) {
|
||||
$this->http = $http;
|
||||
$this->domain = $domain;
|
||||
$this->provider_check = $provider_check;
|
||||
$this->extra = $extra;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user at the remote ip passed the native vichan captcha.
|
||||
*
|
||||
* @param string $user_text Remote user's text input.
|
||||
* @param string $user_cookie Remote user cookie.
|
||||
* @return bool Returns true if the user passed the check.
|
||||
* @throws RuntimeException Throws on IO errors.
|
||||
*/
|
||||
public function verify(string $user_text, string $user_cookie): bool {
|
||||
$data = [
|
||||
'mode' => 'check',
|
||||
'text' => $user_text,
|
||||
'extra' => $this->extra,
|
||||
'cookie' => $user_cookie
|
||||
];
|
||||
|
||||
$ret = $this->http->requestGet($this->domain . '/' . $this->provider_check, $data);
|
||||
return $ret === '1';
|
||||
}
|
||||
}
|
196
inc/template.php
196
inc/template.php
@ -10,33 +10,31 @@ $twig = false;
|
||||
|
||||
function load_twig() {
|
||||
global $twig, $config;
|
||||
|
||||
$cache_dir = "{$config['dir']['template']}/cache/";
|
||||
|
||||
$loader = new Twig\Loader\FilesystemLoader($config['dir']['template']);
|
||||
$loader = new Twig_Loader_Filesystem($config['dir']['template']);
|
||||
$loader->setPaths($config['dir']['template']);
|
||||
$twig = new Twig\Environment($loader, array(
|
||||
$twig = new Twig_Environment($loader, array(
|
||||
'autoescape' => false,
|
||||
'cache' => is_writable('templates/') || (is_dir($cache_dir) && is_writable($cache_dir)) ?
|
||||
new TinyboardTwigCache($cache_dir) : false,
|
||||
'debug' => $config['debug'],
|
||||
'auto_reload' => $config['twig_auto_reload']
|
||||
'cache' => is_writable('templates') || (is_dir('templates/cache') && is_writable('templates/cache')) ?
|
||||
"{$config['dir']['template']}/cache" : false,
|
||||
'debug' => $config['debug']
|
||||
));
|
||||
if ($config['debug'])
|
||||
$twig->addExtension(new \Twig\Extension\DebugExtension());
|
||||
$twig->addExtension(new Tinyboard());
|
||||
$twig->addExtension(new PhpMyAdmin\Twig\Extensions\I18nExtension());
|
||||
$twig->addExtension(new Twig_Extensions_Extension_Tinyboard());
|
||||
$twig->addExtension(new Twig_Extensions_Extension_I18n());
|
||||
}
|
||||
|
||||
function Element($templateFile, array $options) {
|
||||
global $config, $debug, $twig, $build_pages;
|
||||
|
||||
|
||||
if (!$twig)
|
||||
load_twig();
|
||||
|
||||
|
||||
if (function_exists('create_pm_header') && ((isset($options['mod']) && $options['mod']) || isset($options['__mod'])) && !preg_match('!^mod/!', $templateFile)) {
|
||||
$options['pm'] = create_pm_header();
|
||||
}
|
||||
|
||||
if (isset($options['body']) && $config['debug']) {
|
||||
$_debug = $debug;
|
||||
|
||||
|
||||
if (isset($debug['start'])) {
|
||||
$_debug['time']['total'] = '~' . round((microtime(true) - $_debug['start']) * 1000, 2) . 'ms';
|
||||
$_debug['time']['init'] = '~' . round(($_debug['start_debug'] - $_debug['start']) * 1000, 2) . 'ms';
|
||||
@ -54,174 +52,18 @@ function Element($templateFile, array $options) {
|
||||
str_replace("\n", '<br/>', utf8tohtml(print_r($_debug, true))) .
|
||||
'</pre>';
|
||||
}
|
||||
|
||||
|
||||
// Read the template file
|
||||
if (@file_get_contents("{$config['dir']['template']}/{$templateFile}")) {
|
||||
if (@file_get_contents("{$config['dir']['template']}/${templateFile}")) {
|
||||
$body = $twig->render($templateFile, $options);
|
||||
|
||||
|
||||
if ($config['minify_html'] && preg_match('/\.html$/', $templateFile)) {
|
||||
$body = trim(preg_replace("/[\t\r\n]/", '', $body));
|
||||
}
|
||||
|
||||
|
||||
return $body;
|
||||
} else {
|
||||
throw new Exception("Template file '{$templateFile}' does not exist or is empty in '{$config['dir']['template']}'!");
|
||||
throw new Exception("Template file '${templateFile}' does not exist or is empty in '{$config['dir']['template']}'!");
|
||||
}
|
||||
}
|
||||
|
||||
class TinyboardTwigCache extends Twig\Cache\FilesystemCache {
|
||||
private string $directory;
|
||||
|
||||
public function __construct(string $directory) {
|
||||
parent::__construct($directory);
|
||||
$this->directory = $directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function was removed in Twig 2.x due to developer views on the Twig library.
|
||||
* Who says we can't keep it for ourselves though?
|
||||
*/
|
||||
public function clear() {
|
||||
$iter = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($this->directory),
|
||||
RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
|
||||
foreach ($iter as $file) {
|
||||
if ($file->isFile()) {
|
||||
@unlink($file->getPathname());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Tinyboard extends Twig\Extension\AbstractExtension
|
||||
{
|
||||
/**
|
||||
* Returns a list of filters to add to the existing list.
|
||||
*
|
||||
* @return array An array of filters
|
||||
*/
|
||||
public function getFilters()
|
||||
{
|
||||
return array(
|
||||
new Twig\TwigFilter('filesize', 'format_bytes'),
|
||||
new Twig\TwigFilter('truncate', 'twig_truncate_filter'),
|
||||
new Twig\TwigFilter('truncate_body', 'truncate'),
|
||||
new Twig\TwigFilter('truncate_filename', 'twig_filename_truncate_filter'),
|
||||
new Twig\TwigFilter('extension', 'twig_extension_filter'),
|
||||
new Twig\TwigFilter('sprintf', 'sprintf'),
|
||||
new Twig\TwigFilter('capcode', 'capcode'),
|
||||
new Twig\TwigFilter('remove_modifiers', 'remove_modifiers'),
|
||||
new Twig\TwigFilter('hasPermission', 'twig_hasPermission_filter'),
|
||||
new Twig\TwigFilter('date', 'twig_date_filter'),
|
||||
new Twig\TwigFilter('poster_id', 'poster_id'),
|
||||
new Twig\TwigFilter('count', 'count'),
|
||||
new Twig\TwigFilter('ago', 'Vichan\Functions\Format\ago'),
|
||||
new Twig\TwigFilter('until', 'Vichan\Functions\Format\until'),
|
||||
new Twig\TwigFilter('push', 'twig_push_filter'),
|
||||
new Twig\TwigFilter('bidi_cleanup', 'bidi_cleanup'),
|
||||
new Twig\TwigFilter('addslashes', 'addslashes'),
|
||||
new Twig\TwigFilter('cloak_ip', 'cloak_ip'),
|
||||
new Twig\TwigFilter('cloak_mask', 'cloak_mask'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of functions to add to the existing list.
|
||||
*
|
||||
* @return array An array of filters
|
||||
*/
|
||||
public function getFunctions()
|
||||
{
|
||||
return array(
|
||||
new Twig\TwigFunction('time', 'time'),
|
||||
new Twig\TwigFunction('floor', 'floor'),
|
||||
new Twig\TwigFunction('hiddenInputs', 'hiddenInputs'),
|
||||
new Twig\TwigFunction('hiddenInputsHash', 'hiddenInputsHash'),
|
||||
new Twig\TwigFunction('ratio', 'twig_ratio_function'),
|
||||
new Twig\TwigFunction('secure_link_confirm', 'twig_secure_link_confirm'),
|
||||
new Twig\TwigFunction('secure_link', 'twig_secure_link'),
|
||||
new Twig\TwigFunction('link_for', 'link_for')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the extension.
|
||||
*
|
||||
* @return string The extension name
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return 'tinyboard';
|
||||
}
|
||||
}
|
||||
|
||||
function twig_push_filter($array, $value) {
|
||||
array_push($array, $value);
|
||||
return $array;
|
||||
}
|
||||
|
||||
function twig_date_filter($date, $format) {
|
||||
if (is_numeric($date)) {
|
||||
$date = new DateTime("@$date", new DateTimeZone('UTC'));
|
||||
} else {
|
||||
$date = new DateTime($date, new DateTimeZone('UTC'));
|
||||
}
|
||||
return $date->format($format);
|
||||
}
|
||||
|
||||
function twig_hasPermission_filter($mod, $permission, $board = null) {
|
||||
return hasPermission($permission, $board, $mod);
|
||||
}
|
||||
|
||||
function twig_extension_filter($value, $case_insensitive = true) {
|
||||
$ext = mb_substr($value, mb_strrpos($value, '.') + 1);
|
||||
if($case_insensitive)
|
||||
$ext = mb_strtolower($ext);
|
||||
return $ext;
|
||||
}
|
||||
|
||||
function twig_sprintf_filter( $value, $var) {
|
||||
return sprintf($value, $var);
|
||||
}
|
||||
|
||||
function twig_truncate_filter($value, $length = 30, $preserve = false, $separator = '…') {
|
||||
if (mb_strlen($value) > $length) {
|
||||
if ($preserve) {
|
||||
if (false !== ($breakpoint = mb_strpos($value, ' ', $length))) {
|
||||
$length = $breakpoint;
|
||||
}
|
||||
}
|
||||
return mb_substr($value, 0, $length) . $separator;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function twig_filename_truncate_filter($value, $length = 30, $separator = '…') {
|
||||
if (mb_strlen($value) > $length) {
|
||||
$value = strrev($value);
|
||||
$array = array_reverse(explode(".", $value, 2));
|
||||
$array = array_map("strrev", $array);
|
||||
|
||||
$filename = &$array[0];
|
||||
$extension = isset($array[1]) ? $array[1] : false;
|
||||
|
||||
$filename = mb_substr($filename, 0, $length - ($extension ? mb_strlen($extension) + 1 : 0)) . $separator;
|
||||
|
||||
return implode(".", $array);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function twig_ratio_function($w, $h) {
|
||||
return fraction($w, $h, ':');
|
||||
}
|
||||
function twig_secure_link_confirm($text, $title, $confirm_message, $href) {
|
||||
global $config;
|
||||
|
||||
return '<a onclick="if (event.which==2) return true;if (confirm(\'' . htmlentities(addslashes($confirm_message)) . '\')) document.location=\'?/' . htmlspecialchars(addslashes($href . '/' . make_secure_link_token($href))) . '\';return false;" title="' . htmlentities($title) . '" href="?/' . $href . '">' . $text . '</a>';
|
||||
}
|
||||
function twig_secure_link($href) {
|
||||
return $href . '/' . make_secure_link_token($href);
|
||||
}
|
||||
|
192
install.php
192
install.php
@ -1,7 +1,7 @@
|
||||
<?php
|
||||
|
||||
// Installation/upgrade file
|
||||
define('VERSION', '5.2.1');
|
||||
// Installation/upgrade file
|
||||
define('VERSION', '5.1.4');
|
||||
require 'inc/bootstrap.php';
|
||||
loadConfig();
|
||||
|
||||
@ -59,41 +59,41 @@ $page = array(
|
||||
$config['minify_html'] = false;
|
||||
|
||||
if (file_exists($config['has_installed'])) {
|
||||
|
||||
|
||||
// Check the version number
|
||||
$version = trim(file_get_contents($config['has_installed']));
|
||||
if (empty($version))
|
||||
$version = 'v0.9.1';
|
||||
|
||||
|
||||
function __query($sql) {
|
||||
sql_open();
|
||||
|
||||
|
||||
if (mysql_version() >= 50503)
|
||||
return query($sql);
|
||||
else
|
||||
return query(str_replace('utf8mb4', 'utf8', $sql));
|
||||
}
|
||||
|
||||
|
||||
$boards = listBoards();
|
||||
|
||||
|
||||
switch ($version) {
|
||||
case 'v0.9':
|
||||
case 'v0.9.1':
|
||||
// Upgrade to v0.9.2-dev
|
||||
|
||||
|
||||
foreach ($boards as &$_board) {
|
||||
// Add `capcode` field after `trip`
|
||||
query(sprintf("ALTER TABLE `posts_%s` ADD `capcode` VARCHAR( 50 ) NULL AFTER `trip`", $_board['uri'])) or error(db_error());
|
||||
|
||||
|
||||
// Resize `trip` to 15 characters
|
||||
query(sprintf("ALTER TABLE `posts_%s` CHANGE `trip` `trip` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL", $_board['uri'])) or error(db_error());
|
||||
}
|
||||
case 'v0.9.2-dev':
|
||||
// Upgrade to v0.9.2-dev-1
|
||||
|
||||
|
||||
// New table: `theme_settings`
|
||||
query("CREATE TABLE IF NOT EXISTS `theme_settings` ( `name` varchar(40) NOT NULL, `value` text, UNIQUE KEY `name` (`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
|
||||
|
||||
// New table: `news`
|
||||
query("CREATE TABLE IF NOT EXISTS `news` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text NOT NULL, `time` int(11) NOT NULL, `subject` text NOT NULL, `body` text NOT NULL, UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;") or error(db_error());
|
||||
case 'v0.9.2.1-dev':
|
||||
@ -101,7 +101,7 @@ if (file_exists($config['has_installed'])) {
|
||||
// Fix broken version number/mistake
|
||||
$version = 'v0.9.2-dev-1';
|
||||
// Upgrade to v0.9.2-dev-2
|
||||
|
||||
|
||||
foreach ($boards as &$_board) {
|
||||
// Increase field sizes
|
||||
query(sprintf("ALTER TABLE `posts_%s` CHANGE `subject` `subject` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL", $_board['uri'])) or error(db_error());
|
||||
@ -109,7 +109,7 @@ if (file_exists($config['has_installed'])) {
|
||||
}
|
||||
case 'v0.9.2-dev-2':
|
||||
// Upgrade to v0.9.2-dev-3 (v0.9.2)
|
||||
|
||||
|
||||
foreach ($boards as &$_board) {
|
||||
// Add `custom_fields` field
|
||||
query(sprintf("ALTER TABLE `posts_%s` ADD `embed` TEXT NULL", $_board['uri'])) or error(db_error());
|
||||
@ -117,7 +117,7 @@ if (file_exists($config['has_installed'])) {
|
||||
case 'v0.9.2-dev-3': // v0.9.2-dev-3 == v0.9.2
|
||||
case 'v0.9.2':
|
||||
// Upgrade to v0.9.3-dev-1
|
||||
|
||||
|
||||
// Upgrade `theme_settings` table
|
||||
query("TRUNCATE TABLE `theme_settings`") or error(db_error());
|
||||
query("ALTER TABLE `theme_settings` ADD `theme` VARCHAR( 40 ) NOT NULL FIRST") or error(db_error());
|
||||
@ -142,16 +142,16 @@ if (file_exists($config['has_installed'])) {
|
||||
query(sprintf("ALTER TABLE `posts_%s` CHANGE `subject` `subject` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL", $_board['uri'])) or error(db_error());
|
||||
}
|
||||
case 'v0.9.3-dev-6':
|
||||
// change to InnoDB
|
||||
// change to MyISAM
|
||||
$tables = array(
|
||||
'bans', 'boards', 'ip_notes', 'modlogs', 'mods', 'mutes', 'noticeboard', 'pms', 'reports', 'robot', 'theme_settings', 'news'
|
||||
);
|
||||
foreach ($boards as &$board) {
|
||||
$tables[] = "posts_{$board['uri']}";
|
||||
}
|
||||
|
||||
|
||||
foreach ($tables as &$table) {
|
||||
query("ALTER TABLE `{$table}` ENGINE = INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci") or error(db_error());
|
||||
query("ALTER TABLE `{$table}` ENGINE = MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci") or error(db_error());
|
||||
}
|
||||
case 'v0.9.3-dev-7':
|
||||
foreach ($boards as &$board) {
|
||||
@ -173,10 +173,10 @@ if (file_exists($config['has_installed'])) {
|
||||
query("ALTER TABLE `boards` DROP PRIMARY KEY") or error(db_error());
|
||||
query("ALTER TABLE `reports` DROP INDEX `id`") or error(db_error());
|
||||
query("ALTER TABLE `boards` DROP INDEX `uri`") or error(db_error());
|
||||
|
||||
|
||||
query("ALTER IGNORE TABLE `robot` ADD PRIMARY KEY (`hash`)") or error(db_error());
|
||||
query("ALTER TABLE `bans` ADD FULLTEXT (`ip`)") or error(db_error());
|
||||
query("ALTER TABLE `ip_notes` ADD INDEX (`ip`)") or error(db_error());
|
||||
query("ALTER TABLE `ip_notes` ADD INDEX (`ip`)") or error(db_error());
|
||||
query("ALTER TABLE `modlogs` ADD INDEX (`time`)") or error(db_error());
|
||||
query("ALTER TABLE `boards` ADD PRIMARY KEY(`uri`)") or error(db_error());
|
||||
query("ALTER TABLE `mutes` ADD INDEX (`ip`)") or error(db_error());
|
||||
@ -194,9 +194,9 @@ if (file_exists($config['has_installed'])) {
|
||||
<p style="text-align:center">
|
||||
<a href="?confirm=1">I have read and understood the agreement. Proceed to upgrading.</a>
|
||||
</p>';
|
||||
|
||||
|
||||
file_write($config['has_installed'], 'v0.9.4-dev-2');
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
case 'v0.9.4-dev-3':
|
||||
@ -212,16 +212,16 @@ if (file_exists($config['has_installed'])) {
|
||||
foreach ($boards as &$board) {
|
||||
query(sprintf("ALTER TABLE `posts_%s` ADD `body_nomarkup` TEXT NULL AFTER `body`", $board['uri'])) or error(db_error());
|
||||
}
|
||||
query("CREATE TABLE IF NOT EXISTS `cites` ( `board` varchar(8) NOT NULL, `post` int(11) NOT NULL, `target_board` varchar(8) NOT NULL, `target` int(11) NOT NULL, KEY `target` (`target_board`,`target`), KEY `post` (`board`,`post`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
query("CREATE TABLE IF NOT EXISTS `cites` ( `board` varchar(8) NOT NULL, `post` int(11) NOT NULL, `target_board` varchar(8) NOT NULL, `target` int(11) NOT NULL, KEY `target` (`target_board`,`target`), KEY `post` (`board`,`post`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
case 'v0.9.5-dev-2':
|
||||
query("ALTER TABLE `boards`
|
||||
query("ALTER TABLE `boards`
|
||||
CHANGE `uri` `uri` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
|
||||
CHANGE `title` `title` VARCHAR( 40 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
|
||||
CHANGE `subtitle` `subtitle` VARCHAR( 120 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL") or error(db_error());
|
||||
case 'v0.9.5-dev-3':
|
||||
// v0.9.5
|
||||
case 'v0.9.5':
|
||||
query("ALTER TABLE `boards`
|
||||
query("ALTER TABLE `boards`
|
||||
CHANGE `uri` `uri` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
|
||||
CHANGE `title` `title` TINYTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
|
||||
CHANGE `subtitle` `subtitle` TINYTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL") or error(db_error());
|
||||
@ -235,7 +235,7 @@ if (file_exists($config['has_installed'])) {
|
||||
`passed` smallint(6) NOT NULL,
|
||||
PRIMARY KEY (`hash`),
|
||||
KEY `board` (`board`,`thread`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
case 'v0.9.6-dev-2':
|
||||
query("ALTER TABLE `boards`
|
||||
DROP `id`,
|
||||
@ -248,12 +248,12 @@ if (file_exists($config['has_installed'])) {
|
||||
$query->bindValue(':newboard', $board['uri']);
|
||||
$query->bindValue(':oldboard', $board['id']);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
|
||||
$query = prepare("UPDATE `modlogs` SET `board` = :newboard WHERE `board` = :oldboard");
|
||||
$query->bindValue(':newboard', $board['uri']);
|
||||
$query->bindValue(':oldboard', $board['id']);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
|
||||
$query = prepare("UPDATE `reports` SET `board` = :newboard WHERE `board` = :oldboard");
|
||||
$query->bindValue(':newboard', $board['uri']);
|
||||
$query->bindValue(':oldboard', $board['id']);
|
||||
@ -291,10 +291,10 @@ if (file_exists($config['has_installed'])) {
|
||||
if (strlen($user['password']) == 40) {
|
||||
mt_srand(microtime(true) * 100000 + memory_get_usage(true));
|
||||
$salt = md5(uniqid(mt_rand(), true));
|
||||
|
||||
|
||||
$user['salt'] = $salt;
|
||||
$user['password'] = hash('sha256', $user['salt'] . $user['password']);
|
||||
|
||||
|
||||
$_query = prepare("UPDATE `mods` SET `password` = :password, `salt` = :salt WHERE `id` = :id");
|
||||
$_query->bindValue(':id', $user['id']);
|
||||
$_query->bindValue(':password', $user['password']);
|
||||
@ -326,7 +326,7 @@ if (file_exists($config['has_installed'])) {
|
||||
CHANGE `embed` `embed` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;", $board['uri'])) or error(db_error());
|
||||
}
|
||||
|
||||
|
||||
__query("ALTER TABLE `antispam`
|
||||
CHANGE `board` `board` VARCHAR( 120 ) CHARACTER SET ASCII COLLATE ascii_general_ci NOT NULL ,
|
||||
CHANGE `hash` `hash` CHAR( 40 ) CHARACTER SET ASCII COLLATE ascii_bin NOT NULL ,
|
||||
@ -462,7 +462,7 @@ if (file_exists($config['has_installed'])) {
|
||||
KEY `posthash` (`posthash`),
|
||||
KEY `filehash` (`filehash`),
|
||||
KEY `time` (`time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=ascii COLLATE=ascii_bin AUTO_INCREMENT=1 ;") or error(db_error());
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=ascii COLLATE=ascii_bin AUTO_INCREMENT=1 ;") or error(db_error());
|
||||
case 'v0.9.6-dev-19':
|
||||
query("UPDATE ``mods`` SET `type` = 10 WHERE `type` = 0") or error(db_error());
|
||||
query("UPDATE ``mods`` SET `type` = 20 WHERE `type` = 1") or error(db_error());
|
||||
@ -483,47 +483,47 @@ if (file_exists($config['has_installed'])) {
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `expires` (`expires`),
|
||||
KEY `ipstart` (`ipstart`,`ipend`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1") or error(db_error());
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1") or error(db_error());
|
||||
$listquery = query("SELECT * FROM ``bans`` ORDER BY `id`") or error(db_error());
|
||||
while ($ban = $listquery->fetch(PDO::FETCH_ASSOC)) {
|
||||
$query = prepare("INSERT INTO ``bans_new_temp`` VALUES
|
||||
$query = prepare("INSERT INTO ``bans_new_temp`` VALUES
|
||||
(NULL, :ipstart, :ipend, :created, :expires, :board, :creator, :reason, :seen, NULL)");
|
||||
|
||||
|
||||
$range = Bans::parse_range($ban['ip']);
|
||||
if ($range === false) {
|
||||
// Invalid retard ban; just skip it.
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
$query->bindValue(':ipstart', $range[0]);
|
||||
if ($range[1] !== false && $range[1] != $range[0])
|
||||
$query->bindValue(':ipend', $range[1]);
|
||||
else
|
||||
$query->bindValue(':ipend', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
$query->bindValue(':created', $ban['set']);
|
||||
|
||||
|
||||
if ($ban['expires'])
|
||||
$query->bindValue(':expires', $ban['expires']);
|
||||
else
|
||||
$query->bindValue(':expires', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
if ($ban['board'])
|
||||
$query->bindValue(':board', $ban['board']);
|
||||
else
|
||||
$query->bindValue(':board', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
$query->bindValue(':creator', $ban['mod']);
|
||||
|
||||
|
||||
if ($ban['reason'])
|
||||
$query->bindValue(':reason', $ban['reason']);
|
||||
else
|
||||
$query->bindValue(':reason', null, PDO::PARAM_NULL);
|
||||
|
||||
|
||||
$query->bindValue(':seen', $ban['seen']);
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
|
||||
|
||||
// Drop old bans table
|
||||
query("DROP TABLE ``bans``") or error(db_error());
|
||||
// Replace with new table
|
||||
@ -538,7 +538,7 @@ if (file_exists($config['has_installed'])) {
|
||||
`denied` tinyint(1) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ban_id` (`ban_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;") or error(db_error());
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;") or error(db_error());
|
||||
case 'v0.9.6-dev-22':
|
||||
case 'v0.9.6-dev-22 + <a href="https://int.vichan.net/devel/">vichan-devel-4.4.91</a>':
|
||||
case 'v0.9.6-dev-22 + <a href="https://int.vichan.net/devel/">vichan-devel-4.4.92</a>':
|
||||
@ -555,9 +555,9 @@ if (file_exists($config['has_installed'])) {
|
||||
<p style="text-align:center">
|
||||
<a href="?confirm2=1">I have read and understood the agreement. Proceed to upgrading.</a>
|
||||
</p>';
|
||||
|
||||
|
||||
file_write($config['has_installed'], '4.4.97');
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
case '4.4.98-pre':
|
||||
@ -573,9 +573,9 @@ if (file_exists($config['has_installed'])) {
|
||||
<p style="text-align:center">
|
||||
<a href="?confirm3=1">I have read and understood the warning. Proceed to upgrading.</a>
|
||||
</p>';
|
||||
|
||||
|
||||
file_write($config['has_installed'], '4.5.2');
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@ -634,14 +634,14 @@ if (file_exists($config['has_installed'])) {
|
||||
`text` varchar(255),
|
||||
`created_at` int(11),
|
||||
PRIMARY KEY (`cookie`,`extra`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;') or error(db_error());
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;') or error(db_error());
|
||||
case false:
|
||||
// TODO: enhance Tinyboard -> vichan upgrade path.
|
||||
query("CREATE TABLE IF NOT EXISTS ``search_queries`` ( `ip` varchar(39) NOT NULL, `time` int(11) NOT NULL, `query` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
query("CREATE TABLE IF NOT EXISTS ``search_queries`` ( `ip` varchar(39) NOT NULL, `time` int(11) NOT NULL, `query` text NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;") or error(db_error());
|
||||
|
||||
// Update version number
|
||||
file_write($config['has_installed'], VERSION);
|
||||
|
||||
|
||||
$page['title'] = 'Upgraded';
|
||||
$page['body'] = '<p style="text-align:center">Successfully upgraded from ' . $version . ' to <strong>' . VERSION . '</strong>.</p>';
|
||||
break;
|
||||
@ -653,8 +653,8 @@ if (file_exists($config['has_installed'])) {
|
||||
$page['title'] = 'Already installed';
|
||||
$page['body'] = '<p style="text-align:center">It appears that vichan is already installed (' . $version . ') and there is nothing to upgrade! Delete <strong>' . $config['has_installed'] . '</strong> to reinstall.</p>';
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
die(Element('page.html', $page));
|
||||
}
|
||||
|
||||
@ -686,13 +686,11 @@ if ($step == 0) {
|
||||
<p style="text-align:center">
|
||||
<a href="?step=1">I have read and understood the agreement. Proceed to installation.</a>
|
||||
</p>';
|
||||
|
||||
|
||||
echo Element('page.html', $page);
|
||||
} elseif ($step == 1) {
|
||||
// The HTTPS check doesn't work properly when in those arrays, so let's run it here and pass along the result during the actual check.
|
||||
$httpsvalue = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
|
||||
$page['title'] = 'Pre-installation test';
|
||||
|
||||
|
||||
$can_exec = true;
|
||||
if (!function_exists('shell_exec'))
|
||||
$can_exec = false;
|
||||
@ -702,12 +700,12 @@ if ($step == 0) {
|
||||
$can_exec = false;
|
||||
elseif (trim(shell_exec('echo "TEST"')) !== 'TEST')
|
||||
$can_exec = false;
|
||||
|
||||
|
||||
if (!defined('PHP_VERSION_ID')) {
|
||||
$version = explode('.', PHP_VERSION);
|
||||
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
|
||||
}
|
||||
|
||||
|
||||
// Required extensions
|
||||
$extensions = array(
|
||||
'PDO' => array(
|
||||
@ -731,10 +729,17 @@ if ($step == 0) {
|
||||
$tests = array(
|
||||
array(
|
||||
'category' => 'PHP',
|
||||
'name' => 'PHP ≥ 7.4',
|
||||
'name' => 'PHP ≥ 5.4',
|
||||
'result' => PHP_VERSION_ID >= 50400,
|
||||
'required' => true,
|
||||
'message' => 'vichan requires PHP 7.4 or better.',
|
||||
'message' => 'vichan requires PHP 5.4 or better.',
|
||||
),
|
||||
array(
|
||||
'category' => 'PHP',
|
||||
'name' => 'PHP ≥ 5.6',
|
||||
'result' => PHP_VERSION_ID >= 50600,
|
||||
'required' => false,
|
||||
'message' => 'vichan works best on PHP 5.6 or better.',
|
||||
),
|
||||
array(
|
||||
'category' => 'PHP',
|
||||
@ -851,14 +856,14 @@ if ($step == 0) {
|
||||
array(
|
||||
'category' => 'File permissions',
|
||||
'name' => getcwd() . '/templates/cache',
|
||||
'result' => is_dir('templates/cache/') && is_writable('templates/cache/'),
|
||||
'result' => is_writable('templates') || (is_dir('templates/cache') && is_writable('templates/cache')),
|
||||
'required' => true,
|
||||
'message' => 'You must give vichan permission to create (and write to) the <code>templates/cache</code> directory or performance will be drastically reduced.'
|
||||
),
|
||||
array(
|
||||
'category' => 'File permissions',
|
||||
'name' => getcwd() . '/tmp/cache',
|
||||
'result' => is_dir('tmp/cache/') && is_writable('tmp/cache/'),
|
||||
'result' => is_dir('tmp/cache') && is_writable('tmp/cache'),
|
||||
'required' => true,
|
||||
'message' => 'You must give vichan permission to write to the <code>tmp/cache</code> directory.'
|
||||
),
|
||||
@ -871,17 +876,12 @@ if ($step == 0) {
|
||||
),
|
||||
array(
|
||||
'category' => 'Misc',
|
||||
'name' => 'HTTPS being used',
|
||||
'result' => $httpsvalue,
|
||||
'name' => 'Caching available (APC(u), XCache, Memcached or Redis)',
|
||||
'result' => extension_loaded('apcu') || extension_loaded('apc') ||
|
||||
extension_loaded('xcache') || extension_loaded('memcached') ||
|
||||
extension_loaded('redis'),
|
||||
'required' => false,
|
||||
'message' => 'You are not currently using https for vichan, or at least for your backend server. If this intentional, add "$config[\'cookies\'][\'secure_login_only\'] = 0;" (or 1 if using a proxy) on a new line under "Additional configuration" on the next page.'
|
||||
),
|
||||
array(
|
||||
'category' => 'Misc',
|
||||
'name' => 'Caching available (APCu, Memcached or Redis)',
|
||||
'result' => extension_loaded('apcu') || extension_loaded('memcached') || extension_loaded('redis'),
|
||||
'required' => false,
|
||||
'message' => 'You will not be able to enable the additional caching system, designed to minimize SQL queries and significantly improve performance. <a href="https://www.php.net/manual/en/book.apcu.php">APCu</a> is the recommended method of caching, but <a href="http://www.php.net/manual/en/intro.memcached.php">Memcached</a> and <a href="http://pecl.php.net/package/redis">Redis</a> are also supported.'
|
||||
'message' => 'You will not be able to enable the additional caching system, designed to minimize SQL queries and significantly improve performance. <a href="http://php.net/manual/en/book.apc.php">APC</a> is the recommended method of caching, but <a href="http://xcache.lighttpd.net/">XCache</a>, <a href="http://www.php.net/manual/en/intro.memcached.php">Memcached</a> and <a href="http://pecl.php.net/package/redis">Redis</a> are also supported.'
|
||||
),
|
||||
array(
|
||||
'category' => 'Misc',
|
||||
@ -893,7 +893,7 @@ if ($step == 0) {
|
||||
);
|
||||
|
||||
$config['font_awesome'] = true;
|
||||
|
||||
|
||||
$additional_config = array();
|
||||
foreach ($tests as $test) {
|
||||
if ($test['result'] && isset($test['effect'])) {
|
||||
@ -921,8 +921,7 @@ if ($step == 0) {
|
||||
$sg = new SaltGen();
|
||||
$config['cookies']['salt'] = $sg->generate();
|
||||
$config['secure_trip_salt'] = $sg->generate();
|
||||
$config['secure_password_salt'] = $sg->generate();
|
||||
|
||||
|
||||
echo Element('page.html', array(
|
||||
'body' => Element('installer/config.html', array(
|
||||
'config' => $config,
|
||||
@ -935,7 +934,7 @@ if ($step == 0) {
|
||||
$more = $_POST['more'];
|
||||
unset($_POST['more']);
|
||||
|
||||
$instance_config =
|
||||
$instance_config =
|
||||
'<'.'?php
|
||||
|
||||
/*
|
||||
@ -947,13 +946,13 @@ if ($step == 0) {
|
||||
*/
|
||||
|
||||
';
|
||||
|
||||
|
||||
create_config_from_array($instance_config, $_POST);
|
||||
|
||||
|
||||
$instance_config .= "\n";
|
||||
$instance_config .= $more;
|
||||
$instance_config .= "\n";
|
||||
|
||||
|
||||
if (@file_put_contents('inc/secrets.php', $instance_config)) {
|
||||
// flushes opcache if php >= 5.5.0 or opcache is installed via PECL
|
||||
if (function_exists('opcache_invalidate')) {
|
||||
@ -974,38 +973,34 @@ if ($step == 0) {
|
||||
}
|
||||
} elseif ($step == 4) {
|
||||
// SQL installation
|
||||
|
||||
|
||||
buildJavascript();
|
||||
|
||||
|
||||
$sql = @file_get_contents('install.sql') or error("Couldn't load install.sql.");
|
||||
|
||||
|
||||
sql_open();
|
||||
$mysql_version = mysql_version();
|
||||
|
||||
|
||||
// This code is probably horrible, but what I'm trying
|
||||
// to do is find all of the SQL queires and put them
|
||||
// in an array.
|
||||
preg_match_all("/(^|\n)((SET|CREATE|INSERT).+)\n\n/msU", $sql, $queries);
|
||||
$queries = $queries[2];
|
||||
|
||||
|
||||
$queries[] = Element('posts.sql', array('board' => 'b'));
|
||||
|
||||
|
||||
$sql_errors = '';
|
||||
$sql_err_count = 0;
|
||||
foreach ($queries as $query) {
|
||||
if ($mysql_version < 50503)
|
||||
$query = preg_replace('/(CHARSET=|CHARACTER SET )utf8mb4/', '$1utf8', $query);
|
||||
$query = preg_replace('/^([\w\s]*)`([0-9a-zA-Z$_\x{0080}-\x{FFFF}]+)`/u', '$1``$2``', $query);
|
||||
if (!query($query)) {
|
||||
$sql_err_count++;
|
||||
$error = db_error();
|
||||
$sql_errors .= "<li>$sql_err_count<ul><li>$query</li><li>$error</li></ul></li>";
|
||||
}
|
||||
if (!query($query))
|
||||
$sql_errors .= '<li>' . db_error() . '</li>';
|
||||
}
|
||||
|
||||
|
||||
$page['title'] = 'Installation complete';
|
||||
$page['body'] = '<p style="text-align:center">Thank you for using vichan. Please remember to report any bugs you discover. <a href="https://github.com/vichan-devel/vichan/wiki/Configuration-Basics">How do I edit the config files?</a></p>';
|
||||
|
||||
|
||||
if (!empty($sql_errors)) {
|
||||
$page['body'] .= '<div class="ban"><h2>SQL errors</h2><p>SQL errors were encountered when trying to install the database. This may be the result of using a database which is already occupied with a vichan installation; if so, you can probably ignore this.</p><p>The errors encountered were:</p><ul>' . $sql_errors . '</ul><p><a href="?step=5">Ignore errors and complete installation.</a></p></div>';
|
||||
} else {
|
||||
@ -1014,28 +1009,29 @@ if ($step == 0) {
|
||||
setupBoard($_board);
|
||||
buildIndex();
|
||||
}
|
||||
|
||||
|
||||
file_write($config['has_installed'], VERSION);
|
||||
/*if (!file_unlink(__FILE__)) {
|
||||
$page['body'] .= '<div class="ban"><h2>Delete install.php!</h2><p>I couldn\'t remove <strong>install.php</strong>. You will have to remove it manually.</p></div>';
|
||||
}*/
|
||||
}
|
||||
|
||||
|
||||
echo Element('page.html', $page);
|
||||
} elseif ($step == 5) {
|
||||
$page['title'] = 'Installation complete';
|
||||
$page['body'] = '<p style="text-align:center">Thank you for using vichan. Please remember to report any bugs you discover.</p>';
|
||||
|
||||
|
||||
$boards = listBoards();
|
||||
foreach ($boards as &$_board) {
|
||||
setupBoard($_board);
|
||||
buildIndex();
|
||||
}
|
||||
|
||||
|
||||
file_write($config['has_installed'], VERSION);
|
||||
if (!file_unlink(__FILE__)) {
|
||||
$page['body'] .= '<div class="ban"><h2>Delete install.php!</h2><p>I couldn\'t remove <strong>install.php</strong>. You will have to remove it manually.</p></div>';
|
||||
}
|
||||
|
||||
|
||||
echo Element('page.html', $page);
|
||||
}
|
||||
|
||||
|
58
install.sql
58
install.sql
@ -31,7 +31,7 @@ CREATE TABLE IF NOT EXISTS `antispam` (
|
||||
PRIMARY KEY (`hash`),
|
||||
KEY `board` (`board`,`thread`),
|
||||
KEY `expires` (`expires`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=ascii COLLATE=ascii_bin;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=ascii COLLATE=ascii_bin;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -53,7 +53,7 @@ CREATE TABLE IF NOT EXISTS `bans` (
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `expires` (`expires`),
|
||||
KEY `ipstart` (`ipstart`,`ipend`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -67,7 +67,7 @@ CREATE TABLE IF NOT EXISTS `boards` (
|
||||
`subtitle` tinytext,
|
||||
-- `indexed` boolean default true,
|
||||
PRIMARY KEY (`uri`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
--
|
||||
-- Dumping data for table `boards`
|
||||
@ -89,7 +89,7 @@ CREATE TABLE IF NOT EXISTS `cites` (
|
||||
`target` int(11) NOT NULL,
|
||||
KEY `target` (`target_board`,`target`),
|
||||
KEY `post` (`board`,`post`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -105,7 +105,7 @@ CREATE TABLE IF NOT EXISTS `ip_notes` (
|
||||
`body` text NOT NULL,
|
||||
UNIQUE KEY `id` (`id`),
|
||||
KEY `ip_lookup` (`ip`, `time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -121,7 +121,7 @@ CREATE TABLE IF NOT EXISTS `modlogs` (
|
||||
`text` text NOT NULL,
|
||||
KEY `time` (`time`),
|
||||
KEY `mod`(`mod`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -138,7 +138,7 @@ CREATE TABLE IF NOT EXISTS `mods` (
|
||||
`boards` text CHARACTER SET utf8 NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `id` (`id`,`username`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
--
|
||||
-- Dumping data for table `mods`
|
||||
@ -157,7 +157,7 @@ CREATE TABLE IF NOT EXISTS `mutes` (
|
||||
`ip` varchar(39) NOT NULL,
|
||||
`time` int(11) NOT NULL,
|
||||
KEY `ip` (`ip`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=ascii;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=ascii;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -173,7 +173,7 @@ CREATE TABLE IF NOT EXISTS `news` (
|
||||
`body` text NOT NULL,
|
||||
UNIQUE KEY `id` (`id`),
|
||||
KEY `time` (`time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -189,7 +189,7 @@ CREATE TABLE IF NOT EXISTS `noticeboard` (
|
||||
`body` text NOT NULL,
|
||||
UNIQUE KEY `id` (`id`),
|
||||
KEY `time` (`time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -206,7 +206,7 @@ CREATE TABLE IF NOT EXISTS `pms` (
|
||||
`unread` tinyint(1) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `to` (`to`, `unread`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -222,7 +222,7 @@ CREATE TABLE IF NOT EXISTS `reports` (
|
||||
`post` int(11) NOT NULL,
|
||||
`reason` text NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -233,7 +233,7 @@ CREATE TABLE IF NOT EXISTS `reports` (
|
||||
CREATE TABLE IF NOT EXISTS `robot` (
|
||||
`hash` varchar(40) COLLATE ascii_bin NOT NULL COMMENT 'SHA1',
|
||||
PRIMARY KEY (`hash`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=ascii COLLATE=ascii_bin;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=ascii COLLATE=ascii_bin;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -245,7 +245,7 @@ CREATE TABLE IF NOT EXISTS `search_queries` (
|
||||
`ip` varchar(39) NOT NULL,
|
||||
`time` int(11) NOT NULL,
|
||||
`query` text NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -258,7 +258,7 @@ CREATE TABLE IF NOT EXISTS `theme_settings` (
|
||||
`name` varchar(40) DEFAULT NULL,
|
||||
`value` text,
|
||||
KEY `theme` (`theme`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -279,7 +279,7 @@ CREATE TABLE IF NOT EXISTS `flood` (
|
||||
KEY `posthash` (`posthash`),
|
||||
KEY `filehash` (`filehash`),
|
||||
KEY `time` (`time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=ascii COLLATE=ascii_bin AUTO_INCREMENT=1 ;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=ascii COLLATE=ascii_bin AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -294,9 +294,8 @@ CREATE TABLE IF NOT EXISTS `ban_appeals` (
|
||||
`message` text NOT NULL,
|
||||
`denied` tinyint(1) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ban_id` (`ban_id`),
|
||||
CONSTRAINT `fk_ban_id` FOREIGN KEY (`ban_id`) REFERENCES `bans`(`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
KEY `ban_id` (`ban_id`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -313,7 +312,7 @@ CREATE TABLE IF NOT EXISTS `pages` (
|
||||
`content` text,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `u_pages` (`name`,`board`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -331,7 +330,7 @@ CREATE TABLE IF NOT EXISTS `nntp_references` (
|
||||
PRIMARY KEY (`message_id_digest`),
|
||||
UNIQUE KEY `message_id` (`message_id`),
|
||||
UNIQUE KEY `u_board_id` (`board`, `id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
@ -345,8 +344,23 @@ CREATE TABLE IF NOT EXISTS `captchas` (
|
||||
`text` VARCHAR(255),
|
||||
`created_at` INT(11),
|
||||
PRIMARY KEY (`cookie`,`extra`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Table structure for table `telegrams`
|
||||
--
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `telegrams` (
|
||||
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`mod_id` int(11) unsigned NOT NULL,
|
||||
`ip` varchar(39) CHARACTER SET ascii NOT NULL,
|
||||
`message` text NOT NULL,
|
||||
`seen` tinyint(1) NOT NULL DEFAULT FALSE,
|
||||
`created_at` INT(11),
|
||||
PRIMARY KEY(`id`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
||||
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
|
||||
|
@ -15,9 +15,6 @@
|
||||
* //$config['additional_javascript'][] = 'js/titlebar-notifications.js';
|
||||
* $config['additional_javascript'][] = 'js/auto-reload.js';
|
||||
*
|
||||
* You must have boardlinks or else this script will not load.
|
||||
* Search for "$config['boards'] = array(" within your inc/config.php and add something similar to your instance-config.php.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
@ -244,3 +241,4 @@ $(document).ready(function(){
|
||||
auto_update(poll_interval_delay);
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -13,41 +13,46 @@
|
||||
*/
|
||||
|
||||
function catalog() {
|
||||
var board = $("input[name='board']");
|
||||
var boardValue = board.first().val();
|
||||
var board = $("input[name='board']");
|
||||
|
||||
var catalog_url = '';
|
||||
if (window.location.href.includes('mod.php?/')) {
|
||||
catalog_url = configRoot + 'mod.php?/' + boardValue + '/catalog.html';
|
||||
} else {
|
||||
catalog_url = configRoot + boardValue + '/catalog.html';
|
||||
}
|
||||
var catalog_url = configRoot + board.first().val() + "/catalog.html";
|
||||
|
||||
var pages = document.getElementsByClassName('pages')[0];
|
||||
var bottom = document.getElementsByClassName('boardlist bottom')[0];
|
||||
var subtitle = document.getElementsByClassName('subtitle')[0];
|
||||
var pages = document.getElementsByClassName('pages')[0];
|
||||
var bottom = document.getElementsByClassName('boardlist bottom')[0]
|
||||
var subtitle = document.getElementsByClassName('subtitle')[0];
|
||||
|
||||
var link = document.createElement('a');
|
||||
link.href = catalog_url;
|
||||
var link = document.createElement('a');
|
||||
link.href = catalog_url;
|
||||
|
||||
if (!pages) {
|
||||
link.textContent = '['+_('Catalog')+']';
|
||||
link.style.paddingLeft = '10px';
|
||||
link.style.textDecoration = "underline";
|
||||
document.body.insertBefore(link, bottom);
|
||||
}
|
||||
if (pages) {
|
||||
link.textContent = _('Catalog');
|
||||
link.style.color = '#F10000';
|
||||
link.style.padding = '4px';
|
||||
link.style.paddingLeft = '9px';
|
||||
link.style.borderLeft = '1px solid'
|
||||
link.style.borderLeftColor = '#A8A8A8';
|
||||
link.style.textDecoration = "underline";
|
||||
|
||||
if (subtitle) {
|
||||
var link2 = document.createElement('a');
|
||||
link2.textContent = _('Catalog');
|
||||
link2.href = catalog_url;
|
||||
pages.appendChild(link)
|
||||
}
|
||||
else {
|
||||
link.textContent = '['+_('Catalog')+']';
|
||||
link.style.paddingLeft = '10px';
|
||||
link.style.textDecoration = "underline";
|
||||
document.body.insertBefore(link, bottom);
|
||||
}
|
||||
|
||||
var br = document.createElement('br');
|
||||
subtitle.appendChild(br);
|
||||
subtitle.appendChild(link2);
|
||||
}
|
||||
if (subtitle) {
|
||||
var link2 = document.createElement('a');
|
||||
link2.textContent = _('Catalog');
|
||||
link2.href = catalog_url;
|
||||
|
||||
var br = document.createElement('br');
|
||||
subtitle.appendChild(br);
|
||||
subtitle.appendChild(link2);
|
||||
}
|
||||
}
|
||||
|
||||
if (active_page == 'thread' || active_page == 'index') {
|
||||
$(document).ready(catalog);
|
||||
$(document).ready(catalog);
|
||||
}
|
||||
|
@ -2,27 +2,27 @@
|
||||
* catalog-search.js
|
||||
* - Search and filters threads when on catalog view
|
||||
* - Optional shortcuts 's' and 'esc' to open and close the search.
|
||||
*
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/jquery.min.js';
|
||||
* $config['additional_javascript'][] = 'js/comment-toolbar.js';
|
||||
*/
|
||||
if (active_page == 'catalog') {
|
||||
onReady(function() {
|
||||
onready(function () {
|
||||
'use strict';
|
||||
|
||||
// 'true' = enable shortcuts
|
||||
let useKeybinds = true;
|
||||
// 'true' = enable shortcuts
|
||||
var useKeybinds = true;
|
||||
|
||||
// trigger the search 400ms after last keystroke
|
||||
let delay = 400;
|
||||
let timeoutHandle;
|
||||
// trigger the search 400ms after last keystroke
|
||||
var delay = 400;
|
||||
var timeoutHandle;
|
||||
|
||||
// search and hide none matching threads
|
||||
//search and hide none matching threads
|
||||
function filter(search_term) {
|
||||
$('.replies').each(function () {
|
||||
let subject = $(this).children('.intro').text().toLowerCase();
|
||||
let comment = $(this).clone().children().remove(':lt(2)').end().text().trim().toLowerCase();
|
||||
var subject = $(this).children('.intro').text().toLowerCase();
|
||||
var comment = $(this).clone().children().remove(':lt(2)').end().text().trim().toLowerCase();
|
||||
search_term = search_term.toLowerCase();
|
||||
|
||||
if (subject.indexOf(search_term) == -1 && comment.indexOf(search_term) == -1) {
|
||||
@ -34,7 +34,7 @@ if (active_page == 'catalog') {
|
||||
}
|
||||
|
||||
function searchToggle() {
|
||||
let button = $('#catalog_search_button');
|
||||
var button = $('#catalog_search_button');
|
||||
|
||||
if (!button.data('expanded')) {
|
||||
button.data('expanded', '1');
|
||||
@ -59,18 +59,18 @@ if (active_page == 'catalog') {
|
||||
});
|
||||
|
||||
if (useKeybinds) {
|
||||
// 's'
|
||||
// 's'
|
||||
$('body').on('keydown', function (e) {
|
||||
if (e.which === 83 && e.target.tagName === 'BODY' && !(e.ctrlKey || e.altKey || e.shiftKey)) {
|
||||
e.preventDefault();
|
||||
if ($('#search_field').length !== 0) {
|
||||
if ($('#search_field').length !== 0) {
|
||||
$('#search_field').focus();
|
||||
} else {
|
||||
searchToggle();
|
||||
}
|
||||
}
|
||||
});
|
||||
// 'esc'
|
||||
// 'esc'
|
||||
$('.catalog_search').on('keydown', 'input#search_field', function (e) {
|
||||
if (e.which === 27 && !(e.ctrlKey || e.altKey || e.shiftKey)) {
|
||||
window.clearTimeout(timeoutHandle);
|
||||
|
@ -15,16 +15,16 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
let doOriginalFilename = function() {
|
||||
let filename, truncated;
|
||||
onready(function(){
|
||||
var do_original_filename = function() {
|
||||
var filename, truncated;
|
||||
if ($(this).attr('title')) {
|
||||
filename = $(this).attr('title');
|
||||
truncated = true;
|
||||
} else {
|
||||
filename = $(this).text();
|
||||
}
|
||||
|
||||
|
||||
$(this).replaceWith(
|
||||
$('<a></a>')
|
||||
.attr('download', filename)
|
||||
@ -34,9 +34,9 @@ onReady(function() {
|
||||
);
|
||||
};
|
||||
|
||||
$('.postfilename').each(doOriginalFilename);
|
||||
$('.postfilename').each(do_original_filename);
|
||||
|
||||
$(document).on('new_post', function(e, post) {
|
||||
$(post).find('.postfilename').each(doOriginalFilename);
|
||||
$(document).on('new_post', function(e, post) {
|
||||
$(post).find('.postfilename').each(do_original_filename);
|
||||
});
|
||||
});
|
||||
|
@ -16,42 +16,37 @@
|
||||
*
|
||||
*/
|
||||
|
||||
if (active_page == 'ukko' || active_page == 'thread' || active_page == 'index') {
|
||||
onReady(function() {
|
||||
$('hr:first').before('<div id="expand-all-images" style="text-align:right"><a class="unimportant" href="javascript:void(0)"></a></div>');
|
||||
$('div#expand-all-images a')
|
||||
.text(_('Expand all images'))
|
||||
.click(function() {
|
||||
$('a img.post-image').each(function() {
|
||||
// Don't expand YouTube embeds
|
||||
if ($(this).parent().parent().hasClass('video-container')) {
|
||||
return;
|
||||
}
|
||||
if (active_page == 'ukko' || active_page == 'thread' || active_page == 'index')
|
||||
onready(function(){
|
||||
$('hr:first').before('<div id="expand-all-images" style="text-align:right"><a class="unimportant" href="javascript:void(0)"></a></div>');
|
||||
$('div#expand-all-images a')
|
||||
.text(_('Expand all images'))
|
||||
.click(function() {
|
||||
$('a img.post-image').each(function() {
|
||||
// Don't expand YouTube embeds
|
||||
if ($(this).parent().parent().hasClass('video-container'))
|
||||
return;
|
||||
|
||||
// or WEBM
|
||||
if (/^\/player\.php\?/.test($(this).parent().attr('href'))) {
|
||||
return;
|
||||
}
|
||||
// or WEBM
|
||||
if (/^\/player\.php\?/.test($(this).parent().attr('href')))
|
||||
return;
|
||||
|
||||
if (!$(this).parent().data('expanded')) {
|
||||
$(this).parent().click();
|
||||
}
|
||||
});
|
||||
|
||||
if (!$('#shrink-all-images').length) {
|
||||
$('hr:first').before('<div id="shrink-all-images" style="text-align:right"><a class="unimportant" href="javascript:void(0)"></a></div>');
|
||||
}
|
||||
|
||||
$('div#shrink-all-images a')
|
||||
.text(_('Shrink all images'))
|
||||
.click(function() {
|
||||
$('a img.full-image').each(function() {
|
||||
if ($(this).parent().data('expanded')) {
|
||||
$(this).parent().click();
|
||||
}
|
||||
});
|
||||
$(this).parent().remove();
|
||||
});
|
||||
if (!$(this).parent().data('expanded'))
|
||||
$(this).parent().click();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (!$('#shrink-all-images').length) {
|
||||
$('hr:first').before('<div id="shrink-all-images" style="text-align:right"><a class="unimportant" href="javascript:void(0)"></a></div>');
|
||||
}
|
||||
|
||||
$('div#shrink-all-images a')
|
||||
.text(_('Shrink all images'))
|
||||
.click(function(){
|
||||
$('a img.full-image').each(function() {
|
||||
if ($(this).parent().data('expanded'))
|
||||
$(this).parent().click();
|
||||
});
|
||||
$(this).parent().remove();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -1,53 +0,0 @@
|
||||
/*
|
||||
* expand-filename.js
|
||||
* https://github.com/vichan-devel/vichan/blob/master/js/expand-filename.js
|
||||
*
|
||||
* Released under the MIT license
|
||||
* Copyright (c) 2024 Perdedora <weav@anche.no>
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/expand-filename.js';
|
||||
*
|
||||
*/
|
||||
|
||||
function doFilename(element) {
|
||||
const filenames = element.querySelectorAll('[data-truncate="true"]');
|
||||
filenames.forEach(filename => {
|
||||
filename.addEventListener('mouseover', event => addHover(event.target));
|
||||
filename.addEventListener('mouseout', event => removeHover(event.target));
|
||||
});
|
||||
}
|
||||
|
||||
function addHover(element) {
|
||||
element.dataset.truncatedFilename = element.textContent;
|
||||
element.textContent = element.download;
|
||||
}
|
||||
|
||||
function removeHover(element) {
|
||||
element.textContent = element.dataset.truncatedFilename;
|
||||
delete element.dataset.truncatedFilename;
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
doFilename(document);
|
||||
|
||||
// Create a MutationObserver to watch for new elements
|
||||
const observer = new MutationObserver(mutationsList => {
|
||||
mutationsList.forEach(mutation => {
|
||||
if (mutation.type === 'childList') {
|
||||
mutation.addedNodes.forEach(addedNode => {
|
||||
if (addedNode.nodeType === Node.ELEMENT_NODE) {
|
||||
// Apply `doFilename` to newly added elements
|
||||
doFilename(addedNode);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Start observing the document body for changes
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
});
|
39
js/expand-too-long.js
Normal file
39
js/expand-too-long.js
Normal file
@ -0,0 +1,39 @@
|
||||
/*
|
||||
* expand-too-long.js
|
||||
* https://github.com/vichan-devel/vichan/blob/master/js/expand-too-long.js
|
||||
*
|
||||
* Released under the MIT license
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/jquery.min.js';
|
||||
* $config['additional_javascript'][] = 'js/expand-too-long.js';
|
||||
*
|
||||
*/
|
||||
|
||||
$(function() {
|
||||
var do_expand = function() {
|
||||
$(this).find('a').click(function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
var url = $(this).attr('href');
|
||||
var body = $(this).parents('.body');
|
||||
|
||||
$.ajax({
|
||||
url: url,
|
||||
context: document.body,
|
||||
success: function(data) {
|
||||
var content = $(data).find('#'+url.split('#')[1]).parent().parent().find(".body").first().html();
|
||||
|
||||
body.html(content);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
$('.toolong').each(do_expand);
|
||||
|
||||
$(document).on("new_post", function(e, post) {
|
||||
$(post).find('.toolong').each(do_expand)
|
||||
});
|
||||
});
|
@ -2,283 +2,243 @@
|
||||
/* Note: This code expects the global variable configRoot to be set. */
|
||||
|
||||
if (typeof _ == 'undefined') {
|
||||
var _ = function(a) {
|
||||
return a;
|
||||
};
|
||||
var _ = function(a) { return a; };
|
||||
}
|
||||
|
||||
function setupVideo(thumb, url) {
|
||||
if (thumb.videoAlreadySetUp) {
|
||||
return;
|
||||
}
|
||||
thumb.videoAlreadySetUp = true;
|
||||
if (thumb.videoAlreadySetUp) return;
|
||||
thumb.videoAlreadySetUp = true;
|
||||
|
||||
let video = null;
|
||||
let videoContainer, videoHide;
|
||||
let expanded = false;
|
||||
let hovering = false;
|
||||
let loop = true;
|
||||
let loopControls = [document.createElement("span"), document.createElement("span")];
|
||||
let fileInfo = thumb.parentNode.querySelector(".fileinfo");
|
||||
let mouseDown = false;
|
||||
var video = null;
|
||||
var videoContainer, videoHide;
|
||||
var expanded = false;
|
||||
var hovering = false;
|
||||
var loop = true;
|
||||
var loopControls = [document.createElement("span"), document.createElement("span")];
|
||||
var fileInfo = thumb.parentNode.querySelector(".fileinfo");
|
||||
var mouseDown = false;
|
||||
|
||||
function unexpand() {
|
||||
if (expanded) {
|
||||
expanded = false;
|
||||
if (video.pause) {
|
||||
video.pause();
|
||||
}
|
||||
videoContainer.style.display = "none";
|
||||
thumb.style.display = "inline";
|
||||
video.style.maxWidth = "inherit";
|
||||
video.style.maxHeight = "inherit";
|
||||
}
|
||||
}
|
||||
function unexpand() {
|
||||
if (expanded) {
|
||||
expanded = false;
|
||||
if (video.pause) video.pause();
|
||||
videoContainer.style.display = "none";
|
||||
thumb.style.display = "inline";
|
||||
video.style.maxWidth = "inherit";
|
||||
video.style.maxHeight = "inherit";
|
||||
}
|
||||
}
|
||||
|
||||
function unhover() {
|
||||
if (hovering) {
|
||||
hovering = false;
|
||||
if (video.pause) {
|
||||
video.pause();
|
||||
}
|
||||
videoContainer.style.display = "none";
|
||||
video.style.maxWidth = "inherit";
|
||||
video.style.maxHeight = "inherit";
|
||||
}
|
||||
}
|
||||
function unhover() {
|
||||
if (hovering) {
|
||||
hovering = false;
|
||||
if (video.pause) video.pause();
|
||||
videoContainer.style.display = "none";
|
||||
video.style.maxWidth = "inherit";
|
||||
video.style.maxHeight = "inherit";
|
||||
}
|
||||
}
|
||||
|
||||
// Create video element if does not exist yet
|
||||
function getVideo() {
|
||||
if (video == null) {
|
||||
video = document.createElement("video");
|
||||
video.src = url;
|
||||
video.loop = loop;
|
||||
video.innerText = _("Your browser does not support HTML5 video.");
|
||||
// Create video element if does not exist yet
|
||||
function getVideo() {
|
||||
if (video == null) {
|
||||
video = document.createElement("video");
|
||||
video.src = url;
|
||||
video.loop = loop;
|
||||
video.innerText = _("Your browser does not support HTML5 video.");
|
||||
|
||||
videoHide = document.createElement("img");
|
||||
videoHide.src = configRoot + "static/collapse.gif";
|
||||
videoHide.alt = "[ - ]";
|
||||
videoHide.title = "Collapse video";
|
||||
videoHide.style.marginLeft = "-15px";
|
||||
videoHide.style.cssFloat = "left";
|
||||
videoHide.addEventListener("click", unexpand, false);
|
||||
videoHide = document.createElement("img");
|
||||
videoHide.src = configRoot + "static/collapse.gif";
|
||||
videoHide.alt = "[ - ]";
|
||||
videoHide.title = "Collapse video";
|
||||
videoHide.style.marginLeft = "-15px";
|
||||
videoHide.style.cssFloat = "left";
|
||||
videoHide.addEventListener("click", unexpand, false);
|
||||
|
||||
videoContainer = document.createElement("div");
|
||||
videoContainer.style.paddingLeft = "15px";
|
||||
videoContainer.style.display = "none";
|
||||
videoContainer.appendChild(videoHide);
|
||||
videoContainer.appendChild(video);
|
||||
thumb.parentNode.insertBefore(videoContainer, thumb.nextSibling);
|
||||
videoContainer = document.createElement("div");
|
||||
videoContainer.style.paddingLeft = "15px";
|
||||
videoContainer.style.display = "none";
|
||||
videoContainer.appendChild(videoHide);
|
||||
videoContainer.appendChild(video);
|
||||
thumb.parentNode.insertBefore(videoContainer, thumb.nextSibling);
|
||||
|
||||
// Dragging to the left collapses the video
|
||||
video.addEventListener("mousedown", function(e) {
|
||||
if (e.button == 0) mouseDown = true;
|
||||
}, false);
|
||||
video.addEventListener("mouseup", function(e) {
|
||||
if (e.button == 0) mouseDown = false;
|
||||
}, false);
|
||||
video.addEventListener("mouseenter", function(e) {
|
||||
mouseDown = false;
|
||||
}, false);
|
||||
video.addEventListener("mouseout", function(e) {
|
||||
if (mouseDown && e.clientX - video.getBoundingClientRect().left <= 0) {
|
||||
unexpand();
|
||||
}
|
||||
mouseDown = false;
|
||||
}, false);
|
||||
}
|
||||
}
|
||||
// Dragging to the left collapses the video
|
||||
video.addEventListener("mousedown", function(e) {
|
||||
if (e.button == 0) mouseDown = true;
|
||||
}, false);
|
||||
video.addEventListener("mouseup", function(e) {
|
||||
if (e.button == 0) mouseDown = false;
|
||||
}, false);
|
||||
video.addEventListener("mouseenter", function(e) {
|
||||
mouseDown = false;
|
||||
}, false);
|
||||
video.addEventListener("mouseout", function(e) {
|
||||
if (mouseDown && e.clientX - video.getBoundingClientRect().left <= 0) {
|
||||
unexpand();
|
||||
}
|
||||
mouseDown = false;
|
||||
}, false);
|
||||
}
|
||||
}
|
||||
|
||||
function setVolume() {
|
||||
const volume = setting("videovolume");
|
||||
video.volume = volume;
|
||||
video.muted = (volume === 0);
|
||||
}
|
||||
// Clicking on thumbnail expands video
|
||||
thumb.addEventListener("click", function(e) {
|
||||
if (setting("videoexpand") && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||
getVideo();
|
||||
expanded = true;
|
||||
hovering = false;
|
||||
|
||||
// Clicking on thumbnail expands video
|
||||
thumb.addEventListener("click", function(e) {
|
||||
if (setting("videoexpand") && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||
getVideo();
|
||||
expanded = true;
|
||||
hovering = false;
|
||||
video.style.position = "static";
|
||||
video.style.pointerEvents = "inherit";
|
||||
video.style.display = "inline";
|
||||
videoHide.style.display = "inline";
|
||||
videoContainer.style.display = "block";
|
||||
videoContainer.style.position = "static";
|
||||
video.parentNode.parentNode.removeAttribute('style');
|
||||
thumb.style.display = "none";
|
||||
|
||||
video.style.position = "static";
|
||||
video.style.pointerEvents = "inherit";
|
||||
video.style.display = "inline";
|
||||
videoHide.style.display = "inline";
|
||||
videoContainer.style.display = "block";
|
||||
videoContainer.style.position = "static";
|
||||
video.parentNode.parentNode.removeAttribute('style');
|
||||
thumb.style.display = "none";
|
||||
video.muted = (setting("videovolume") == 0);
|
||||
video.volume = setting("videovolume");
|
||||
video.controls = true;
|
||||
if (video.readyState == 0) {
|
||||
video.addEventListener("loadedmetadata", expand2, false);
|
||||
} else {
|
||||
setTimeout(expand2, 0);
|
||||
}
|
||||
video.play();
|
||||
e.preventDefault();
|
||||
}
|
||||
}, false);
|
||||
|
||||
setVolume();
|
||||
video.controls = true;
|
||||
if (video.readyState == 0) {
|
||||
video.addEventListener("loadedmetadata", expand2, false);
|
||||
} else {
|
||||
setTimeout(expand2, 0);
|
||||
}
|
||||
let promise = video.play();
|
||||
if (promise !== undefined) {
|
||||
promise.then(_ => {
|
||||
}).catch(_ => {
|
||||
video.muted = true;
|
||||
video.play();
|
||||
});
|
||||
}
|
||||
e.preventDefault();
|
||||
}
|
||||
}, false);
|
||||
function expand2() {
|
||||
video.style.maxWidth = "100%";
|
||||
video.style.maxHeight = window.innerHeight + "px";
|
||||
var bottom = video.getBoundingClientRect().bottom;
|
||||
if (bottom > window.innerHeight) {
|
||||
window.scrollBy(0, bottom - window.innerHeight);
|
||||
}
|
||||
// work around Firefox volume control bug
|
||||
video.volume = Math.max(setting("videovolume") - 0.001, 0);
|
||||
video.volume = setting("videovolume");
|
||||
}
|
||||
|
||||
function expand2() {
|
||||
video.style.maxWidth = "100%";
|
||||
video.style.maxHeight = window.innerHeight + "px";
|
||||
var bottom = video.getBoundingClientRect().bottom;
|
||||
if (bottom > window.innerHeight) {
|
||||
window.scrollBy(0, bottom - window.innerHeight);
|
||||
}
|
||||
// work around Firefox volume control bug
|
||||
video.volume = Math.max(setting("videovolume") - 0.001, 0);
|
||||
video.volume = setting("videovolume");
|
||||
}
|
||||
// Hovering over thumbnail displays video
|
||||
thumb.addEventListener("mouseover", function(e) {
|
||||
if (setting("videohover")) {
|
||||
getVideo();
|
||||
expanded = false;
|
||||
hovering = true;
|
||||
|
||||
// Hovering over thumbnail displays video
|
||||
thumb.addEventListener("mouseover", function(e) {
|
||||
if (setting("videohover")) {
|
||||
getVideo();
|
||||
expanded = false;
|
||||
hovering = true;
|
||||
var docRight = document.documentElement.getBoundingClientRect().right;
|
||||
var thumbRight = thumb.querySelector("img, video").getBoundingClientRect().right;
|
||||
var maxWidth = docRight - thumbRight - 20;
|
||||
if (maxWidth < 250) maxWidth = 250;
|
||||
|
||||
let docRight = document.documentElement.getBoundingClientRect().right;
|
||||
let thumbRight = thumb.querySelector("img, video").getBoundingClientRect().right;
|
||||
let maxWidth = docRight - thumbRight - 20;
|
||||
if (maxWidth < 250) {
|
||||
maxWidth = 250;
|
||||
}
|
||||
video.style.position = "fixed";
|
||||
video.style.right = "0px";
|
||||
video.style.top = "0px";
|
||||
var docRight = document.documentElement.getBoundingClientRect().right;
|
||||
var thumbRight = thumb.querySelector("img, video").getBoundingClientRect().right;
|
||||
video.style.maxWidth = maxWidth + "px";
|
||||
video.style.maxHeight = "100%";
|
||||
video.style.pointerEvents = "none";
|
||||
|
||||
video.style.position = "fixed";
|
||||
video.style.right = "0px";
|
||||
video.style.top = "0px";
|
||||
docRight = document.documentElement.getBoundingClientRect().right;
|
||||
thumbRight = thumb.querySelector("img, video").getBoundingClientRect().right;
|
||||
video.style.maxWidth = maxWidth + "px";
|
||||
video.style.maxHeight = "100%";
|
||||
video.style.pointerEvents = "none";
|
||||
video.style.display = "inline";
|
||||
videoHide.style.display = "none";
|
||||
videoContainer.style.display = "inline";
|
||||
videoContainer.style.position = "fixed";
|
||||
|
||||
video.style.display = "inline";
|
||||
videoHide.style.display = "none";
|
||||
videoContainer.style.display = "inline";
|
||||
videoContainer.style.position = "fixed";
|
||||
video.muted = (setting("videovolume") == 0);
|
||||
video.volume = setting("videovolume");
|
||||
video.controls = false;
|
||||
video.play();
|
||||
}
|
||||
}, false);
|
||||
|
||||
setVolume();
|
||||
video.controls = false;
|
||||
let promise = video.play();
|
||||
if (promise !== undefined) {
|
||||
promise.then(_ => {
|
||||
}).catch(_ => {
|
||||
video.muted = true;
|
||||
video.play();
|
||||
});
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
thumb.addEventListener("mouseout", unhover, false);
|
||||
|
||||
thumb.addEventListener("mouseout", unhover, false);
|
||||
// Scroll wheel on thumbnail adjusts default volume
|
||||
thumb.addEventListener("wheel", function(e) {
|
||||
if (setting("videohover")) {
|
||||
var volume = setting("videovolume");
|
||||
if (e.deltaY > 0) volume -= 0.1;
|
||||
if (e.deltaY < 0) volume += 0.1;
|
||||
if (volume < 0) volume = 0;
|
||||
if (volume > 1) volume = 1;
|
||||
if (video != null) {
|
||||
video.muted = (volume == 0);
|
||||
video.volume = volume;
|
||||
}
|
||||
changeSetting("videovolume", volume);
|
||||
e.preventDefault();
|
||||
}
|
||||
}, false);
|
||||
|
||||
// Scroll wheel on thumbnail adjusts default volume
|
||||
thumb.addEventListener("wheel", function(e) {
|
||||
if (setting("videohover")) {
|
||||
var volume = setting("videovolume");
|
||||
if (e.deltaY > 0) {
|
||||
volume -= 0.1;
|
||||
}
|
||||
if (e.deltaY < 0) {
|
||||
volume += 0.1;
|
||||
}
|
||||
if (volume < 0) {
|
||||
volume = 0;
|
||||
}
|
||||
if (volume > 1) {
|
||||
volume = 1;
|
||||
}
|
||||
if (video != null) {
|
||||
video.muted = (volume == 0);
|
||||
video.volume = volume;
|
||||
}
|
||||
changeSetting("videovolume", volume);
|
||||
e.preventDefault();
|
||||
}
|
||||
}, false);
|
||||
// [play once] vs [loop] controls
|
||||
function setupLoopControl(i) {
|
||||
loopControls[i].addEventListener("click", function(e) {
|
||||
loop = (i != 0);
|
||||
thumb.href = thumb.href.replace(/([\?&])loop=\d+/, "$1loop=" + i);
|
||||
if (video != null) {
|
||||
video.loop = loop;
|
||||
if (loop && video.currentTime >= video.duration) {
|
||||
video.currentTime = 0;
|
||||
}
|
||||
}
|
||||
loopControls[i].style.fontWeight = "bold";
|
||||
loopControls[1-i].style.fontWeight = "inherit";
|
||||
}, false);
|
||||
}
|
||||
|
||||
// [play once] vs [loop] controls
|
||||
function setupLoopControl(i) {
|
||||
loopControls[i].addEventListener("click", function(e) {
|
||||
loop = (i != 0);
|
||||
thumb.href = thumb.href.replace(/([\?&])loop=\d+/, "$1loop=" + i);
|
||||
if (video != null) {
|
||||
video.loop = loop;
|
||||
if (loop && video.currentTime >= video.duration) {
|
||||
video.currentTime = 0;
|
||||
}
|
||||
}
|
||||
loopControls[i].style.fontWeight = "bold";
|
||||
loopControls[1-i].style.fontWeight = "inherit";
|
||||
}, false);
|
||||
}
|
||||
|
||||
loopControls[0].textContent = _("[play once]");
|
||||
loopControls[1].textContent = _("[loop]");
|
||||
loopControls[1].style.fontWeight = "bold";
|
||||
for (var i = 0; i < 2; i++) {
|
||||
setupLoopControl(i);
|
||||
loopControls[i].style.whiteSpace = "nowrap";
|
||||
fileInfo.appendChild(document.createTextNode(" "));
|
||||
fileInfo.appendChild(loopControls[i]);
|
||||
}
|
||||
loopControls[0].textContent = _("[play once]");
|
||||
loopControls[1].textContent = _("[loop]");
|
||||
loopControls[1].style.fontWeight = "bold";
|
||||
for (var i = 0; i < 2; i++) {
|
||||
setupLoopControl(i);
|
||||
loopControls[i].style.whiteSpace = "nowrap";
|
||||
fileInfo.appendChild(document.createTextNode(" "));
|
||||
fileInfo.appendChild(loopControls[i]);
|
||||
}
|
||||
}
|
||||
|
||||
function setupVideosIn(element) {
|
||||
let thumbs = element.querySelectorAll("a.file");
|
||||
for (let i = 0; i < thumbs.length; i++) {
|
||||
if (/\.webm$|\.mp4$/.test(thumbs[i].pathname)) {
|
||||
setupVideo(thumbs[i], thumbs[i].href);
|
||||
} else {
|
||||
let m = thumbs[i].search.match(/\bv=([^&]*)/);
|
||||
if (m != null) {
|
||||
let url = decodeURIComponent(m[1]);
|
||||
if (/\.webm$|\.mp4$/.test(url)) {
|
||||
setupVideo(thumbs[i], url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var thumbs = element.querySelectorAll("a.file");
|
||||
for (var i = 0; i < thumbs.length; i++) {
|
||||
if (/\.webm$|\.mp4$/.test(thumbs[i].pathname)) {
|
||||
setupVideo(thumbs[i], thumbs[i].href);
|
||||
} else {
|
||||
var m = thumbs[i].search.match(/\bv=([^&]*)/);
|
||||
if (m != null) {
|
||||
var url = decodeURIComponent(m[1]);
|
||||
if (/\.webm$|\.mp4$/.test(url)) setupVideo(thumbs[i], url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onReady(function(){
|
||||
// Insert menu from settings.js
|
||||
if (typeof settingsMenu != "undefined" && typeof Options == "undefined") {
|
||||
document.body.insertBefore(settingsMenu, document.getElementsByTagName("hr")[0]);
|
||||
}
|
||||
onready(function(){
|
||||
// Insert menu from settings.js
|
||||
if (typeof settingsMenu != "undefined" && typeof Options == "undefined")
|
||||
document.body.insertBefore(settingsMenu, document.getElementsByTagName("hr")[0]);
|
||||
|
||||
// Setup Javascript events for videos in document now
|
||||
setupVideosIn(document);
|
||||
// Setup Javascript events for videos in document now
|
||||
setupVideosIn(document);
|
||||
|
||||
// Setup Javascript events for videos added by updater
|
||||
if (window.MutationObserver) {
|
||||
let observer = new MutationObserver(function(mutations) {
|
||||
for (let i = 0; i < mutations.length; i++) {
|
||||
let additions = mutations[i].addedNodes;
|
||||
if (additions == null) {
|
||||
continue;
|
||||
}
|
||||
for (let j = 0; j < additions.length; j++) {
|
||||
let node = additions[j];
|
||||
if (node.nodeType == 1) {
|
||||
setupVideosIn(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, {childList: true, subtree: true});
|
||||
}
|
||||
// Setup Javascript events for videos added by updater
|
||||
if (window.MutationObserver) {
|
||||
var observer = new MutationObserver(function(mutations) {
|
||||
for (var i = 0; i < mutations.length; i++) {
|
||||
var additions = mutations[i].addedNodes;
|
||||
if (additions == null) continue;
|
||||
for (var j = 0; j < additions.length; j++) {
|
||||
var node = additions[j];
|
||||
if (node.nodeType == 1) {
|
||||
setupVideosIn(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, {childList: true, subtree: true});
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -8,11 +8,6 @@
|
||||
*/
|
||||
function init_file_selector(max_images) {
|
||||
|
||||
// Temporarily block iOS
|
||||
if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$(document).ready(function () {
|
||||
// add options panel item
|
||||
if (window.Options && Options.get_tab('general')) {
|
||||
|
@ -1,23 +0,0 @@
|
||||
/*
|
||||
* Adds 4chan-like [Start a New Thread] and [Post a Reply] buttons to pages.
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/jquery.min.js';
|
||||
* $config['additional_javascript'][] = 'js/hide-form.js';
|
||||
*
|
||||
*/
|
||||
|
||||
$(document).ready(() => {
|
||||
if (active_page !== 'index' && active_page !== 'thread')
|
||||
return;
|
||||
|
||||
let form_el = $('form[name="post"]');
|
||||
let form_msg = active_page === 'index' ? 'Start a New Thread' : 'Post a Reply';
|
||||
|
||||
form_el.hide();
|
||||
form_el.after(`<div id="show-post-form" style="font-size:175%;text-align:center;font-weight:bold">[<a href="#" style="text-decoration:none">${_(form_msg)}</a>]</div>`);
|
||||
$('div#show-post-form').click(() => {
|
||||
$('div#show-post-form').hide();
|
||||
form_el.show();
|
||||
});
|
||||
});
|
@ -13,21 +13,21 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
let inlineExpandingFilename = function() {
|
||||
$(this).find(".fileinfo > a").click(function() {
|
||||
let imagelink = $(this).parent().parent().find('a[target="_blank"]:first');
|
||||
if (imagelink.length > 0) {
|
||||
onready(function(){
|
||||
var inline_expanding_filename = function() {
|
||||
$(this).find(".fileinfo > a").click(function(){
|
||||
var imagelink = $(this).parent().parent().find('a[target="_blank"]:first');
|
||||
if(imagelink.length > 0) {
|
||||
imagelink.click();
|
||||
return false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
$('div[id^="thread_"]').each(inlineExpandingFilename);
|
||||
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
inlineExpandingFilename.call(post);
|
||||
});
|
||||
$('div[id^="thread_"]').each(inline_expanding_filename);
|
||||
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
inline_expanding_filename.call(post);
|
||||
});
|
||||
});
|
||||
|
@ -17,45 +17,29 @@ $(document).ready(function(){
|
||||
'use strict';
|
||||
|
||||
var iso8601 = function(s) {
|
||||
var parts = s.split('T');
|
||||
if (parts.length === 2) {
|
||||
var timeParts = parts[1].split(':');
|
||||
if (timeParts.length === 3) {
|
||||
var seconds = timeParts[2];
|
||||
if (seconds.length > 2) {
|
||||
seconds = seconds.substr(0, 2) + '.' + seconds.substr(2);
|
||||
}
|
||||
// Ensure seconds part is valid
|
||||
if (parseFloat(seconds) > 59) {
|
||||
seconds = '59';
|
||||
}
|
||||
timeParts[2] = seconds;
|
||||
}
|
||||
parts[1] = timeParts.join(':');
|
||||
}
|
||||
s = parts.join('T');
|
||||
|
||||
if (!s.endsWith('Z')) {
|
||||
s += 'Z';
|
||||
}
|
||||
s = s.replace(/\.\d\d\d+/,""); // remove milliseconds
|
||||
s = s.replace(/-/,"/").replace(/-/,"/");
|
||||
s = s.replace(/T/," ").replace(/Z/," UTC");
|
||||
s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
|
||||
return new Date(s);
|
||||
};
|
||||
|
||||
var zeropad = function(num, count) {
|
||||
return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
|
||||
};
|
||||
|
||||
var dateformat = (typeof strftime === 'undefined') ? function(t) {
|
||||
return zeropad(t.getMonth() + 1, 2) + "/" + zeropad(t.getDate(), 2) + "/" + t.getFullYear().toString().substring(2) +
|
||||
" (" + ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][t.getDay()] + ") " +
|
||||
" (" + [_("Sun"), _("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun")][t.getDay()] + ") " +
|
||||
// time
|
||||
zeropad(t.getHours(), 2) + ":" + zeropad(t.getMinutes(), 2) + ":" + zeropad(t.getSeconds(), 2);
|
||||
|
||||
} : function(t) {
|
||||
// post_date is defined in templates/main.js
|
||||
return strftime(window.post_date, t, datelocale);
|
||||
};
|
||||
|
||||
function timeDifference(current, previous) {
|
||||
|
||||
var msPerMinute = 60 * 1000;
|
||||
var msPerHour = msPerMinute * 60;
|
||||
var msPerDay = msPerHour * 24;
|
||||
@ -67,35 +51,36 @@ $(document).ready(function(){
|
||||
if (elapsed < msPerMinute) {
|
||||
return 'Just now';
|
||||
} else if (elapsed < msPerHour) {
|
||||
return Math.round(elapsed / msPerMinute) + (Math.round(elapsed / msPerMinute) <= 1 ? ' minute ago' : ' minutes ago');
|
||||
} else if (elapsed < msPerDay) {
|
||||
return Math.round(elapsed / msPerHour) + (Math.round(elapsed / msPerHour) <= 1 ? ' hour ago' : ' hours ago');
|
||||
return Math.round(elapsed/msPerMinute) + (Math.round(elapsed/msPerMinute)<=1 ? ' minute ago':' minutes ago');
|
||||
} else if (elapsed < msPerDay ) {
|
||||
return Math.round(elapsed/msPerHour ) + (Math.round(elapsed/msPerHour)<=1 ? ' hour ago':' hours ago');
|
||||
} else if (elapsed < msPerMonth) {
|
||||
return Math.round(elapsed / msPerDay) + (Math.round(elapsed / msPerDay) <= 1 ? ' day ago' : ' days ago');
|
||||
return Math.round(elapsed/msPerDay) + (Math.round(elapsed/msPerDay)<=1 ? ' day ago':' days ago');
|
||||
} else if (elapsed < msPerYear) {
|
||||
return Math.round(elapsed / msPerMonth) + (Math.round(elapsed / msPerMonth) <= 1 ? ' month ago' : ' months ago');
|
||||
return Math.round(elapsed/msPerMonth) + (Math.round(elapsed/msPerMonth)<=1 ? ' month ago':' months ago');
|
||||
} else {
|
||||
return Math.round(elapsed / msPerYear) + (Math.round(elapsed / msPerYear) <= 1 ? ' year ago' : ' years ago');
|
||||
return Math.round(elapsed/msPerYear ) + (Math.round(elapsed/msPerYear)<=1 ? ' year ago':' years ago');
|
||||
}
|
||||
}
|
||||
|
||||
var do_localtime = function(elem) {
|
||||
var do_localtime = function(elem) {
|
||||
var times = elem.getElementsByTagName('time');
|
||||
var currentTime = Date.now();
|
||||
|
||||
for (var i = 0; i < times.length; i++) {
|
||||
for(var i = 0; i < times.length; i++) {
|
||||
var t = times[i].getAttribute('datetime');
|
||||
var postTime = iso8601(t);
|
||||
var postTime = new Date(t);
|
||||
|
||||
times[i].setAttribute('data-local', 'true');
|
||||
|
||||
if (localStorage.show_relative_time === 'false') {
|
||||
times[i].innerHTML = dateformat(postTime);
|
||||
times[i].innerHTML = dateformat(iso8601(t));
|
||||
times[i].setAttribute('title', timeDifference(currentTime, postTime.getTime()));
|
||||
} else {
|
||||
times[i].innerHTML = timeDifference(currentTime, postTime.getTime());
|
||||
times[i].setAttribute('title', dateformat(postTime));
|
||||
times[i].setAttribute('title', dateformat(iso8601(t)));
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
@ -116,7 +101,7 @@ $(document).ready(function(){
|
||||
});
|
||||
|
||||
if (localStorage.show_relative_time !== 'false') {
|
||||
$('#show-relative-time>input').attr('checked', 'checked');
|
||||
$('#show-relative-time>input').attr('checked','checked');
|
||||
interval_id = setInterval(do_localtime, 30000, document);
|
||||
}
|
||||
|
||||
@ -128,4 +113,3 @@ $(document).ready(function(){
|
||||
|
||||
do_localtime(document);
|
||||
});
|
||||
|
||||
|
@ -37,7 +37,7 @@ var banlist_init = function(token, my_boards, inMod) {
|
||||
}
|
||||
return pre+f.mask;
|
||||
} },
|
||||
reason: {name: _("Reason"), width: "calc(100% - 770px - 6 * 4px)", fmt: function(f) {
|
||||
reason: {name: _("Reason"), width: "calc(100% - 715px - 6 * 4px)", fmt: function(f) {
|
||||
var add = "", suf = '';
|
||||
if (f.seen == 1) add += "<i class='fa fa-check' title='"+_("Seen")+"'></i>";
|
||||
if (f.message) {
|
||||
@ -60,8 +60,8 @@ var banlist_init = function(token, my_boards, inMod) {
|
||||
// duration?
|
||||
expires: {name: _("Expires"), width: "235px", fmt: function(f) {
|
||||
if (!f.expires || f.expires == 0) return "<em>"+_("never")+"</em>";
|
||||
var formattedDate = strftime("%m/%d/%Y (%a) %H:%M:%S", new Date((f.expires|0)*1000), datelocale);
|
||||
return formattedDate + ((f.expires < time()) ? "" : " <small>"+_("in ")+until(f.expires|0)+"</small>");
|
||||
return strftime(window.post_date, new Date((f.expires|0)*1000), datelocale) +
|
||||
((f.expires < time()) ? "" : " <small>"+_("in ")+until(f.expires|0)+"</small>");
|
||||
} },
|
||||
username: {name: _("Staff"), width: "100px", fmt: function(f) {
|
||||
var pre='',suf='',un=f.username;
|
||||
@ -73,12 +73,7 @@ var banlist_init = function(token, my_boards, inMod) {
|
||||
un = "<em>"+_("system")+"</em>";
|
||||
}
|
||||
return pre + un + suf;
|
||||
} },
|
||||
id: {
|
||||
name: (inMod)?_("Edit"):" ", width: (inMod)?"35px":"0px", fmt: function(f) {
|
||||
if (!inMod) return '';
|
||||
return "<a href='?/edit_ban/"+f.id+"'>Edit</a>";
|
||||
} }
|
||||
} }
|
||||
}, {}, t);
|
||||
|
||||
$("#select-all").click(function(e) {
|
||||
@ -129,16 +124,14 @@ var banlist_init = function(token, my_boards, inMod) {
|
||||
$(".banform").on("submit", function() { return false; });
|
||||
|
||||
$("#unban").on("click", function() {
|
||||
if (confirm('Are you sure you want to unban the selected IPs?')) {
|
||||
$(".banform .hiddens").remove();
|
||||
$("<input type='hidden' name='unban' value='unban' class='hiddens'>").appendTo(".banform");
|
||||
|
||||
$.each(selected, function(e) {
|
||||
$("<input type='hidden' name='ban_"+e+"' value='unban' class='hiddens'>").appendTo(".banform");
|
||||
});
|
||||
|
||||
$(".banform").off("submit").submit();
|
||||
}
|
||||
$(".banform .hiddens").remove();
|
||||
$("<input type='hidden' name='unban' value='unban' class='hiddens'>").appendTo(".banform");
|
||||
|
||||
$.each(selected, function(e) {
|
||||
$("<input type='hidden' name='ban_"+e+"' value='unban' class='hiddens'>").appendTo(".banform");
|
||||
});
|
||||
|
||||
$(".banform").off("submit").submit();
|
||||
});
|
||||
|
||||
if (device_type == 'desktop') {
|
||||
|
@ -1,12 +0,0 @@
|
||||
/*
|
||||
* mod_snippets.js
|
||||
*
|
||||
* Javascript snippets to be loaded when in mod mode
|
||||
*
|
||||
*/
|
||||
|
||||
function populateFormJQuery(frm, data) {
|
||||
$.each(data, function(key, value){
|
||||
$('[name='+key+']', frm).val(value);
|
||||
});
|
||||
}
|
@ -375,7 +375,7 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
|
||||
var list = getList();
|
||||
var postId = $post.find('.post_no').not('[id]').text();
|
||||
var name, trip, uid, subject, comment, flag;
|
||||
var name, trip, uid, subject, comment;
|
||||
var i, length, array, rule, pattern; // temp variables
|
||||
|
||||
var boardId = $post.data('board');
|
||||
@ -388,7 +388,6 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
|
||||
var hasTrip = ($post.find('.trip').length > 0);
|
||||
var hasSub = ($post.find('.subject').length > 0);
|
||||
var hasFlag = ($post.find('.flag').length > 0);
|
||||
|
||||
$post.data('hidden', false);
|
||||
$post.data('hiddenByUid', false);
|
||||
@ -397,7 +396,6 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
$post.data('hiddenByTrip', false);
|
||||
$post.data('hiddenBySubject', false);
|
||||
$post.data('hiddenByComment', false);
|
||||
$post.data('hiddenByFlag', false);
|
||||
|
||||
// add post with matched UID to localList
|
||||
if (hasUID &&
|
||||
@ -438,8 +436,6 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
});
|
||||
comment = array.join(' ');
|
||||
|
||||
if (hasFlag)
|
||||
flag = $post.find('.flag').attr('title')
|
||||
|
||||
for (i = 0, length = list.generalFilter.length; i < length; i++) {
|
||||
rule = list.generalFilter[i];
|
||||
@ -471,12 +467,6 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
hide(post);
|
||||
}
|
||||
break;
|
||||
case 'flag':
|
||||
if (hasFlag && pattern.test(flag)) {
|
||||
$post.data('hiddenByFlag', true);
|
||||
hide(post);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (rule.type) {
|
||||
@ -506,13 +496,6 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
hide(post);
|
||||
}
|
||||
break;
|
||||
case 'flag':
|
||||
pattern = new RegExp('\\b'+ rule.value+ '\\b');
|
||||
if (hasFlag && pattern.test(flag)) {
|
||||
$post.data('hiddenByFlag', true);
|
||||
hide(post);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -638,8 +621,7 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
name: 'name',
|
||||
trip: 'tripcode',
|
||||
sub: 'subject',
|
||||
com: 'comment',
|
||||
flag: 'flag'
|
||||
com: 'comment'
|
||||
};
|
||||
|
||||
$ele.empty();
|
||||
@ -678,7 +660,6 @@ if (active_page === 'thread' || active_page === 'index' || active_page === 'cata
|
||||
'<option value="trip">'+_('Tripcode')+'</option>' +
|
||||
'<option value="sub">'+_('Subject')+'</option>' +
|
||||
'<option value="com">'+_('Comment')+'</option>' +
|
||||
'<option value="flag">'+_('Flag')+'</option>' +
|
||||
'</select>' +
|
||||
'<input type="text">' +
|
||||
'<input type="checkbox">' +
|
||||
|
177
js/post-hover.js
177
js/post-hover.js
@ -13,62 +13,59 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
let dontFetchAgain = [];
|
||||
initHover = function() {
|
||||
let link = $(this);
|
||||
let id;
|
||||
let matches;
|
||||
onready(function(){
|
||||
var dont_fetch_again = [];
|
||||
init_hover = function() {
|
||||
var $link = $(this);
|
||||
|
||||
var id;
|
||||
var matches;
|
||||
|
||||
if (link.is('[data-thread]')) {
|
||||
id = link.attr('data-thread');
|
||||
} else if (matches = link.text().match(/^>>(?:>\/([^\/]+)\/)?(\d+)$/)) {
|
||||
if ($link.is('[data-thread]')) {
|
||||
id = $link.attr('data-thread');
|
||||
}
|
||||
else if(matches = $link.text().match(/^>>(?:>\/([^\/]+)\/)?(\d+)$/)) {
|
||||
id = matches[2];
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
return;
|
||||
}
|
||||
|
||||
let board = $(this);
|
||||
|
||||
var board = $(this);
|
||||
while (board.data('board') === undefined) {
|
||||
board = board.parent();
|
||||
}
|
||||
let threadid;
|
||||
if (link.is('[data-thread]')) {
|
||||
threadid = 0;
|
||||
} else {
|
||||
threadid = board.attr('id').replace("thread_", "");
|
||||
}
|
||||
var threadid;
|
||||
if ($link.is('[data-thread]')) threadid = 0;
|
||||
else threadid = board.attr('id').replace("thread_", "");
|
||||
|
||||
board = board.data('board');
|
||||
|
||||
let parentboard = board;
|
||||
var parentboard = board;
|
||||
|
||||
if ($link.is('[data-thread]')) parentboard = $('form[name="post"] input[name="board"]').val();
|
||||
else if (matches[1] !== undefined) board = matches[1];
|
||||
|
||||
if (link.is('[data-thread]')) {
|
||||
parentboard = $('form[name="post"] input[name="board"]').val();
|
||||
} else if (matches[1] !== undefined) {
|
||||
board = matches[1];
|
||||
}
|
||||
|
||||
let post = false;
|
||||
let hovering = false;
|
||||
let hoveredAt;
|
||||
link.hover(function(e) {
|
||||
var $post = false;
|
||||
var hovering = false;
|
||||
var hovered_at;
|
||||
$link.hover(function(e) {
|
||||
hovering = true;
|
||||
hoveredAt = {'x': e.pageX, 'y': e.pageY};
|
||||
|
||||
let startHover = function(link) {
|
||||
if (post.is(':visible') &&
|
||||
post.offset().top >= $(window).scrollTop() &&
|
||||
post.offset().top + post.height() <= $(window).scrollTop() + $(window).height()) {
|
||||
hovered_at = {'x': e.pageX, 'y': e.pageY};
|
||||
|
||||
var start_hover = function($link) {
|
||||
if ($post.is(':visible') &&
|
||||
$post.offset().top >= $(window).scrollTop() &&
|
||||
$post.offset().top + $post.height() <= $(window).scrollTop() + $(window).height()) {
|
||||
// post is in view
|
||||
post.addClass('highlighted');
|
||||
$post.addClass('highlighted');
|
||||
} else {
|
||||
let newPost = post.clone();
|
||||
newPost.find('>.reply, >br').remove();
|
||||
newPost.find('span.mentioned').remove();
|
||||
newPost.find('a.post_anchor').remove();
|
||||
var $newPost = $post.clone();
|
||||
$newPost.find('>.reply, >br').remove();
|
||||
$newPost.find('span.mentioned').remove();
|
||||
$newPost.find('a.post_anchor').remove();
|
||||
|
||||
newPost
|
||||
$newPost
|
||||
.attr('id', 'post-hover-' + id)
|
||||
.attr('data-board', board)
|
||||
.addClass('post-hover')
|
||||
@ -79,99 +76,95 @@ onReady(function() {
|
||||
.css('font-style', 'normal')
|
||||
.css('z-index', '100')
|
||||
.addClass('reply').addClass('post')
|
||||
.insertAfter(link.parent())
|
||||
.insertAfter($link.parent())
|
||||
|
||||
link.trigger('mousemove');
|
||||
$link.trigger('mousemove');
|
||||
}
|
||||
};
|
||||
|
||||
post = $('[data-board="' + board + '"] div.post#reply_' + id + ', [data-board="' + board + '"]div#thread_' + id);
|
||||
if (post.length > 0) {
|
||||
startHover($(this));
|
||||
|
||||
$post = $('[data-board="' + board + '"] div.post#reply_' + id + ', [data-board="' + board + '"]div#thread_' + id);
|
||||
if($post.length > 0) {
|
||||
start_hover($(this));
|
||||
} else {
|
||||
let url = link.attr('href').replace(/#.*$/, '');
|
||||
|
||||
if ($.inArray(url, dontFetchAgain) != -1) {
|
||||
var url = $link.attr('href').replace(/#.*$/, '');
|
||||
|
||||
if($.inArray(url, dont_fetch_again) != -1) {
|
||||
return;
|
||||
}
|
||||
dontFetchAgain.push(url);
|
||||
|
||||
dont_fetch_again.push(url);
|
||||
|
||||
$.ajax({
|
||||
url: url,
|
||||
context: document.body,
|
||||
success: function(data) {
|
||||
let mythreadid = $(data).find('div[id^="thread_"]').attr('id').replace("thread_", "");
|
||||
var mythreadid = $(data).find('div[id^="thread_"]').attr('id').replace("thread_", "");
|
||||
|
||||
if (mythreadid == threadid && parentboard == board) {
|
||||
$(data).find('div.post.reply').each(function() {
|
||||
if ($('[data-board="' + board + '"] #' + $(this).attr('id')).length == 0) {
|
||||
if($('[data-board="' + board + '"] #' + $(this).attr('id')).length == 0) {
|
||||
$('[data-board="' + board + '"]#thread_' + threadid + " .post.reply:first").before($(this).hide().addClass('hidden'));
|
||||
}
|
||||
});
|
||||
} else if ($('[data-board="' + board + '"]#thread_' + mythreadid).length > 0) {
|
||||
}
|
||||
else if ($('[data-board="' + board + '"]#thread_'+mythreadid).length > 0) {
|
||||
$(data).find('div.post.reply').each(function() {
|
||||
if ($('[data-board="' + board + '"] #' + $(this).attr('id')).length == 0) {
|
||||
if($('[data-board="' + board + '"] #' + $(this).attr('id')).length == 0) {
|
||||
$('[data-board="' + board + '"]#thread_' + mythreadid + " .post.reply:first").before($(this).hide().addClass('hidden'));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
$(data).find('div[id^="thread_"]').hide().attr('data-cached', 'yes').prependTo('form[name="postcontrols"]');
|
||||
}
|
||||
|
||||
post = $('[data-board="' + board + '"] div.post#reply_' + id + ', [data-board="' + board + '"]div#thread_' + id);
|
||||
$post = $('[data-board="' + board + '"] div.post#reply_' + id + ', [data-board="' + board + '"]div#thread_' + id);
|
||||
|
||||
if (hovering && post.length > 0) {
|
||||
startHover(link);
|
||||
if(hovering && $post.length > 0) {
|
||||
start_hover($link);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}, function() {
|
||||
hovering = false;
|
||||
if (!post) {
|
||||
if(!$post)
|
||||
return;
|
||||
}
|
||||
|
||||
post.removeClass('highlighted');
|
||||
if (post.hasClass('hidden') || post.data('cached') == 'yes') {
|
||||
post.css('display', 'none');
|
||||
}
|
||||
|
||||
$post.removeClass('highlighted');
|
||||
if($post.hasClass('hidden') || $post.data('cached') == 'yes')
|
||||
$post.css('display', 'none');
|
||||
$('.post-hover').remove();
|
||||
}).mousemove(function(e) {
|
||||
if (!post) {
|
||||
if(!$post)
|
||||
return;
|
||||
}
|
||||
|
||||
let hover = $('#post-hover-' + id + '[data-board="' + board + '"]');
|
||||
if (hover.length == 0) {
|
||||
|
||||
var $hover = $('#post-hover-' + id + '[data-board="' + board + '"]');
|
||||
if($hover.length == 0)
|
||||
return;
|
||||
}
|
||||
|
||||
let scrollTop = $(window).scrollTop();
|
||||
if (link.is("[data-thread]")) {
|
||||
scrollTop = 0;
|
||||
}
|
||||
let epy = e.pageY;
|
||||
if (link.is("[data-thread]")) {
|
||||
epy -= $(window).scrollTop();
|
||||
}
|
||||
var scrollTop = $(window).scrollTop();
|
||||
if ($link.is("[data-thread]")) scrollTop = 0;
|
||||
var epy = e.pageY;
|
||||
if ($link.is("[data-thread]")) epy -= $(window).scrollTop();
|
||||
|
||||
let top = (epy ? epy : hoveredAt['y']) - 10;
|
||||
|
||||
if (epy < scrollTop + 15) {
|
||||
var top = (epy ? epy : hovered_at['y']) - 10;
|
||||
|
||||
if(epy < scrollTop + 15) {
|
||||
top = scrollTop;
|
||||
} else if (epy > scrollTop + $(window).height() - hover.height() - 15) {
|
||||
top = scrollTop + $(window).height() - hover.height() - 15;
|
||||
} else if(epy > scrollTop + $(window).height() - $hover.height() - 15) {
|
||||
top = scrollTop + $(window).height() - $hover.height() - 15;
|
||||
}
|
||||
|
||||
hover.css('left', (e.pageX ? e.pageX : hoveredAt['x'])).css('top', top);
|
||||
|
||||
|
||||
$hover.css('left', (e.pageX ? e.pageX : hovered_at['x'])).css('top', top);
|
||||
});
|
||||
};
|
||||
|
||||
$('div.body a:not([rel="nofollow"])').each(initHover);
|
||||
|
||||
|
||||
$('div.body a:not([rel="nofollow"])').each(init_hover);
|
||||
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
$(post).find('div.body a:not([rel="nofollow"])').each(initHover);
|
||||
$(post).find('div.body a:not([rel="nofollow"])').each(init_hover);
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -10,20 +10,20 @@
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/jquery.min.js';
|
||||
* $config['additional_javascript'][] = 'js/quote-selection.js';
|
||||
*
|
||||
*/
|
||||
|
||||
$(document).ready(function() {
|
||||
if (!window.getSelection) {
|
||||
$(document).ready(function(){
|
||||
if (!window.getSelection)
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
$.fn.selectRange = function(start, end) {
|
||||
return this.each(function() {
|
||||
if (this.setSelectionRange) {
|
||||
this.focus();
|
||||
this.setSelectionRange(start, end);
|
||||
} else if (this.createTextRange) {
|
||||
let range = this.createTextRange();
|
||||
var range = this.createTextRange();
|
||||
range.collapse(true);
|
||||
range.moveEnd('character', end);
|
||||
range.moveStart('character', start);
|
||||
@ -31,81 +31,88 @@ $(document).ready(function() {
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let altKey = false;
|
||||
let ctrlKey = false;
|
||||
let metaKey = false;
|
||||
|
||||
|
||||
var altKey = false;
|
||||
var ctrlKey = false;
|
||||
var metaKey = false;
|
||||
|
||||
$(document).keyup(function(e) {
|
||||
if (e.keyCode == 18) {
|
||||
if (e.keyCode == 18)
|
||||
altKey = false;
|
||||
} else if (e.keyCode == 17) {
|
||||
else if (e.keyCode == 17)
|
||||
ctrlKey = false;
|
||||
} else if (e.keyCode == 91) {
|
||||
else if (e.keyCode == 91)
|
||||
metaKey = false;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
$(document).keydown(function(e) {
|
||||
if (e.altKey) {
|
||||
if (e.altKey)
|
||||
altKey = true;
|
||||
} else if (e.ctrlKey) {
|
||||
else if (e.ctrlKey)
|
||||
ctrlKey = true;
|
||||
} else if (e.metaKey) {
|
||||
else if (e.metaKey)
|
||||
metaKey = true;
|
||||
}
|
||||
|
||||
|
||||
if (altKey || ctrlKey || metaKey) {
|
||||
// console.log('CTRL/ALT/Something used. Ignoring');
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.keyCode < 48 || e.keyCode > 90) {
|
||||
|
||||
if (e.keyCode < 48 || e.keyCode > 90)
|
||||
return;
|
||||
|
||||
var selection = window.getSelection();
|
||||
var $post = $(selection.anchorNode).parents('.post');
|
||||
if ($post.length == 0) {
|
||||
// console.log('Start of selection was not post div', $(selection.anchorNode).parent());
|
||||
return;
|
||||
}
|
||||
|
||||
let selection = window.getSelection();
|
||||
let post = $(selection.anchorNode).parents('.post');
|
||||
if (post.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let postID = post.find('.post_no:eq(1)').text();
|
||||
|
||||
|
||||
var postID = $post.find('.post_no:eq(1)').text();
|
||||
|
||||
if (postID != $(selection.focusNode).parents('.post').find('.post_no:eq(1)').text()) {
|
||||
// console.log('Selection left post div', $(selection.focusNode).parent());
|
||||
return;
|
||||
}
|
||||
|
||||
let selectedText = selection.toString();
|
||||
|
||||
if ($('body').hasClass('debug')) {
|
||||
|
||||
;
|
||||
var selectedText = selection.toString();
|
||||
// console.log('Selected text: ' + selectedText.replace(/\n/g, '\\n').replace(/\r/g, '\\r'));
|
||||
|
||||
if ($('body').hasClass('debug'))
|
||||
alert(selectedText);
|
||||
}
|
||||
|
||||
if (selectedText.length == 0) {
|
||||
|
||||
if (selectedText.length == 0)
|
||||
return;
|
||||
}
|
||||
|
||||
let body = $('textarea#body')[0];
|
||||
|
||||
let last_quote = body.value.match(/[\S.]*(^|[\S\s]*)>>(\d+)/);
|
||||
if (last_quote) {
|
||||
|
||||
var body = $('textarea#body')[0];
|
||||
|
||||
var last_quote = body.value.match(/[\S.]*(^|[\S\s]*)>>(\d+)/);
|
||||
if (last_quote)
|
||||
last_quote = last_quote[2];
|
||||
}
|
||||
|
||||
|
||||
/* to solve some bugs on weird browsers, we need to replace \r\n with \n and then undo that after */
|
||||
let quote = (last_quote != postID ? '>>' + postID + '\r\n' : '') + $.trim(selectedText).replace(/\r\n/g, '\n').replace(/^/mg, '>').replace(/\n/g, '\r\n') + '\r\n';
|
||||
|
||||
var quote = (last_quote != postID ? '>>' + postID + '\r\n' : '') + $.trim(selectedText).replace(/\r\n/g, '\n').replace(/^/mg, '>').replace(/\n/g, '\r\n') + '\r\n';
|
||||
|
||||
// console.log('Deselecting text');
|
||||
selection.removeAllRanges();
|
||||
|
||||
if (body.selectionStart || body.selectionStart == '0') {
|
||||
let start = body.selectionStart;
|
||||
let end = body.selectionEnd;
|
||||
|
||||
|
||||
if (document.selection) {
|
||||
// IE
|
||||
body.focus();
|
||||
var sel = document.selection.createRange();
|
||||
sel.text = quote;
|
||||
body.focus();
|
||||
} else if (body.selectionStart || body.selectionStart == '0') {
|
||||
// Mozilla
|
||||
var start = body.selectionStart;
|
||||
var end = body.selectionEnd;
|
||||
|
||||
if (!body.value.substring(0, start).match(/(^|\n)$/)) {
|
||||
quote = '\r\n\r\n' + quote;
|
||||
}
|
||||
|
||||
body.value = body.value.substring(0, start) + quote + body.value.substring(end, body.value.length);
|
||||
|
||||
body.value = body.value.substring(0, start) + quote + body.value.substring(end, body.value.length);
|
||||
$(body).selectRange(start + quote.length, start + quote.length);
|
||||
} else {
|
||||
// ???
|
||||
@ -114,3 +121,4 @@ $(document).ready(function() {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -4,7 +4,7 @@
|
||||
*
|
||||
* Released under the MIT license
|
||||
* Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/jquery.min.js';
|
||||
@ -13,54 +13,49 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
let showBackLinks = function() {
|
||||
let reply_id = $(this).attr('id').replace(/(^reply_)|(^op_)/, '');
|
||||
|
||||
onready(function(){
|
||||
var showBackLinks = function() {
|
||||
var reply_id = $(this).attr('id').replace(/(^reply_)|(^op_)/, '');
|
||||
|
||||
$(this).find('div.body a:not([rel="nofollow"])').each(function() {
|
||||
let id, post, $mentioned;
|
||||
|
||||
if (id = $(this).text().match(/^>>(\d+)$/)) {
|
||||
var id, post, $mentioned;
|
||||
|
||||
if(id = $(this).text().match(/^>>(\d+)$/))
|
||||
id = id[1];
|
||||
} else {
|
||||
else
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
$post = $('#reply_' + id);
|
||||
if ($post.length == 0){
|
||||
if($post.length == 0){
|
||||
$post = $('#op_' + id);
|
||||
if ($post.length == 0) {
|
||||
if($post.length == 0)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$mentioned = $post.find('p.intro span.mentioned');
|
||||
if($mentioned.length == 0) {
|
||||
if($mentioned.length == 0)
|
||||
$mentioned = $('<span class="mentioned unimportant"></span>').appendTo($post.find('p.intro'));
|
||||
}
|
||||
|
||||
if ($mentioned.find('a.mentioned-' + reply_id).length != 0) {
|
||||
|
||||
if ($mentioned.find('a.mentioned-' + reply_id).length != 0)
|
||||
return;
|
||||
}
|
||||
|
||||
let link = $('<a class="mentioned-' + reply_id + '" onclick="highlightReply(\'' + reply_id + '\');" href="#' + reply_id + '">>>' +
|
||||
|
||||
var $link = $('<a class="mentioned-' + reply_id + '" onclick="highlightReply(\'' + reply_id + '\');" href="#' + reply_id + '">>>' +
|
||||
reply_id + '</a>');
|
||||
link.appendTo($mentioned)
|
||||
|
||||
$link.appendTo($mentioned)
|
||||
|
||||
if (window.init_hover) {
|
||||
link.each(init_hover);
|
||||
$link.each(init_hover);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
$('div.post.reply').each(showBackLinks);
|
||||
$('div.post.op').each(showBackLinks);
|
||||
|
||||
$(document).on('new_post', function(e, post) {
|
||||
$(document).on('new_post', function(e, post) {
|
||||
showBackLinks.call(post);
|
||||
if ($(post).hasClass("op")) {
|
||||
$(post).find('div.post.reply').each(showBackLinks);
|
||||
} else {
|
||||
$(post).parent().find('div.post.reply').each(showBackLinks);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@ -4,7 +4,7 @@
|
||||
*
|
||||
* Released under the MIT license
|
||||
* Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/mobile-style.js';
|
||||
@ -12,11 +12,11 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
if (device_type == 'mobile') {
|
||||
let fix_spoilers = function(where) {
|
||||
let spoilers = where.getElementsByClassName('spoiler');
|
||||
for (let i = 0; i < spoilers.length; i++) {
|
||||
onready(function(){
|
||||
if(device_type == 'mobile') {
|
||||
var fix_spoilers = function(where) {
|
||||
var spoilers = where.getElementsByClassName('spoiler');
|
||||
for(var i = 0; i < spoilers.length; i++) {
|
||||
spoilers[i].onmousedown = function() {
|
||||
this.style.color = 'white';
|
||||
};
|
||||
@ -24,10 +24,11 @@ onReady(function() {
|
||||
};
|
||||
fix_spoilers(document);
|
||||
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
fix_spoilers(post);
|
||||
});
|
||||
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
fix_spoilers(post);
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
*
|
||||
* Released under the MIT license
|
||||
* Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
*
|
||||
* Usage:
|
||||
* $config['additional_javascript'][] = 'js/jquery.min.js';
|
||||
@ -14,32 +14,32 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
let stylesDiv = $('div.styles');
|
||||
let stylesSelect = $('<select></select>');
|
||||
|
||||
let i = 1;
|
||||
onready(function(){
|
||||
var stylesDiv = $('div.styles');
|
||||
var stylesSelect = $('<select></select>');
|
||||
|
||||
var i = 1;
|
||||
stylesDiv.children().each(function() {
|
||||
let opt = $('<option></option>')
|
||||
var opt = $('<option></option>')
|
||||
.html(this.innerHTML.replace(/(^\[|\]$)/g, ''))
|
||||
.val(i);
|
||||
if ($(this).hasClass('selected')) {
|
||||
if ($(this).hasClass('selected'))
|
||||
opt.attr('selected', true);
|
||||
}
|
||||
stylesSelect.append(opt);
|
||||
$(this).attr('id', 'style-select-' + i);
|
||||
i++;
|
||||
});
|
||||
|
||||
|
||||
stylesSelect.change(function() {
|
||||
$('#style-select-' + $(this).val()).click();
|
||||
});
|
||||
|
||||
|
||||
stylesDiv.hide();
|
||||
|
||||
|
||||
stylesDiv.after(
|
||||
$('<div id="style-select" style="float:right;margin-bottom:10px"></div>')
|
||||
.text(_('Style: '))
|
||||
.append(stylesSelect)
|
||||
);
|
||||
});
|
||||
|
||||
|
@ -1 +0,0 @@
|
||||
Subproject commit 25dc1757783115136a83af34c42c603ac8b470aa
|
@ -10,7 +10,7 @@
|
||||
*
|
||||
* Released under the MIT license
|
||||
* Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
* Copyright (c) 2013-2014 Marcin Łabanowski <marcin@6irc.net>
|
||||
*
|
||||
* Usage:
|
||||
* $config['embedding'] = array();
|
||||
@ -22,12 +22,13 @@
|
||||
*
|
||||
*/
|
||||
|
||||
onReady(function() {
|
||||
let do_embed_yt = function(tag) {
|
||||
$('div.video-container a', tag).click(function() {
|
||||
let videoID = $(this.parentNode).data('video');
|
||||
|
||||
$(this.parentNode).html('<iframe style="float:left;margin: 10px 20px" type="text/html" ' +
|
||||
onready(function(){
|
||||
var do_embed_yt = function(tag) {
|
||||
$('div.video-container a', tag).click(function() {
|
||||
var videoID = $(this.parentNode).data('video');
|
||||
|
||||
$(this.parentNode).html('<iframe style="float:left;margin: 10px 20px" type="text/html" '+
|
||||
'width="360" height="270" src="//www.youtube.com/embed/' + videoID +
|
||||
'?autoplay=1&html5=1" allowfullscreen frameborder="0"/>');
|
||||
|
||||
@ -36,8 +37,9 @@ onReady(function() {
|
||||
};
|
||||
do_embed_yt(document);
|
||||
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
do_embed_yt(post);
|
||||
});
|
||||
// allow to work with auto-reload.js, etc.
|
||||
$(document).on('new_post', function(e, post) {
|
||||
do_embed_yt(post);
|
||||
});
|
||||
});
|
||||
|
||||
|
82
mod.php
82
mod.php
@ -1,38 +1,35 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) 2010-2014 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
require_once 'inc/bootstrap.php';
|
||||
|
||||
if ($config['debug']) {
|
||||
if ($config['debug'])
|
||||
$parse_start_time = microtime(true);
|
||||
}
|
||||
|
||||
require_once 'inc/mod/pages.php';
|
||||
|
||||
|
||||
$ctx = Vichan\build_context($config);
|
||||
|
||||
check_login($ctx, true);
|
||||
check_login(true);
|
||||
|
||||
$query = isset($_SERVER['QUERY_STRING']) ? rawurldecode($_SERVER['QUERY_STRING']) : '';
|
||||
|
||||
$pages = [
|
||||
$pages = array(
|
||||
'' => ':?/', // redirect to dashboard
|
||||
'/' => 'dashboard', // dashboard
|
||||
'/confirm/(.+)' => 'confirm', // confirm action (if javascript didn't work)
|
||||
'/logout' => 'secure logout', // logout
|
||||
|
||||
|
||||
'/users' => 'users', // manage users
|
||||
'/users/(\d+)/(promote|demote)' => 'secure user_promote', // prmote/demote user
|
||||
'/users/(\d+)' => 'secure_POST user', // edit user
|
||||
'/users/new' => 'secure_POST user_new', // create a new user
|
||||
|
||||
|
||||
'/new_PM/([^/]+)' => 'secure_POST new_pm', // create a new pm
|
||||
'/PM/(\d+)(/reply)?' => 'pm', // read a pm
|
||||
'/inbox' => 'inbox', // pm inbox
|
||||
|
||||
|
||||
'/log' => 'log', // modlog
|
||||
'/log/(\d+)' => 'log', // modlog
|
||||
'/log:([^/:]+)' => 'user_log', // modlog
|
||||
@ -48,27 +45,27 @@ $pages = [
|
||||
'/edit_page/(\d+)' => 'secure_POST edit_page',
|
||||
'/edit_pages/delete/([a-z0-9]+)' => 'secure delete_page',
|
||||
'/edit_pages/delete/([a-z0-9]+)/(\%b)' => 'secure delete_page_board',
|
||||
|
||||
|
||||
'/noticeboard' => 'secure_POST noticeboard', // view noticeboard
|
||||
'/noticeboard/(\d+)' => 'secure_POST noticeboard', // view noticeboard
|
||||
'/noticeboard/delete/(\d+)' => 'secure noticeboard_delete', // delete from noticeboard
|
||||
|
||||
|
||||
'/edit/(\%b)' => 'secure_POST edit_board', // edit board details
|
||||
'/new-board' => 'secure_POST new_board', // create a new board
|
||||
|
||||
|
||||
'/rebuild' => 'secure_POST rebuild', // rebuild static files
|
||||
'/reports' => 'reports', // report queue
|
||||
'/reports/(\d+)/dismiss(&all|&post)?' => 'secure report_dismiss', // dismiss a report
|
||||
|
||||
'/reports/(\d+)/dismiss(all)?' => 'secure report_dismiss', // dismiss a report
|
||||
|
||||
'/IP/([\w.:]+)' => 'secure_POST ip', // view ip address
|
||||
'/IP/([\w.:]+)/remove_note/(\d+)' => 'secure ip_remove_note', // remove note from ip address
|
||||
'/IP/([\w.:-]+)/remove_telegram/(\d+)' => 'secure ip_remove_telegram', // remove telegram from ip address
|
||||
|
||||
'/ban' => 'secure_POST ban', // new ban
|
||||
'/bans' => 'secure_POST bans', // ban list
|
||||
'/bans.json' => 'secure bans_json', // ban list JSON
|
||||
'/edit_ban/(\d+)' => 'secure_POST edit_ban',
|
||||
'/ban-appeals' => 'secure_POST ban_appeals', // view ban appeals
|
||||
|
||||
|
||||
'/recent/(\d+)' => 'recent_posts', // view recent posts
|
||||
|
||||
'/search' => 'search_redirect', // search
|
||||
@ -87,20 +84,21 @@ $pages = [
|
||||
'/(\%b)/(un)?sticky/(\d+)' => 'secure sticky', // sticky thread
|
||||
'/(\%b)/(un)?cycle/(\d+)' => 'secure cycle', // cycle thread
|
||||
'/(\%b)/bump(un)?lock/(\d+)' => 'secure bumplock', // "bumplock" thread
|
||||
|
||||
|
||||
'/themes' => 'themes_list', // manage themes
|
||||
'/themes/(\w+)' => 'secure_POST theme_configure', // configure/reconfigure theme
|
||||
'/themes/(\w+)/rebuild' => 'secure theme_rebuild', // rebuild theme
|
||||
'/themes/(\w+)/uninstall' => 'secure theme_uninstall', // uninstall theme
|
||||
|
||||
|
||||
'/config' => 'secure_POST config', // config editor
|
||||
'/config/(\%b)' => 'secure_POST config', // config editor
|
||||
|
||||
|
||||
// these pages aren't listed in the dashboard without $config['debug']
|
||||
//'/debug/antispam' => 'debug_antispam',
|
||||
//'/debug/recent' => 'debug_recent_posts',
|
||||
//'/debug/apc' => 'debug_apc',
|
||||
//'/debug/sql' => 'secure_POST debug_sql',
|
||||
|
||||
|
||||
// This should always be at the end:
|
||||
'/(\%b)/' => 'view_board',
|
||||
'/(\%b)/' . preg_quote($config['file_index'], '!') => 'view_board',
|
||||
@ -112,14 +110,14 @@ $pages = [
|
||||
str_replace('%d', '(\d+)', preg_quote($config['file_page'], '!')) => 'view_thread',
|
||||
|
||||
'/(\%b)/' . preg_quote($config['dir']['res'], '!') .
|
||||
str_replace([ '%d','%s' ], [ '(\d+)', '[a-z0-9-]+' ], preg_quote($config['file_page50_slug'], '!')) => 'view_thread50',
|
||||
str_replace(array('%d','%s'), array('(\d+)', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '!')) => 'view_thread50',
|
||||
'/(\%b)/' . preg_quote($config['dir']['res'], '!') .
|
||||
str_replace([ '%d','%s' ], [ '(\d+)', '[a-z0-9-]+' ], preg_quote($config['file_page_slug'], '!')) => 'view_thread',
|
||||
];
|
||||
str_replace(array('%d','%s'), array('(\d+)', '[a-z0-9-]+'), preg_quote($config['file_page_slug'], '!')) => 'view_thread',
|
||||
);
|
||||
|
||||
|
||||
if (!$mod) {
|
||||
$pages = [ '!^(.+)?$!' => 'login' ];
|
||||
$pages = array('!^(.+)?$!' => 'login');
|
||||
} elseif (isset($_GET['status'], $_GET['r'])) {
|
||||
header('Location: ' . $_GET['r'], true, (int)$_GET['status']);
|
||||
exit;
|
||||
@ -129,11 +127,10 @@ if (isset($config['mod']['custom_pages'])) {
|
||||
$pages = array_merge($pages, $config['mod']['custom_pages']);
|
||||
}
|
||||
|
||||
$new_pages = [];
|
||||
$new_pages = array();
|
||||
foreach ($pages as $key => $callback) {
|
||||
if (is_string($callback) && preg_match('/^secure /', $callback)) {
|
||||
if (is_string($callback) && preg_match('/^secure /', $callback))
|
||||
$key .= '(/(?P<token>[a-f0-9]{8}))?';
|
||||
}
|
||||
$key = str_replace('\%b', '?P<board>' . sprintf(substr($config['board_path'], 0, -1), $config['board_regex']), $key);
|
||||
$new_pages[(!empty($key) and $key[0] == '!') ? $key : '!^' . $key . '(?:&[^&=]+=[^&]*)*$!u'] = $callback;
|
||||
}
|
||||
@ -141,8 +138,8 @@ $pages = $new_pages;
|
||||
|
||||
foreach ($pages as $uri => $handler) {
|
||||
if (preg_match($uri, $query, $matches)) {
|
||||
$matches[0] = $ctx; // Replace the text captured by the full pattern with a reference to the context.
|
||||
|
||||
$matches = array_slice($matches, 1);
|
||||
|
||||
if (isset($matches['board'])) {
|
||||
$board_match = $matches['board'];
|
||||
unset($matches['board']);
|
||||
@ -151,21 +148,21 @@ foreach ($pages as $uri => $handler) {
|
||||
$matches[$key] = $board_match[1];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (is_string($handler) && preg_match('/^secure(_POST)? /', $handler, $m)) {
|
||||
$secure_post_only = isset($m[1]);
|
||||
if (!$secure_post_only || $_SERVER['REQUEST_METHOD'] == 'POST') {
|
||||
$token = isset($matches['token']) ? $matches['token'] : (isset($_POST['token']) ? $_POST['token'] : false);
|
||||
|
||||
|
||||
if ($token === false) {
|
||||
if ($secure_post_only)
|
||||
error($config['error']['csrf']);
|
||||
else {
|
||||
mod_confirm($ctx, substr($query, 1));
|
||||
mod_confirm(substr($query, 1));
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// CSRF-protected page; validate security token
|
||||
$actual_query = preg_replace('!/([a-f0-9]{8})$!', '', $query);
|
||||
if ($token != make_secure_link_token(substr($actual_query, 1))) {
|
||||
@ -174,22 +171,26 @@ foreach ($pages as $uri => $handler) {
|
||||
}
|
||||
$handler = preg_replace('/^secure(_POST)? /', '', $handler);
|
||||
}
|
||||
|
||||
|
||||
if ($config['debug']) {
|
||||
$debug['mod_page'] = [
|
||||
$debug['mod_page'] = array(
|
||||
'req' => $query,
|
||||
'match' => $uri,
|
||||
'handler' => $handler,
|
||||
];
|
||||
);
|
||||
$debug['time']['parse_mod_req'] = '~' . round((microtime(true) - $parse_start_time) * 1000, 2) . 'ms';
|
||||
}
|
||||
|
||||
// We don't want to call named parameters (PHP 8).
|
||||
$matches = array_values($matches);
|
||||
if (is_array($matches)) {
|
||||
// we don't want to call named parameters (PHP 8)
|
||||
$matches = array_values($matches);
|
||||
}
|
||||
|
||||
if (is_string($handler)) {
|
||||
if ($handler[0] == ':') {
|
||||
header('Location: ' . substr($handler, 1), true, $config['redirect_http']);
|
||||
} elseif (is_callable("mod_page_$handler")) {
|
||||
call_user_func_array("mod_page_$handler", $matches);
|
||||
} elseif (is_callable("mod_$handler")) {
|
||||
call_user_func_array("mod_$handler", $matches);
|
||||
} else {
|
||||
@ -200,9 +201,10 @@ foreach ($pages as $uri => $handler) {
|
||||
} else {
|
||||
error("Mod page '$handler' not a string, and not callable!");
|
||||
}
|
||||
|
||||
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
error($config['error']['404']);
|
||||
|
||||
|
@ -9,22 +9,15 @@
|
||||
$queries_per_minutes_all = $config['search']['queries_per_minutes_all'];
|
||||
$search_limit = $config['search']['search_limit'];
|
||||
|
||||
//Is there a whitelist? Let's list those boards and if not, let's list everything.
|
||||
if (isset($config['search']['boards'])) {
|
||||
$boards = $config['search']['boards'];
|
||||
} else {
|
||||
$boards = listBoards(TRUE);
|
||||
}
|
||||
|
||||
//Let's remove any disallowed boards from the above list (the blacklist)
|
||||
if (isset($config['search']['disallowed_boards'])) {
|
||||
$boards = array_values(array_diff($boards, $config['search']['disallowed_boards']));
|
||||
}
|
||||
|
||||
$body = Element('search_form.html', Array('boards' => $boards, 'board' => isset($_GET['board']) ? $_GET['board'] : false, 'search' => isset($_GET['search']) ? str_replace('"', '"', utf8tohtml($_GET['search'])) : false));
|
||||
|
||||
if(isset($_GET['search']) && !empty($_GET['search']) && isset($_GET['board']) && in_array($_GET['board'], $boards)) {
|
||||
|
||||
$phrase = $_GET['search'];
|
||||
$_body = '';
|
||||
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 15 KiB |
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user