commit c5f39ea2cd7cf02246705ea8872d3b350526165c Author: Freya Murphy Date: Fri May 24 09:05:42 2024 -0400 initial diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b8ed77b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +.git +.gitignore +deployments +target diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0fc50fe --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +src/public/css/*.css +data diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2d58298 --- /dev/null +++ b/LICENSE @@ -0,0 +1,428 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c5ac2a4 --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ + +MIXINS = $(shell find src/scss -name "_*.scss") +SCSS = $(shell find src/scss -name "*.scss" -not -name "_*") +CSS = $(patsubst src/scss/%.scss,src/public/css/%.css,$(SCSS)) + +.PHONY: all css dir clean + +css: dir $(CSS) + +dir: + @mkdir -p src/public/css + +clean: + @printf "\033[31m RM \033[0m%s\n" src/public/css + @rm -f src/public/css/*.css + +all: clean css + +$(CSS): src/public/css/%.css : src/scss/%.scss $(MIXINS) + @printf "\033[33m SCSS \033[0m%s\n" $< + @sassc --style compressed $< $@ + diff --git a/build/init/Dockerfile b/build/init/Dockerfile new file mode 100644 index 0000000..98eb285 --- /dev/null +++ b/build/init/Dockerfile @@ -0,0 +1,21 @@ +FROM alpine:3.19 + +# install packages +RUN apk add --no-cache postgresql16-client tini shadow +RUN rm -fr /var/cache/apk/* + +# setup main user +RUN adduser -D init +RUN groupmod --gid 1000 init +RUN usermod --uid 1000 init + +# copy scripts +COPY ./init /usr/local/bin/init + +# remove build packages +RUN apk del shadow + +# do the +USER init +ENTRYPOINT ["/sbin/tini", "--"] +CMD ["/usr/local/bin/init"] diff --git a/build/init/init b/build/init/init new file mode 100755 index 0000000..a889a8b --- /dev/null +++ b/build/init/init @@ -0,0 +1,108 @@ +#!/bin/sh + +errors=$(mktemp) + +step() { + printf '\x1b[34;1m>> %s\x1b[0m\n' "$*" +} + +error() { + { + printf '\x1b[31;1merror: \x1b[0m%s\n' "$*"; + grep -v 'current transaction is aborted' < "$errors"; + printf "\x1b[31m;1error: \x1b[0mAborting migrations, fix file(s) then restart process."; + } 1>&2; +} + +try() { + "$@" 2> "$errors"; + count=$(grep -c 'ERROR' < "$errors") + if [ "$count" -eq 0 ]; then + return 0; + else + return 1; + fi +} + +export PGPASSWORD="$POSTGRES_PASSWORD" + +psql() { + /usr/bin/psql \ + -h db \ + -p 5432 \ + -d "$POSTGRES_DB" \ + -U "$POSTGRES_USER" \ + "$@" +} + +pg_isready() { + /usr/bin/pg_isready \ + -h db \ + -p 5432 \ + -d "$POSTGRES_DB" \ + -U "$POSTGRES_USER" +} + +curr_revision() { + psql -qtAX -f /db/rev.sql; +} + +wait_until_ready() { + step 'Checking if the database is ready...'; + while true; do + pg_isready; + code=$?; + if [ $code -eq 0 ]; then + break; + fi + sleep 3; + done +} + +run_migrations() { + i="$1" + while true; do + name=$(printf "%04d" "$i"); + file="/db/migrations/$name.sql" + if [ -f "$file" ]; then + if try psql -f "$file"; then + i=$((i+1)); + continue; + else + error "An error occoured during a migration (rev $name)" + return 1; + fi + else + return 0; + fi + done +} + +init () { + # reomve ready status + # so php ignores requests + rm -f /status/ready + + step 'Waiting for database'; + # make sure the database is running + # before we run any requests + wait_until_ready; + step 'Database ready'; + + step 'Peforming migrations'; + # get the current revision + REV=$(curr_revision); + step "Database at revision: $REV" + # run each migration that is + # higher than our current revision + if ! run_migrations "$REV"; then + return 1; + fi + + step 'Database is initialized' + # database is ready + touch /status/ready +} + +init +rm "$errors" diff --git a/build/nginx/Dockerfile b/build/nginx/Dockerfile new file mode 100644 index 0000000..6aa4e00 --- /dev/null +++ b/build/nginx/Dockerfile @@ -0,0 +1,21 @@ +FROM alpine:3.19 + +# install packages +RUN apk add --no-cache nginx shadow tini +RUN rm -fr /var/cache/apk/* + +# update nginx user +RUN groupmod --gid 1000 nginx +RUN usermod --uid 1000 nginx + +# remove build packages +RUN apk del shadow + +# make log syms +RUN ln -sf /dev/stdout /var/log/nginx/access.log && \ + ln -sf /dev/stderr /var/log/nginx/error.log + +# do the +USER nginx +ENTRYPOINT ["/sbin/tini", "--"] +CMD ["/usr/sbin/nginx", "-c", "/etc/nginx/nginx.conf"] diff --git a/build/php/Dockerfile b/build/php/Dockerfile new file mode 100644 index 0000000..5f4bdd5 --- /dev/null +++ b/build/php/Dockerfile @@ -0,0 +1,17 @@ +FROM php:fpm-alpine + +# install packages +RUN apk add --no-cache postgresql-dev runuser shadow +RUN rm -fr /var/cache/apk/* + +# update php user +RUN groupmod --gid 1000 www-data +RUN usermod --uid 1000 www-data + +# install php packages +RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql +RUN docker-php-ext-install pdo pdo_pgsql + +# remove build packages +RUN apk del shadow +USER www-data diff --git a/build/postgres/Dockerfile b/build/postgres/Dockerfile new file mode 100644 index 0000000..32bca6e --- /dev/null +++ b/build/postgres/Dockerfile @@ -0,0 +1,21 @@ +FROM postgres:16-alpine + +# install packages +RUN apk add --no-cache make git shadow +RUN rm -fr /var/cache/apk/* + +# install pgjwt +RUN git clone https://github.com/michelp/pgjwt.git /tmp/pgjwt +WORKDIR /tmp/pgjwt +RUN make install + +# update postgres user +RUN groupmod --gid 1000 postgres +RUN usermod --uid 1000 postgres + +# remove build packages +RUN apk del make git shadow + +# fix workdir +WORKDIR / +USER postgres diff --git a/conf/nginx/nginx.conf b/conf/nginx/nginx.conf new file mode 100644 index 0000000..ae17eba --- /dev/null +++ b/conf/nginx/nginx.conf @@ -0,0 +1,50 @@ +worker_processes 4; +daemon off; +pid /tmp/nginx.pid; +error_log /var/log/nginx/error.log; + +events { + worker_connections 1024; +} + +http { + include mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 70; + server_tokens off; + client_max_body_size 2m; + + access_log /var/log/nginx/access.log; + + server { + listen 8080; + root /opt/website; + + gzip on; + gzip_vary on; + gzip_proxied any; + gzip_comp_level 6; + gzip_buffers 16 8k; + gzip_http_version 1.1; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml image/x-icon; + + location /favicon.ico { + add_header Cache-Control "public, max-age=31536000, immutable"; + root /opt/website/public/icons; + } + + location /public { + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + + location / { + add_header Content-Security-Policy "script-src 'none'; object-src 'none'; base-uri 'none'"; + root /opt/website/web; + include fastcgi_params; + fastcgi_pass php:9000; + fastcgi_param SCRIPT_FILENAME $document_root/index.php; + } + } +} diff --git a/conf/postgres/database.env b/conf/postgres/database.env new file mode 100644 index 0000000..4d4eeb0 --- /dev/null +++ b/conf/postgres/database.env @@ -0,0 +1,3 @@ +POSTGRES_USER=website +POSTGRES_PASSWORD=cannothackme +POSTGRES_DB=website diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a457272 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,43 @@ +services: + web: + build: ./build/nginx + restart: unless-stopped + ports: + - '80:8080' + volumes: + - ./src:/opt/website:ro + - ./conf/nginx/nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + - php + + php: + build: ./build/php + restart: unless-stopped + env_file: + - ./conf/postgres/database.env + volumes: + - ./src:/opt/website:ro + - ./data/status:/status:ro + depends_on: + - db + + db: + build: ./build/postgres + restart: unless-stopped + env_file: + - ./conf/postgres/database.env + environment: + - POSTGRES_INITDB_ARGS=--encoding=UTF-8 --lc-collate=C --lc-ctype=C + volumes: + - './data/schemas:/var/lib/postgresql/data' + - ./src/db:/db:ro + + init: + build: ./build/init + env_file: + - ./conf/postgres/database.env + volumes: + - ./src/db:/db:ro + - ./data/status:/status + depends_on: + - db diff --git a/src/assets/blog/2023-02-23.md b/src/assets/blog/2023-02-23.md new file mode 100644 index 0000000..89b87b5 --- /dev/null +++ b/src/assets/blog/2023-02-23.md @@ -0,0 +1,18 @@ +--- +name: Vaultwarden +date: 2023-02-23T18:00:00.000-04:00 +desc: Hosting your own password manager is cool +--- + +### LastPass +Hopefully we all know of the semi-recent LastPass breach, where a lot of customers had their encrypted vaults leaked. They were still encrypted, but your passwords were now possibly out there. My vault was also sadly leaked as well. Also, I don't know why I used LastPass in the first place, since I pretty much just used the same password over and over again anyways. + +### Other Options? +Well I could just keep using the same password over and over again, but we all know that is *really* not a good idea. Also that password has been in like 5 different breaches, so it was time I actually cared. + +I decided to self host my own password manager, [Vaultwarden](https://hub.docker.com/r/vaultwarden/server), an unofficial Bitwarden server written in Rust. I chose it because my Hetzner server only has 2GB of RAM and only 2 VCPUs, therefore I don't really have the resources to spare. And I also chose self host since It's really easy to setup, and I don't have to worry about breaches. + +### Here Is How Its Been +Vaultwarden only uses about 25MB of RAM for me, which is a really small amount. The server uses the Bitwarden API so I can use any of the very well built Bitwarden clients, and they sync together flawlessly. It also supports TOTP, therefore I no longer have to use Authy, a proprietary service, to manage my 2FA. Even in the rare chance that my server goes down, the clients store an encrypted version of the vault locally, so I will never loose my passwords. + +Overall, it was really easy to set up in docker, and everything has been smooth. So if you are looking at self hosting a password manager, look at Vaultwarden. diff --git a/src/assets/blog/2023-09-28.md b/src/assets/blog/2023-09-28.md new file mode 100644 index 0000000..b1e19fe --- /dev/null +++ b/src/assets/blog/2023-09-28.md @@ -0,0 +1,74 @@ +--- +name: IntraNet +date: 2023-09-28T10:00:00.000-04:00 +desc: Securing my network +--- + +### IntraNet + +*So what is even a IntraNet?* Well, it's an inernal network of computers contained from the outside network. +They can be used to host services, software, applications, and more, but not give access to the outside world. If you can connect +to a service from any public ip, we say thats on the public internet. Even if the application is secured, and it's open to the public going.... + +> Hey i exist!!!! + +...anyone can access it. We all have herd of the times when companies internal services were accidentally made publically available to the outside web, and +then how they end up getting pwned (im looking at you hospitals). + +> But why would I want it? + +Well the main reason is it seemed fun. I like to do new things at times, and It seemed like a cool project. Also I want very +keen on keeping many of my internal services public. Yes they were secured by single sign, and ip whitelisted, but I really didnt feel like anyone +should be able to send any http request to my nextcloud instance, or any other service im running. Also whitelisting IPs was very annoying. +Ive already seen what can happen to mail servers (foreshadowing), so Id like to keep as much stuff internal that I possibly can. + +### Network Architecture and Design + +> Well how does it work?! + +Well its fairly simple. I run a dual DNS setup, my own CA, and wireguard to add the ability to vpn into the network. +First, I run Bind on my network which runs as my internal DNS server. This reroutes any domain name under "in.freya.cat" to the device on the network that is hosting +that service. For example "cloud.in.freya.cat" is routed to my server that is running my internal Nextcloud instance. Now If I was right, you might of just tried to access +my nextcloud, but instead you should of gotten something that says ACCESS DENIED! + +You have been blocked! Haha. This is where the 2nd DNS comes in. Since my domain is registered through cloudflare, any DNS request gets routed to my Hetzner VPS which acts as +a public sinkhole for my entire internal network. If you try accessing any of my services, you cant. Instead of getting the right ip, you get hetzner. And even if you knew the ip, +it wouldn't matter since they are LAN ips and arent even port forwarded outside my network. This is also why I use wireguard, as It allows me to vpn into my network and access my +services even while im away from home. + +### Network Routing + +Ok so thats cool and all but how do you even route your traffic? + +At first, I just created IPs using the wireguard configs, and then had /etc/local.d start scripts that would `wg-quick up` on computer startup. This worked, but it made routing traffic +really hard. It was fine when I only had two servers, my VPS and my house, but as soon as I started to try to add more servers, everything fell apart. This is because in the Allowed IPs +section of a config, you have to set what IPs are routed though that wireguard interface. So if one sever adds another server I can talk too, every other server has to manually update what +they route to that server. For eaxample if Server A was talking to only Server B, but Server B could talk to Server C, Server A would have to put that Server B gets all traffic for Server B and C. +So I needed a solution to automatically generate route, beacuse doing it manually wasnt going to cut it anymore. + +### OSPF + +Ah, yes, the solution is OSPF. OSPF, or Open Shortest Path First, is a protocol designed for this very purpose. Its mostly seen in companies (like ISPs) that run their own ASN (autonomous system), +because they have thousands of servers that all need to be able to route traffic to eachother. So the goal was to still use wireguard to pass the traffic though, but instead to run a OSPF daemon +over those wireguard tunnels to route my traffic! The solution was a piece of software called bird. Bird can do more than OSPF, it can also route protocols such as BGP, but that is outside of the +scope for this blog post. If bird is setup of every server that was a main routing hub for my internal network, all I would have to do is say what wireguard interfaces to route ontop of. This is beacuse +bird can automatically detect the IPs that you controll on your network, meaning that once it has all the serveres it can talk to, it will automatically start asking the other servers what IPs they control, +and those servers will do the same. This them cascaces over the entire connection tree, peering IP routes to anywhere on the network to every server. Once that is all done, bird just creates a iptables route +and all is done! Woohoo!!! + +### Root CA? + +You might of notices I briefly mentioned that I run my own Certificate Authority, but you may be asking why? Who does that? For what reason would you need to? And I totally agree with +you. I'd rather not host it if I didn't need it, but I do have a reason. Since all my internal domains are routed to my hetzner, my internal network cant complete ACME challenges. Since +it cannot complete ACME challenges, Lets Encrypt wont give me a certificate for my domain. So I decided to run my own cerficiate authority. Now I don't do anything crazy, I just run step-ca +inside of docker. This is great because since I use Caddy for my reverse proxy, Caddy can auto request new certificates from StepCA, and everything is automated. The only thing I have to do +is install my root certificate on my devices, for which I have three. And now I have https on my internal network! + +### Overview + +Overall, this setup allows me to run many services I want to internally. I can run my plex server, nextcloud, photo hosting with immich, sso with authentik, irc, document hosting, +file syncing with syncthing, and still more to list. And with my setup, no one besides me and who I let on my network can even deam about accessing my services. This increases my +security, and really was just a ton of fun to figure out and setup. + +Though make sure to setup wireguard to not nat every network device or theoretically it will break dockers ip routing, and theoretically it will cause containers to see all ips as internal, and +theoretically services like mailcow, an email server, will not require authentication since its totally comming from mailcow, and theoretically your email server can become an open realy. Theoretically though. diff --git a/src/assets/blog/2023-11-03.md b/src/assets/blog/2023-11-03.md new file mode 100644 index 0000000..12df67f --- /dev/null +++ b/src/assets/blog/2023-11-03.md @@ -0,0 +1,28 @@ +--- +name: Mastodon +date: 2023-11-03T10:29:40.000-04:00 +desc: Joining the fediverse +--- + +### Mastodon + +Hello, small blog post today. + +I am prod to announce I have joined the fediverse!! +Well Im already on matrix, but this is like the first public instance open too. + +#### Experiences + +So as of writing this, I have only been hosting my own instance for 2 days now. It was a bit +annoying to setup (just a few docker containers and proxy shenanigans), but hey it works now! +The main gripe I currently have with activity pub so far is the lack of discovery and reading older events. + +Currently you can only search for things that you are directly federated with. So for example, my server is federated with `lgbt.tech`, so I can search for things on there. Also I cant see older posts. If I go to anyone I follow, I can only see posts since I started federating with them. Any older posts require me to go to their mastodon (or anything that supports activity pub) instance. + +A cool thing though that ive noticed is that activity pub allows federation outside mastodon. So far Ive only seen lemmy accounts, but I find that cool. + +#### Long way to go + +Overall, I think activity pub as a protocol has a long way to go. There are some things I wish where implemented, mainly things that matrix has. But overall its really cool, and Im going to continue to use it for the foreseeable future. + +Cheers! diff --git a/src/assets/profanity.txt b/src/assets/profanity.txt new file mode 100644 index 0000000..e9ccebe --- /dev/null +++ b/src/assets/profanity.txt @@ -0,0 +1,375 @@ +2g1c +2 girls 1 cup +acrotomophilia +alabama hot pocket +alaskan pipeline +anal +anilingus +anus +apeshit +arsehole +assmunch +auto erotic +autoerotic +babeland +baby batter +baby juice +ball gag +ball gravy +ball kicking +ball licking +ball sack +ball sucking +bangbros +bangbus +bareback +barely legal +barenaked +bastard +bastardo +bastinado +bdsm +beaner +beaners +beaver cleaver +beaver lips +beastiality +bestiality +big black +big breasts +big knockers +big tits +bimbos +birdlock +black cock +blonde action +blonde on blonde action +blowjob +blow job +blow your load +blue waffle +blumpkin +bollocks +bondage +boner +booty call +brown showers +brunette action +bukkake +bulldyke +bullet vibe +bullshit +bung hole +bunghole +busty +buttcheeks +butthole +camel toe +camgirl +camslut +camwhore +carpet muncher +carpetmuncher +chocolate rosebuds +cialis +circlejerk +cleveland steamer +clit +clitoris +clover clamps +clusterfuck +cock +cocks +coprolagnia +coprophilia +cornhole +creampie +cum +cumming +cumshot +cumshots +cunnilingus +cunt +darkie +date rape +daterape +deep throat +deepthroat +dendrophilia +dildo +dingleberry +dingleberries +dirty pillows +dirty sanchez +doggie style +doggiestyle +doggy style +doggystyle +dog style +dolcett +domination +dominatrix +dommes +donkey punch +double dong +double penetration +dp action +dry hump +dvda +eat my ass +ecchi +ejaculation +erotic +erotism +escort +eunuch +fag +faggot +fecal +felch +fellatio +feltch +female squirting +femdom +figging +fingerbang +fingering +fisting +foot fetish +footjob +frotting +fuck buttons +fucktards +fudge packer +fudgepacker +futanari +gangbang +gang bang +gay sex +genitals +giant cock +girl on +girl on top +girls gone wild +goatcx +goatse +god damn +gokkun +golden shower +goodpoop +goo girl +goregasm +grope +group sex +g-spot +guro +hand job +handjob +hard core +hardcore +hentai +homoerotic +honkey +hooker +horny +hot carl +hot chick +how to kill +how to murder +huge fat +humping +incest +intercourse +jack off +jail bait +jailbait +jelly donut +jerk off +jigaboo +jiggaboo +jiggerboo +jizz +juggs +kike +kinbaku +kinkster +kinky +knobbing +leather restraint +leather straight jacket +lemon party +livesex +lolita +lovemaking +make me come +male squirting +masturbate +masturbating +masturbation +menage a trois +milf +missionary position +mong +motherfucker +mound of venus +mr hands +muff diver +muffdiving +nambla +nawashi +negro +neonazi +nigga +nigger +nig nog +nimphomania +nipple +nipples +nsfw images +nude +nudity +nutten +nympho +nymphomania +octopussy +omorashi +one cup two girls +one guy one jar +orgasm +orgy +paedophile +paki +panties +panty +pedobear +pedophile +pegging +penis +phone sex +piece of shit +pikey +pissing +piss pig +pisspig +playboy +pleasure chest +pole smoker +ponyplay +poof +poon +poontang +punany +poop chute +poopchute +porn +porno +pornography +prince albert piercing +pthc +pubes +pussy +queaf +queef +quim +raghead +raging boner +rape +raping +rapist +rectum +reverse cowgirl +rimjob +rimming +rosy palm +rosy palm and her 5 sisters +rusty trombone +sadism +santorum +scat +schlong +scissoring +semen +sexcam +sexo +sexual +sexually +shaved beaver +shaved pussy +shemale +shibari +shitblimp +shota +shrimping +skeet +slanteye +slut +s&m +smut +snatch +snowballing +sodomize +sodomy +spastic +spic +splooge +splooge moose +spooge +spread legs +spunk +strap on +strapon +strappado +strip club +style doggy +suicide girls +sultry women +swastika +swinger +tainted love +taste my +tea bagging +threesome +throating +thumbzilla +tight white +tits +titties +titty +tongue in a +topless +tosser +towelhead +tranny +tribadism +tub girl +tubgirl +tushy +twat +twink +twinkie +two girls one cup +undressing +upskirt +urethra play +urophilia +vagina +venus mound +viagra +vibrator +violet wand +vorarephilia +voyeur +voyeurweb +voyuer +vulva +wank +wetback +wet dream +white power +whore +worldsex +wrapping men +wrinkled starfish +yellow showers +yiffy +zoophilia diff --git a/src/assets/projects/00-minecraft.md b/src/assets/projects/00-minecraft.md new file mode 100644 index 0000000..d377563 --- /dev/null +++ b/src/assets/projects/00-minecraft.md @@ -0,0 +1,7 @@ +--- +name: minecraft vulkan +repo: minecraftVulkan +--- + +Minecraft Vulkan is a Minecraft clone I wrote in C++, and rendered using the Vulkan API. +It is procedurally generated, and uses multi threading to offload the generating and meshing to separate threads. diff --git a/src/assets/projects/01-crab.md b/src/assets/projects/01-crab.md new file mode 100644 index 0000000..9774dfc --- /dev/null +++ b/src/assets/projects/01-crab.md @@ -0,0 +1,8 @@ +--- +name: crab +repo: crab +--- + +Crab, a.k.a Cool Rust Authentication Binary, is a privilege escalation program for Linux systems written in rust. +It allows users to temporarily gain root privileges for what they need, given they are allowed to in the crab conf file. +It authenticates the current user with the PAM api built into Linux. diff --git a/src/assets/projects/02-xssbook.md b/src/assets/projects/02-xssbook.md new file mode 100644 index 0000000..6585006 --- /dev/null +++ b/src/assets/projects/02-xssbook.md @@ -0,0 +1,9 @@ +--- +name: xssbook +repo: xssbook +--- + +xssbook is a website I created for xss scripting vulnerabilities. +It is a facebook clone, backend written in rust with axum, and the frontend made in html, css, and vanilla javascript. +The site work by failing to parse user input every step of the way, and renders it as direct html. +You can view my hosted version at [xssbook.com](https://xssbook.com). diff --git a/src/assets/projects/03-brainfucked.md b/src/assets/projects/03-brainfucked.md new file mode 100644 index 0000000..f45c157 --- /dev/null +++ b/src/assets/projects/03-brainfucked.md @@ -0,0 +1,10 @@ +--- +name: brainfucked +repo: brainfucked +--- + +brainfucked is a brainfuck dialect that makes you manage your memory manually! +The original interpreter gives you a tape of 30,000 cells, while i only give you +as much as a pointer takes up on your system: 4 or 8 depending if your on a 32bit or 64bit system. +You can than allocate a new tape and then use that! Also brainfucked is tuing complete proven by +this amzing [proof](/blog/writeup?name=proof.md) that my friend [trimill](https://trimill.xyz) made. diff --git a/src/assets/projects/04-wrapper.md b/src/assets/projects/04-wrapper.md new file mode 100644 index 0000000..22a6bd6 --- /dev/null +++ b/src/assets/projects/04-wrapper.md @@ -0,0 +1,8 @@ +--- +name: wrapper +repo: wrapper +--- + +wrapper is a simple and lightweight DNS server written in C. It supports custom user defined records in a config files, +and it also supports a few custom build records for fun! For example, there is a CMD record that runs a command on the +host system, and returns the result as a TXT record! Read more on the readme! diff --git a/src/assets/projects/05-wig.md b/src/assets/projects/05-wig.md new file mode 100644 index 0000000..5622bc0 --- /dev/null +++ b/src/assets/projects/05-wig.md @@ -0,0 +1,8 @@ +--- +name: wig +repo: wig +--- + + wig is a simple DNS client written in C. It supports all the important features as most DNS clients, + but displays its results in a simple and concise format without all the clutter. It gives you what + you want fast and simple. diff --git a/src/assets/projects/06-lazysphere.md b/src/assets/projects/06-lazysphere.md new file mode 100644 index 0000000..4a36ee6 --- /dev/null +++ b/src/assets/projects/06-lazysphere.md @@ -0,0 +1,8 @@ +--- +name: lazysphere +repo: lazysphere +--- + +lazysphere is a gnu coreutils/busybox clone, supporting commands such as su, +rm (the french), and also (but not exluding) yes. Its written in C +with no dependencies because they are bad. diff --git a/src/assets/projects/07-tuxman.md b/src/assets/projects/07-tuxman.md new file mode 100644 index 0000000..46d82f6 --- /dev/null +++ b/src/assets/projects/07-tuxman.md @@ -0,0 +1,9 @@ +--- +name: tuxman +repo: tuxman +--- + +tuxman is a recreation of the arcade multiplayer pacman battle game where pacman +have to avoid ghosts and each eachother to win! Its written in TypeScript (im sorry), +and fetures a full map editor with custom map support. It uses [rollback](https://git.tint.red/tint/rollback) +netcode, and you can play a hosted version at [freya.cat/pacbattle](https://freya.cat/pacbattle). diff --git a/src/assets/projects/08-nbtvis.md b/src/assets/projects/08-nbtvis.md new file mode 100644 index 0000000..31a361f --- /dev/null +++ b/src/assets/projects/08-nbtvis.md @@ -0,0 +1,7 @@ +--- +name: nbtvis +repo: nbtvis +--- + +nbtvis, a.k.a NBT visualizer, is a simple C program that can convert Minecraft Binary NBT, String NBT, +or JSON from one format from another. diff --git a/src/assets/projects/09-corn.md b/src/assets/projects/09-corn.md new file mode 100644 index 0000000..10f41de --- /dev/null +++ b/src/assets/projects/09-corn.md @@ -0,0 +1,7 @@ +--- +name: corn +repo: corn +--- + +corn is a x86_64 operating system micro kernel implemented in C. It uses the multiboot bootloader standard, and suports BIOS and UEFI boot. For memory managment, it +supportes full paging, along with a physical and virtual memory allocator, and page allocating on first write. ACPI, PCI, graphics, and debugger support also exist. diff --git a/src/assets/projects/10-matrix.md b/src/assets/projects/10-matrix.md new file mode 100644 index 0000000..fafe0fe --- /dev/null +++ b/src/assets/projects/10-matrix.md @@ -0,0 +1,6 @@ +--- +name: matrix +repo: matrix +--- + +matrix is a fully featured expression based bytecode vm programming language. Implemented in Rust, it has its own lexer, parser, compiler, and vm runtime environment. Alogn with the base tooling, there is a included standard library that contains standard math, string, file, and system operations to make the language able to do more than simple number crunching. Matrix also contains a built in Repl with error checking, simple completion, and syntax highlighting. diff --git a/src/assets/writeup/proof.md b/src/assets/writeup/proof.md new file mode 100644 index 0000000..1f5eeda --- /dev/null +++ b/src/assets/writeup/proof.md @@ -0,0 +1,55 @@ +--- +name: Brainfucked +desc: trimills turing completeness proof for brainfucked +--- + +### Turing-completeness proof for Brainfucked + +By producing an algorithm that can translate arbitrary Brainfuck programs into +Brainfucked, we prove that the latter must have computational class greater than +or equal to the former, thus proving that Brainfucked is Turing-complete. + +Proof that Brainfucked is not of a greater computational class than Brainfuck is +left as an exercise to the reader. + +Since Brainfucked tapes have a limited amount of memory, we will implement a +tape as a linked list. Each item in the linked list will be a tape of length +ten with the following structure: + +- The first cell contains the item's value +- The second cell is 1 if the next item has already been allocated and 0 otherwise +- The remaining 8 cells are the pointer to the next item + +The second byte is not strictly necessary, as we could just check whether the pointer +is null, however it makes the translation significantly easier. + +First, we prefix the output program with `++++++++++*(`. Since the original tape is +only 8 bytes wide, we need to make a new one with a size of 10. `+`, `-`, `[`, `]`, +`.`, and `,` all translate to themselves. + +`>` can be translated as `>-[>++++++++++*<+]+>(`. This will allocate the next tape +if it does not yet exist and then enter it. + +First, consider the case where next tape has not yet been allocated. We decrement the +allocation marker cell, which wraps around to 255, allowing us to enter the loop. We +then allocate the next tape and increment the allocation marker back to 0. After exiting +the loop, it is incremented again to 1, signalling that the next tape is now allocated. +We can then enter the newly allocated tape. If the tape was already allocated, the loop +will never be entered and the marker will remain 1. + +`<` can be translated as `)<<`. We exit the current tape and move back over to the data cell. + +This proof only uses a subset of Brainfucked consisting of the characters `+-<>[]()*,.`. +One of `+` or `-` can be trivially eliminated by replacing it with 255 copies of the other. +Additionally, `,` and `.` are not required for Turing-completeness, as input can be encoded into +the initial tape configuration and output can be read off the tape once the program halts. +I conjecture that no smaller subset of Brainfucked is Turing-complete. + +#### Example translation script (Lua) +```lua +src = io.read("*a") +src = src:gsub("%<", ")<<") +src = src:gsub("%>", ">-[>++++++++++*<+]+>(") +src = "++++++++++*(" .. src +io.write(src) +``` diff --git a/src/db/migrations/0000.sql b/src/db/migrations/0000.sql new file mode 100644 index 0000000..bc4b3b9 --- /dev/null +++ b/src/db/migrations/0000.sql @@ -0,0 +1,89 @@ +BEGIN TRANSACTION; +SET search_path = public; + +-- Migration Start + +CREATE SCHEMA sys; + +ALTER SCHEMA sys OWNER TO website; + +CREATE TABLE sys.database_info ( + name TEXT DEFAULT ''::text NOT NULL, + curr_revision INTEGER DEFAULT 0 NOT NULL +); + +ALTER TABLE ONLY sys.database_info + ADD CONSTRAINT database_info_pkey PRIMARY KEY (name); + +ALTER TABLE sys.database_info OWNER TO website; + +INSERT INTO sys.database_info + (name, curr_revision) VALUES (current_database(), 0); + +CREATE SCHEMA admin; + +ALTER SCHEMA admin OWNER TO website; + +CREATE SEQUENCE sys.request_log_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +CREATE TYPE admin.request_log_method_type AS ENUM ( + 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', + 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH' +); + +CREATE TABLE admin.request_log ( + id INTEGER DEFAULT nextval('sys.request_log_id_seq'::regclass) NOT NULL, + date TIMESTAMP WITH TIME ZONE DEFAULT clock_timestamp() NOT NULL, + ip INET NOT NULL, + method admin.request_log_method_type NOT NULL, + uri TEXT NOT NULL +); + +ALTER TABLE admin.request_log OWNER TO website; + +ALTER TABLE ONLY admin.request_log + ADD CONSTRAINT request_log_pkey PRIMARY KEY (id); + +CREATE TABLE admin.banned ( + ip INET NOT NULL, + date TIMESTAMP WITH TIME ZONE DEFAULT clock_timestamp() NOT NULL, + reason TEXT DEFAULT 'unspecified'::text NOT NULL +); + +ALTER TABLE admin.banned OWNER TO website; + +ALTER TABLE ONLY admin.banned + ADD CONSTRAINT banned_pkey PRIMARY KEY (ip); + +CREATE SEQUENCE sys.comment_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +CREATE TABLE admin.comment ( + id INTEGER DEFAULT nextval('sys.comment_id_seq'::regclass) NOT NULL, + author TEXT NOT NULL, + content TEXT NOT NULL, + page TEXT NOT NULL, + created TIMESTAMP WITH TIME ZONE DEFAULT clock_timestamp() NOT NULL, + ip INET NOT NULL, + vulgar BOOLEAN DEFAULT FALSE +); + +ALTER TABLE admin.comment OWNER TO website; + +ALTER TABLE ONLY admin.comment + ADD CONSTRAINT comment_pkey PRIMARY KEY (id); +-- Migration End; + +-- Set Current Revision +UPDATE sys.database_info SET curr_revision = 1 WHERE name = current_database(); + +COMMIT TRANSACTION; diff --git a/src/db/rev.sql b/src/db/rev.sql new file mode 100644 index 0000000..bd02f3d --- /dev/null +++ b/src/db/rev.sql @@ -0,0 +1,21 @@ +CREATE OR REPLACE FUNCTION curr_revision() +RETURNS INTEGER +LANGUAGE plpgsql VOLATILE +AS $BODY$ +DECLARE + _revision INTEGER; +BEGIN + BEGIN + SELECT curr_revision INTO _revision + FROM sys.database_info + WHERE name = current_database(); + RETURN _revision; + EXCEPTION WHEN OTHERS THEN + RETURN 0; + END; +END +$BODY$; + +GRANT EXECUTE ON FUNCTION curr_revision() TO website; + +SELECT curr_revision(); diff --git a/src/public/buttons/apiopage.png b/src/public/buttons/apiopage.png new file mode 100644 index 0000000..686ec4c Binary files /dev/null and b/src/public/buttons/apiopage.png differ diff --git a/src/public/buttons/apiopage.webp b/src/public/buttons/apiopage.webp new file mode 100644 index 0000000..b3f3ffd Binary files /dev/null and b/src/public/buttons/apiopage.webp differ diff --git a/src/public/buttons/eyes.gif b/src/public/buttons/eyes.gif new file mode 100644 index 0000000..6dfeb64 Binary files /dev/null and b/src/public/buttons/eyes.gif differ diff --git a/src/public/buttons/eyes.png b/src/public/buttons/eyes.png new file mode 100644 index 0000000..1a5cd46 Binary files /dev/null and b/src/public/buttons/eyes.png differ diff --git a/src/public/buttons/eyes.webp b/src/public/buttons/eyes.webp new file mode 100644 index 0000000..0d70e16 Binary files /dev/null and b/src/public/buttons/eyes.webp differ diff --git a/src/public/buttons/gnu-linux.png b/src/public/buttons/gnu-linux.png new file mode 100644 index 0000000..0c8420b Binary files /dev/null and b/src/public/buttons/gnu-linux.png differ diff --git a/src/public/buttons/gnu-linux.webp b/src/public/buttons/gnu-linux.webp new file mode 100644 index 0000000..b26fb88 Binary files /dev/null and b/src/public/buttons/gnu-linux.webp differ diff --git a/src/public/buttons/vim.gif b/src/public/buttons/vim.gif new file mode 100644 index 0000000..7a00d7f Binary files /dev/null and b/src/public/buttons/vim.gif differ diff --git a/src/public/buttons/vim.png b/src/public/buttons/vim.png new file mode 100644 index 0000000..89948f6 Binary files /dev/null and b/src/public/buttons/vim.png differ diff --git a/src/public/buttons/vim.webp b/src/public/buttons/vim.webp new file mode 100644 index 0000000..9e4a121 Binary files /dev/null and b/src/public/buttons/vim.webp differ diff --git a/src/public/font/CourierNew.eot b/src/public/font/CourierNew.eot new file mode 100644 index 0000000..4a77a73 Binary files /dev/null and b/src/public/font/CourierNew.eot differ diff --git a/src/public/font/CourierNew.otf b/src/public/font/CourierNew.otf new file mode 100644 index 0000000..8861479 Binary files /dev/null and b/src/public/font/CourierNew.otf differ diff --git a/src/public/font/CourierNew.svg b/src/public/font/CourierNew.svg new file mode 100644 index 0000000..a03861a --- /dev/null +++ b/src/public/font/CourierNew.svg @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/public/font/CourierNew.ttf b/src/public/font/CourierNew.ttf new file mode 100644 index 0000000..229c1e7 Binary files /dev/null and b/src/public/font/CourierNew.ttf differ diff --git a/src/public/font/CourierNew.woff b/src/public/font/CourierNew.woff new file mode 100644 index 0000000..a516ee7 Binary files /dev/null and b/src/public/font/CourierNew.woff differ diff --git a/src/public/font/CourierNew.woff2 b/src/public/font/CourierNew.woff2 new file mode 100644 index 0000000..9b2c777 Binary files /dev/null and b/src/public/font/CourierNew.woff2 differ diff --git a/src/public/font/FontStuck-Extended.eot b/src/public/font/FontStuck-Extended.eot new file mode 100644 index 0000000..886b45e Binary files /dev/null and b/src/public/font/FontStuck-Extended.eot differ diff --git a/src/public/font/FontStuck-Extended.otf b/src/public/font/FontStuck-Extended.otf new file mode 100644 index 0000000..3cded5e Binary files /dev/null and b/src/public/font/FontStuck-Extended.otf differ diff --git a/src/public/font/FontStuck-Extended.svg b/src/public/font/FontStuck-Extended.svg new file mode 100644 index 0000000..daaca48 --- /dev/null +++ b/src/public/font/FontStuck-Extended.svg @@ -0,0 +1,242 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/public/font/FontStuck-Extended.ttf b/src/public/font/FontStuck-Extended.ttf new file mode 100644 index 0000000..266de37 Binary files /dev/null and b/src/public/font/FontStuck-Extended.ttf differ diff --git a/src/public/font/FontStuck-Extended.woff b/src/public/font/FontStuck-Extended.woff new file mode 100644 index 0000000..3fb6428 Binary files /dev/null and b/src/public/font/FontStuck-Extended.woff differ diff --git a/src/public/font/FontStuck-Extended.woff2 b/src/public/font/FontStuck-Extended.woff2 new file mode 100644 index 0000000..f9794b5 Binary files /dev/null and b/src/public/font/FontStuck-Extended.woff2 differ diff --git a/src/public/font/Merriweather.eot b/src/public/font/Merriweather.eot new file mode 100644 index 0000000..c118dcc Binary files /dev/null and b/src/public/font/Merriweather.eot differ diff --git a/src/public/font/Merriweather.otf b/src/public/font/Merriweather.otf new file mode 100644 index 0000000..e694c71 Binary files /dev/null and b/src/public/font/Merriweather.otf differ diff --git a/src/public/font/Merriweather.svg b/src/public/font/Merriweather.svg new file mode 100644 index 0000000..4d0db2a --- /dev/null +++ b/src/public/font/Merriweather.svg @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/public/font/Merriweather.ttf b/src/public/font/Merriweather.ttf new file mode 100644 index 0000000..7c5738a Binary files /dev/null and b/src/public/font/Merriweather.ttf differ diff --git a/src/public/font/Merriweather.woff b/src/public/font/Merriweather.woff new file mode 100644 index 0000000..ddb9d27 Binary files /dev/null and b/src/public/font/Merriweather.woff differ diff --git a/src/public/font/Merriweather.woff2 b/src/public/font/Merriweather.woff2 new file mode 100644 index 0000000..38a2394 Binary files /dev/null and b/src/public/font/Merriweather.woff2 differ diff --git a/src/public/icons/favicon.ico b/src/public/icons/favicon.ico new file mode 100644 index 0000000..30b36d4 Binary files /dev/null and b/src/public/icons/favicon.ico differ diff --git a/src/public/icons/logo16.png b/src/public/icons/logo16.png new file mode 100644 index 0000000..6dfa7e5 Binary files /dev/null and b/src/public/icons/logo16.png differ diff --git a/src/public/icons/logo32.png b/src/public/icons/logo32.png new file mode 100644 index 0000000..e3cad38 Binary files /dev/null and b/src/public/icons/logo32.png differ diff --git a/src/public/icons/logo320.png b/src/public/icons/logo320.png new file mode 100644 index 0000000..82c1bfd Binary files /dev/null and b/src/public/icons/logo320.png differ diff --git a/src/public/icons/logo512.png b/src/public/icons/logo512.png new file mode 100644 index 0000000..308f2ef Binary files /dev/null and b/src/public/icons/logo512.png differ diff --git a/src/public/icons/logo64.png b/src/public/icons/logo64.png new file mode 100644 index 0000000..730d5c7 Binary files /dev/null and b/src/public/icons/logo64.png differ diff --git a/src/public/icons/logo640.png b/src/public/icons/logo640.png new file mode 100644 index 0000000..eabaf98 Binary files /dev/null and b/src/public/icons/logo640.png differ diff --git a/src/public/img/background.jpg b/src/public/img/background.jpg new file mode 100644 index 0000000..7b61bc5 Binary files /dev/null and b/src/public/img/background.jpg differ diff --git a/src/public/img/bee.png b/src/public/img/bee.png new file mode 100644 index 0000000..917a5ef Binary files /dev/null and b/src/public/img/bee.png differ diff --git a/src/public/img/bee.webp b/src/public/img/bee.webp new file mode 100644 index 0000000..7af6759 Binary files /dev/null and b/src/public/img/bee.webp differ diff --git a/src/public/img/headerLogo.png b/src/public/img/headerLogo.png new file mode 100644 index 0000000..29178fb Binary files /dev/null and b/src/public/img/headerLogo.png differ diff --git a/src/public/img/headerLogo.webp b/src/public/img/headerLogo.webp new file mode 100644 index 0000000..873fffb Binary files /dev/null and b/src/public/img/headerLogo.webp differ diff --git a/src/public/polyfills/boxsizing.htc b/src/public/polyfills/boxsizing.htc new file mode 100644 index 0000000..f5936e7 --- /dev/null +++ b/src/public/polyfills/boxsizing.htc @@ -0,0 +1,461 @@ + + + + + + + + diff --git a/src/public/polyfills/display-table.htc b/src/public/polyfills/display-table.htc new file mode 100644 index 0000000..395209c --- /dev/null +++ b/src/public/polyfills/display-table.htc @@ -0,0 +1,272 @@ + + + + diff --git a/src/scss/_mixins.scss b/src/scss/_mixins.scss new file mode 100644 index 0000000..0879b18 --- /dev/null +++ b/src/scss/_mixins.scss @@ -0,0 +1,91 @@ +@mixin box-sizing { + * { + -moz-box-sizing: border-box; + -webkit-border-box: border-box; + box-sizing: border-box; + } +} + +@mixin section { + border: $border-width solid $border-color; + @include border-radius($outer-radius); + background: $black; + margin-bottom: $outer-gap; +} + +@mixin linear-gradient($deg, $first, $values...) { + background-color: $first; + background: -webkit-linear-gradient($deg, $first, $values); + background: -moz-linear-gradient($deg, $first, $values); + background: linear-gradient($deg, $first, $values); +} + +@mixin border-radius($radius) { + -moz-border-radius: $radius; + -webkit-border-radius: $radius; + border-radius: $radius; +} + +@mixin text-decoration($decor) { + -moz-text-decoration: $decor; + -webkit-text-decoration: $decor; + text-decoration: $decor; +} + +@mixin keyframes($name) { + @-webkit-keyframes #{$name} { @content; } + @-moz-keyframes #{$name} { @content; } + @keyframes #{$name} { @content; } +} + +@mixin animation($args...) { + -moz-animation: $args; + -webkit-animation: $args; + animation: $args; +} + +@mixin animation-delay($args...) { + -moz-animation-delay: $args; + -webkit-animation-delay: $args; + animation-delay: $args; +} + +@mixin transition($trans...) { + -moz-transition: $trans; + -webkit-transition: $trans; + transition: $trans; +} + +@mixin transform($trans...) { + -moz-transform: $trans; + -webkit-transform: $trans; + transform: $trans; +} + +@mixin font-face($name) { + @font-face { + font-family: $name; + src: url("../font/" + $name + ".eot"); + src: url("../font/" + $name + ".eot?#iefix") format("embedded-opentype"), + url("../font/" + $name + ".woff2") format("woff2"), + url("../font/" + $name + ".woff") format("woff"), + url("../font/" + $name + ".ttf") format("truetype"), + url("../font/" + $name + ".otf") format("opentype"), + url("../font/" + $name + ".svg#" + $name) format('svg'); + font-weight: normal; + font-style: normal; + font-display: swap; + } +} + +@mixin display-table($spacing) { + -dt-display: table; + display: table; + border-spacing: $spacing; + -dt-border-spacing: $spacing; +} + +@mixin display-table-cell { + -dt-display: table-cell; + display: table-cell; +} diff --git a/src/scss/_variables.scss b/src/scss/_variables.scss new file mode 100644 index 0000000..cfb5f0c --- /dev/null +++ b/src/scss/_variables.scss @@ -0,0 +1,25 @@ + +$white: #e6edf0; +$white-alt: #9dabb0; +$yellow: #dcde81; +$yellow-alt: #808037; +$green: #4fd15a; +$green-alt: #519c57; +$blue: #366199; +$blue-alt: #244266; +$black: #14171d; +$black-alt: #242526; + +$font: 'Courier New', Courier, monospace; +$header-font: 'FontStuck-Extended', monospace; + +$inner-gap: 16px; +$outer-gap: 16px; + +$outer-radius: 8px; +$inner-radius: 4px; + +$border-width: 5px; +$border-color: #ccc; + +$page-width: 1000px; diff --git a/src/scss/blog.scss b/src/scss/blog.scss new file mode 100644 index 0000000..ff17caf --- /dev/null +++ b/src/scss/blog.scss @@ -0,0 +1,61 @@ +@import "./variables"; +@import "./mixins"; + +#blog { + padding-bottom: $inner-gap; +} + +#main span { + display: inline-block; +} + +#comments { + > span { + margin-bottom: 10px; + } + + .comment { + .header { + display: inline-block;; + } + .date { + font-size: 70%; + display: inline-block;; + } + .content { + margin-top: 0; + } + } + + #new_comment { + margin-left: $inner-gap; + max-width: 400px; + padding-right: $inner-gap; + + input.hidden { + display: none; + } + + input#author, + input#content { + width: 100%; + } + + input { + @include border-radius($inner-radius); + display: block; + margin: 10px 0; + padding: 5px; + border: 2px solid $white-alt; + background: $black-alt; + color: $white; + + &:hover, + &:focus, + &:active { + outline: none; + border: 2px solid $white; + } + } + } +} diff --git a/src/scss/bucket.scss b/src/scss/bucket.scss new file mode 100644 index 0000000..efba81a --- /dev/null +++ b/src/scss/bucket.scss @@ -0,0 +1,2 @@ +@import "./bucket/default"; +@import "./bucket/style"; diff --git a/src/scss/bucket/_default.scss b/src/scss/bucket/_default.scss new file mode 100644 index 0000000..a9d0add --- /dev/null +++ b/src/scss/bucket/_default.scss @@ -0,0 +1,55 @@ +@import "../mixins"; + +$red: #ffcaca !default; +$orange: #ffedc1 !default; +$yellow: #feffb8 !default; +$green: #c4ffcb !default; +$blue: #add8ff !default; +$purple: #ccafe9 !default; + +$darkgreen: #3E885B !default; +$darkblue: #7fb4f5 !default; + +$white: #fefefa !default; +$lightgray: #94B0C2 !default; +$lightblue: #d1e9ff !default; +$gray: #ADACB5 !default; +$darkgray: #333C57 !default; +$black: #454545 !default; +$trueblack: #242424 !default; + +$lessred: #ffcacaaa !default; +$lessorange: #ffedc1aa !default; +$lessyellow: #feffb8aa !default; +$lessgreen: #c4ffcbaa !default; +$lessblue: #add8ffaa !default; +$lesspurple: #ccafe9aa !default; + +$rainbowright: + to right, + $red 0%, + $orange 20%, + $yellow 40%, + $green 60%, + $blue 80%, + $purple 100% !default; + +$hrainbow: + to right, + #00000000 0%, + $lessred 14%, + $orange 28%, + $yellow 42%, + $green 56%, + $blue 70%, + $lesspurple 84%, + #00000000 100% !default; + +$bgrainbow: + to right, + $lessred 0%, + $lessorange 20%, + $lessyellow 40%, + $lessgreen 60%, + $lessblue 80%, + $lesspurple 100% !default; diff --git a/src/scss/bucket/_style.scss b/src/scss/bucket/_style.scss new file mode 100644 index 0000000..b449ab4 --- /dev/null +++ b/src/scss/bucket/_style.scss @@ -0,0 +1,109 @@ +@include box-sizing; +@include font-face("Merriweather"); +@include font-face("CourierNew"); + +* { + font-family: Merriweather, Georgia, serif; + color: $lightblue; +} + +html { + background-color: #454545; +} + +html, body { + height: 100%; + margin: 0; +} + +a { + display: inline-block; + position: relative; + text-decoration: none; + transition: linear 0.2s; + color: $purple; + + &:before { + content: ''; + height: 2px; + position: absolute; + bottom: -1.5px; + width: 100%; + left: 50%; + @include linear-gradient($rainbowright...); + @include transform(translate(-50%, 0)); + @include transition(width 0.2s ease-in-out); + } + + &:hover { + color: $white; + } + + &:hover:before { + width: 0; + } +} + +@mixin animate-letter($n) { + .e#{$n} { + position: relative; + $delay: (12 - $n) * -100ms; + @include animation-delay($delay); + @include animation( + wave 1s linear $delay infinite, + rainbow 3s linear $delay infinite); + } +} + +#webring { + position: relative; + width: 100%; + padding: 0.5em; + + .left { + float: left; + } + + .right { + float: right; + } + + center { + width: 100%; + left: 0; + position: absolute; + + .center { + .header { + @for $i from 0 through 12 { + @include animate-letter($i); + } + } + } + } + +} + +@media (prefers-reduced-motion: reduce) { + .header span { + animation: none !important; + } +} + +@include keyframes(wave) { + 0% {top: 0px;} + 25% {top: -1px;} + 50% {top: 0px;} + 75% {top: 1px;} + 100% {top: 0px;} +} + +@include keyframes(rainbow) { + 0% {color: $red;} + 17% {color: $orange;} + 33% {color: $yellow;} + 50% {color: $green;} + 67% {color: $blue;} + 83% {color: $purple;} + 100% {color: $red;} +} diff --git a/src/scss/bucket_light.scss b/src/scss/bucket_light.scss new file mode 100644 index 0000000..8782426 --- /dev/null +++ b/src/scss/bucket_light.scss @@ -0,0 +1,36 @@ +@import "./bucket/default"; + +$white: #fff; +$red: #B80000; +$orange: #B88400; +$yellow: #B5B800; +$green: #00B815; +$blue: #0069CC; +$purple: #7030B0; + +$darkgreen: #3E885B; +$darkblue: #7fb4f5; + +$background: #fefefa; + +$rainbowright: + to right, + $red 0%, + $orange 20%, + $yellow 40%, + $green 60%, + $blue 80%, + $purple 100%; + +$hrainbow: + to right, + #FFFFFF00 0%, + $lessred 14%, + $orange 28%, + $yellow 42%, + $green 56%, + $blue 70%, + $lesspurple 84%, + #FFFFFF00 100%; + +@import "./bucket/style"; diff --git a/src/scss/error.scss b/src/scss/error.scss new file mode 100644 index 0000000..34c9d21 --- /dev/null +++ b/src/scss/error.scss @@ -0,0 +1,14 @@ +@import "./variables"; + +.section { + text-align: center; +} + +#main h1 { + color: $green; + text-shadow: 4px 4px $green-alt; +} + +#main h2 { + text-shadow: 3px 3px $white-alt; +} diff --git a/src/scss/home.scss b/src/scss/home.scss new file mode 100644 index 0000000..0501941 --- /dev/null +++ b/src/scss/home.scss @@ -0,0 +1,23 @@ +@import "./variables"; + +#main .col { + width: 50%; + padding: 0; + margin: 0; + display: table-cell; +} + +#main .left { + padding-right: $outer-gap; +} + +@media (max-width: 800px) { + #main .col { + display: block; + width: 100%; + } + + #main .left { + padding-right: 0; + } +} diff --git a/src/scss/legacy.scss b/src/scss/legacy.scss new file mode 100644 index 0000000..52c1a18 --- /dev/null +++ b/src/scss/legacy.scss @@ -0,0 +1,21 @@ +/* IE 6 & 7 Styles */ + +@import "./variables"; + +* { + behavior: url(boxsizing.htc); +} + +#main.legacy .col { + display: block !important; + width: 100% !important; +} + +#main.legacy .left { + padding-right: 0 !important; + padding-bottom: $outer-gap; +} + +#nav { + behavior: url(display-table.htc); +} diff --git a/src/scss/main.scss b/src/scss/main.scss new file mode 100644 index 0000000..d18cdc0 --- /dev/null +++ b/src/scss/main.scss @@ -0,0 +1,328 @@ +@import "./variables"; +@import "./mixins"; + +@include box-sizing; +@include font-face("FontStuck-Extended"); +@include font-face("CourierNew"); + +@include keyframes(shake) { + 0% { @include transform(translate(1px, 1px) rotate(0deg)); } + 10% { @include transform(translate(-1px, -2px) rotate(-1deg)); } + 20% { @include transform(translate(-3px, 0px) rotate(1deg)); } + 30% { @include transform(translate(3px, 2px) rotate(0deg)); } + 40% { @include transform(translate(1px, -1px) rotate(1deg)); } + 50% { @include transform(translate(-1px, 2px) rotate(-1deg)); } + 60% { @include transform(translate(-3px, 1px) rotate(0deg)); } + 70% { @include transform(translate(3px, 1px) rotate(-1deg)); } + 80% { @include transform(translate(-1px, -1px) rotate(1deg)); } + 90% { @include transform(translate(1px, 2px) rotate(0deg)); } + 100% { @include transform(translate(1px, -2px) rotate(-1deg)); } +} + +img:hover { + @include animation(shake 0.5s linear infinite); +} + +@media (prefers-reduced-motion) { + img:hover { + @include animation(none !important); + } +} + +* { + scrollbar-color: $blue transparent; +} + +h1 { + font-family: $header-font; + font-size: 325%; + line-height: 100%; + margin: 15px 0; +} + +h2 { + font-family: $header-font; + font-size: 200%; + line-height: 100%; + margin: 12px 0; +} + +h3 { + font-family: $header-font; + font-size: 150%; + line-height: 100%; + margin: 5px 0; +} + +h4 { + font-family: $header-font; + font-size: 130%; + line-height: 100%; + margin: 2px 0; +} + +a, +a:visited { + color: $yellow; + @include text-decoration(underline); +} + +a:hover { + color: $yellow-alt; + @include text-decoration(underline); +} + +html { + color: $white; + font-family: $font; + font-size: 120%; + background: #181818; + background-image: url("../img/background.jpg?ref=2"); + background-repeat: repeat; + background-size: 512px; +} + +html, +body, +#container { + width: 100%; + margin: 0; + padding: 0; +} + +body { + padding: $inner-gap; + min-height: 100%; + + .center { + display: table; + margin: 0 auto; + } +} + +#header, +#main, +#footer, +#container { + @include border-radius($outer-radius); + width: $page-width; + text-align: left; +} + +@media (max-width: ($page-width + $outer-gap * 2)) { + body, #header, + #main, #footer, + #container { + width: 100%; + min-width: 250px; + } +} + +#header, +#footer { + display: block; + @include section; +} + +#header { + $logo-size: 200px; + height: #{$logo-size + $inner-gap * 2 + 10px}; + padding: $inner-gap; + + img { + @include border-radius($inner-radius); + float: left; + height: $logo-size; + width: $logo-size; + } + + .content { + padding-top: 30px; + padding-left: $logo-size; + + .logo-text { + margin: 0; + text-align: center; + text-shadow: 3px 3px $white-alt; + } + + #nav { + margin: 0; + padding: 0; + list-style-type: none; + margin: 0 auto; + @include display-table($inner-gap); + + li { + @include display-table-cell; + float: left; + padding: $inner-gap; + + a { + @include text-decoration(none); + + &:hover, + &:active { + color: $yellow; + @include text-decoration(underline); + } + + h2 { + margin: 0; + text-shadow: 3px 3px $yellow-alt; + } + } + } + } + } +} + +@media (max-width: 800px) { + #header { + display: block; + height: auto; + + img { + float: none; + display: block; + margin: 0 auto; + } + + .content { + padding-top: 0; + padding-left: 0; + + #nav { + text-align: center; + } + } + } +} + +@media (max-width: 550px) { + #header .content #nav { + li { + float: none; + display: block; + } + } +} + +#footer { + padding: $inner-gap; + + .footer-text { + display: block; + margin: 10px 0; + } + + .bucket { + margin-top: $inner-gap; + width: 100%; + height: 40px; + border: none; + } + + .john { + display: block; + max-width: 732px; + height: 94px; + width: 100%; + border: none; + + @media(max-width: 732px) { + height: 12vw; + } + } + + .buttons { + a, img { + height: 30px; + } + } +} + +#main .section { + @include section; + + .heading { + @include linear-gradient(to bottom, $blue, $black); + margin: 0; + padding-left: $inner-gap; + @include border-radius($inner-radius $inner-radius 0 0); + } + + h1, h2, h3, h4, h5, + span, pre { + margin-left: $inner-gap; + } + + p { + padding: 0 $inner-gap; + } + + blockquote p { + border-left: 5px solid $blue; + } + + pre { + background: black; + margin-right: $inner-gap; + @include border-radius($outer-radius); + padding: $inner-gap; + } + + code { + font-family: $font; + color: $green; + } + + pre code { + color: $white; + } + + table { + width: 100%; + + th, td { + padding: $outer-radius; + font-family: $header-font; + font-size: 120%; + line-height: 120%; + + @media (max-width: 400px) { + font-size: 100%; + line-height: 100%; + } + + @media (max-width: 360px) { + font-size: 90%; + line-height: 90%; + } + + @media (max-width: 320px) { + font-size: 80%; + line-height: 80%; + } + + } + + td { + background: $blue-alt; + } + + th { + background: $blue; + text-align: left; + } + + tr:last-child { + th { + @include border-radius(0 0 0 $inner-radius); + } + tr { + @include border-radius(0 0 $inner-radius 0); + } + } + } +} diff --git a/src/web/_controller/_comments.php b/src/web/_controller/_comments.php new file mode 100644 index 0000000..4b87a94 --- /dev/null +++ b/src/web/_controller/_comments.php @@ -0,0 +1,87 @@ +comments_model = $this->load->model('_comments'); + } + + + public function comments($page, $ref): void { + $data = $this->comments_model->get_comments($page); + $this->view('comments', array( + 'comments' => $data, + 'ref' => $ref, + 'page' => $page + )); + } + + public function post(): void { + $author = ''; $content = ''; $ref = ''; + if ( + !array_key_exists('author', $_GET) || + !array_key_exists('content', $_GET) || + !array_key_exists('ref', $_GET) || + !array_key_exists('page', $_GET) + ) { + $this->error(400); return; + } + + $author = trim($_GET['author']); + $content = trim($_GET['content']); + $page = $_GET['page']; + $ref = $_GET['ref']; + $url = NULL; + + $author_len = strlen($author); + $content_len = strlen($content); + + if ($author_len < 1 || $content_len < 1) { + $this->error(400); + return; + } + + if ($author_len > 30 || $content_len > 500) { + $this->error(413); + return; + } + + if (base64_encode(base64_decode($ref)) !== $ref) { + // invalid base64 + $this->error(400); + return; + } + + try { + $ref = base64_decode($ref); + $url = parse_url($ref); + if (!$url && array_key_exists('host', $url)) { + // dont allow redirects off this site + $this->error(400); + return; + } + } catch (Exception $e) { + $this->error(400); + return; + } + + $vulgar = 'false'; + if ( + $this->comments_model->is_vulgar($author) || + $this->comments_model->is_vulgar($content) + ) { + $vulgar = 'true'; + } + + $result = $this->comments_model + ->post_comment($author, $content, $page, $vulgar); + + if ($result) { + header('Location: ' . $this->main->get_url($ref) . '#comments'); + } else { + $this->error(500); + } + } +} diff --git a/src/web/_controller/_meta.php b/src/web/_controller/_meta.php new file mode 100644 index 0000000..801d254 --- /dev/null +++ b/src/web/_controller/_meta.php @@ -0,0 +1,76 @@ +main->get_url_full('sitemap.xml'); + + echo "User-agent: *\n"; + echo "Disallow:\n"; + echo "Crawl-delay: 5\n"; + echo "Disallow: /_comments/\n"; + echo "Disallow: /pacbattle/\n"; + echo "Disallow: /bucket/\n"; + echo "Sitemap: {$sitemap}\n"; + } + + private function sitemap_page($url, $priority) { + echo "\n"; + echo "{$this->main->get_url_full($url)}\n"; + echo "{$priority}\n"; + echo ""; + } + + public function sitemap() { + header("Content-Type: application/xml"); + + echo "\n"; + echo "\n"; + + $this->sitemap_page('home', 1); + $this->sitemap_page('projects', 0.8); + $this->sitemap_page('blog', 0.8); + + $this->load->app_lang('blog'); + $blog_modal = $this->load->model('blog'); + $blog = $blog_modal->get_data()['blog']; + + foreach ($blog as $name => $_) { + $this->sitemap_page("blog/post?name={$name}", 0.5); + } + + echo "\n"; + } + + public function manifest() { + $json = array( + 'short_name' => lang('domain'), + 'name' => lang('domain'), + 'icons' => [ + array( + 'src' => $this->main->get_url('public/icons/logo512.png'), + 'type' => 'image/png', + 'sizes' => '512x512', + 'purpose' => 'any maskable' + ) + ], + 'id' => $this->main->get_url('home'), + 'start_url' => $this->main->get_url('home'), + 'background_color' => lang('theme_color'), + 'display' => 'standalone', + 'scope' => lang('base_path'), + 'theme_color' => lang('theme_color'), + 'shortcuts' => [], + 'description' => lang('default_short_desc'), + 'screenshots' => [] + ); + + header('Content-type: application/json'); + echo json_encode($json); + } + +} diff --git a/src/web/_controller/blog.php b/src/web/_controller/blog.php new file mode 100644 index 0000000..f13ffd1 --- /dev/null +++ b/src/web/_controller/blog.php @@ -0,0 +1,74 @@ +blog_model = $this->load->model('blog'); + $this->comments_controller = $this->load->controller('_comments'); + } + + public function index(): void { + parent::index(); + $data = $this->blog_model->get_data(); + $this->view('header', $data); + $this->view('apps/blog', $data); + $this->view('footer', $data); + } + + private function protect($folder) { + if (!array_key_exists('name', $_GET)) { + $this->error(400); + } + + $basepath = $GLOBALS['assetroot'] . '/' . $folder . '/'; + $realBase = realpath($basepath); + + $userpath = $basepath . $_GET['name']; + $realUserPath = realpath($userpath); + + if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) { + $this->error(404); + } + } + + public function post(): void { + $this->protect('blog'); + parent::index(); + $data = $this->blog_model->get_post($_GET['name']); + if ($data === FALSE) { + $this->error(404); + } + $this->view('header', $data); + $this->view('apps/blog_post', $data); + $ref = 'blog/post?name=' . $_GET['name']; + $this->comments_controller->comments($data['post']['meta']['name'], $ref); + $this->view('footer', $data); + } + + public function writeup(): void { + $this->protect('writeup'); + parent::index(); + $data = $this->blog_model->get_writeup($_GET['name']); + if ($data === FALSE) { + $this->error(404); + } + $this->view('header', $data); + $this->view('apps/blog_writeup', $data); + $ref = 'blog/writeup?name=' . $_GET['name']; + $this->comments_controller->comments($data['post']['meta']['name'], $ref); + $this->view('footer', $data); + } + + public function rss() { + $data = $this->blog_model->get_data(); + header('Content-Type: application/xml'); + $this->view('apps/blog_rss', $data); + die(); + } + +} + +?> diff --git a/src/web/_controller/bucket.php b/src/web/_controller/bucket.php new file mode 100644 index 0000000..ed15ef8 --- /dev/null +++ b/src/web/_controller/bucket.php @@ -0,0 +1,22 @@ +bucket_model = $this->load->model('bucket'); + } + + public function index(): void { + parent::index(); + $data = $this->bucket_model->get_data(); + if ($data === NULL) { + $this->error(400); + return; + } + $this->view('apps/bucket', $data); + } +} + +?> diff --git a/src/web/_controller/error.php b/src/web/_controller/error.php new file mode 100644 index 0000000..d24308b --- /dev/null +++ b/src/web/_controller/error.php @@ -0,0 +1,21 @@ +error_model = $this->load->model('error'); + } + + public function index(): void { + parent::index(); + $data = $this->error_model->get_data(); + $this->view('header', $data); + $this->view('apps/error', $data); + $this->view('footer', $data); + } + +} + +?> diff --git a/src/web/_controller/home.php b/src/web/_controller/home.php new file mode 100644 index 0000000..12dff64 --- /dev/null +++ b/src/web/_controller/home.php @@ -0,0 +1,17 @@ +main->get_data(); + $this->view('header', $data); + $this->view('apps/home', $data); + $this->view('footer', $data); + } + +} + +?> diff --git a/src/web/_controller/projects.php b/src/web/_controller/projects.php new file mode 100644 index 0000000..9ee2136 --- /dev/null +++ b/src/web/_controller/projects.php @@ -0,0 +1,21 @@ +projects_model = $this->load->model('projects'); + } + + public function index(): void { + parent::index(); + $data = $this->projects_model->get_data(); + $this->view('header', $data); + $this->view('apps/projects', $data); + $this->view('footer', $data); + } + +} + +?> diff --git a/src/web/_model/_comments.php b/src/web/_model/_comments.php new file mode 100644 index 0000000..73c1fc7 --- /dev/null +++ b/src/web/_model/_comments.php @@ -0,0 +1,66 @@ + $line) { + if ($line == '') { + continue; + } + if ($idx != 0) { + $regex .= '|'; + } + $regex .= $line; + } + $regex .= ')/'; + + return $regex; + } + + public function is_vulgar($text) { + $profanity = $this->load_profanity(); + return preg_match($profanity, $text); + } + + public function get_comments($page) { + $ip = $this->main->info['ip']; + $query = $this->db + ->select('*') + ->from('admin.comment c') + ->where('c.page') + ->eq($page) + ->query('AND ( + (c.vulgar IS FALSE) OR + (c.vulgar IS TRUE and c.ip = ?) + )') + ->order_by('c.id', 'DESC'); + $result = $query->rows($ip); + return $result; + } + + public function ban_user() { + $ip = $this->main->info['ip']; + $this->db + ->insert_into('admin.banned', 'ip', 'reason') + ->values($ip, 'vulgar language') + ->execute(); + } + + public function post_comment($author, $content, $page, $vulgar) { + $ip = $this->main->info['ip']; + return $this->db + ->insert_into('admin.comment', + 'author', 'content', 'page', 'ip', 'vulgar') + ->values($author, $content, $page, $ip, $vulgar) + ->execute(); + } + +} diff --git a/src/web/_model/blog.php b/src/web/_model/blog.php new file mode 100644 index 0000000..42cee97 --- /dev/null +++ b/src/web/_model/blog.php @@ -0,0 +1,80 @@ +markdown = new MarkdownParser(); + } + + private function load_blog(&$data) { + $blog = array(); + $dir = $GLOBALS['assetroot'] . '/blog'; + if ($handle = opendir($dir)) { + while (false !== ($entry = readdir($handle))) { + if (str_starts_with($entry, ".")) { + continue; + } + $path = $dir . '/' . $entry; + $md = $this->markdown->parse($path); + $blog[$entry] = $md; + } + } + krsort($blog); + $data['blog'] = $blog; + } + + public function get_data(): ?array { + $data = parent::get_data(); + $this->load_blog($data); + $data['title'] = lang('title'); + $data['desc'] = lang('blog_short_desc'); + return $data; + } + + private function load_post($name) { + $dir = $GLOBALS['assetroot'] . '/blog'; + $path = $dir . '/' . $name; + if(!file_exists($path)) { + return FALSE; + } + $md = $this->markdown->parse($path); + return $md; + } + + public function get_post($name) { + $data = parent::get_data(); + $post = $this->load_post($name); + if (!$post) { + return FALSE; + } + $data['title'] = $post['meta']['name']; + $data['desc'] = $post['meta']['desc']; + $data['post'] = $post; + return $data; + } + + private function load_writeup($name) { + $dir = $GLOBALS['assetroot'] . '/writeup'; + $path = $dir . '/' . $name; + if(!file_exists($path)) { + return FALSE; + } + $md = $this->markdown->parse($path); + return $md; + } + + public function get_writeup($name) { + $data = parent::get_data(); + $writeup = $this->load_writeup($name); + if (!$writeup) { + return FALSE; + } + $data['title'] = $writeup['meta']['name']; + $data['desc'] = $writeup['meta']['desc']; + $data['post'] = $writeup; + return $data; + } +} +?> diff --git a/src/web/_model/bucket.php b/src/web/_model/bucket.php new file mode 100644 index 0000000..f38bebe --- /dev/null +++ b/src/web/_model/bucket.php @@ -0,0 +1,26 @@ + diff --git a/src/web/_model/error.php b/src/web/_model/error.php new file mode 100644 index 0000000..0a08fdd --- /dev/null +++ b/src/web/_model/error.php @@ -0,0 +1,31 @@ +get_msg($data); + return $data; + } +} +?> diff --git a/src/web/_model/main.php b/src/web/_model/main.php new file mode 100644 index 0000000..6767010 --- /dev/null +++ b/src/web/_model/main.php @@ -0,0 +1,97 @@ +\d+)/i', @$_SERVER['HTTP_USER_AGENT'], $B)) { + return $B['v']; + } else { + return PHP_INT_MAX; + } + } + + /** + * Gets the full url including the http scheme and host part + * Needed for IE 6 & 7 need. + */ + public function get_url_full($path): string { + $host = $_SERVER['HTTP_HOST']; + $base = lang('base_path'); + $url = "http://{$host}{$base}{$path}"; + return $url; + } + + /** + * Gets a full path url from a relative path + */ + public function get_url($path): string { + if ($this->get_ie_version() <= 7) { + return $this->get_url_full($path); + } + $base = lang('base_path'); + $url = "{$base}{$path}"; + return $url; + } + + /** + * Loads a css html link + * @param string $path - the path to the css file + */ + public function link_css($path): string { + $stamp = $this->asset_stamp($path); + $href = $this->get_url("public/{$path}?stamp={$stamp}"); + return ''; + } + + /** + * Loads a css html link + * @param string $path - the path to the css file + */ + public function embed_css($path): string { + $file = $GLOBALS['publicroot'] . '/' . $path; + if (file_exists($file)) { + $text = file_get_contents($file); + return ""; + } else { + return ""; + } + } + + /** + * Formats a ISO date + * @param $iso_date the ISO date + */ + public function format_date($iso_date): string { + return date("Y-m-d D H:m", strtotime($iso_date)); + } +} + +?> diff --git a/src/web/_model/projects.php b/src/web/_model/projects.php new file mode 100644 index 0000000..5373a78 --- /dev/null +++ b/src/web/_model/projects.php @@ -0,0 +1,36 @@ +markdown = new MarkdownParser(); + } + + private function load_projects(&$data) { + $projects = array(); + $dir = $GLOBALS['assetroot'] . '/projects'; + if ($handle = opendir($dir)) { + while (false !== ($entry = readdir($handle))) { + if (str_starts_with($entry, ".")) { + continue; + } + $path = $dir . '/' . $entry; + $md = $this->markdown->parse($path); + $projects[$entry] = $md; + } + } + krsort($projects); + $data['projects'] = $projects; + } + + public function get_data(): ?array { + $data = parent::get_data(); + $this->load_projects($data); + $data['title'] = lang('title'); + $data['desc'] = lang('short_desc'); + return $data; + } +} +?> diff --git a/src/web/_views/apps/blog.php b/src/web/_views/apps/blog.php new file mode 100644 index 0000000..e8908e6 --- /dev/null +++ b/src/web/_views/apps/blog.php @@ -0,0 +1,13 @@ + + +

