This commit is contained in:
igna 2022-09-23 22:40:52 -03:00
parent 9dd8863e24
commit 686f1e7bcd
74 changed files with 9782 additions and 2 deletions

10
.gitignore vendored Normal file
View file

@ -0,0 +1,10 @@
.DS_Store
node_modules
dist
build
vendor
package-lock.json
uguu.sq3
.idea
.phpdoc
.vscode

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "ansible/ansible-role-uguu"]
path = ansible/ansible-role-uguu
url = https://github.com/s3lva-kumar/ansible-role-uguu

1
.mailmap Normal file
View file

@ -0,0 +1 @@
Go Johansson <neku@pomf.se>

1
.sonarcloud.properties Normal file
View file

@ -0,0 +1 @@
sonar.exclusions=phpdocs

109
Makefile Normal file
View file

@ -0,0 +1,109 @@
MAKE="make"
INSTALL="install"
TAR="tar"
GREP="grep"
NODE="node"
NPM="npm"
HOSTS_FILE = $(HOSTS_FILE)
NODEJQ="node_modules/node-jq/bin/jq"
SQLITE="sqlite3"
CONF="src/config.json"
PHP="php"
CURL="curl"
DESTDIR = $(shell $(CURDIR)/$(NODEJQ) -r ".dest" $(CURDIR)/$(CONF))
NPX="npx"
PKG_VERSION = $(shell $(CURDIR)/$(NODEJQ) -r ".version" $(CURDIR)/package.json)
TMPDIR = $(shell mktemp -d)
DOCKER_IMAGE = "$(shell basename $(CURDIR) | tr [:upper:] [:lower:])"
DOCKER_TAG="$(DOCKER_TAG)"
CONTAINER_NAME="$(CONTAINER_NAME)"
# default modules
MODULES="php"
pageList = $(shell $(CURDIR)/$(NODEJQ) -r ".pages[]" $(CURDIR)/$(CONF))
noExt = $(shell echo $(i) | cut -d '.' -f1)
all: builddirs npm_dependencies composer ejs minify-all copy-img copy-php
ejs:
$(foreach i,$(pageList), \
$(NPX) ejs -f $(CURDIR)/$(CONF) $(CURDIR)/src/templates/$(i) -o $(CURDIR)/build/html/unmin/$(noExt).html;)
minify-all:
$(NPX) minify-all-cli -s $(CURDIR)/src/static/js -d $(CURDIR)/build/js
$(NPX) minify-all-cli -s $(CURDIR)/src/static/css -d $(CURDIR)/build/css
$(NPX) minify-all-cli -s $(CURDIR)/build/html/unmin/ -d $(CURDIR)/build/html/min/ -h
installdirs:
mkdir -p $(DESTDIR)/ $(DESTDIR)/img
mkdir -p $(DESTDIR)/ $(DESTDIR)/img/grills
copy-img:
$(NPX) imagemin $(CURDIR)/src/static/img/*.png -o=$(CURDIR)/build/img/
$(NPX) imagemin $(CURDIR)/src/static/img/grills/*.png --plugin=pngquant -o=$(CURDIR)/build/img/grills/
copy-php:
cp -v $(CURDIR)/src/static/php/*.php $(CURDIR)/build/php/
install: installdirs
cp -rv $(CURDIR)/build/* $(DESTDIR)/
mv $(DESTDIR)/html/min/* $(DESTDIR)/
mv $(DESTDIR)/js/* $(DESTDIR)/
mv $(DESTDIR)/css/* $(DESTDIR)/
mv $(DESTDIR)/php/* $(DESTDIR)/
rm -rf $(DESTDIR)/html
rm -rf $(DESTDIR)/css
rm -rf $(DESTDIR)/js
rm -rf $(DESTDIR)/php
mv $(DESTDIR)/uguu.css $(DESTDIR)/uguu.min.css
mv $(DESTDIR)/uguu.js $(DESTDIR)/uguu.min.js
submodule-update:
cd ansible && git clone git@github.com:s3lva-kumar/ansible-role-uguu.git && git submodule update --remote
deploy:
ansible-playbook -i $(HOSTS_FILE) ansible/site.yml
dist:
DESTDIR=$(TMPDIR)/uguu-$(PKGVERSION)
export DESTDIR
install
$(TAR) cJf uguu-$(PKG_VERSION).tar.xz $(DESTDIR)
rm -rf $(TMPDIR)
clean:
rm -rvf $(CURDIR)/node_modules
rm -rvf $(CURDIR)/build
uninstall:
rm -rvf $(DESTDIR)/
npm_dependencies:
$(NPM) install
composer:
$(CURL) -o composer-setup.php https://raw.githubusercontent.com/composer/getcomposer.org/main/web/installer
$(PHP) composer-setup.php --quiet
rm composer-setup.php
php composer.phar update
php composer.phar install
build-image:
tar --exclude='./uguuForDocker.tar.gz' --exclude='./vendor' --exclude='./node_modules' -czf uguuForDocker.tar.gz .
mv uguuForDocker.tar.gz docker/
docker build -f docker/Dockerfile --build-arg VERSION=$(UGUU_RELEASE_VER) --no-cache -t $(DOCKER_IMAGE):$(DOCKER_TAG) .
run-container:
docker run --name $(CONTAINER_NAME) -d -p 8080:80 -p 8081:443 $(DOCKER_IMAGE):$(DOCKER_TAG)
purge-container:
if docker images | grep $(DOCKER_IMAGE); then \
docker rm -f $(CONTAINER_NAME) && docker rmi $(DOCKER_IMAGE):$(DOCKER_TAG) || true;\
fi;
builddirs:
mkdir -p $(CURDIR)/build $(CURDIR)/build/img $(CURDIR)/build/html $(CURDIR)/build/html/min $(CURDIR)/build/html/unmin $(CURDIR)/build/js $(CURDIR)/build/css $(CURDIR)/build/php

View file

@ -1,3 +1,61 @@
# intent.cool
# Uguu
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nokonoko_Uguu&metric=alert_status)](https://sonarcloud.io/dashboard?id=nokonoko_Uguu)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Documentation Status](https://docs.uguu.se/img/flat.svg)](https://docs.uguu.se)
yet another files host - based from uguu.se code
# What is Uguu?
Uguu is a simple lightweight temporary file hosting and sharing platform, but can also be used as a permanent file host.
## Features
- One click uploading, no registration required
- A minimal, modern web interface
- Drag & Drop & Paste supported
- Upload API with multiple response choices
- JSON
- HTML
- Text
- CSV
- Supports [ShareX](https://getsharex.com/) and other screenshot tools
### Demo
See the real world site at [uguu.se](https://uguu.se).
## Requirements
Tested and working with Nginx + PHP-8.0/8.1 + SQLite/MySQL.
Node is used to compile Uguu, after that it runs on PHP.
## Installation
Installation and configuration can be found at [Uguu Documentation](https://docs.uguu.se).
If you need a admin panel check out [Moe Panel](https://github.com/Pomf/MoePanel).
## Getting help
Hit me up at [@nekunekus](https://twitter.com/nekunekus) or email me at neku@pomf.se
## Contributing
We'd really like if you can take some time to make sure your coding style is
consistent with the project. Uguu follows [PHP
PSR-12](https://www.php-fig.org/psr/psr-12/) and [Airbnb JavaScript
(ES5)](https://github.com/airbnb/javascript/tree/es5-deprecated/es5) (`airbnb/legacy`)
coding style guides. We use ESLint and PHPCS tools to enforce these standards.
You can also help by sending us feature requests or writing documentation and
tests.
## Credits
Uguu is based on [Pomf](http://github.com/pomf/pomf) which was written by Emma Lejack & Go Johansson (nekunekus) and with help from the open source community.
## License
Uguu is free software, and is released under the terms of the GPL-3.0 license. See
`LICENSE`.

10
ansible/site.yml Normal file
View file

@ -0,0 +1,10 @@
- name: "install uguu"
hosts: all
become: yes
roles:
- ansible-role-uguu
vars:
paypalUrl: ""
bitcoinAddress: ""
flattrUrl: ""

31
composer.json Normal file
View file

@ -0,0 +1,31 @@
{
"name": "pomf/uguu",
"description": "Uguu is a simple lightweight temporary file host with support for drop, paste, click and API uploading.",
"type": "library",
"license": "GPL-3.0",
"autoload": {
"psr-4": {
"Pomf\\Uguu\\": "src/",
"Pomf\\Uguu\\Classes\\": "src/Classes"
}
},
"authors": [
{
"name": "Go Johansson (neku)",
"email": "neku@pomf.se"
}
],
"minimum-stability": "stable",
"require": {
"ext-fileinfo": "*",
"ext-pdo": "*"
},
"require-dev": {
"phpunit/phpunit": "@stable",
"squizlabs/php_codesniffer": "@stable",
"phpmd/phpmd": "@stable",
"friendsofphp/php-cs-fixer": "@stable",
"phpstan/phpstan": "@stable",
"vimeo/psalm": "@stable"
}
}

5116
composer.lock generated Normal file

File diff suppressed because it is too large Load diff

81
docker/Dockerfile Normal file
View file

@ -0,0 +1,81 @@
FROM php:8.1-alpine
ARG VERSION
RUN apk add --no-cache $PHPIZE_DEPS \
php-fpm zlib-dev libzip-dev libgomp; \
docker-php-ext-install intl pcntl gd exif zip pdo mysql dom; \
apk del $PHPIZE_DEPS; \
rm -rf /tmp/pear;
# Install the needed software
RUN apk add --no-cache sqlite nodejs git npm bash build-base supervisor curl wget nginx
#php8-fileinfo php8-pdo php8-tokenizer php8-dom php8-iconv php8-xml php8-simplexml \
#php8-sqlite3 php8-opcache php8-mbstring php8-phar php8-openssl
# Create the www-data user and group
#RUN set -x ; \
# addgroup -g 82 -S www-data ; \
# adduser -u 82 -D -S -G www-data www-data && exit 0 ; exit 1
# Copy supervisor conf file
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# Set default workdir
WORKDIR /var/www/
COPY docker/docker-entrypoint.sh .
# Decompress into Docker
COPY docker/uguuForDocker.tar.gz /var/www/
RUN mkdir /var/www/uguu
RUN tar -xvf uguuForDocker.tar.gz -C uguu
# Create the needed directories
RUN mkdir /var/www/files && \
mkdir /var/www/db
# Create the Sqlite DB
RUN sqlite3 /var/www/db/uguu.sq3 -init /var/www/uguu/src/static/dbSchemas/sqlite_schema.sql && \
chown -R www-data:www-data /var/www && \
chmod -R 775 /var/www/
# Fix script paths
RUN chmod a+x /var/www/uguu/src/static/scripts/checkdb.sh && \
chmod a+x /var/www/uguu/src/static/scripts/checkfiles.sh && \
sed -i 's#/path/to/files/#/var/www/uguu/files/#g' /var/www/uguu/src/static/scripts/checkfiles.sh && \
sed -i 's#/path/to/db/uguu.sq3#/var/www/db/uguu.sq3#g' /var/www/uguu/src/static/scripts/checkdb.sh
# Add scripts to cron
RUN echo "0,30 * * * * bash /var/www/uguu/src/static/scripts/checkfiles.sh" >> /var/spool/cron/crontabs/www-data && \
echo "0,30 * * * * bash /var/www/uguu/src/static/scripts/checkdb.sh" >> /var/spool/cron/crontabs/www-data
# Copy Nginx Server conf
COPY docker/nginx/uguu.conf /etc/nginx/http.d/
# Copy SSL certs
COPY docker/ssl /etc/ssl
# Copy PHP config
COPY docker/php/php.ini /etc/php8/
COPY docker/php/www.conf /etc/php8/php-fpm.d/
RUN mkdir /var/run/php
# Copy Uguu config
COPY src/config.json /var/www/uguu/config.json
# Give permissions to www-data
RUN chown -R www-data:www-data /run /var/lib/nginx /var/log/nginx /etc/nginx /etc/php8 /var/log/php8 /var/run/php
# Change user to www-data
USER www-data
# Expose port 80 from the container
EXPOSE 80
# Expose port 443 from the container
EXPOSE 443
# Load entrypoint
ENTRYPOINT [ "bash", "/var/www/docker-entrypoint.sh" ]

View file

@ -0,0 +1,11 @@
#!/bin/bash
cd /var/www/uguu/
make
make install
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
php composer.phar install
php composer.phar update
/usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf

36
docker/nginx/uguu.conf Normal file
View file

@ -0,0 +1,36 @@
server{
listen 80;
server_name 192.168.240.9;
#ssl on;
#ssl_certificate /etc/nginx/ssl/fullchain.pem;
#ssl_certificate_key /etc/nginx/ssl/privkey.pem;
#ssl_protocols TLSv1.2 TLSv1.3;
#ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
#ssl_ecdh_curve secp384r1;
root /var/www/uguu/dist/;
autoindex on;
access_log on;
index index.html index.php;
location ~* \.(css|js|jpg|jpeg|gif|png|ico|xml|eot|woff|woff2|ttf|svg|otf|x-icon|avif|webp|apng)$ {
expires 30d;
}
client_max_body_size 128M;
gzip on;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_proxied any;
gzip_types text/css text/js text/javascript application/javascript application/x-javascript;
location ~* \.php$ {
fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
fastcgi_intercept_errors on;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

1946
docker/php/php.ini Normal file

File diff suppressed because it is too large Load diff

455
docker/php/www.conf Normal file
View file

@ -0,0 +1,455 @@
; Start a new pool named 'www'.
; the variable $pool can be used in any directive and will be replaced by the
; pool name ('www' here)
[www]
; Per pool prefix
; It only applies on the following directives:
; - 'access.log'
; - 'slowlog'
; - 'listen' (unixsocket)
; - 'chroot'
; - 'chdir'
; - 'php_values'
; - 'php_admin_values'
; When not set, the global prefix (or /usr) applies instead.
; Note: This directive can also be relative to the global prefix.
; Default Value: none
;prefix = /path/to/pools/$pool
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
user = nobody
group = nobody
; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses
; (IPv6 and IPv4-mapped) on a specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /var/run/php/php8.0-fpm.sock
; Set listen(2) backlog.
; Default Value: 511 (-1 on FreeBSD and OpenBSD)
;listen.backlog = 511
; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. The owner
; and group can be specified either by name or by their numeric IDs.
; Default Values: user and group are set as the running user
; mode is set to 0660
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0660
; When POSIX Access Control Lists are supported you can set them using
; these options, value is a comma separated list of user/group names.
; When set, listen.owner and listen.group are ignored
;listen.acl_users =
;listen.acl_groups =
; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
;listen.allowed_clients = 127.0.0.1
; Specify the nice(2) priority to apply to the pool processes (only if set)
; The value can vary from -19 (highest priority) to 20 (lower priority)
; Note: - It will only work if the FPM master process is launched as root
; - The pool processes will inherit the master process priority
; unless it specified otherwise
; Default Value: no set
; process.priority = -19
; Set the process dumpable flag (PR_SET_DUMPABLE prctl) even if the process user
; or group is different than the master process user. It allows to create process
; core dump and ptrace the process for the pool user.
; Default Value: no
; process.dumpable = yes
; Choose how the process manager will control the number of child processes.
; Possible Values:
; static - a fixed number (pm.max_children) of child processes;
; dynamic - the number of child processes are set dynamically based on the
; following directives. With this process management, there will be
; always at least 1 children.
; pm.max_children - the maximum number of children that can
; be alive at the same time.
; pm.start_servers - the number of children created on startup.
; pm.min_spare_servers - the minimum number of children in 'idle'
; state (waiting to process). If the number
; of 'idle' processes is less than this
; number then some children will be created.
; pm.max_spare_servers - the maximum number of children in 'idle'
; state (waiting to process). If the number
; of 'idle' processes is greater than this
; number then some children will be killed.
; ondemand - no children are created at startup. Children will be forked when
; new requests will connect. The following parameter are used:
; pm.max_children - the maximum number of children that
; can be alive at the same time.
; pm.process_idle_timeout - The number of seconds after which
; an idle process will be killed.
; Note: This value is mandatory.
pm = dynamic
; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 5
; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: (min_spare_servers + max_spare_servers) / 2
pm.start_servers = 2
; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 1
; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 3
; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
;pm.process_idle_timeout = 10s;
; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500
; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. It shows the following information:
; pool - the name of the pool;
; process manager - static, dynamic or ondemand;
; start time - the date and time FPM has started;
; start since - number of seconds since FPM has started;
; accepted conn - the number of request accepted by the pool;
; listen queue - the number of request in the queue of pending
; connections (see backlog in listen(2));
; max listen queue - the maximum number of requests in the queue
; of pending connections since FPM has started;
; listen queue len - the size of the socket queue of pending connections;
; idle processes - the number of idle processes;
; active processes - the number of active processes;
; total processes - the number of idle + active processes;
; max active processes - the maximum number of active processes since FPM
; has started;
; max children reached - number of times, the process limit has been reached,
; when pm tries to start more children (works only for
; pm 'dynamic' and 'ondemand');
; Value are updated in real time.
; Example output:
; pool: www
; process manager: static
; start time: 01/Jul/2011:17:53:49 +0200
; start since: 62636
; accepted conn: 190460
; listen queue: 0
; max listen queue: 1
; listen queue len: 42
; idle processes: 4
; active processes: 11
; total processes: 15
; max active processes: 12
; max children reached: 0
;
; By default the status page output is formatted as text/plain. Passing either
; 'html', 'xml' or 'json' in the query string will return the corresponding
; output syntax. Example:
; http://www.foo.bar/status
; http://www.foo.bar/status?json
; http://www.foo.bar/status?html
; http://www.foo.bar/status?xml
;
; By default the status page only outputs short status. Passing 'full' in the
; query string will also return status for each pool process.
; Example:
; http://www.foo.bar/status?full
; http://www.foo.bar/status?json&full
; http://www.foo.bar/status?html&full
; http://www.foo.bar/status?xml&full
; The Full status returns for each process:
; pid - the PID of the process;
; state - the state of the process (Idle, Running, ...);
; start time - the date and time the process has started;
; start since - the number of seconds since the process has started;
; requests - the number of requests the process has served;
; request duration - the duration in µs of the requests;
; request method - the request method (GET, POST, ...);
; request URI - the request URI with the query string;
; content length - the content length of the request (only with POST);
; user - the user (PHP_AUTH_USER) (or '-' if not set);
; script - the main script called (or '-' if not set);
; last request cpu - the %cpu the last request consumed
; it's always 0 if the process is not in Idle state
; because CPU calculation is done when the request
; processing has terminated;
; last request memory - the max amount of memory the last request consumed
; it's always 0 if the process is not in Idle state
; because memory calculation is done when the request
; processing has terminated;
; If the process is in Idle state, then informations are related to the
; last request the process has served. Otherwise informations are related to
; the current request being served.
; Example output:
; ************************
; pid: 31330
; state: Running
; start time: 01/Jul/2011:17:53:49 +0200
; start since: 63087
; requests: 12808
; request duration: 1250261
; request method: GET
; request URI: /test_mem.php?N=10000
; content length: 0
; user: -
; script: /home/fat/web/docs/php/test_mem.php
; last request cpu: 0.00
; last request memory: 0
;
; Note: There is a real-time FPM status monitoring sample web page available
; It's available in: /usr/share/php8/fpm/status.html
;
; Note: The value must start with a leading slash (/). The value can be
; anything, but it may not be a good idea to use the .php extension or it
; may conflict with a real PHP file.
; Default Value: not set
;pm.status_path = /status
; The address on which to accept FastCGI status request. This creates a new
; invisible pool that can handle requests independently. This is useful
; if the main pool is busy with long running requests because it is still possible
; to get the status before finishing the long running requests.
;
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses
; (IPv6 and IPv4-mapped) on a specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Default Value: value of the listen option
;pm.status_listen = 127.0.0.1:9001
; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
; anything, but it may not be a good idea to use the .php extension or it
; may conflict with a real PHP file.
; Default Value: not set
;ping.path = /ping
; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
;ping.response = pong
; The access log file
; Default: not set
;access.log = log/php8/$pool.access.log
; The access log format.
; The following syntax is allowed
; %%: the '%' character
; %C: %CPU used by the request
; it can accept the following format:
; - %{user}C for user CPU only
; - %{system}C for system CPU only
; - %{total}C for user + system CPU (default)
; %d: time taken to serve the request
; it can accept the following format:
; - %{seconds}d (default)
; - %{milliseconds}d
; - %{mili}d
; - %{microseconds}d
; - %{micro}d
; %e: an environment variable (same as $_ENV or $_SERVER)
; it must be associated with embraces to specify the name of the env
; variable. Some examples:
; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
; %f: script filename
; %l: content-length of the request (for POST request only)
; %m: request method
; %M: peak of memory allocated by PHP
; it can accept the following format:
; - %{bytes}M (default)
; - %{kilobytes}M
; - %{kilo}M
; - %{megabytes}M
; - %{mega}M
; %n: pool name
; %o: output header
; it must be associated with embraces to specify the name of the header:
; - %{Content-Type}o
; - %{X-Powered-By}o
; - %{Transfert-Encoding}o
; - ....
; %p: PID of the child that serviced the request
; %P: PID of the parent of the child that serviced the request
; %q: the query string
; %Q: the '?' character if query string exists
; %r: the request URI (without the query string, see %q and %Q)
; %R: remote IP address
; %s: status (response code)
; %t: server time the request was received
; it can accept a strftime(3) format:
; %d/%b/%Y:%H:%M:%S %z (default)
; The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
; %T: time the log has been written (the request has finished)
; it can accept a strftime(3) format:
; %d/%b/%Y:%H:%M:%S %z (default)
; The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
; %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"
; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
;slowlog = log/php8/$pool.slow.log
; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0
; Depth of slow log stack trace.
; Default Value: 20
;request_slowlog_trace_depth = 20
; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0
; The timeout set by 'request_terminate_timeout' ini option is not engaged after
; application calls 'fastcgi_finish_request' or when application has finished and
; shutdown functions are being called (registered via register_shutdown_function).
; This option will enable timeout limit to be applied unconditionally
; even in such cases.
; Default Value: no
;request_terminate_timeout_track_finished = no
; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024
; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0
; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
; of its subdirectories. If the pool prefix is not set, the global prefix
; will be used instead.
; Note: chrooting is a great security feature and should be used whenever
; possible. However, all PHP paths will be relative to the chroot
; (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot =
; Chdir to this directory at the start.
; Note: relative path can be used.
; Default Value: current directory or / when chroot
;chdir = /var/www
; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Note: on highloaded environment, this can cause some delay in the page
; process time (several ms).
; Default Value: no
;catch_workers_output = yes
; Decorate worker output with prefix and suffix containing information about
; the child that writes to the log and if stdout or stderr is used as well as
; log level and time. This options is used only if catch_workers_output is yes.
; Settings to "no" will output data as written to the stdout or stderr.
; Default value: yes
;decorate_workers_output = no
; Clear environment in FPM workers
; Prevents arbitrary environment variables from reaching FPM worker processes
; by clearing the environment in workers before env vars specified in this
; pool configuration are added.
; Setting to "no" will make all environment variables available to PHP code
; via getenv(), $_ENV and $_SERVER.
; Default Value: yes
;clear_env = no
; Limits the extensions of the main script FPM will allow to parse. This can
; prevent configuration mistakes on the web server side. You should only limit
; FPM to .php extensions to prevent malicious users to use other extensions to
; execute php code.
; Note: set an empty value to allow all extensions.
; Default Value: .php
;security.limit_extensions = .php .php3 .php4 .php5 .php7
; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp
; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
; php_value/php_flag - you can set classic ini defines which can
; be overwritten from PHP call 'ini_set'.
; php_admin_value/php_admin_flag - these directives won't be overwritten by
; PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.
; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.
; Note: path INI options can be relative and will be expanded with the prefix
; (pool, global or /usr)
; Default Value: nothing is defined by default except the values in php.ini and
; specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
;php_admin_value[error_log] = /var/log/php8/$pool.error.log
;php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 32M

0
docker/ssl/fullchain.pem Normal file
View file

0
docker/ssl/privkey.pem Normal file
View file

32
docker/supervisord.conf Normal file
View file

@ -0,0 +1,32 @@
[supervisord]
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
pidfile=/run/supervisord.pid
[program:php-fpm]
command=php-fpm8 -F
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0
[program:nginx]
command=nginx -g 'daemon off;'
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0
[program:crond]
command=crond -b
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=false
startretries=0

8
docker_build.sh Normal file
View file

@ -0,0 +1,8 @@
#!/bin/bash
echo ">>> BUILDING UGUU CONTAINER <<<"
make UGUU_RELEASE_VER="$(cat package.json | grep version | cut -d '"' -f4)" DOCKER_TAG="$(cat package.json | grep version | cut -d '"' -f4)" build-image
echo ">>> DONE! <<<"
echo ">>> Starting Uguu container! <<<"
make DOCKER_TAG="$(cat package.json | grep version | cut -d '"' -f4)" CONTAINER_NAME=uguu run-container
echo ">>> DONE! <<<"

2
docker_purge.sh Normal file
View file

@ -0,0 +1,2 @@
#!/bin/bash
make DOCKER_TAG="$(cat package.json | grep version | cut -d '"' -f4)" CONTAINER_NAME=uguu purge-container

27
package.json Normal file
View file

@ -0,0 +1,27 @@
{
"name": "uguu",
"version": "1.6.0",
"description": "Uguu is a simple lightweight temporary file host with support for drop, paste, click and API uploading.",
"homepage": "https://uguu.se",
"repository": {
"type": "git",
"url": "https://github.com/nokonoko/uguu"
},
"author": "Go Johansson <neku@pomf.se>",
"contributors": [
"Pomf Community <github.com/pomf/pomf>",
"Uguu Community <github.com/nokonoko/uguu>"
],
"license": "GPLV3",
"bugs": {
"url": "https://github.com/nokonoko/uguu/issues"
},
"devDependencies" : {
"ejs": "^3.1.8",
"minify-all-cli": "^1.0.13",
"node-jq": "^2.3.3",
"npx": "^10.2.2",
"imagemin-cli": "^7.0.0",
"imagemin-pngquant": "^9.0.2"
}
}

15
psalm.xml Normal file
View file

@ -0,0 +1,15 @@
<?xml version="1.0"?>
<psalm
errorLevel="3"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="." />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
</psalm>

66
src/Classes/Connector.php Normal file
View file

@ -0,0 +1,66 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu\Classes;
use Exception;
use PDO;
class Connector extends Database
{
public PDO $DB;
public array $CONFIG;
/**
* @throws Exception
*/
public function __construct()
{
if (!file_exists(__DIR__ . '/../config.json')) {
throw new Exception('Cant read settings file.', 500);
}
try {
$this->CONFIG = json_decode(
file_get_contents(__DIR__ . '/../config.json'),
true
);
$this->assemble();
} catch (Exception) {
throw new Exception('Cant populate settings.', 500);
}
}
/**
* @throws Exception
*/
public function assemble()
{
try {
$this->DB = new PDO(
$this->CONFIG['DB_MODE'] . ':' . $this->CONFIG['DB_PATH'],
$this->CONFIG['DB_USER'],
$this->CONFIG['DB_PASS']
);
} catch (Exception) {
throw new Exception('Cant connect to DB.', 500);
}
}
}

View file

@ -0,0 +1,45 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu\Classes;
class CuteGrills
{
public array $GRILLS;
public function showGrills(): void
{
$this->loadGrills();
if (!headers_sent()) {
header(
'Location: /img/grills/' .
$this->GRILLS[array_rand($this->GRILLS)],
true,
303
);
}
}
public function loadGrills(): void
{
$this->GRILLS = array_slice(scandir('img/grills/'), 2);
}
}

185
src/Classes/Database.php Normal file
View file

@ -0,0 +1,185 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu\Classes;
use Exception;
use PDO;
class Database
{
private PDO $DB;
public function setDB($DB): void
{
$this->DB = $DB;
}
/**
* @throws Exception
*/
public function dbCheckNameExists($name): string
{
try {
$q = $this->DB->prepare('SELECT COUNT(filename) FROM files WHERE filename = (:name)');
$q->bindValue(':name', $name);
$q->execute();
return $q->fetchColumn();
} catch (Exception) {
throw new Exception('Cant check if name exists in DB.', 500);
}
}
/**
* @throws Exception
*/
public function checkFileBlacklist($FILE_INFO): void
{
try {
$q = $this->DB->prepare('SELECT hash, COUNT(*) AS count FROM blacklist WHERE hash = (:hash)');
$q->bindValue(':hash', $FILE_INFO['SHA1']);
$q->execute();
$result = $q->fetch();
if ($result['count'] > 0) {
throw new Exception('File blacklisted!', 415);
}
} catch (Exception) {
throw new Exception('Cant check blacklist DB.', 500);
}
}
/**
* @throws Exception
*/
public function antiDupe($hash): bool | array | string
{
if (!$this->CONFIG['ANTI_DUPE']) {
return true;
}
try {
$q = $this->DB->prepare(
'SELECT filename, COUNT(*) AS count FROM files WHERE hash = (:hash)'
);
$q->bindValue(':hash', $hash);
$q->execute();
$result = $q->fetch();
if ($result['count'] > 0) {
return $result['filename'];
} else {
return true;
}
} catch (Exception) {
throw new Exception('Cant check for dupes in DB.', 500);
}
}
/**
* @throws Exception
*/
public function newIntoDB($FILE_INFO, $fingerPrintInfo): void
{
try {
$q = $this->DB->prepare(
'INSERT INTO files (hash, originalname, filename, size, date, ip)' .
'VALUES (:hash, :orig, :name, :size, :date, :ip)'
);
$q->bindValue(':hash', $FILE_INFO['SHA1']);
$q->bindValue(':orig', $FILE_INFO['NAME']);
$q->bindValue(':name', $FILE_INFO['NEW_NAME']);
$q->bindValue(':size', $FILE_INFO['SIZE'], PDO::PARAM_INT);
$q->bindValue(':date', $fingerPrintInfo['timestamp']);
$q->bindValue(':ip', $fingerPrintInfo['ip']);
$q->execute();
} catch (Exception) {
throw new Exception('Cant insert into DB.', 500);
}
}
public function createRateLimit($fingerPrintInfo): void
{
$q = $this->DB->prepare(
'INSERT INTO timestamp (iphash, files, time)' .
'VALUES (:iphash, :files, :time)'
);
$q->bindValue(':iphash', $fingerPrintInfo['ip_hash']);
$q->bindValue(':files', $fingerPrintInfo['files_amount']);
$q->bindValue(':time', $fingerPrintInfo['timestamp']);
$q->execute();
}
public function updateRateLimit($fCount, $iStamp, $fingerPrintInfo): void
{
if ($iStamp) {
$q = $this->DB->prepare(
'UPDATE ratelimit SET files = (:files), time = (:time) WHERE iphash = (:iphash)'
);
$q->bindValue(':time', $fingerPrintInfo['timestamp']);
} else {
$q = $this->DB->prepare(
'UPDATE ratelimit SET files = (:files) WHERE iphash = (:iphash)'
);
}
$q->bindValue(':files', $fCount);
$q->bindValue(':iphash', $fingerPrintInfo['ip_hash']);
$q->execute();
}
public function checkRateLimit($fingerPrintInfo): bool
{
$q = $this->DB->prepare(
'SELECT files, time, iphash, COUNT(*) AS count FROM ratelimit WHERE iphash = (:iphash)'
);
$q->bindValue(':iphash', $fingerPrintInfo['ip_hash']);
$q->execute();
$result = $q->fetch();
$nTime = $fingerPrintInfo['timestamp'] - (60);
switch (true) {
//If more then 100 files trigger rate-limit
case $result['files'] > 100:
return true;
//if timestamp is older than one minute, set new files count and timestamp
case $result['time'] < $nTime:
$this->updateRateLimit($fingerPrintInfo['files_amount'], true, $fingerPrintInfo);
break;
//if timestamp isn't older than one-minute update the files count
case $result['time'] > $nTime:
$this->updateRateLimit($fingerPrintInfo['files_amount'] + $result['files'], false, $fingerPrintInfo);
break;
//If there is no other match a record does not exist, create one
default:
$this->createRateLimit($fingerPrintInfo);
break;
}
return false;
}
}