+ $post) { + $meta = $post['meta']; + $link = $this->main->get_url('blog/post?name=' . $name); + echo '

' . $meta['name'] . '

'; + echo '' . $meta['desc'] . '
'; + echo ''; + } + ?> + diff --git a/src/web/_views/apps/blog_post.php b/src/web/_views/apps/blog_post.php new file mode 100644 index 0000000..d5ad255 --- /dev/null +++ b/src/web/_views/apps/blog_post.php @@ -0,0 +1,6 @@ + + + : +
+ + diff --git a/src/web/_views/apps/blog_rss.php b/src/web/_views/apps/blog_rss.php new file mode 100644 index 0000000..1d0dcd4 --- /dev/null +++ b/src/web/_views/apps/blog_rss.php @@ -0,0 +1,20 @@ + + + + <?=lang('title')?> + + + + $post) { + echo ''; + echo '' . $post['meta']['name'] . ''; + echo '' . $post['meta']['desc'] . ''; + echo '' . $post['meta']['date'] . ''; + echo '' . lang('root_url') . '/blog/post?name=' . $name . ''; + echo '' . lang('root_url') . '/blog/post?name=' . $name . ''; + echo ''; + } + ?> + + diff --git a/src/web/_views/apps/blog_writeup.php b/src/web/_views/apps/blog_writeup.php new file mode 100644 index 0000000..b0f18e7 --- /dev/null +++ b/src/web/_views/apps/blog_writeup.php @@ -0,0 +1,5 @@ + + +
+ + diff --git a/src/web/_views/apps/bucket.php b/src/web/_views/apps/bucket.php new file mode 100644 index 0000000..58925f1 --- /dev/null +++ b/src/web/_views/apps/bucket.php @@ -0,0 +1,41 @@ + + view('head', $data); + if ($lightmode === 'true') { + echo $this->main->link_css('css/bucket_light.css'); + } else { + echo $this->main->link_css('css/bucket.css'); + } + ?> + + +
+
+ + 🏳️‍🌈 + + bucket webring + + 🏳️‍🌈 + +
+ + +
+ + + diff --git a/src/web/_views/apps/error.php b/src/web/_views/apps/error.php new file mode 100644 index 0000000..efe7546 --- /dev/null +++ b/src/web/_views/apps/error.php @@ -0,0 +1,6 @@ + + +