151
src/Classes/Response.php Normal file
View file

@ -0,0 +1,151 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu\Classes;
class Response
{
public mixed $type;
public function __construct($response_type = "json")
{
switch ($response_type) {
case 'csv':
header('Content-Type: text/csv; charset=UTF-8');
$this->type = $response_type;
break;
case 'html':
header('Content-Type: text/html; charset=UTF-8');
$this->type = $response_type;
break;
case 'json':
header('Content-Type: application/json; charset=UTF-8');
$this->type = $response_type;
break;
case 'gyazo':
header('Content-Type: text/plain; charset=UTF-8');
$this->type = 'text';
break;
case 'text':
header('Content-Type: text/plain; charset=UTF-8');
$this->type = $response_type;
break;
default:
header('Content-Type: application/json; charset=UTF-8');
$this->type = 'json';
$this->error(400, 'Invalid response type. Valid options are: csv, html, json, text.');
break;
}
}
public function error($code, $desc): void
{
$response = match ($this->type) {
'csv' => $this->csvError($desc),
'html' => $this->htmlError($code, $desc),
'json' => $this->jsonError($code, $desc),
'text' => $this->textError($code, $desc),
};
http_response_code($code);
echo $response;
}
private static function csvError($description): string
{
return '"error"' . "\r\n" . "\"$description\"" . "\r\n";
}
private static function htmlError($code, $description): string
{
return '<p>ERROR: (' . $code . ') ' . $description . '</p>';
}
private static function jsonError($code, $description): bool|string
{
return json_encode([
'success' => false,
'errorcode' => $code,
'description' => $description,
], JSON_PRETTY_PRINT);
}
private static function textError($code, $description): string
{
return 'ERROR: (' . $code . ') ' . $description;
}
public function send($files): void
{
$response = match ($this->type) {
'csv' => $this->csvSuccess($files),
'html' => $this->htmlSuccess($files),
'json' => $this->jsonSuccess($files),
'text' => $this->textSuccess($files),
};
http_response_code(200); // "200 OK". Success.
echo $response;
}
private static function csvSuccess($files): string
{
$result = '"name","url","hash","size"' . "\r\n";
foreach ($files as $file) {
$result .= '"' . $file['name'] . '"' . ',' .
'"' . $file['url'] . '"' . ',' .
'"' . $file['hash'] . '"' . ',' .
'"' . $file['size'] . '"' . "\r\n";
}
return $result;
}
private static function htmlSuccess($files): string
{
$result = '';
foreach ($files as $file) {
$result .= '<a href="' . $file['url'] . '">' . $file['url'] . '</a><br>';
}
return $result;
}
private static function jsonSuccess($files): bool|string
{
return json_encode([
'success' => true,
'files' => $files,
], JSON_PRETTY_PRINT);
}
private static function textSuccess($files): string
{
$result = '';
foreach ($files as $file) {
$result .= $file['url'] . "\n";
}
return $result;
}
}

206
src/Classes/Upload.php Normal file
View file

@ -0,0 +1,206 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu\Classes;
use Exception;
class Upload extends Response
{
public array $FILE_INFO;
public array $fingerPrintInfo;
private mixed $Connector;
/**
* @throws Exception
*/
public function reFiles($files): array
{
$this->Connector = new Connector();
$this->Connector->setDB($this->Connector->DB);
$result = [];
$files = $this->diverseArray($files);
foreach ($files as $file) {
$hash = sha1_file($file['tmp_name']);
$this->FILE_INFO = [
'TEMP_NAME' => $file['tmp_name'],
'NAME' => strip_tags($file['name']),
'SIZE' => $file['size'],
'SHA1' => $hash,
'EXTENSION' => $this->fileExtension($file),
'MIME' => $this->fileMIME($file),
'NEW_NAME' => $this->generateName($this->fileExtension($file), $hash)
];
$result[] = [
$this->FILE_INFO['TEMP_NAME'],
$this->FILE_INFO['NAME'],
$this->FILE_INFO['SIZE'],
$this->FILE_INFO['SHA1'],
$this->FILE_INFO['EXTENSION'],
$this->FILE_INFO['MIME']
];
}
return $result;
}
public function diverseArray($files): array
{
$result = [];
foreach ($files as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
$result[$key2][$key1] = $value2;
}
}
return $result;
}
/**
* @throws Exception
*/
public function uploadFile(): array
{
if ($this->Connector->CONFIG['RATE_LIMIT']) {
$this->Connector->checkRateLimit($this->fingerPrintInfo);
}
if ($this->Connector->CONFIG['BLACKLIST_DB']) {
$this->Connector->checkFileBlacklist($this->FILE_INFO);
}
if ($this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION'])) {
$this->checkMimeBlacklist();
}
if ($this->Connector->CONFIG['FILTER_MODE'] && !empty($this->FILE_INFO['EXTENSION'])) {
$this->checkMimeBlacklist();
$this->checkExtensionBlacklist();
}
if (!is_dir($this->Connector->CONFIG['FILES_ROOT'])) {
throw new Exception('File storage path not accessible.', 500);
}
if (
!move_uploaded_file($this->FILE_INFO['TEMP_NAME'], $this->Connector->CONFIG['FILES_ROOT'] .
$this->FILE_INFO['NEW_NAME'])
) {
throw new Exception('Failed to move file to destination', 500);
}
if (!chmod($this->Connector->CONFIG['FILES_ROOT'] . $this->FILE_INFO['NEW_NAME'], 0644)) {
throw new Exception('Failed to change file permissions', 500);
}
if (!$this->Connector->CONFIG['LOG_IP']) {
$this->fingerPrintInfo['ip'] = null;
}
$this->Connector->newIntoDB($this->FILE_INFO, $this->fingerPrintInfo);
return [
'hash' => $this->FILE_INFO['SHA1'],
'name' => $this->FILE_INFO['NAME'],
'url' => $this->Connector->CONFIG['FILES_URL'] . '/' . $this->FILE_INFO['NEW_NAME'],
'size' => $this->FILE_INFO['SIZE']
];
}
public function fingerPrint($files_amount): void
{
$this->fingerPrintInfo = [
'timestamp' => time(),
'useragent' => $_SERVER['HTTP_USER_AGENT'],
'ip' => $_SERVER['REMOTE_ADDR'],
'ip_hash' => hash('sha1', $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']),
'files_amount' => $files_amount
];
}
public function fileMIME($file): string
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
return finfo_file($finfo, $file['tmp_name']);
}
public function fileExtension($file): ?string
{
$extension = explode('.', $file['name']);
if (substr_count($file['name'], '.') > 0) {
return end($extension);
} else {
return null;
}
}
/**
* @throws Exception
*/
public function checkMimeBlacklist(): void
{
if (in_array($this->FILE_INFO['MIME'], $this->Connector->CONFIG['BLOCKED_MIME'])) {
throw new Exception('Filetype not allowed.', 415);
}
}
/**
* Check if file extension is blacklisted
* if it does throw an exception.
*
* @throws Exception
*/
public function checkExtensionBlacklist(): void
{
if (in_array($this->FILE_INFO['EXTENSION'], $this->Connector->CONFIG['BLOCKED_EXTENSIONS'])) {
throw new Exception('Filetype not allowed.', 415);
}
}
/**
* @throws Exception
*/
public function generateName($extension, $hash): string
{
$a = $this->Connector->antiDupe($hash);
if ($a === true) {
do {
if ($this->Connector->CONFIG['FILES_RETRIES'] === 0) {
throw new Exception('Gave up trying to find an unused name!', 500);
}
$NEW_NAME = '';
for ($i = 0; $i < $this->Connector->CONFIG['NAME_LENGTH']; ++$i) {
$NEW_NAME .= $this->Connector->CONFIG['ID_CHARSET']
[mt_rand(0, strlen($this->Connector->CONFIG['ID_CHARSET']))];
}
if (!is_null($extension)) {
$NEW_NAME .= '.' . $extension;
}
} while ($this->Connector->dbCheckNameExists($NEW_NAME) > 0);
return $NEW_NAME;
} else {
return $a;
}
}
}