+

+

+ diff --git a/src/web/_views/apps/home.php b/src/web/_views/apps/home.php new file mode 100644 index 0000000..8e59423 --- /dev/null +++ b/src/web/_views/apps/home.php @@ -0,0 +1,55 @@ + +
+ +

+
+ + +

+ + + +
+ + + + + + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + +
contact@freyacat.org
@freya:freya.cat
freya@freya.cat
@freya@freya.cat
+ + + diff --git a/src/web/_views/apps/projects.php b/src/web/_views/apps/projects.php new file mode 100644 index 0000000..bac1004 --- /dev/null +++ b/src/web/_views/apps/projects.php @@ -0,0 +1,11 @@ + +

' . $meta['name'] . '

'; + echo $content; + } + ?> + diff --git a/src/web/_views/comments.php b/src/web/_views/comments.php new file mode 100644 index 0000000..d72afd6 --- /dev/null +++ b/src/web/_views/comments.php @@ -0,0 +1,51 @@ + + + '; + echo '

' . esc($comment['author']) . '

'; + echo '' . $date . ''; + echo '

' . esc($comment['content']) . '

'; + echo ''; + } + if (!count($comments)) { + echo ''. lang('no_comments') .''; + } + ?> +
+

+
+ + + + + +
+
+ + diff --git a/src/web/_views/footer.php b/src/web/_views/footer.php new file mode 100644 index 0000000..1eac625 --- /dev/null +++ b/src/web/_views/footer.php @@ -0,0 +1,51 @@ + +main->get_ie_version() <= 7; +?> + + + + + + + + + + diff --git a/src/web/_views/head.php b/src/web/_views/head.php new file mode 100644 index 0000000..e30e05c --- /dev/null +++ b/src/web/_views/head.php @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + <?=$title?> + + + + + + + + main->get_ie_version() <= 7) + echo $this->main->link_css('css/legacy.css'); + ?> + main->embed_css($file); + ?> diff --git a/src/web/_views/header.php b/src/web/_views/header.php new file mode 100644 index 0000000..b037038 --- /dev/null +++ b/src/web/_views/header.php @@ -0,0 +1,43 @@ + +view('head', $data); + echo $this->main->link_css('css/main.css'); + $legacy = $this->main->get_ie_version() <= 7; +?> + + + +
+ +
+ + + +
+ +
+ +
diff --git a/src/web/config/routes.php b/src/web/config/routes.php new file mode 100644 index 0000000..cb78a72 --- /dev/null +++ b/src/web/config/routes.php @@ -0,0 +1,10 @@ +load = $load; + $this->main = $this->load->model('main'); + + $this->load->lang(); + $info = $this->main->info; + $app = $info['app']; + if ($app) { + $this->load->app_lang($app); + } + } + + public function index() {} + + public function redirect($link) { + header('Location: '. $link, true, 301); + die(); + } + + protected function view($__name, $data = array()) { + $__root = $GLOBALS['webroot']; + $__path = $__root . '/_views/' . $__name . '.php'; + if (is_file($__path)) { + extract($data); + require($__path); + return; + } + } + + protected function error($code): void { + $_GET['code'] = $code; + $this->main->info['app'] = 'error'; + $error_controller = $this->load->controller('error'); + $error_controller->index(); + die(); + } + +} diff --git a/src/web/core/_model.php b/src/web/core/_model.php new file mode 100644 index 0000000..4c27b1b --- /dev/null +++ b/src/web/core/_model.php @@ -0,0 +1,50 @@ +load = $load; + if ($main) { + $this->main = $this; + } else { + $this->main = $this->load->model('main'); + } + $this->db = $this->load->db(); + } + + /** + * @returns the base model data + */ + public function get_data(): ?array { + $data = array(); + + $info = $this->main->info; + $app = $info['app']; + + $data['title'] = lang('first_name'); + $data['desc'] = lang('default_short_desc'); + $data['css'] = array(); + + $style = $GLOBALS['style']; + if (isset($style[$app])) { + $css = $style[$app]; + if (!is_array($css)) + $css = array($css); + $data['css'] = $css; + } + + return $data; + } +} diff --git a/src/web/core/loader.php b/src/web/core/loader.php new file mode 100644 index 0000000..b0a1cbd --- /dev/null +++ b/src/web/core/loader.php @@ -0,0 +1,111 @@ +loaded = array(); + } + + /** + * Loads a $type of object from a $dir with a given $name + * @param string $name - the name of the object to load + * @param string $dir - the directory theese objects are stored in + * @param string $type - the type of the object + */ + private function load_type($name, $dir, $type): object|NULL { + $path = $dir . '/' . $name . '.php'; + if (array_key_exists($path, $this->loaded)) { + return $this->loaded[$path]; + } + + if (!file_exists($path)) { + return NULL; + } + + $parts = explode('/', $name); + $part = end($parts); + $class = ucfirst($part) . '_' . $type; + require($path); + + $ref = NULL; + try { + $ref = new ReflectionClass($class); + } catch (Exception $_e) {} + + if ($ref === NULL) { + return NULL; + } + + $obj = $ref->newInstance($this); + $this->loaded[$path] = $obj; + + return $obj; + } + + /** + * Loads a model + * @param string $name - the name of the model to load + */ + public function model($name): object|NULL { + $root = $GLOBALS['webroot']; + $dir = $root . '/_model'; + return $this->load_type($name, $dir, 'model'); + } + + /** + * Loads a controller + * @param string $name - the name of the controller to load + */ + public function controller($name): Controller|NULL { + $root = $GLOBALS['webroot']; + $dir = $root . '/_controller'; + return $this->load_type($name, $dir, 'controller'); + } + + /** + * Loads the given common lang + */ + public function lang(): void { + $dir = $GLOBALS['webroot'] . '/lang/'; + $lang = $GLOBALS['lang']; + if ($handle = opendir($dir)) { + while (false !== ($entry = readdir($handle))) { + if ($entry === '.' || $entry === '..' || $entry === 'apps') { + continue; + } + $path = $dir . $entry; + require($path); + } + } + $GLOBALS['lang'] = $lang; + } + + /** + * Loads a given app specific lang + * @param string $name - the name of the app + */ + public function app_lang($name): void { + $dir = $GLOBALS['webroot'] . '/lang/apps/'; + $file = $dir . $name . '.php'; + if (file_exists($file)) { + $lang = $GLOBALS['lang']; + require($dir . $name . '.php'); + $GLOBALS['lang'] = $lang; + } + } + + public function db() { + if ($this->db) { + return $this->db; + } else { + $this->db = new DatabaseHelper(); + return $this->db; + } + } + +} diff --git a/src/web/core/router.php b/src/web/core/router.php new file mode 100644 index 0000000..c8fb142 --- /dev/null +++ b/src/web/core/router.php @@ -0,0 +1,248 @@ +load = $load; + $this->db = $load->db(); + $this->main = $this->load->model('main'); + $this->db_ready = file_exists('/status/ready'); + } + + /** + * @param string $path - the current request path + * Gets the current route + * @return array + */ + private function get_req_route($path): array { + // trim the path + $path = trim($path); + // remove first '/' + $path = substr($path, 1); + // get path parts + $parts = explode('/', $path); + + $len = count($parts); + + // get route info + $route = array(); + // e.g. / + if ($path === '') { + $route = array( + 'app' => '', + 'slug' => 'index', + ); + // e.g. /home /login + } else if ($len === 1) { + $route = array( + 'app' => $parts[0], + 'slug' => 'index', + ); + // e.g. /home/posts + } else { + $route = array ( + 'app' => implode('/', array_slice($parts, 0, -1)), + 'slug' => end($parts) + ); + }; + + $routes = $GLOBALS['routes']; + if (array_key_exists($route['app'], $routes)) { + $parts = explode('/', $routes[$route['app']]); + if (count($parts) == 1) { + $route['app'] = $parts[0]; + } else { + $route['app'] = $parts[0]; + $route['slug'] = $parts[1]; + } + } + + return $route; + } + + /** + * Gets the users ip + */ + private function get_ip(): string { + $ip = ''; + if (!empty($_SERVER['HTTP_CLIENT_IP'])) { + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } else { + $ip = $_SERVER['REMOTE_ADDR']; + } + return $ip; + } + + /** + * Gets the curret request info + * @return array + */ + private function get_req(): array|bool { + $method = $_SERVER['REQUEST_METHOD']; + + $uri_str = $_SERVER['REQUEST_URI']; + $uri = parse_url($uri_str); + if (!$uri) { + return FALSE; + } + + $path = ''; + if (array_key_exists('path', $uri)) { + $path = $uri['path']; + } + + return array_merge( + array( + 'uri' => $uri, + 'uri_str' => $uri_str, + 'method' => $method, + 'ip' => $this->get_ip() + ), + $this->get_req_route($path), + ); + } + + /** + * Handles a router error code + * @param int $code - the http error code + * @param bool $recursed + */ + private function handle_error($code, $recursed): void { + if ($recursed) { + die($code . ' (recursed)'); + } + $uri_str = $_SERVER['REQUEST_URI']; + $req = array(); + $req['slug'] = 'index'; + $req['app'] = 'error'; + $req['uri_str'] = $uri_str; + $this->main->info = $req; + $_GET['code'] = $code; + $this->handle_req($req, TRUE); + } + + private function load_htc($req, $recursed): void { + $parts = explode('/', $req['uri_str']); + $file = end($parts); + $path = $GLOBALS['publicroot'] . '/polyfills/' . $file; + + if (file_exists($path)) { + header('Content-type: text/x-component'); + include($path); + } else { + $this->handle_error(400, $recursed); + } + } + + /** + * @param array $req + * @param bool $recursed + */ + private function handle_req($req, $recursed = FALSE): void { + + if ($recursed === false) { + if ( + $this->db_ready === false && + in_array($req['app'], $GLOBALS['serviceable']) === false + ) { + $this->handle_error(503, $recursed); + return; + } + + if ($this->check_banned($req)) { + $this->handle_error(401, $recursed); + return; + } + } + + if (!$req) { + $this->handle_error(500, $recursed); + return; + } + + if (str_ends_with($req['uri_str'], '.htc')) { + $this->load_htc($req, $recursed); + return; + } + + $controller = $this->load->controller($req['app']); + + if ($controller === NULL) { + $this->handle_error(404, $recursed); + return; + } + + $ref = NULL; + try { + $ref = new ReflectionMethod($controller, $req['slug']); + } catch (Exception $_e) {} + + if ($ref === NULL || !$ref->isPublic()) { + $this->handle_error(404, $recursed); + return; + + } + + $ref->invoke($controller); + } + + private function log_request($req): void { + if ( + $req === FALSE || + $this->db_ready === FALSE || + in_array($req['app'], $GLOBALS['serviceable']) + ) { + return; + } + + $query = $this->db + ->insert_into('admin.request_log', + 'ip', 'method', 'uri') + ->values( + $req['ip'], $req['method'], $req['uri_str']); + + $query->execute(); + } + + private function check_banned($req) { + $ip = FALSE; + if ($req) { + $ip = $req['ip']; + } else { + $ip = $this->get_ip(); + } + $query = $this->db + ->select('TRUE') + ->from('admin.banned') + ->where('ip')->eq($ip); + + return !!($query->row()); + } + + /** + * Handels the incomming reuqest + */ + public function handle_request(): void { + $req = $this->get_req(); + $this->log_request($req); + $this->main->info = $req; + $this->handle_req($req); + } + +} diff --git a/src/web/helpers/aria.php b/src/web/helpers/aria.php new file mode 100644 index 0000000..8ebfcc5 --- /dev/null +++ b/src/web/helpers/aria.php @@ -0,0 +1,16 @@ +', + $id, $idh); + $out .= sprintf('

%s

', + $idh, $title); + } else { + $out .= sprintf('
', + $id); + } + return $out; +} diff --git a/src/web/helpers/database.php b/src/web/helpers/database.php new file mode 100644 index 0000000..25cb5ba --- /dev/null +++ b/src/web/helpers/database.php @@ -0,0 +1,282 @@ +conn = $conn; + $this->query = ''; + + $this->set = FALSE; + $this->where = FALSE; + $this->param = array(); + } + + /// + /// ARBITRARY QUERY + /// + + public function query($query) { + $this->query .= $query; + return $this; + } + + /// + /// SELECT + /// + + public function select($select) { + $this->query .= "SELECT $select\n"; + return $this; + } + + public function from($from) { + $this->query .= "FROM $from\n"; + return $this; + } + + /// + /// INSERT + /// + + public function insert_into($insert, ...$columns) { + $this->query .= "INSERT INTO $insert\n ("; + foreach ($columns as $idx => $column) { + if ($idx !== 0) { + $this->query .= ","; + } + $this->query .= $column; + } + $this->query .= ")\n"; + return $this; + } + + public function values(...$values) { + $this->query .= "VALUES ("; + foreach ($values as $idx => $value) { + if ($idx !== 0) { + $this->query .= ","; + } + $this->query .= "?"; + array_push($this->param, $value); + } + $this->query .= ")\n"; + return $this; + } + + /// + /// WHERE + /// + + public function where($cond) { + if (!$this->where) { + $this->where = TRUE; + $this->query .= "WHERE "; + } else { + $this->query .= "AND "; + } + $this->query .= "$cond "; + return $this; + } + + public function where_in($column, $array) { + if (!$this->where) { + $this->where = TRUE; + $this->query .= "WHERE "; + } else { + $this->query .= "AND "; + } + if (empty($array)) { + $this->query .= "FALSE\n"; + return $this; + } + $in = $this->in($array); + $this->query .= "$column $in\n"; + return $this; + } + + private function in($array) { + $in = 'IN ('; + foreach ($array as $idx => $item) { + if ($idx != 0) { + $in .= ","; + } + $in .= "?"; + array_push($this->param, $item); + } + $in .= ")"; + return $in; + } + + /// + /// OPERATORS + /// + + public function like($item) { + $this->query .= "LIKE ?\n"; + array_push($this->param, $item); + return $this; + } + + public function eq($item) { + $this->query .= "= ?\n"; + array_push($this->param, $item); + return $this; + } + + public function ne($item) { + $this->query .= "<> ?\n"; + array_push($this->param, $item); + return $this; + } + + public function lt($item) { + $this->query .= "< ?\n"; + array_push($this->param, $item); + return $this; + } + + public function le($item) { + $this->query .= "<= ?\n"; + array_push($this->param, $item); + return $this; + } + + /// + /// JOINS + /// + + public function join($table, $on, $type = 'LEFT') { + $this->query .= "$type JOIN $table ON $on\n"; + return $this; + } + + /// + /// LIMIT, OFFSET, ORDER + /// + + public function limit($limit) { + $this->query .= "LIMIT ?\n"; + array_push($this->param, $limit); + return $this; + } + + public function offset($offset) { + $this->query .= "OFFSET ?\n"; + array_push($this->param, $offset); + return $this; + } + + public function order_by($column, $order = 'ASC') { + $this->query .= "ORDER BY " . $column . ' ' . $order . ' '; + return $this; + } + + /// + /// COLLECT + /// + + public function rows(...$params) { + $args = $this->param; + foreach ($params as $param) { + array_push($args, $param); + } + $stmt = $this->conn->prepare($this->query); + try { + $stmt->execute($args); + } catch (Exception $ex) { + echo $ex; + echo '
>> caused by <<
'; + echo str_replace("\n", "
", $this->query); + } + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + public function row(...$params) { + $args = $this->param; + foreach ($params as $param) { + array_push($args, $param); + } + $stmt = $this->conn->prepare($this->query); + $stmt->execute($args); + return $stmt->fetch(PDO::FETCH_ASSOC); + } + + public function execute(...$params) { + $args = $this->param; + foreach ($params as $param) { + array_push($args, $param); + } + $stmt = $this->conn->prepare($this->query); + try { + $stmt->execute($args); + return TRUE; + } catch (Exception $_e) { + echo $_e; + echo '
>> caused by <<
'; + echo str_replace("\n", "
", $this->query); + return FALSE; + } + } +} + +/** + * DatabaseHelper + * allows queries on the + * postgres database + */ +class DatabaseHelper { + + private $conn; + + function __construct() { + $this->conn = NULL; + } + + private function connect() { + if ($this->conn === NULL) { + $user = getenv("POSTGRES_USER"); + $pass = getenv("POSTGRES_PASSWORD"); + $db = getenv("POSTGRES_DB"); + $host = 'db'; + $port = '5432'; + + $conn_str = sprintf("pgsql:host=%s;port=%d;dbname=%s;user=%s;password=%s", + $host, + $port, + $db, + $user, + $pass + ); + $this->conn = new \PDO($conn_str); + $this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + } + return $this->conn; + } + + public function select($select) { + $conn = $this->connect(); + $query = new DatabaseQuery($conn); + return $query->select($select); + } + + public function insert_into($insert, ...$columns) { + $conn = $this->connect(); + $query = new DatabaseQuery($conn); + return $query->insert_into($insert, ...$columns); + } + + public function query($query_str) { + $conn = $this->connect(); + $query = new DatabaseQuery($conn); + return $query->query($query_str); + } +} + diff --git a/src/web/helpers/image.php b/src/web/helpers/image.php new file mode 100644 index 0000000..c18154a --- /dev/null +++ b/src/web/helpers/image.php @@ -0,0 +1,94 @@ +get_url('public/' . $name . '.' . $format); + $mime = __get_mime($format); + return sprintf('', + $mime, $path, $media); +} + +function image( + $name, + $alt, + $formats = array('webp', 'png'), + $animated = FALSE, + $attrs = array(), + + $height = NULL, + $width = NULL, + $size = NULL, +) :string { + + if ($animated === TRUE) { + $animated = array('gif'); + } + + if (!$animated) { + $animated = array(); + } + + $out = ""; + + foreach ($formats as $format) { + $media = count($animated) ? '(prefers-reduced-motion: reduce)' : NULL; + $out .= __make_source($name, $format, $media); + } + + foreach ($animated as $format) { + $out .= __make_source($name, $format, NULL); + } + + $format = end($formats); + $main = $GLOBALS['main_model']; + $path = $main->get_url('public/' . $name . '.' . $format); + $out .= " $value) { + $out .= " $key=\"$value\""; + } + $out .= '>'; + + return $out; +} diff --git a/src/web/helpers/lang.php b/src/web/helpers/lang.php new file mode 100644 index 0000000..e8fa29e --- /dev/null +++ b/src/web/helpers/lang.php @@ -0,0 +1,79 @@ + $attr) { + echo $key . '="' . $attr . '" '; + } + echo '> '; + if ($icon) { + echo ''; + if ($content) { + echo $content; + } + echo ''; + } + if ($text) { + echo '<' . $container; + if ($icon) { + echo ' class="ml-sm"'; + } + echo '>' . $text . ''; + } + if ($click || $button) { + echo ''; + } else { + echo ''; + } +} diff --git a/src/web/helpers/markdown.php b/src/web/helpers/markdown.php new file mode 100644 index 0000000..39b430c --- /dev/null +++ b/src/web/helpers/markdown.php @@ -0,0 +1,33 @@ +parsedown = new ParsedownExtra(); + } + + function parse($path) { + $content = file_get_contents($path); + $data = array( + 'meta' => array(), + 'content' => $content + ); + if (str_starts_with($content, '---')) { + $parts = explode('---', $content); + $data['content'] = trim(implode('---', array_slice($parts, 2))); + $meta = array_filter(explode("\n", $parts[1]), fn($x) => $x != ''); + foreach ($meta as $set) { + $parts = explode(": ", $set); + $key = trim($parts[0]); + $value = trim($parts[1]); + $data['meta'][$key] = $value; + } + + } + $data['content'] = $this->parsedown->text($data['content']); + return $data; + } + +} diff --git a/src/web/helpers/sanitize.php b/src/web/helpers/sanitize.php new file mode 100644 index 0000000..5d37852 --- /dev/null +++ b/src/web/helpers/sanitize.php @@ -0,0 +1,8 @@ +', '>', $data); + return $data; +} diff --git a/src/web/index.php b/src/web/index.php new file mode 100644 index 0000000..e33e750 --- /dev/null +++ b/src/web/index.php @@ -0,0 +1,38 @@ +handle_request(); +}; + +__init(); diff --git a/src/web/lang/apps/blog.php b/src/web/lang/apps/blog.php new file mode 100644 index 0000000..d860a8a --- /dev/null +++ b/src/web/lang/apps/blog.php @@ -0,0 +1,16 @@ +RSS feed.'; + +$lang['comments'] = 'Comments'; +$lang['no_comments'] = 'No comments'; +$lang['new_comment_title'] = 'New comment:'; +$lang['new_comment_author_ph'] = 'Identify yourself'; +$lang['new_comment_author_label'] = 'Name'; +$lang['new_comment_content_ph'] = 'Write the stuff'; +$lang['new_comment_content_label'] = 'Content'; +$lang['new_comment_submit_text'] = 'Post Comment'; diff --git a/src/web/lang/apps/error.php b/src/web/lang/apps/error.php new file mode 100644 index 0000000..79574b5 --- /dev/null +++ b/src/web/lang/apps/error.php @@ -0,0 +1,13 @@ + diff --git a/src/web/lang/apps/home.php b/src/web/lang/apps/home.php new file mode 100644 index 0000000..b3e3a16 --- /dev/null +++ b/src/web/lang/apps/home.php @@ -0,0 +1,35 @@ +RFC 9225 compliant.", + "JS free since always", + "Thank you for visiting the", + "footer text", + "If problems occur, stop doing the bad", + ":(){ :|: & };:", + "Approved by russian hackers", + "Shake well", + "Help im stuck inside footer text!", + "abort: no x11 display server found", +]; diff --git a/src/web/third_party/parsedown.php b/src/web/third_party/parsedown.php new file mode 100644 index 0000000..4d60658 --- /dev/null +++ b/src/web/third_party/parsedown.php @@ -0,0 +1,1995 @@ +textElements($text); + + # convert to markup + $markup = $this->elements($Elements); + + # trim line breaks + $markup = trim($markup, "\n"); + + return $markup; + } + + protected function textElements($text) + { + # make sure no definitions are set + $this->DefinitionData = array(); + + # standardize line breaks + $text = str_replace(array("\r\n", "\r"), "\n", $text); + + # remove surrounding line breaks + $text = trim($text, "\n"); + + # split text into lines + $lines = explode("\n", $text); + + # iterate through lines to identify blocks + return $this->linesElements($lines); + } + + # + # Setters + # + + function setBreaksEnabled($breaksEnabled) + { + $this->breaksEnabled = $breaksEnabled; + + return $this; + } + + protected $breaksEnabled; + + function setMarkupEscaped($markupEscaped) + { + $this->markupEscaped = $markupEscaped; + + return $this; + } + + protected $markupEscaped; + + function setUrlsLinked($urlsLinked) + { + $this->urlsLinked = $urlsLinked; + + return $this; + } + + protected $urlsLinked = true; + + function setSafeMode($safeMode) + { + $this->safeMode = (bool) $safeMode; + + return $this; + } + + protected $safeMode; + + function setStrictMode($strictMode) + { + $this->strictMode = (bool) $strictMode; + + return $this; + } + + protected $strictMode; + + protected $safeLinksWhitelist = array( + 'http://', + 'https://', + 'ftp://', + 'ftps://', + 'mailto:', + 'tel:', + 'data:image/png;base64,', + 'data:image/gif;base64,', + 'data:image/jpeg;base64,', + 'irc:', + 'ircs:', + 'git:', + 'ssh:', + 'news:', + 'steam:', + ); + + # + # Lines + # + + protected $BlockTypes = array( + '#' => array('Header'), + '*' => array('Rule', 'List'), + '+' => array('List'), + '-' => array('SetextHeader', 'Table', 'Rule', 'List'), + '0' => array('List'), + '1' => array('List'), + '2' => array('List'), + '3' => array('List'), + '4' => array('List'), + '5' => array('List'), + '6' => array('List'), + '7' => array('List'), + '8' => array('List'), + '9' => array('List'), + ':' => array('Table'), + '<' => array('Comment', 'Markup'), + '=' => array('SetextHeader'), + '>' => array('Quote'), + '[' => array('Reference'), + '_' => array('Rule'), + '`' => array('FencedCode'), + '|' => array('Table'), + '~' => array('FencedCode'), + ); + + # ~ + + protected $unmarkedBlockTypes = array( + 'Code', + ); + + # + # Blocks + # + + protected function lines(array $lines) + { + return $this->elements($this->linesElements($lines)); + } + + protected function linesElements(array $lines) + { + $Elements = array(); + $CurrentBlock = null; + + foreach ($lines as $line) + { + if (chop($line) === '') + { + if (isset($CurrentBlock)) + { + $CurrentBlock['interrupted'] = (isset($CurrentBlock['interrupted']) + ? $CurrentBlock['interrupted'] + 1 : 1 + ); + } + + continue; + } + + while (($beforeTab = strstr($line, "\t", true)) !== false) + { + $shortage = 4 - mb_strlen($beforeTab, 'utf-8') % 4; + + $line = $beforeTab + . str_repeat(' ', $shortage) + . substr($line, strlen($beforeTab) + 1) + ; + } + + $indent = strspn($line, ' '); + + $text = $indent > 0 ? substr($line, $indent) : $line; + + # ~ + + $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); + + # ~ + + if (isset($CurrentBlock['continuable'])) + { + $methodName = 'block' . $CurrentBlock['type'] . 'Continue'; + $Block = $this->$methodName($Line, $CurrentBlock); + + if (isset($Block)) + { + $CurrentBlock = $Block; + + continue; + } + else + { + if ($this->isBlockCompletable($CurrentBlock['type'])) + { + $methodName = 'block' . $CurrentBlock['type'] . 'Complete'; + $CurrentBlock = $this->$methodName($CurrentBlock); + } + } + } + + # ~ + + $marker = $text[0]; + + # ~ + + $blockTypes = $this->unmarkedBlockTypes; + + if (isset($this->BlockTypes[$marker])) + { + foreach ($this->BlockTypes[$marker] as $blockType) + { + $blockTypes []= $blockType; + } + } + + # + # ~ + + foreach ($blockTypes as $blockType) + { + $Block = $this->{"block$blockType"}($Line, $CurrentBlock); + + if (isset($Block)) + { + $Block['type'] = $blockType; + + if ( ! isset($Block['identified'])) + { + if (isset($CurrentBlock)) + { + $Elements[] = $this->extractElement($CurrentBlock); + } + + $Block['identified'] = true; + } + + if ($this->isBlockContinuable($blockType)) + { + $Block['continuable'] = true; + } + + $CurrentBlock = $Block; + + continue 2; + } + } + + # ~ + + if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph') + { + $Block = $this->paragraphContinue($Line, $CurrentBlock); + } + + if (isset($Block)) + { + $CurrentBlock = $Block; + } + else + { + if (isset($CurrentBlock)) + { + $Elements[] = $this->extractElement($CurrentBlock); + } + + $CurrentBlock = $this->paragraph($Line); + + $CurrentBlock['identified'] = true; + } + } + + # ~ + + if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type'])) + { + $methodName = 'block' . $CurrentBlock['type'] . 'Complete'; + $CurrentBlock = $this->$methodName($CurrentBlock); + } + + # ~ + + if (isset($CurrentBlock)) + { + $Elements[] = $this->extractElement($CurrentBlock); + } + + # ~ + + return $Elements; + } + + protected function extractElement(array $Component) + { + if ( ! isset($Component['element'])) + { + if (isset($Component['markup'])) + { + $Component['element'] = array('rawHtml' => $Component['markup']); + } + elseif (isset($Component['hidden'])) + { + $Component['element'] = array(); + } + } + + return $Component['element']; + } + + protected function isBlockContinuable($Type) + { + return method_exists($this, 'block' . $Type . 'Continue'); + } + + protected function isBlockCompletable($Type) + { + return method_exists($this, 'block' . $Type . 'Complete'); + } + + # + # Code + + protected function blockCode($Line, $Block = null) + { + if (isset($Block) and $Block['type'] === 'Paragraph' and ! isset($Block['interrupted'])) + { + return; + } + + if ($Line['indent'] >= 4) + { + $text = substr($Line['body'], 4); + + $Block = array( + 'element' => array( + 'name' => 'pre', + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ), + ); + + return $Block; + } + } + + protected function blockCodeContinue($Line, $Block) + { + if ($Line['indent'] >= 4) + { + if (isset($Block['interrupted'])) + { + $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); + + unset($Block['interrupted']); + } + + $Block['element']['element']['text'] .= "\n"; + + $text = substr($Line['body'], 4); + + $Block['element']['element']['text'] .= $text; + + return $Block; + } + } + + protected function blockCodeComplete($Block) + { + return $Block; + } + + # + # Comment + + protected function blockComment($Line) + { + if ($this->markupEscaped or $this->safeMode) + { + return; + } + + if (strpos($Line['text'], '') !== false) + { + $Block['closed'] = true; + } + + return $Block; + } + } + + protected function blockCommentContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + $Block['element']['rawHtml'] .= "\n" . $Line['body']; + + if (strpos($Line['text'], '-->') !== false) + { + $Block['closed'] = true; + } + + return $Block; + } + + # + # Fenced Code + + protected function blockFencedCode($Line) + { + $marker = $Line['text'][0]; + + $openerLength = strspn($Line['text'], $marker); + + if ($openerLength < 3) + { + return; + } + + $infostring = trim(substr($Line['text'], $openerLength), "\t "); + + if (strpos($infostring, '`') !== false) + { + return; + } + + $Element = array( + 'name' => 'code', + 'text' => '', + ); + + if ($infostring !== '') + { + /** + * https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * Every HTML element may have a class attribute specified. + * The attribute, if specified, must have a value that is a set + * of space-separated tokens representing the various classes + * that the element belongs to. + * [...] + * The space characters, for the purposes of this specification, + * are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), + * U+000A LINE FEED (LF), U+000C FORM FEED (FF), and + * U+000D CARRIAGE RETURN (CR). + */ + $language = substr($infostring, 0, strcspn($infostring, " \t\n\f\r")); + + $Element['attributes'] = array('class' => "language-$language"); + } + + $Block = array( + 'char' => $marker, + 'openerLength' => $openerLength, + 'element' => array( + 'name' => 'pre', + 'element' => $Element, + ), + ); + + return $Block; + } + + protected function blockFencedCodeContinue($Line, $Block) + { + if (isset($Block['complete'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); + + unset($Block['interrupted']); + } + + if (($len = strspn($Line['text'], $Block['char'])) >= $Block['openerLength'] + and chop(substr($Line['text'], $len), ' ') === '' + ) { + $Block['element']['element']['text'] = substr($Block['element']['element']['text'], 1); + + $Block['complete'] = true; + + return $Block; + } + + $Block['element']['element']['text'] .= "\n" . $Line['body']; + + return $Block; + } + + protected function blockFencedCodeComplete($Block) + { + return $Block; + } + + # + # Header + + protected function blockHeader($Line) + { + $level = strspn($Line['text'], '#'); + + if ($level > 6) + { + return; + } + + $text = trim($Line['text'], '#'); + + if ($this->strictMode and isset($text[0]) and $text[0] !== ' ') + { + return; + } + + $text = trim($text, ' '); + + $Block = array( + 'element' => array( + 'name' => 'h' . $level, + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $text, + 'destination' => 'elements', + ) + ), + ); + + return $Block; + } + + # + # List + + protected function blockList($Line, array $CurrentBlock = null) + { + list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]{1,9}+[.\)]'); + + if (preg_match('/^('.$pattern.'([ ]++|$))(.*+)/', $Line['text'], $matches)) + { + $contentIndent = strlen($matches[2]); + + if ($contentIndent >= 5) + { + $contentIndent -= 1; + $matches[1] = substr($matches[1], 0, -$contentIndent); + $matches[3] = str_repeat(' ', $contentIndent) . $matches[3]; + } + elseif ($contentIndent === 0) + { + $matches[1] .= ' '; + } + + $markerWithoutWhitespace = strstr($matches[1], ' ', true); + + $Block = array( + 'indent' => $Line['indent'], + 'pattern' => $pattern, + 'data' => array( + 'type' => $name, + 'marker' => $matches[1], + 'markerType' => ($name === 'ul' ? $markerWithoutWhitespace : substr($markerWithoutWhitespace, -1)), + ), + 'element' => array( + 'name' => $name, + 'elements' => array(), + ), + ); + $Block['data']['markerTypeRegex'] = preg_quote($Block['data']['markerType'], '/'); + + if ($name === 'ol') + { + $listStart = ltrim(strstr($matches[1], $Block['data']['markerType'], true), '0') ?: '0'; + + if ($listStart !== '1') + { + if ( + isset($CurrentBlock) + and $CurrentBlock['type'] === 'Paragraph' + and ! isset($CurrentBlock['interrupted']) + ) { + return; + } + + $Block['element']['attributes'] = array('start' => $listStart); + } + } + + $Block['li'] = array( + 'name' => 'li', + 'handler' => array( + 'function' => 'li', + 'argument' => !empty($matches[3]) ? array($matches[3]) : array(), + 'destination' => 'elements' + ) + ); + + $Block['element']['elements'] []= & $Block['li']; + + return $Block; + } + } + + protected function blockListContinue($Line, array $Block) + { + if (isset($Block['interrupted']) and empty($Block['li']['handler']['argument'])) + { + return null; + } + + $requiredIndent = ($Block['indent'] + strlen($Block['data']['marker'])); + + if ($Line['indent'] < $requiredIndent + and ( + ( + $Block['data']['type'] === 'ol' + and preg_match('/^[0-9]++'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches) + ) or ( + $Block['data']['type'] === 'ul' + and preg_match('/^'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches) + ) + ) + ) { + if (isset($Block['interrupted'])) + { + $Block['li']['handler']['argument'] []= ''; + + $Block['loose'] = true; + + unset($Block['interrupted']); + } + + unset($Block['li']); + + $text = isset($matches[1]) ? $matches[1] : ''; + + $Block['indent'] = $Line['indent']; + + $Block['li'] = array( + 'name' => 'li', + 'handler' => array( + 'function' => 'li', + 'argument' => array($text), + 'destination' => 'elements' + ) + ); + + $Block['element']['elements'] []= & $Block['li']; + + return $Block; + } + elseif ($Line['indent'] < $requiredIndent and $this->blockList($Line)) + { + return null; + } + + if ($Line['text'][0] === '[' and $this->blockReference($Line)) + { + return $Block; + } + + if ($Line['indent'] >= $requiredIndent) + { + if (isset($Block['interrupted'])) + { + $Block['li']['handler']['argument'] []= ''; + + $Block['loose'] = true; + + unset($Block['interrupted']); + } + + $text = substr($Line['body'], $requiredIndent); + + $Block['li']['handler']['argument'] []= $text; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $text = preg_replace('/^[ ]{0,'.$requiredIndent.'}+/', '', $Line['body']); + + $Block['li']['handler']['argument'] []= $text; + + return $Block; + } + } + + protected function blockListComplete(array $Block) + { + if (isset($Block['loose'])) + { + foreach ($Block['element']['elements'] as &$li) + { + if (end($li['handler']['argument']) !== '') + { + $li['handler']['argument'] []= ''; + } + } + } + + return $Block; + } + + # + # Quote + + protected function blockQuote($Line) + { + if (preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) + { + $Block = array( + 'element' => array( + 'name' => 'blockquote', + 'handler' => array( + 'function' => 'linesElements', + 'argument' => (array) $matches[1], + 'destination' => 'elements', + ) + ), + ); + + return $Block; + } + } + + protected function blockQuoteContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + if ($Line['text'][0] === '>' and preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) + { + $Block['element']['handler']['argument'] []= $matches[1]; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $Block['element']['handler']['argument'] []= $Line['text']; + + return $Block; + } + } + + # + # Rule + + protected function blockRule($Line) + { + $marker = $Line['text'][0]; + + if (substr_count($Line['text'], $marker) >= 3 and chop($Line['text'], " $marker") === '') + { + $Block = array( + 'element' => array( + 'name' => 'hr', + ), + ); + + return $Block; + } + } + + # + # Setext + + protected function blockSetextHeader($Line, array $Block = null) + { + if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) + { + return; + } + + if ($Line['indent'] < 4 and chop(chop($Line['text'], ' '), $Line['text'][0]) === '') + { + $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; + + return $Block; + } + } + + # + # Markup + + protected function blockMarkup($Line) + { + if ($this->markupEscaped or $this->safeMode) + { + return; + } + + if (preg_match('/^<[\/]?+(\w*)(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+(\/)?>/', $Line['text'], $matches)) + { + $element = strtolower($matches[1]); + + if (in_array($element, $this->textLevelElements)) + { + return; + } + + $Block = array( + 'name' => $matches[1], + 'element' => array( + 'rawHtml' => $Line['text'], + 'autobreak' => true, + ), + ); + + return $Block; + } + } + + protected function blockMarkupContinue($Line, array $Block) + { + if (isset($Block['closed']) or isset($Block['interrupted'])) + { + return; + } + + $Block['element']['rawHtml'] .= "\n" . $Line['body']; + + return $Block; + } + + # + # Reference + + protected function blockReference($Line) + { + if (strpos($Line['text'], ']') !== false + and preg_match('/^\[(.+?)\]:[ ]*+?(?:[ ]+["\'(](.+)["\')])?[ ]*+$/', $Line['text'], $matches) + ) { + $id = strtolower($matches[1]); + + $Data = array( + 'url' => $matches[2], + 'title' => isset($matches[3]) ? $matches[3] : null, + ); + + $this->DefinitionData['Reference'][$id] = $Data; + + $Block = array( + 'element' => array(), + ); + + return $Block; + } + } + + # + # Table + + protected function blockTable($Line, array $Block = null) + { + if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) + { + return; + } + + if ( + strpos($Block['element']['handler']['argument'], '|') === false + and strpos($Line['text'], '|') === false + and strpos($Line['text'], ':') === false + or strpos($Block['element']['handler']['argument'], "\n") !== false + ) { + return; + } + + if (chop($Line['text'], ' -:|') !== '') + { + return; + } + + $alignments = array(); + + $divider = $Line['text']; + + $divider = trim($divider); + $divider = trim($divider, '|'); + + $dividerCells = explode('|', $divider); + + foreach ($dividerCells as $dividerCell) + { + $dividerCell = trim($dividerCell); + + if ($dividerCell === '') + { + return; + } + + $alignment = null; + + if ($dividerCell[0] === ':') + { + $alignment = 'left'; + } + + if (substr($dividerCell, - 1) === ':') + { + $alignment = $alignment === 'left' ? 'center' : 'right'; + } + + $alignments []= $alignment; + } + + # ~ + + $HeaderElements = array(); + + $header = $Block['element']['handler']['argument']; + + $header = trim($header); + $header = trim($header, '|'); + + $headerCells = explode('|', $header); + + if (count($headerCells) !== count($alignments)) + { + return; + } + + foreach ($headerCells as $index => $headerCell) + { + $headerCell = trim($headerCell); + + $HeaderElement = array( + 'name' => 'th', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $headerCell, + 'destination' => 'elements', + ) + ); + + if (isset($alignments[$index])) + { + $alignment = $alignments[$index]; + + $HeaderElement['attributes'] = array( + 'style' => "text-align: $alignment;", + ); + } + + $HeaderElements []= $HeaderElement; + } + + # ~ + + $Block = array( + 'alignments' => $alignments, + 'identified' => true, + 'element' => array( + 'name' => 'table', + 'elements' => array(), + ), + ); + + $Block['element']['elements'] []= array( + 'name' => 'thead', + ); + + $Block['element']['elements'] []= array( + 'name' => 'tbody', + 'elements' => array(), + ); + + $Block['element']['elements'][0]['elements'] []= array( + 'name' => 'tr', + 'elements' => $HeaderElements, + ); + + return $Block; + } + + protected function blockTableContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + if (count($Block['alignments']) === 1 or $Line['text'][0] === '|' or strpos($Line['text'], '|')) + { + $Elements = array(); + + $row = $Line['text']; + + $row = trim($row); + $row = trim($row, '|'); + + preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches); + + $cells = array_slice($matches[0], 0, count($Block['alignments'])); + + foreach ($cells as $index => $cell) + { + $cell = trim($cell); + + $Element = array( + 'name' => 'td', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $cell, + 'destination' => 'elements', + ) + ); + + if (isset($Block['alignments'][$index])) + { + $Element['attributes'] = array( + 'style' => 'text-align: ' . $Block['alignments'][$index] . ';', + ); + } + + $Elements []= $Element; + } + + $Element = array( + 'name' => 'tr', + 'elements' => $Elements, + ); + + $Block['element']['elements'][1]['elements'] []= $Element; + + return $Block; + } + } + + # + # ~ + # + + protected function paragraph($Line) + { + return array( + 'type' => 'Paragraph', + 'element' => array( + 'name' => 'p', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $Line['text'], + 'destination' => 'elements', + ), + ), + ); + } + + protected function paragraphContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + $Block['element']['handler']['argument'] .= "\n".$Line['text']; + + return $Block; + } + + # + # Inline Elements + # + + protected $InlineTypes = array( + '!' => array('Image'), + '&' => array('SpecialCharacter'), + '*' => array('Emphasis'), + ':' => array('Url'), + '<' => array('UrlTag', 'EmailTag', 'Markup'), + '[' => array('Link'), + '_' => array('Emphasis'), + '`' => array('Code'), + '~' => array('Strikethrough'), + '\\' => array('EscapeSequence'), + ); + + # ~ + + protected $inlineMarkerList = '!*_&[:<`~\\'; + + # + # ~ + # + + public function line($text, $nonNestables = array()) + { + return $this->elements($this->lineElements($text, $nonNestables)); + } + + protected function lineElements($text, $nonNestables = array()) + { + # standardize line breaks + $text = str_replace(array("\r\n", "\r"), "\n", $text); + + $Elements = array(); + + $nonNestables = (empty($nonNestables) + ? array() + : array_combine($nonNestables, $nonNestables) + ); + + # $excerpt is based on the first occurrence of a marker + + while ($excerpt = strpbrk($text, $this->inlineMarkerList)) + { + $marker = $excerpt[0]; + + $markerPosition = strlen($text) - strlen($excerpt); + + $Excerpt = array('text' => $excerpt, 'context' => $text); + + foreach ($this->InlineTypes[$marker] as $inlineType) + { + # check to see if the current inline type is nestable in the current context + + if (isset($nonNestables[$inlineType])) + { + continue; + } + + $Inline = $this->{"inline$inlineType"}($Excerpt); + + if ( ! isset($Inline)) + { + continue; + } + + # makes sure that the inline belongs to "our" marker + + if (isset($Inline['position']) and $Inline['position'] > $markerPosition) + { + continue; + } + + # sets a default inline position + + if ( ! isset($Inline['position'])) + { + $Inline['position'] = $markerPosition; + } + + # cause the new element to 'inherit' our non nestables + + + $Inline['element']['nonNestables'] = isset($Inline['element']['nonNestables']) + ? array_merge($Inline['element']['nonNestables'], $nonNestables) + : $nonNestables + ; + + # the text that comes before the inline + $unmarkedText = substr($text, 0, $Inline['position']); + + # compile the unmarked text + $InlineText = $this->inlineText($unmarkedText); + $Elements[] = $InlineText['element']; + + # compile the inline + $Elements[] = $this->extractElement($Inline); + + # remove the examined text + $text = substr($text, $Inline['position'] + $Inline['extent']); + + continue 2; + } + + # the marker does not belong to an inline + + $unmarkedText = substr($text, 0, $markerPosition + 1); + + $InlineText = $this->inlineText($unmarkedText); + $Elements[] = $InlineText['element']; + + $text = substr($text, $markerPosition + 1); + } + + $InlineText = $this->inlineText($text); + $Elements[] = $InlineText['element']; + + foreach ($Elements as &$Element) + { + if ( ! isset($Element['autobreak'])) + { + $Element['autobreak'] = false; + } + } + + return $Elements; + } + + # + # ~ + # + + protected function inlineText($text) + { + $Inline = array( + 'extent' => strlen($text), + 'element' => array(), + ); + + $Inline['element']['elements'] = self::pregReplaceElements( + $this->breaksEnabled ? '/[ ]*+\n/' : '/(?:[ ]*+\\\\|[ ]{2,}+)\n/', + array( + array('name' => 'br'), + array('text' => "\n"), + ), + $text + ); + + return $Inline; + } + + protected function inlineCode($Excerpt) + { + $marker = $Excerpt['text'][0]; + + if (preg_match('/^(['.$marker.']++)[ ]*+(.+?)[ ]*+(? strlen($matches[0]), + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ); + } + } + + protected function inlineEmailTag($Excerpt) + { + $hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'; + + $commonMarkEmail = '[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]++@' + . $hostnameLabel . '(?:\.' . $hostnameLabel . ')*'; + + if (strpos($Excerpt['text'], '>') !== false + and preg_match("/^<((mailto:)?$commonMarkEmail)>/i", $Excerpt['text'], $matches) + ){ + $url = $matches[1]; + + if ( ! isset($matches[2])) + { + $url = "mailto:$url"; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $matches[1], + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + protected function inlineEmphasis($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + $marker = $Excerpt['text'][0]; + + if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'strong'; + } + elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'em'; + } + else + { + return; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => $emphasis, + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $matches[1], + 'destination' => 'elements', + ) + ), + ); + } + + protected function inlineEscapeSequence($Excerpt) + { + if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) + { + return array( + 'element' => array('rawHtml' => $Excerpt['text'][1]), + 'extent' => 2, + ); + } + } + + protected function inlineImage($Excerpt) + { + if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') + { + return; + } + + $Excerpt['text']= substr($Excerpt['text'], 1); + + $Link = $this->inlineLink($Excerpt); + + if ($Link === null) + { + return; + } + + $Inline = array( + 'extent' => $Link['extent'] + 1, + 'element' => array( + 'name' => 'img', + 'attributes' => array( + 'src' => $Link['element']['attributes']['href'], + 'alt' => $Link['element']['handler']['argument'], + ), + 'autobreak' => true, + ), + ); + + $Inline['element']['attributes'] += $Link['element']['attributes']; + + unset($Inline['element']['attributes']['href']); + + return $Inline; + } + + protected function inlineLink($Excerpt) + { + $Element = array( + 'name' => 'a', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => null, + 'destination' => 'elements', + ), + 'nonNestables' => array('Url', 'Link'), + 'attributes' => array( + 'href' => null, + 'title' => null, + ), + ); + + $extent = 0; + + $remainder = $Excerpt['text']; + + if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches)) + { + $Element['handler']['argument'] = $matches[1]; + + $extent += strlen($matches[0]); + + $remainder = substr($remainder, $extent); + } + else + { + return; + } + + if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*+"|\'[^\']*+\'))?\s*+[)]/', $remainder, $matches)) + { + $Element['attributes']['href'] = $matches[1]; + + if (isset($matches[2])) + { + $Element['attributes']['title'] = substr($matches[2], 1, - 1); + } + + $extent += strlen($matches[0]); + } + else + { + if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) + { + $definition = strlen($matches[1]) ? $matches[1] : $Element['handler']['argument']; + $definition = strtolower($definition); + + $extent += strlen($matches[0]); + } + else + { + $definition = strtolower($Element['handler']['argument']); + } + + if ( ! isset($this->DefinitionData['Reference'][$definition])) + { + return; + } + + $Definition = $this->DefinitionData['Reference'][$definition]; + + $Element['attributes']['href'] = $Definition['url']; + $Element['attributes']['title'] = $Definition['title']; + } + + return array( + 'extent' => $extent, + 'element' => $Element, + ); + } + + protected function inlineMarkup($Excerpt) + { + if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false) + { + return; + } + + if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w[\w-]*+[ ]*+>/s', $Excerpt['text'], $matches)) + { + return array( + 'element' => array('rawHtml' => $matches[0]), + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] === '!' and preg_match('/^/s', $Excerpt['text'], $matches)) + { + return array( + 'element' => array('rawHtml' => $matches[0]), + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w[\w-]*+(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+\/?>/s', $Excerpt['text'], $matches)) + { + return array( + 'element' => array('rawHtml' => $matches[0]), + 'extent' => strlen($matches[0]), + ); + } + } + + protected function inlineSpecialCharacter($Excerpt) + { + if (substr($Excerpt['text'], 1, 1) !== ' ' and strpos($Excerpt['text'], ';') !== false + and preg_match('/^&(#?+[0-9a-zA-Z]++);/', $Excerpt['text'], $matches) + ) { + return array( + 'element' => array('rawHtml' => '&' . $matches[1] . ';'), + 'extent' => strlen($matches[0]), + ); + } + + return; + } + + protected function inlineStrikethrough($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) + { + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'del', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $matches[1], + 'destination' => 'elements', + ) + ), + ); + } + } + + protected function inlineUrl($Excerpt) + { + if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') + { + return; + } + + if (strpos($Excerpt['context'], 'http') !== false + and preg_match('/\bhttps?+:[\/]{2}[^\s<]+\b\/*+/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE) + ) { + $url = $matches[0][0]; + + $Inline = array( + 'extent' => strlen($matches[0][0]), + 'position' => $matches[0][1], + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + + return $Inline; + } + } + + protected function inlineUrlTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w++:\/{2}[^ >]++)>/i', $Excerpt['text'], $matches)) + { + $url = $matches[1]; + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + # ~ + + protected function unmarkedText($text) + { + $Inline = $this->inlineText($text); + return $this->element($Inline['element']); + } + + # + # Handlers + # + + protected function handle(array $Element) + { + if (isset($Element['handler'])) + { + if (!isset($Element['nonNestables'])) + { + $Element['nonNestables'] = array(); + } + + if (is_string($Element['handler'])) + { + $function = $Element['handler']; + $argument = $Element['text']; + unset($Element['text']); + $destination = 'rawHtml'; + } + else + { + $function = $Element['handler']['function']; + $argument = $Element['handler']['argument']; + $destination = $Element['handler']['destination']; + } + + $Element[$destination] = $this->{$function}($argument, $Element['nonNestables']); + + if ($destination === 'handler') + { + $Element = $this->handle($Element); + } + + unset($Element['handler']); + } + + return $Element; + } + + protected function handleElementRecursive(array $Element) + { + return $this->elementApplyRecursive(array($this, 'handle'), $Element); + } + + protected function handleElementsRecursive(array $Elements) + { + return $this->elementsApplyRecursive(array($this, 'handle'), $Elements); + } + + protected function elementApplyRecursive($closure, array $Element) + { + $Element = call_user_func($closure, $Element); + + if (isset($Element['elements'])) + { + $Element['elements'] = $this->elementsApplyRecursive($closure, $Element['elements']); + } + elseif (isset($Element['element'])) + { + $Element['element'] = $this->elementApplyRecursive($closure, $Element['element']); + } + + return $Element; + } + + protected function elementApplyRecursiveDepthFirst($closure, array $Element) + { + if (isset($Element['elements'])) + { + $Element['elements'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['elements']); + } + elseif (isset($Element['element'])) + { + $Element['element'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['element']); + } + + $Element = call_user_func($closure, $Element); + + return $Element; + } + + protected function elementsApplyRecursive($closure, array $Elements) + { + foreach ($Elements as &$Element) + { + $Element = $this->elementApplyRecursive($closure, $Element); + } + + return $Elements; + } + + protected function elementsApplyRecursiveDepthFirst($closure, array $Elements) + { + foreach ($Elements as &$Element) + { + $Element = $this->elementApplyRecursiveDepthFirst($closure, $Element); + } + + return $Elements; + } + + protected function element(array $Element) + { + if ($this->safeMode) + { + $Element = $this->sanitiseElement($Element); + } + + # identity map if element has no handler + $Element = $this->handle($Element); + + $hasName = isset($Element['name']); + + $markup = ''; + + if ($hasName) + { + $markup .= '<' . $Element['name']; + + if (isset($Element['attributes'])) + { + foreach ($Element['attributes'] as $name => $value) + { + if ($value === null) + { + continue; + } + + $markup .= " $name=\"".self::escape($value).'"'; + } + } + } + + $permitRawHtml = false; + + if (isset($Element['text'])) + { + $text = $Element['text']; + } + // very strongly consider an alternative if you're writing an + // extension + elseif (isset($Element['rawHtml'])) + { + $text = $Element['rawHtml']; + + $allowRawHtmlInSafeMode = isset($Element['allowRawHtmlInSafeMode']) && $Element['allowRawHtmlInSafeMode']; + $permitRawHtml = !$this->safeMode || $allowRawHtmlInSafeMode; + } + + $hasContent = isset($text) || isset($Element['element']) || isset($Element['elements']); + + if ($hasContent) + { + $markup .= $hasName ? '>' : ''; + + if (isset($Element['elements'])) + { + $markup .= $this->elements($Element['elements']); + } + elseif (isset($Element['element'])) + { + $markup .= $this->element($Element['element']); + } + else + { + if (!$permitRawHtml) + { + $markup .= self::escape($text, true); + } + else + { + $markup .= $text; + } + } + + $markup .= $hasName ? '' : ''; + } + elseif ($hasName) + { + $markup .= ' />'; + } + + return $markup; + } + + protected function elements(array $Elements) + { + $markup = ''; + + $autoBreak = true; + + foreach ($Elements as $Element) + { + if (empty($Element)) + { + continue; + } + + $autoBreakNext = (isset($Element['autobreak']) + ? $Element['autobreak'] : isset($Element['name']) + ); + // (autobreak === false) covers both sides of an element + $autoBreak = !$autoBreak ? $autoBreak : $autoBreakNext; + + $markup .= ($autoBreak ? "\n" : '') . $this->element($Element); + $autoBreak = $autoBreakNext; + } + + $markup .= $autoBreak ? "\n" : ''; + + return $markup; + } + + # ~ + + protected function li($lines) + { + $Elements = $this->linesElements($lines); + + if ( ! in_array('', $lines) + and isset($Elements[0]) and isset($Elements[0]['name']) + and $Elements[0]['name'] === 'p' + ) { + unset($Elements[0]['name']); + } + + return $Elements; + } + + # + # AST Convenience + # + + /** + * Replace occurrences $regexp with $Elements in $text. Return an array of + * elements representing the replacement. + */ + protected static function pregReplaceElements($regexp, $Elements, $text) + { + $newElements = array(); + + while (preg_match($regexp, $text, $matches, PREG_OFFSET_CAPTURE)) + { + $offset = $matches[0][1]; + $before = substr($text, 0, $offset); + $after = substr($text, $offset + strlen($matches[0][0])); + + $newElements[] = array('text' => $before); + + foreach ($Elements as $Element) + { + $newElements[] = $Element; + } + + $text = $after; + } + + $newElements[] = array('text' => $text); + + return $newElements; + } + + # + # Deprecated Methods + # + + function parse($text) + { + $markup = $this->text($text); + + return $markup; + } + + protected function sanitiseElement(array $Element) + { + static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/'; + static $safeUrlNameToAtt = array( + 'a' => 'href', + 'img' => 'src', + ); + + if ( ! isset($Element['name'])) + { + unset($Element['attributes']); + return $Element; + } + + if (isset($safeUrlNameToAtt[$Element['name']])) + { + $Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]); + } + + if ( ! empty($Element['attributes'])) + { + foreach ($Element['attributes'] as $att => $val) + { + # filter out badly parsed attribute + if ( ! preg_match($goodAttribute, $att)) + { + unset($Element['attributes'][$att]); + } + # dump onevent attribute + elseif (self::striAtStart($att, 'on')) + { + unset($Element['attributes'][$att]); + } + } + } + + return $Element; + } + + protected function filterUnsafeUrlInAttribute(array $Element, $attribute) + { + foreach ($this->safeLinksWhitelist as $scheme) + { + if (self::striAtStart($Element['attributes'][$attribute], $scheme)) + { + return $Element; + } + } + + $Element['attributes'][$attribute] = str_replace(':', '%3A', $Element['attributes'][$attribute]); + + return $Element; + } + + # + # Static Methods + # + + protected static function escape($text, $allowQuotes = false) + { + return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8'); + } + + protected static function striAtStart($string, $needle) + { + $len = strlen($needle); + + if ($len > strlen($string)) + { + return false; + } + else + { + return strtolower(substr($string, 0, $len)) === strtolower($needle); + } + } + + static function instance($name = 'default') + { + if (isset(self::$instances[$name])) + { + return self::$instances[$name]; + } + + $instance = new static(); + + self::$instances[$name] = $instance; + + return $instance; + } + + private static $instances = array(); + + # + # Fields + # + + protected $DefinitionData; + + # + # Read-Only + + protected $specialCharacters = array( + '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', '~' + ); + + protected $StrongRegex = array( + '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s', + '_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us', + ); + + protected $EmRegex = array( + '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', + '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us', + ); + + protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+'; + + protected $voidElements = array( + 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', + ); + + protected $textLevelElements = array( + 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', + 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', + 'i', 'rp', 'del', 'code', 'strike', 'marquee', + 'q', 'rt', 'ins', 'font', 'strong', + 's', 'tt', 'kbd', 'mark', + 'u', 'xm', 'sub', 'nobr', + 'sup', 'ruby', + 'var', 'span', + 'wbr', 'time', + ); +} + diff --git a/src/web/third_party/parsedown_extra.php b/src/web/third_party/parsedown_extra.php new file mode 100644 index 0000000..8cdb5d2 --- /dev/null +++ b/src/web/third_party/parsedown_extra.php @@ -0,0 +1,686 @@ +BlockTypes[':'] []= 'DefinitionList'; + $this->BlockTypes['*'] []= 'Abbreviation'; + + # identify footnote definitions before reference definitions + array_unshift($this->BlockTypes['['], 'Footnote'); + + # identify footnote markers before before links + array_unshift($this->InlineTypes['['], 'FootnoteMarker'); + } + + # + # ~ + + function text($text) + { + $Elements = $this->textElements($text); + + # convert to markup + $markup = $this->elements($Elements); + + # trim line breaks + $markup = trim($markup, "\n"); + + # merge consecutive dl elements + + $markup = preg_replace('/<\/dl>\s+
\s+/', '', $markup); + + # add footnotes + + if (isset($this->DefinitionData['Footnote'])) + { + $Element = $this->buildFootnoteElement(); + + $markup .= "\n" . $this->element($Element); + } + + return $markup; + } + + # + # Blocks + # + + # + # Abbreviation + + protected function blockAbbreviation($Line) + { + if (preg_match('/^\*\[(.+?)\]:[ ]*(.+?)[ ]*$/', $Line['text'], $matches)) + { + $this->DefinitionData['Abbreviation'][$matches[1]] = $matches[2]; + + $Block = array( + 'hidden' => true, + ); + + return $Block; + } + } + + # + # Footnote + + protected function blockFootnote($Line) + { + if (preg_match('/^\[\^(.+?)\]:[ ]?(.*)$/', $Line['text'], $matches)) + { + $Block = array( + 'label' => $matches[1], + 'text' => $matches[2], + 'hidden' => true, + ); + + return $Block; + } + } + + protected function blockFootnoteContinue($Line, $Block) + { + if ($Line['text'][0] === '[' and preg_match('/^\[\^(.+?)\]:/', $Line['text'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + if ($Line['indent'] >= 4) + { + $Block['text'] .= "\n\n" . $Line['text']; + + return $Block; + } + } + else + { + $Block['text'] .= "\n" . $Line['text']; + + return $Block; + } + } + + protected function blockFootnoteComplete($Block) + { + $this->DefinitionData['Footnote'][$Block['label']] = array( + 'text' => $Block['text'], + 'count' => null, + 'number' => null, + ); + + return $Block; + } + + # + # Definition List + + protected function blockDefinitionList($Line, $Block) + { + if ( ! isset($Block) or $Block['type'] !== 'Paragraph') + { + return; + } + + $Element = array( + 'name' => 'dl', + 'elements' => array(), + ); + + $terms = explode("\n", $Block['element']['handler']['argument']); + + foreach ($terms as $term) + { + $Element['elements'] []= array( + 'name' => 'dt', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $term, + 'destination' => 'elements' + ), + ); + } + + $Block['element'] = $Element; + + $Block = $this->addDdElement($Line, $Block); + + return $Block; + } + + protected function blockDefinitionListContinue($Line, array $Block) + { + if ($Line['text'][0] === ':') + { + $Block = $this->addDdElement($Line, $Block); + + return $Block; + } + else + { + if (isset($Block['interrupted']) and $Line['indent'] === 0) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['dd']['handler']['function'] = 'textElements'; + $Block['dd']['handler']['argument'] .= "\n\n"; + + $Block['dd']['handler']['destination'] = 'elements'; + + unset($Block['interrupted']); + } + + $text = substr($Line['body'], min($Line['indent'], 4)); + + $Block['dd']['handler']['argument'] .= "\n" . $text; + + return $Block; + } + } + + # + # Header + + protected function blockHeader($Line) + { + $Block = parent::blockHeader($Line); + + if ($Block !== null && preg_match('/[ #]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) + { + $attributeString = $matches[1][0]; + + $Block['element']['attributes'] = $this->parseAttributeData($attributeString); + + $Block['element']['handler']['argument'] = substr($Block['element']['handler']['argument'], 0, $matches[0][1]); + } + + return $Block; + } + + # + # Markup + + protected function blockMarkup($Line) + { + if ($this->markupEscaped or $this->safeMode) + { + return; + } + + if (preg_match('/^<(\w[\w-]*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) + { + $element = strtolower($matches[1]); + + if (in_array($element, $this->textLevelElements)) + { + return; + } + + $Block = array( + 'name' => $matches[1], + 'depth' => 0, + 'element' => array( + 'rawHtml' => $Line['text'], + 'autobreak' => true, + ), + ); + + $length = strlen($matches[0]); + $remainder = substr($Line['text'], $length); + + if (trim($remainder) === '') + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + $Block['closed'] = true; + $Block['void'] = true; + } + } + else + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + return; + } + if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) + { + $Block['closed'] = true; + } + } + + return $Block; + } + } + + protected function blockMarkupContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open + { + $Block['depth'] ++; + } + + if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close + { + if ($Block['depth'] > 0) + { + $Block['depth'] --; + } + else + { + $Block['closed'] = true; + } + } + + if (isset($Block['interrupted'])) + { + $Block['element']['rawHtml'] .= "\n"; + unset($Block['interrupted']); + } + + $Block['element']['rawHtml'] .= "\n".$Line['body']; + + return $Block; + } + + protected function blockMarkupComplete($Block) + { + if ( ! isset($Block['void'])) + { + $Block['element']['rawHtml'] = $this->processTag($Block['element']['rawHtml']); + } + + return $Block; + } + + # + # Setext + + protected function blockSetextHeader($Line, array $Block = null) + { + $Block = parent::blockSetextHeader($Line, $Block); + + if ($Block !== null && preg_match('/[ ]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) + { + $attributeString = $matches[1][0]; + + $Block['element']['attributes'] = $this->parseAttributeData($attributeString); + + $Block['element']['handler']['argument'] = substr($Block['element']['handler']['argument'], 0, $matches[0][1]); + } + + return $Block; + } + + # + # Inline Elements + # + + # + # Footnote Marker + + protected function inlineFootnoteMarker($Excerpt) + { + if (preg_match('/^\[\^(.+?)\]/', $Excerpt['text'], $matches)) + { + $name = $matches[1]; + + if ( ! isset($this->DefinitionData['Footnote'][$name])) + { + return; + } + + $this->DefinitionData['Footnote'][$name]['count'] ++; + + if ( ! isset($this->DefinitionData['Footnote'][$name]['number'])) + { + $this->DefinitionData['Footnote'][$name]['number'] = ++ $this->footnoteCount; # » & + } + + $Element = array( + 'name' => 'sup', + 'attributes' => array('id' => 'fnref'.$this->DefinitionData['Footnote'][$name]['count'].':'.$name), + 'element' => array( + 'name' => 'a', + 'attributes' => array('href' => '#fn:'.$name, 'class' => 'footnote-ref'), + 'text' => $this->DefinitionData['Footnote'][$name]['number'], + ), + ); + + return array( + 'extent' => strlen($matches[0]), + 'element' => $Element, + ); + } + } + + private $footnoteCount = 0; + + # + # Link + + protected function inlineLink($Excerpt) + { + $Link = parent::inlineLink($Excerpt); + + $remainder = $Link !== null ? substr($Excerpt['text'], $Link['extent']) : ''; + + if (preg_match('/^[ ]*{('.$this->regexAttribute.'+)}/', $remainder, $matches)) + { + $Link['element']['attributes'] += $this->parseAttributeData($matches[1]); + + $Link['extent'] += strlen($matches[0]); + } + + return $Link; + } + + # + # ~ + # + + private $currentAbreviation; + private $currentMeaning; + + protected function insertAbreviation(array $Element) + { + if (isset($Element['text'])) + { + $Element['elements'] = self::pregReplaceElements( + '/\b'.preg_quote($this->currentAbreviation, '/').'\b/', + array( + array( + 'name' => 'abbr', + 'attributes' => array( + 'title' => $this->currentMeaning, + ), + 'text' => $this->currentAbreviation, + ) + ), + $Element['text'] + ); + + unset($Element['text']); + } + + return $Element; + } + + protected function inlineText($text) + { + $Inline = parent::inlineText($text); + + if (isset($this->DefinitionData['Abbreviation'])) + { + foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning) + { + $this->currentAbreviation = $abbreviation; + $this->currentMeaning = $meaning; + + $Inline['element'] = $this->elementApplyRecursiveDepthFirst( + array($this, 'insertAbreviation'), + $Inline['element'] + ); + } + } + + return $Inline; + } + + # + # Util Methods + # + + protected function addDdElement(array $Line, array $Block) + { + $text = substr($Line['text'], 1); + $text = trim($text); + + unset($Block['dd']); + + $Block['dd'] = array( + 'name' => 'dd', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $text, + 'destination' => 'elements' + ), + ); + + if (isset($Block['interrupted'])) + { + $Block['dd']['handler']['function'] = 'textElements'; + + unset($Block['interrupted']); + } + + $Block['element']['elements'] []= & $Block['dd']; + + return $Block; + } + + protected function buildFootnoteElement() + { + $Element = array( + 'name' => 'div', + 'attributes' => array('class' => 'footnotes'), + 'elements' => array( + array('name' => 'hr'), + array( + 'name' => 'ol', + 'elements' => array(), + ), + ), + ); + + uasort($this->DefinitionData['Footnote'], 'self::sortFootnotes'); + + foreach ($this->DefinitionData['Footnote'] as $definitionId => $DefinitionData) + { + if ( ! isset($DefinitionData['number'])) + { + continue; + } + + $text = $DefinitionData['text']; + + $textElements = parent::textElements($text); + + $numbers = range(1, $DefinitionData['count']); + + $backLinkElements = array(); + + foreach ($numbers as $number) + { + $backLinkElements[] = array('text' => ' '); + $backLinkElements[] = array( + 'name' => 'a', + 'attributes' => array( + 'href' => "#fnref$number:$definitionId", + 'rev' => 'footnote', + 'class' => 'footnote-backref', + ), + 'rawHtml' => '↩', + 'allowRawHtmlInSafeMode' => true, + 'autobreak' => false, + ); + } + + unset($backLinkElements[0]); + + $n = count($textElements) -1; + + if ($textElements[$n]['name'] === 'p') + { + $backLinkElements = array_merge( + array( + array( + 'rawHtml' => ' ', + 'allowRawHtmlInSafeMode' => true, + ), + ), + $backLinkElements + ); + + unset($textElements[$n]['name']); + + $textElements[$n] = array( + 'name' => 'p', + 'elements' => array_merge( + array($textElements[$n]), + $backLinkElements + ), + ); + } + else + { + $textElements[] = array( + 'name' => 'p', + 'elements' => $backLinkElements + ); + } + + $Element['elements'][1]['elements'] []= array( + 'name' => 'li', + 'attributes' => array('id' => 'fn:'.$definitionId), + 'elements' => array_merge( + $textElements + ), + ); + } + + return $Element; + } + + # ~ + + protected function parseAttributeData($attributeString) + { + $Data = array(); + + $attributes = preg_split('/[ ]+/', $attributeString, - 1, PREG_SPLIT_NO_EMPTY); + + foreach ($attributes as $attribute) + { + if ($attribute[0] === '#') + { + $Data['id'] = substr($attribute, 1); + } + else # "." + { + $classes []= substr($attribute, 1); + } + } + + if (isset($classes)) + { + $Data['class'] = implode(' ', $classes); + } + + return $Data; + } + + # ~ + + protected function processTag($elementMarkup) # recursive + { + # http://stackoverflow.com/q/1148928/200145 + libxml_use_internal_errors(true); + + $DOMDocument = new DOMDocument; + + # http://stackoverflow.com/q/11309194/200145 + $elementMarkup = mb_convert_encoding($elementMarkup, 'HTML-ENTITIES', 'UTF-8'); + + # http://stackoverflow.com/q/4879946/200145 + $DOMDocument->loadHTML($elementMarkup); + $DOMDocument->removeChild($DOMDocument->doctype); + $DOMDocument->replaceChild($DOMDocument->firstChild->firstChild->firstChild, $DOMDocument->firstChild); + + $elementText = ''; + + if ($DOMDocument->documentElement->getAttribute('markdown') === '1') + { + foreach ($DOMDocument->documentElement->childNodes as $Node) + { + $elementText .= $DOMDocument->saveHTML($Node); + } + + $DOMDocument->documentElement->removeAttribute('markdown'); + + $elementText = "\n".$this->text($elementText)."\n"; + } + else + { + foreach ($DOMDocument->documentElement->childNodes as $Node) + { + $nodeMarkup = $DOMDocument->saveHTML($Node); + + if ($Node instanceof DOMElement and ! in_array($Node->nodeName, $this->textLevelElements)) + { + $elementText .= $this->processTag($nodeMarkup); + } + else + { + $elementText .= $nodeMarkup; + } + } + } + + # because we don't want for markup to get encoded + $DOMDocument->documentElement->nodeValue = 'placeholder\x1A'; + + $markup = $DOMDocument->saveHTML($DOMDocument->documentElement); + $markup = str_replace('placeholder\x1A', $elementText, $markup); + + return $markup; + } + + # ~ + + protected function sortFootnotes($A, $B) # callback + { + return $A['number'] - $B['number']; + } + + # + # Fields + # + + protected $regexAttribute = '(?:[#.][-\w]+[ ]*)'; +}