30
src/GrillLoader.php Normal file
View file

@ -0,0 +1,30 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu;
class GrillLoader extends Classes\CuteGrills
{
public function __construct()
{
$this->showGrills();
}
}

53
src/UploadGateway.php Normal file
View file

@ -0,0 +1,53 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu;
use Exception;
use Pomf\Uguu\Classes\Response;
class UploadGateway extends Classes\Upload
{
/**
* @throws Exception
*/
public function handleFile($output, $files)
{
$type = $output ?? 'json';
$response = (new Response($type));
if (isset($_FILES['files'])) {
$files = $this->reFiles($files);
try {
$this->fingerPrint(count($files));
foreach ($files as $ignored) {
$res[] = $this->uploadFile();
}
if (isset($res)) {
$response->send($res);
}
} catch (Exception $e) {
$response->error($e->getCode(), $e->getMessage());
}
} else {
$response->error(400, 'No input file(s)');
}
}
}

67
src/config.json Normal file
View file

@ -0,0 +1,67 @@
{
"init": {
"allowErrors": false
},
"dest": "dist",
"pkgVersion": "1.6.0",
"pages": [
"index.ejs",
"faq.ejs",
"tools.ejs"
],
"max_upload_size": 128,
"expireTime": "48H",
"siteName": "Uguu",
"subTitle": "wahooo",
"siteUrl": "https://domain.com",
"abuseContact": "abuse@example.com",
"infoContact": "info@example.com",
"ServerCountryLocation": "Sweden",
"SiteMetaInfo": "SITENAME is a temporary file hosting service, upload files up to 128MiB for 24 hours.",
"ToolsDesc": "The following tools might need editing to work on this clone of Uguu, usually editing the URL works.",
"donationBanner": false,
"paypalUrl": "",
"bitcoinAddress": "",
"flattrUrl": "",
"kofiUrl": "",
"malwareBanner": false,
"DB_MODE": "sqlite",
"DB_PATH": "/var/www/db/uguu.sq3",
"DB_USER": "NULL",
"DB_PASS": "NULL",
"LOG_IP": false,
"ANTI_DUPE": false,
"BLACKLIST_DB": true,
"FILTER_MODE": true,
"RATE_LIMIT": false,
"FILES_ROOT": "/var/www/files/",
"FILES_RETRIES": 15,
"FILES_URL": "https://files.domain.com",
"NAME_LENGTH": 8,
"ID_CHARSET": "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ",
"BLOCKED_EXTENSIONS": [
"exe",
"scr",
"com",
"vbs",
"bat",
"cmd",
"htm",
"html",
"jar",
"msi",
"apk",
"phtml",
"svg"
],
"BLOCKED_MIME": [
"application/msword",
"text/html",
"application/x-dosexec",
"application/java",
"application/java-archive",
"application/x-executable",
"application/x-mach-binary",
"image/svg+xml"
]
}

400
src/static/css/uguu.css Normal file
View file

@ -0,0 +1,400 @@
/**
* Copyright (c) 2011, 2012, 2013 Twitter, Inc.
* Copyright (c) 2013, 2014 Peter Lejeck <peter.lejeck@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* USE BORDER BOX
*/
*,
*:before,
*:after {
box-sizing: border-box;
}
/**
* PAGE LAYOUT
*/
body {
background-attachment: fixed, fixed;
background-color: #F7F7F7;
background-image: url('grill.php'), url('img/bg.png');
background-position: 85% 100%, top left;
background-repeat: no-repeat, repeat;
color: #333;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
height: 100%;
line-height: 20px;
margin: 0;
padding-top: 20px;
padding-bottom: 40px;
}
.container {
margin: 0 auto;
max-width: 700px;
}
/**
* ELEMENTS
*/
/* paragraphs */
p {
margin: 0 0 10px;
}
/* images */
input[type=image], img {
vertical-align: middle;
}
/* links */
a {
color: #0078B4;
text-decoration: none;
transition: color 0.25s;
}
a:hover,
a:focus,
a:active {
color: #005580;
}
a:focus {
outline: thin dotted #333;
}
/**
* JUMBOTRON
*/
.jumbotron {
margin: 60px 0;
text-align: center;
transition: width 0.5s, height 0.5s, margin 0.5s, padding 0.5s;
}
.jumbotron h1 {
color: inherit;
font-family: inherit;
font-size: 72px;
font-weight: bold;
line-height: 1;
margin: 10px 0;
cursor: default;
text-rendering: optimizelegibility;
}
.jumbotron .lead {
font-size: 21px;
font-weight: 200;
line-height: 30px;
margin-bottom: 20px;
transition: font-size 0.5s;
}
.jumbotron .btn {
background: rgba(202, 230, 190, 0.75);
border: 1px solid #B7D1A0;
border-radius: 4px;
color: #468847;
cursor: pointer;
display: inline-block;
font-size: 24px;
padding: 28px 48px;
text-shadow: 0 1px rgba(255, 255, 255, 0.5);
transition: background-color 0.25s, width 0.5s, height 0.5s;
}
.jumbotron .btn:hover,
.jumbotron .btn:active,
.jumbotron .btn:focus,
.jumbotron .btn.drop {
background-color: rgb(188, 228, 170);
text-decoration: none;
}
/**
* BOXES
*/
.alert {
background-color: #FCF8E3;
border: 1px solid #FBEED5;
border-radius: 4px;
margin-bottom: 20px;
padding: 8px 14px;
text-shadow: 0px 1px rgba(255, 255, 255, 0.5);
transition: width 0.5s, margin 0.5s, padding 0.5s, background-color 0.5s;
}
.alert-error {
background-color: #F2DEDE;
border-color: #EED3D7;
color: #AA4342;
}
.alert-info {
background-color: #D9EDF7;
border-color: #BCE8F1;
color: #167196;
}
/**
* DONATION BUTTONS
*/
span.donate-btns {
display: block;
text-align: center;
margin: 11px 0 3px;
}
a.donate-btn {
height: 26px;
display: inline-block;
margin: 2px 5px;
background: hsl(0, 0%, 95%);
line-height: 16px;
padding: 3px 8px 3px 24px;
border-radius: 3px;
color: hsl(0, 0%, 25%);
border: 1px solid hsl(0, 0%, 85%);
transition: all .2s;
}
a.donate-btn:hover {
color: #000;
border: 1px solid hsl(0, 0%, 70%);
background-color: hsl(0, 0%, 80%);
}
.icon {
display: block;
height: 16px;
width: 16px;
float: left;
margin-left: -20px;
margin-top: 1px;
}
.icon-paypal {
background-image: url('img/paypal.png');
}
.icon-bitcoin {
background-image: url('img/bitcoin.png');
}
.icon-flattr {
background-image: url('img/flattr.png');
}
.icon-kofi {
background-image: url('img/kofi.png');
}
/**
* NAVIGATION LINKS
*/
nav > ul,
nav a {
color: #33799B;
list-style: none;
margin: 0;
padding: 0;
text-align: center;
}
nav > ul > li {
display: inline-block;
margin: 0;
padding: 0;
cursor: default;
}
nav > ul > li:after {
content: "|";
margin: 0 8px;
opacity: 0.3;
}
nav > ul > li:last-child:after {
content: "";
margin: 0;
}
/**
* UPLOAD FILE LIST
*/
#upload-filelist {
list-style-type: none;
margin: 20px 50px;
padding: 0;
text-align: left;
}
.error#upload-filelist {
color: #891A18;
}
button.upload-clipboard-btn {
margin-left: 5px;
height: 32px;
}
.error#upload-filelist .progress-percent {
color: #B94A48;
}
.error#upload-filelist .file-progress {
display: none;
}
#upload-filelist > li {
margin-top: 5px;
overflow: hidden;
}
#upload-filelist > li.total {
border-top: 1px solid rgba(0, 0, 0, 0.05);
font-weight: bold;
padding-top: 5px;
}
.file-name {
float: left;
overflow: hidden;
max-width: 70%;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-progress,
.file-url {
display: inline-block;
float: right;
font-size: 0.9em;
margin-left: 8px;
vertical-align: middle;
}
.file-url a {
color: #5C5C5C;
}
.file-url a:hover {
color: #1C1C1C;
}
.progress-percent {
float: right;
}
progress[value] {
/* Reset the default appearance */
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: none;
}
progress[value]::-webkit-progress-bar {
background-color: #eee;
border-radius: 2px;
box-shadow: 0 2px 5px rgba(0,0,0,0.25) inset;
}
/* completed rows */
.completed .file-progress,
.completed .progress-percent {
display: none;
}
.completed .file-url {
display: block;
}
/**
* PROGRESS BARS
*/
.progress-outer {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid white;
border-radius: 4px;
box-shadow: 0 0 0 1px black;
color: transparent;
display: inline-block;
font-size: 0;
float: right;
height: 8px;
margin: 6px 6px 0;
overflow: hidden;
vertical-align: middle;
width: 50px;
}
.progress-inner {
background-color: black;
height: 6px;
margin: 0;
width: 0;
}
/**
* MEDIA QUERIES
*/
@media only screen and (max-device-width: 320px), only screen and (max-width: 400px) {
body {
padding: 10px 0 0 0;
}
.jumbotron {
margin: 20px 0 30px;
}
.jumbotron .lead {
font-size: 18px;
}
.jumbotron .btn, .alert, #upload-filelist {
border-radius: 0;
border-width: 1px 0;
width: 100%;
margin-left: 0;
margin-right: 0;
padding-left: 20px;
padding-right: 20px;
}
#upload-filelist {
background-color: rgba(255, 255, 255, 0.75);
overflow: hidden;
}
#upload-filelist > li.file {
margin-top: 12px;
margin-bottom: 12px;
}
.file-progress {
width: 70%;
}
.file-name, .file-url {
width: 100%;
max-width: 100%;
}
.file-url a {
text-decoration: underline;
margin-left: 15px;
}
.file-url a:before {
content: "http://";
}
.alert {
font-size: 13px;
}
.alert-error {
background-color: rgba(248, 223, 223, 0.75);
}
nav {
background-color: rgba(255, 255, 255, 0.75);
border: #FFFFFF;
padding: 10px 0;
}
}
/*
* no js
*/
#upload-btn {
display: none;
}
.js #upload-input {
display: none;
}
.js input[type="submit"]{
display: none;
}
.js #upload-btn {
display: inline-block !important;
}

View file

@ -0,0 +1,26 @@
CREATE TABLE `files` (
`id` int(20) unsigned NOT NULL auto_increment,
`hash` char(40) DEFAULT NULL,
`originalname` varchar(255) default NULL,
`filename` varchar(30) default NULL,
`size` int(15) DEFAULT NULL,
`date` int(15) DEFAULT NULL,
`ip` char(15) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `accounts` (
`id` int(20) unsigned NOT NULL auto_increment,
`email` varchar(255) default NULL,
`pass` varchar(255) default NULL,
`level` int(15) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `blacklist` (
`id` int(20) unsigned NOT NULL auto_increment,
`hash` char(40) DEFAULT NULL,
`originalname` varchar(255) default NULL,
`time` int(15) DEFAULT NULL,
PRIMARY KEY (`id`)
);

View file

@ -0,0 +1,31 @@
PRAGMA synchronous = OFF;
PRAGMA journal_mode = MEMORY;
BEGIN TRANSACTION;
CREATE TABLE `files` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT
, `hash` char(40) default NULL
, `originalname` varchar(255) default NULL
, `filename` varchar(30) default NULL
, `size` integer default NULL
, `date` integer default NULL
, `ip` char(15) default NULL
);
CREATE TABLE `accounts` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT
, `email` varchar(255) default NULL
, `pass` varchar(255) default NULL
, `level` integer default NULL
);
CREATE TABLE `blacklist` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT
, `hash` char(40) default NULL
, `originalname` varchar(255) default NULL
, `time` integer default NULL
);
CREATE TABLE `ratelimit` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT
, `iphash` char(40) default NULL
, `time` integer default NULL
, `files` integer default NULL
);
END TRANSACTION;

BIN
src/static/img/bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
src/static/img/bitcoin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 945 B

BIN
src/static/img/donate.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
src/static/img/flattr.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 902 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

BIN
src/static/img/grills/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
src/static/img/grills/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
src/static/img/grills/4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
src/static/img/grills/5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
src/static/img/grills/6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
src/static/img/grills/7.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
src/static/img/grills/8.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

BIN
src/static/img/grills/9.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
src/static/img/kofi.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1 KiB

BIN
src/static/img/paypal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 553 B

286
src/static/js/uguu.js Normal file
View file

@ -0,0 +1,286 @@
/*
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nekunekus) <neku@pomf.se> <github.com/nokonoko>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
document.addEventListener('DOMContentLoaded', function () {
/**
* Sets up the elements inside file upload rows.
*
* @param {File} file
* @return {HTMLLIElement} row
*/
function addRow(file)
{
const row = document.createElement('li');
const name = document.createElement('span');
name.textContent = file.name;
name.className = 'file-name';
const progressIndicator = document.createElement('span');
progressIndicator.className = 'progress-percent';
progressIndicator.textContent = '0%';
const progressBar = document.createElement('progress');
progressBar.className = 'file-progress';
progressBar.setAttribute('max', '100');
progressBar.setAttribute('value', '0');
row.appendChild(name);
row.appendChild(progressBar);
row.appendChild(progressIndicator);
document.getElementById('upload-filelist').appendChild(row);
return row;
}
/**
* Updates the page while the file is being uploaded.
*
* @param {ProgressEvent} evt
*/
function handleUploadProgress(evt)
{
let xhr = evt.target;
let bar = xhr.bar;
let percentIndicator = xhr.percent;
/* If we have amounts of work done/left that we can calculate with
(which, unless we're uploading dynamically resizing data, is always), calculate the percentage. */
if (evt.lengthComputable) {
let progressPercent = Math.floor((evt.loaded / evt.total) * 100);
bar.setAttribute('value', progressPercent);
percentIndicator.textContent = progressPercent + '%';
}
}
/**
* Complete the uploading process by checking the response status and, if the
* upload was successful, writing the URL(s) and creating the copy element(s)
* for the files.
*
* @param {ProgressEvent} evt
*/
function handleUploadComplete(evt)
{
let xhr = evt.target;
let bar = xhr.bar;
let row = xhr.row;
let percentIndicator = xhr.percent;
percentIndicator.style.visibility = 'hidden';
bar.style.visibility = 'hidden';
row.removeChild(bar);
row.removeChild(percentIndicator);
let respStatus = xhr.status;
let url = document.createElement('span');
url.className = 'file-url';
row.appendChild(url);
let link = document.createElement('a');
if (respStatus === 200) {
let response = JSON.parse(xhr.responseText);
if (response.success) {
link.textContent = response.files[0].url.replace(/.*?:\/\//g, '');
link.href = response.files[0].url;
url.appendChild(link);
const copy = document.createElement('button');
copy.className = 'upload-clipboard-btn';
const glyph = document.createElement('img');
glyph.src = 'img/glyphicons-512-copy.png';
copy.appendChild(glyph);
url.appendChild(copy);
copy.addEventListener("click", function () {
/* Why create an element? The text needs to be on screen to be
selected and thus copied. The only text we have on-screen is the link
without the http[s]:// part. So, this creates an element with the
full link for a moment and then deletes it.
See the "Complex Example: Copy to clipboard without displaying
input" section at: https://stackoverflow.com/a/30810322 */
const element = document.createElement('a');
element.textContent = response.files[0].url;
link.appendChild(element);
let range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("copy");
link.removeChild(element);
});
} else {
bar.innerHTML = 'Error: ' + response.description;
}
} else if (respStatus === 413) {
link.textContent = 'File too big!';
url.appendChild(link);
} else {
let response = JSON.parse(xhr.responseText);
link.textContent = response.description;
url.appendChild(link);
}
}
/**
* Updates the page while the file is being uploaded.
*
* @param {File} file
* @param {HTMLLIElement} row
*/
function uploadFile(file, row)
{
let bar = row.querySelector('.file-progress');
let percentIndicator = row.querySelector('.progress-percent');
let xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr['row'] = row;
xhr['bar'] = bar;
xhr['percent'] = percentIndicator;
xhr.upload['bar'] = bar;
xhr.upload['percent'] = percentIndicator;
xhr.addEventListener('load', handleUploadComplete, false);
xhr.upload.onprogress = handleUploadProgress;
let form = new FormData();
form.append('files[]', file);
xhr.send(form);
}
/**
* Prevents the browser for allowing the normal actions associated with an event.
* This is used by event handlers to allow custom functionality without
* having to worry about the other consequences of that action.
*
* @param {Event} evt
*/
function stopDefaultEvent(evt)
{
evt.stopPropagation();
evt.preventDefault();
}
/**
* Adds 1 to the state and changes the text.
*
* @param {Object} state
* @param {HTMLButtonElement} element
* @param {DragEvent} evt
*/
function handleDrag(state, element, evt)
{
stopDefaultEvent(evt);
if (state.dragCount === 1) {
element.textContent = 'Drop it here~';
}
state.dragCount += 1;
}
/**
* Subtracts 1 from the state and changes the text back.
*
* @param {Object} state
* @param {HTMLButtonElement} element
* @param {DragEvent} evt
*/
function handleDragAway(state, element, evt)
{
stopDefaultEvent(evt);
state.dragCount -= 1;
if (state.dragCount === 0) {
element.textContent = 'Select or drop file(s)';
}
}
/**
* Prepares files for uploading after being added via drag-drop.
*
* @param {Object} state
* @param {HTMLButtonElement} element
* @param {DragEvent} evt
*/
function handleDragDrop(state, element, evt)
{
stopDefaultEvent(evt);
handleDragAway(state, element, evt);
let len = evt.dataTransfer.files.length;
for (let i = 0; i < len; i++) {
let file = evt.dataTransfer.files[i];
let row = addRow(file);
uploadFile(file, row);
}
}
/**
* Prepares the files to be uploaded when they're added to the <input> element.
*
* @param {InputEvent} evt
*/
function uploadFiles(evt)
{
let len = evt.target.files.length;
// For each file, make a row, and upload the file.
for (let i = 0; i < len; i++) {
let file = evt.target.files[i];
let row = addRow(file);
uploadFile(file, row);
}
}
/**
* Opens up a "Select files.." dialog window to allow users to select files to upload.
*
* @param {HTMLInputElement} target
* @param {InputEvent} evt
*/
function selectFiles(target, evt)
{
stopDefaultEvent(evt);
target.click();
}
/* Handles the pasting function */
window.addEventListener("paste", e => {
let len = e.clipboardData.files.length;
for (let i = 0; i < len; i++) {
let file = e.clipboardData.files[i];
let row = addRow(file);
uploadFile(file, row);
}
});
/* Set up the event handlers for the <button>, <input> and the window itself
and also set the "js" class on selector "#upload-form", presumably to
allow custom styles for clients running javascript. */
let state = {dragCount: 0};
let uploadButton = document.getElementById('upload-btn');
window.addEventListener('dragenter', handleDrag.bind(this, state, uploadButton), false);
window.addEventListener('dragleave', handleDragAway.bind(this, state, uploadButton), false);
window.addEventListener('drop', handleDragAway.bind(this, state, uploadButton), false);
window.addEventListener('dragover', stopDefaultEvent, false);
let uploadInput = document.getElementById('upload-input');
uploadInput.addEventListener('change', uploadFiles);
uploadButton.addEventListener('click', selectFiles.bind(this, uploadInput));
uploadButton.addEventListener('drop', handleDragDrop.bind(this, state, uploadButton), false);
document.getElementById('upload-form').classList.add('js');
});

26
src/static/php/grill.php Normal file
View file

@ -0,0 +1,26 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use Pomf\Uguu\GrillLoader;
new GrillLoader();

33
src/static/php/upload.php Normal file
View file

@ -0,0 +1,33 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
error_reporting(0);
require_once __DIR__ . '/../vendor/autoload.php';
use Pomf\Uguu\UploadGateway;
$Upload = new UploadGateway();
try {
$Upload->handleFile($_GET['output'], $_FILES['files']);
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}

View file

@ -0,0 +1 @@
sqlite3 /path/to/db/uguu.sq3 "DELETE FROM files WHERE date <= strftime('%s', datetime('now', '-1 day'));"

View file

@ -0,0 +1,2 @@
#! /bin/sh
find /path/to/files/ -mmin +1440 -exec rm -f {} \;

64
src/templates/faq.ejs Normal file
View file

@ -0,0 +1,64 @@
<%- include('./src/templates/partials/header.ejs'); -%>
<div class="container">
<article>
<div class="jumbotron">
<h1>
<abbr title="Frequently asked questions">FAQ</abbr>
</h1>
</div>
<div class="alert alert-info">
<h2>What is <%= siteName %>?</h2>
<p><%= siteName %> is a simple to use free file hosting service where files get
deleted after <%= expireTime %>. It lets you share your photos, documents, music, videos and more with
others online.</p>
<h2>What files are allowed?</h2>
<p>Any kind of file is allowed, as long as the file is legal in <%= ServerCountryLocation %> and you have the legal
right to publish the file on our service.</p>
<p>As an exception to this policy to prevent abuse, we do not allow malware on our service. Any malware that
could be used to infect other computers may be removed from our service at our discretion.</p>
<h2>Do you keep logs of uploaded files?</h2>
<% if (LOG_IP) { %>
<p>A database of the current active files are kept which includes the name, hash and IP of the file and time of upload,
this data is deleted when the file expires.</p>
<% } else { %>
<p>A database of the current active files are kept which includes the name and hash of the file and time of upload,
this data is deleted when the file expires.</p>
<% } %>
<p>Downloads and visits are not tracked or logged in respect for your privacy.</p>
<h2>Can you remove my copyrighted file?</h2>
<p>
Please submit your copyright takedown notice to
<a href="mailto:<%= abuseContact %>"><%= abuseContact %></a>
. We will
handle your notice within <%= expireTime %> and disable access to the infringing file after receiving a notice
compliant with the Copyright Act.
</p>
<h2>Can you remove files that are defaming me or otherwise infringing my non-copyright rights?</h2>
<p>
<%= siteName %> respects takedowns for other files when accompanied with a certified <%= ServerCountryLocation %> court order. If
you are unable to obtain the order, a preliminary injuction or court order is typically also sufficient.
Please forward the notice to
<a href="mailto:<%= abuseContact %>"><%= abuseContact %></a>
.
</p>
<h2>Can you remove illegal files?</h2>
<p>Please contact the appropriate law enforcement agency if you notice illegal files hosted on <%= siteName %>. We
have not been trained or qualified to investigate and fight crimes and enforce the law, so it's not
appropriate to send accusations of illegal activity to us.</p>
<p>
You must contact the appropriate law enforcement office. They may then contact us if appropriate.
If you are an law enforcement official and you need our assistance, please contact
<a href="mailto:<%= abuseContact %>"><%= abuseContact %></a>
. If you are a law enforcement official from another
country, we may voluntarily cooperate if the crime you are investigating would also be illegal in
<%= ServerCountryLocation %>.
</p>
<h2>I have a question...</h2>
Send an email to
<a href="mailto:<%= infoContact %>"><%= infoContact %></a>
.
</div>
</article>
<%- include('./src/templates/partials/footer.ejs'); -%>

15
src/templates/index.ejs Normal file
View file

@ -0,0 +1,15 @@
<%- include('./src/templates/partials/header.ejs'); -%>
<div class="container">
<div class="jumbotron">
<%- include('./src/templates/partials/lead.ejs'); -%>
<%- include('./src/templates/partials/upload_form.ejs'); -%>
</div>
<% if (malwareBanner) { %>
<%- include('./src/templates/partials/malware_banner.ejs'); -%>
<% } %>
<% if (donationBanner) { %>
<%- include('./src/templates/partials/donation_banner.ejs'); -%>
<% } %>
<%- include('./src/templates/partials/footer.ejs'); -%>

View file

@ -0,0 +1,35 @@
<p class="alert alert-info">
<strong><%= siteName %> is free to use, but our hosting costs are not</strong>
&mdash; donations are what keep <%= siteName %> alive, free from ads and fast.
<span class="donate-btns">
<% if (bitcoinAddress) { %>
<a class="donate-btn donate-bitcoin" href="bitcoin:<%= bitcoinAddress %>?label=<%= siteName %>&amp;message=Hosting%20Costs" target="_BLANK">
<span class="icon icon-bitcoin"></span>
Bitcoin
</a>
<% } %>
<% if (paypalUrl) { %>
<a class="donate-btn donate-paypal" href="<%= paypalUrl %>" target="_BLANK">
<span class="icon icon-paypal"></span>
PayPal
</a>
<% } %>
<% if (flattrUrl) { %>
<a class="donate-btn donate-flattr" href="<%= flattrUrl %>" target="_BLANK">
<span class="icon icon-flattr"></span>
Flattr
</a>
<% } %>
<% if (kofiUrl) { %>
<a class="donate-btn donate-kofi" href="<%= kofiUrl %>" target="_BLANK">
<span class="icon icon-kofi"></span>
Ko-Fi
</a>
<% } %>
</span>
</p>

View file

@ -0,0 +1,4 @@
<%- include('./src/templates/partials/nav.ejs'); -%>
</div>
</body>
</html>

View file

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="Uguu <%= pkgVersion %>">
<meta name="description" content="<%= SiteMetaInfo %>">
<title><%= siteName %> &middot; <%= subTitle %></title>
<link rel="icon" type="image/png" sizes="32x32" href="/img/favicon-32x32.png">
<link rel="stylesheet" href="uguu.min.css">
<script src="uguu.min.js"></script>
</head>
<body>

View file

@ -0,0 +1,7 @@
<h1><%= siteName %>~</h1>
<p class="lead">
Max upload size is <%= max_upload_size %>&nbsp;MiB & files expire after <%= expireTime %>, read the
<a href="faq.html">
<abbr title="Frequently asked questions">FAQ</abbr>
</a>
</p>

View file

@ -0,0 +1,4 @@
<p class="alert alert-error">
<strong>Malware is not allowed</strong>
&mdash; files identified as malware will be removed without further notice.
</p>

View file

@ -0,0 +1,13 @@
<nav>
<ul>
<li>
<a href="/"><%= siteName %></a>
</li>
<li>
<a href="tools.html">Tools</a>
</li>
<li>
<a href="https://github.com/nokonoko/uguu">Github</a>
</li>
</ul>
</nav>

View file

@ -0,0 +1,6 @@
<form id="upload-form" enctype="multipart/form-data" method="post" action="upload.php?output=html">
<button id="upload-btn" class="btn" type="button">Drop or paste file(s)</button>
<input type="file" id="upload-input" name="files[]" multiple data-max-size="<%= max_upload_size %>MiB">
<input type="submit" value="Submit">
</form>
<ul id="upload-filelist"></ul>

59
src/templates/tools.ejs Normal file
View file

@ -0,0 +1,59 @@
<%- include('./src/templates/partials/header.ejs'); -%>
<div class="container">
<div class="jumbotron">
<h1><%= siteName %> Tools</h1>
</div>
<div class="alert alert-info">
<section>
<h3>
To upload using curl or make a tool you can post using:
<br>
curl -i -F files[]=@yourfile.jpeg <%= siteUrl %>/upload.php (JSON Response)
</h3>
<p>To upload using curl or make a tool you can post using: curl -i -F files[]=@yourfile.jpeg <%= siteUrl %>/upload.php (JSON Response)</p>
<section>
<h2>ShareX</h2>
<dl>
<dt>Download</dt>
<dd>
<a href="https://github.com/ShareX/ShareX">https://github.com/ShareX/ShareX</a>
</dd>
</dl>
</section>
<h2>uguuecho</h2>
<dl>
<dt>Download</dt>
<dd>
<a href="https://git.teknik.io/nekunekus/uguucho">https://git.teknik.io/nekunekus/uguucho</a>
</dd>
</dl>
</section>
<h2>pomfload</h2>
<dl>
<dt>Download</dt>
<dd>
<a href="https://github.com/ewhal/pomfload">https://github.com/ewhal/pomfload</a>
</dd>
</dl>
<section>
<h2>Pomfshare</h2>
<dl>
<dt>Download</dt>
<dd>
<a href="https://github.com/Nyubis/Pomfshare">https://github.com/Nyubis/Pomfshare</a>
</dd>
</dl>
</section>
<section>
<h2>Pomf Rehost</h2>
<dl>
<dt>Download</dt>
<dd>
<a href="https://git.fuwafuwa.moe/lesderid/pomf-rehost">
https://git.fuwafuwa.moe/lesderid/pomf-rehost
</a>
</dd>
</dl>
</section>
</div>
<%- include('./src/templates/partials/footer.ejs'); -%>