Initial commit

This commit is contained in:
rjindael 2022-10-22 16:41:36 -07:00
commit 17fb2065e2
No known key found for this signature in database
GPG Key ID: D069369C906CCF31
460 changed files with 46775 additions and 0 deletions

17
.dockerignore Normal file
View File

@ -0,0 +1,17 @@
# Artifacts
vendor/
storage/
app/bootstrap/cache/*
# Developer utilities
.git*
.env*
.editorconfig
Dockerfile
docker-compose.yml
docker/Dockerfile
docker/supervisord.conf
phpstan.neon
README.md
!.env.example

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

91
.env.example Normal file
View File

@ -0,0 +1,91 @@
APP_NAME=Tadah
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://tadah.loc
APP_TIMEZONE=UTC
ROBLOX_PRIVATE_KEY_PASSPHRASE=
ARBITER_PRIVATE_KEY_PASSPHRASE=
HORIZON_PATH=admin/horizon
HORIZON_ENABLED=true
TELESCOPE_PATH=admin/telescope
TELESCOPE_DRIVER=database
TELESCOPE_ENABLED=true
SAIL_XDEBUG_MODE=develop,debug
EMAIL_VERIFICATION=true
REQUIRE_INVITE_KEYS=false
USERS_CREATE_INVITE_KEYS=true
USERS_DISCORD_REQUIRED=true
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=pgsql
DB_HOST=pgsql
DB_PORT=5432
DB_DATABASE=tadah
DB_USERNAME=sail
DB_PASSWORD=password
BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
SESSION_DRIVER=database
SESSION_LIFETIME=120
MEMCACHED_HOST=memcached
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="tadah@tadah.loc"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=app-id
PUSHER_APP_KEY=app-key
PUSHER_APP_SECRET=app-key
PUSHER_HOST=soketi
PUSHER_CLIENT_HOST="tadah.loc"
PUSHER_PORT=6001
PUSHER_SCHEME="http"
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_CLIENT_HOST="${PUSHER_CLIENT_HOST}"
MIX_PUSHER_PORT="${PUSHER_PORT}"
MIX_PUSHER_SCHEME="${PUSHER_SCHEME}"
SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://meilisearch:7700
MEILISEARCH_KEY=
CIPHERSWEET_KEY=
# https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do
RECAPTCHA_SITE_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
RECAPTCHA_SECRET_KEY=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
OCTANE_SERVER=swoole
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
DISCORD_REDIRECT_URI=http://tadah.loc/my/discord/callback

91
.env.testing Normal file
View File

@ -0,0 +1,91 @@
APP_NAME=Tadah
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://tadah.loc
APP_TIMEZONE=UTC
ROBLOX_PRIVATE_KEY_PASSPHRASE=
ARBITER_PRIVATE_KEY_PASSPHRASE=
HORIZON_PATH=admin/horizon
HORIZON_ENABLED=false
TELESCOPE_PATH=admin/telescope
TELESCOPE_DRIVER=database
TELESCOPE_ENABLED=false
SAIL_XDEBUG_MODE=develop,debug
EMAIL_VERIFICATION=true
REQUIRE_INVITE_KEYS=false
USERS_CREATE_INVITE_KEYS=true
USERS_DISCORD_REQUIRED=true
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=pgsql
DB_HOST=pgsql
DB_PORT=5432
DB_DATABASE=tadah
DB_USERNAME=sail
DB_PASSWORD=password
BROADCAST_DRIVER=pusher
CACHE_DRIVER=redis
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
SESSION_DRIVER=database
SESSION_LIFETIME=120
MEMCACHED_HOST=memcached
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="tadah@tadah.loc"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=app-id
PUSHER_APP_KEY=app-key
PUSHER_APP_SECRET=app-key
PUSHER_HOST=soketi
PUSHER_CLIENT_HOST="tadah.loc"
PUSHER_PORT=6001
PUSHER_SCHEME="http"
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_CLIENT_HOST="${PUSHER_CLIENT_HOST}"
MIX_PUSHER_PORT="${PUSHER_PORT}"
MIX_PUSHER_SCHEME="${PUSHER_SCHEME}"
SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://meilisearch:7700
MEILISEARCH_KEY=
CIPHERSWEET_KEY=
# https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do
RECAPTCHA_SITE_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
RECAPTCHA_SECRET_KEY=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
OCTANE_SERVER=swoole
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
DISCORD_REDIRECT_URI=http://tadah.loc/my/discord/callback

10
.gitattributes vendored Normal file
View File

@ -0,0 +1,10 @@
* text=auto
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore

22
.gitignore vendored Normal file
View File

@ -0,0 +1,22 @@
/node_modules
/public/hot
/public/storage
/public/css/app.css
/public/js/app.js
/public/js/app.js.LICENSE.txt
/public/mix-manifest.json
/public/vendor
/storage/*.key
/storage/framework/disposable_domains.json
/vendor
.env
.env.backup
.phpunit.result.cache
docker-compose.override.yml
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
/.idea
/.vscode
_ide_helper*

13
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,13 @@
default:
image: php:8.1-alpine
before_script:
- apk add -q --no-progress libpng-dev
- docker-php-ext-install gd > /dev/null
- curl -s -S https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
- cp .env.testing .env
- composer i -q -n --no-ansi --no-progress
static analysis:
script:
- php -d memory_limit=512M vendor/bin/phpstan analyse -c phpstan.neon

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

44
README.md Normal file
View File

@ -0,0 +1,44 @@
# Tadah
The Tadah Website
## CI/CD
Tadah.Web is available on the Tadah CI. TeamCity builds the Docker image and uploads it to the Tadah internal Docker image registry (CI), and then tells the server to pull the newest image (CD).
- [production](https://ci.tadah.sipr/buildConfiguration/Tadah_Web_Production) (on https://tadah.rocks/)
- [development](https://ci.tadah.sipr/buildConfiguration/Tadah_Web_Development) (on https://tadahlabs.rocks/)
## Notes
- Deploys are run on each push to `dev`. They are pushed to https://tadahlabs.rocks. Upon proper assessment, these updates can manually be pushed to production on https://tadah.rocks. The dev website is barred off and should only be accessible to developers. A mock database will be run on https://tadahlabs.rocks - it shall not be linked to the production database.
- Do not force-push build artifacts, such as CSS or JavaScript assets generated from Laravel Mix. Laravel Mix gets run during the deploy process. Force pushing build artifacts will result in endless merge conflicts, and is generally bad practice.
- Please submit bugs, issues, and features to add as an issue. New features should be a separate branch and should be a pull request once ready to merge with the trunk branch. The production branch should never be touched manually.
- Please sign your commits.
## Stack
Tadah uses a BALL stack; Bootstrap, Alpine, Livewire, Laravel. On the backend, we use PostgreSQL for our Database. Additionally, Redis is used for cache, Meilisearch is used for search, and Mailhog is used for mail environment simulation.
Docker is used both on the developer's environment (in the form of Laravel Sail) and on the production environment (in the form a fully independent Docker container.)
## Local Environment
If on Linux, read steps starting from step 5. If on Windows, read all steps.
1. Download and install Ubuntu (no version -- get generic) from the Microsoft Store
2. Download and install Docker Desktop for Windows. Install WSL2 if need be.
3. Enable Docker -> Ubuntu integration by opening Docker Desktop and navigating to Settings -> Resources -> WSL Integration and toggling Ubuntu
4. Open your Ubuntu terminal. Navigate to where you are keeping the Tadah repository (i.e. if on `C:\Tadah`, you do `cd /mnt/c/Tadah`)
5. Copy `.env.example` to `.env`. Line breaks might be malformed on Windows. If so, replace all occurrences of `\r\n` in `.env` with `\n`
7. Run `composer install` if you don't have the composer dependencies installed yet.
8. Run `./vendor/bin/sail up -d`
9. Generate the application keys:
- App: `./vendor/bin/sail artisan key:generate`
- Pusher: `./vendor/bin/sail artisan pusher:secret`
- Ciphersweet: `./vendor/bin/sail artisan ciphersweet:key`
- Meilisearch: `./vendor/bin/sail artisan meilisearch:key`
10. Run `./vendor/bin/sail npm ci && npm run dev`
11. Run `./vendor/bin/sail artisan migrate` if your migrations are not up already.
12. You may now navigate to http://127.0.0.1 to view Tadah.
You may consult the [Laravel Sail documentation](https://laravel.com/docs/8.x/sail) for running Artisan and Composer commands.
## License
~~Copyright (c) Tadah 2021-2022. All rights reserved. Not for public use.~~
Licensed under the GNU Affero General Public License v3.0. A copy of it [has been included](https://github.com/tadah-foss/web/blob/trunk/LICENSE).

View File

@ -0,0 +1,32 @@
<?php
namespace App\Broadcasting;
use App\Roles\GameServers;
use App\Models\User;
use App\Models\GameServer;
class GameServerChannel
{
/**
* Create a new channel instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Authenticate the user's access to the channel.
*
* @param \App\Models\User $user
* @param \App\Models\GameServer $game_server
* @return array|bool
*/
public function join($user, $game_server)
{
return $user->may(GameServers::roleset(), GameServers::CONNECT);
}
}

50
app/Cdn/Manager.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace App\Cdn;
class Manager
{
/**
* Returns whether or not a given hash exists in the CDN file database.
*
* @param string $hash
* @return bool
*/
public static function hasHashedFile(string $hash): bool
{
return false;
}
/**
* Fetches the data of a hashed file in the CDN file database.
*
* @param string $hash
* @return mixed
*/
public static function fetchHashedFile(string $hash): mixed
{
return null;
}
/**
* Returns whether a given asset ID exists in the CDN file database.
*
* @param int $id
* @return bool
*/
public static function hasAssetId(int $id): bool
{
return false;
}
/**
* Fetches the data of a asset ID in the CDN file database.
*
* @param int $id
* @return mixed
*/
public static function fetchAssetId(int $id): mixed
{
return null;
}
}

View File

@ -0,0 +1,129 @@
<?php
namespace App\Console\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class MeilisearchKeyGenerate extends Command
{
use ConfirmableTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'meilisearch:key
{--show : Display the key instead of modifying files}
{--force : Force the operation to run when in production}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate and set a random Meilisearch key';
/**
* Execute the console command.
*
* @throws \Exception
*/
public function handle()
{
$key = $this->generateRandomKey();
if ($this->option('show'))
{
$this->line('<comment>' . $key . '</comment>');
return;
}
if (!$this->setKeyInEnvironmentFile($key))
{
return;
}
$this->laravel['config']['scout.meilisearch.key'] = $key;
$this->info('Meilisearch key set successfully.');
}
/**
* Generate a random key for the application.
*
* @return string
* @throws \Exception
*/
protected function generateRandomKey(): string
{
return bin2hex(random_bytes(64));
}
/**
* Set the Meilisearch key in the environment file.
*
* @param string $key
* @return bool
*/
protected function setKeyInEnvironmentFile($key): bool
{
if (!$this->confirmToProceed())
{
return false;
}
$this->writeNewEnvironmentFileWith($key);
return true;
}
/**
* Write a new environment file with the given Meilisearch key.
*
* @param string $key
*/
protected function writeNewEnvironmentFileWith($key)
{
/** @var mixed */
$laravel = $this->laravel;
$content = file_get_contents(
$laravel->environmentFilePath()
);
if (!Str::contains($content, 'MEILISEARCH_KEY'))
{
file_put_contents(
$laravel->environmentFilePath(),
'MEILISEARCH_KEY=' . $key,
FILE_APPEND
);
return;
}
file_put_contents(
$laravel->environmentFilePath(),
preg_replace(
$this->keyReplacementPattern(),
'MEILISEARCH_KEY=' . $key,
$content
)
);
}
/**
* Get a regex pattern that will match env MEILISEARCH_KEY with any random key.
*
* @return string
*/
protected function keyReplacementPattern()
{
$escaped = preg_quote('=' . $this->laravel['config']['scout.meilisearch.key'], '/');
return "/^MEILISEARCH_KEY{$escaped}/m";
}
}

View File

@ -0,0 +1,129 @@
<?php
namespace App\Console\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class PusherIdGenerate extends Command
{
use ConfirmableTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'pusher:id
{--show : Display the ID instead of modifying files}
{--force : Force the operation to run when in production}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate and set a random Pusher app ID';
/**
* Execute the console command.
*
* @throws \Exception
*/
public function handle()
{
$id = $this->generateRandomId();
if ($this->option('show'))
{
$this->line('<comment>' . $id . '</comment>');
return;
}
if (!$this->setIdInEnvironmentFile($id))
{
return;
}
$this->laravel['config']['broadcasting.connections.pusher.app_id'] = $id;
$this->info('Pusher app ID set successfully.');
}
/**
* Generate a random ID for the application.
*
* @return string
* @throws \Exception
*/
protected function generateRandomId(): string
{
return uuid();
}
/**
* Set the application ID in the environment file.
*
* @param string $id
* @return bool
*/
protected function setIdInEnvironmentFile($id): bool
{
if (!$this->confirmToProceed())
{
return false;
}
$this->writeNewEnvironmentFileWith($id);
return true;
}
/**
* Write a new environment file with the given app ID.
*
* @param string $id
*/
protected function writeNewEnvironmentFileWith($id)
{
/** @var mixed */
$laravel = $this->laravel;
$content = file_get_contents(
$laravel->environmentFilePath()
);
if (!Str::contains($content, 'PUSHER_APP_ID'))
{
file_put_contents(
$laravel->environmentFilePath(),
'PUSHER_APP_ID=' . $id,
FILE_APPEND
);
return;
}
file_put_contents(
$laravel->environmentFilePath(),
preg_replace(
$this->idReplacementPattern(),
'PUSHER_APP_ID=' . $id,
$content
)
);
}
/**
* Get a regex pattern that will match env PUSHER_APP_ID with any random app ID.
*
* @return string
*/
protected function idReplacementPattern()
{
$escaped = preg_quote('=' . $this->laravel['config']['broadcasting.connections.pusher.app_id'], '/');
return "/^PUSHER_APP_ID{$escaped}/m";
}
}

View File

@ -0,0 +1,129 @@
<?php
namespace App\Console\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class PusherSecretGenerate extends Command
{
use ConfirmableTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'pusher:secret
{--show : Display the secret instead of modifying files}
{--force : Force the operation to run when in production}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate and set a random Pusher app secret';
/**
* Execute the console command.
*
* @throws \Exception
*/
public function handle()
{
$secret = $this->generateRandomSecret();
if ($this->option('show'))
{
$this->line('<comment>' . $secret . '</comment>');
return;
}
if (!$this->setSecretInEnvironmentFile($secret))
{
return;
}
$this->laravel['config']['broadcasting.connections.pusher.secret'] = $secret;
$this->info('Pusher secret set successfully.');
}
/**
* Generate a random secret for the application.
*
* @return string
* @throws \Exception
*/
protected function generateRandomSecret(): string
{
return bin2hex(random_bytes(32));
}
/**
* Set the application secret in the environment file.
*
* @param string $secret
* @return bool
*/
protected function setSecretInEnvironmentFile($secret): bool
{
if (!$this->confirmToProceed())
{
return false;
}
$this->writeNewEnvironmentFileWith($secret);
return true;
}
/**
* Write a new environment file with the given secret.
*
* @param string $secret
*/
protected function writeNewEnvironmentFileWith($secret)
{
/** @var mixed */
$laravel = $this->laravel;
$content = file_get_contents(
$laravel->environmentFilePath()
);
if (!Str::contains($content, 'PUSHER_APP_SECRET'))
{
file_put_contents(
$laravel->environmentFilePath(),
'PUSHER_APP_SECRET=' . $secret,
FILE_APPEND
);
return;
}
file_put_contents(
$laravel->environmentFilePath(),
preg_replace(
$this->secretReplacementPattern(),
'PUSHER_APP_SECRET=' . $secret,
$content
)
);
}
/**
* Get a regex pattern that will match env PUSHER_APP_SECRET with any random secret.
*
* @return string
*/
protected function secretReplacementPattern(): string
{
$escaped = preg_quote('=' . $this->laravel['config']['broadcasting.connections.pusher.secret'], '/');
return "/^PUSHER_APP_SECRET{$escaped}/m";
}
}

30
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('disposable:update')->weekly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
}
}

52
app/Discord/User.php Normal file
View File

@ -0,0 +1,52 @@
<?php
namespace App\Discord;
use Illuminate\Support\Facades\Http;
class User
{
/**
* The user's Discord ID.
*/
public int $id;
/**
* The user's username.
*/
public string $username;
/**
* The user's 4-digit Discord tag.
*/
public string $discriminator;
/**
* The user's avatar hash.
*/
public string $avatar;
/**
* The user's avatar image URL.
*/
public string $avatarUrl;
/**
* Gets the Discord profile of a given Discord user snowflake.
*
* @param int $discord_id
*/
public function __construct(int $discord_id)
{
$data = Http::withHeaders(['Authorization' => sprintf('Bot: %s', env('DISCORD_BOT_TOKEN'))])
->get(sprintf('https://discord.com/api/v9/users/%d', $discord_id));
$data = json_decode($data);
$this->id = $data->id;
$this->username = $data->username;
$this->discriminator = $data->discriminator;
$this->avatar = $data->avatar;
$this->avatarUrl = sprintf('https://cdn.discordapp.com/avatars/%d/%s', $discord_id, $data->avatar);
}
}

68
app/Enums/Actions.php Normal file
View File

@ -0,0 +1,68 @@
<?php
namespace App\Enums;
enum Actions : int
{
case TempBannedUser = 0;
case PermBannedUser = 1;
case PoisonBannedUser = 2;
case WarnedUser = 3;
case PardonedUser = 4;
case CreatedGameServer = 5;
case DeletedGameServer = 6;
case ModifiedGameServer = 7;
case AddIPBan = 8;
case RemoveIPBan = 9;
case SiteAlert = 10;
case ApprovedAsset = 11;
case DeniedAsset = 12;
case ModeratedAsset = 13;
case ChangedUserPermissions = 14;
case DeletedThread = 15;
case DeletedReply = 16;
case CreatedCategory = 17;
case ModifiedCategory = 18;
case DeletedCategory = 19;
case ToggleStickiedThread = 20;
case EditedReply = 21;
case EditedThread = 22;
case PrunedPosts = 23;
/**
* Return the string for the action log type.
*
* @return string
*/
public function text(): string
{
return match($this)
{
self::TempBannedUser => 'Temporarily banned :name until :date.',
self::PermBannedUser => 'Permanently banned :name.',
self::PoisonBannedUser => 'Poison banned :name.',
self::WarnedUser => 'Warned :name.',
self::PardonedUser => 'Pardoned :name.',
self::CreatedGameServer => 'Created game server :ip.',
self::DeletedGameServer => 'Deleted game server :ip.',
self::ModifiedGameServer => 'Modified game server :ip.',
self::AddIPBan => 'Added an IP ban.',
self::RemoveIPBan => 'Removed an IP ban.',
self::SiteAlert => 'Changed the site alert.',
self::ApprovedAsset => 'Approved a :type: :name. (Asset ID: :id)',
self::DeniedAsset => 'Denied a :type: :name. (Asset ID: :id)',
self::ModeratedAsset => 'Moderated a :type: :name. (Asset ID: :id)',
self::ChangedUserPermissions => 'Changed permissions for :name.',
self::DeletedThread => 'Deleted thread :name. (Thread ID: :id)',
self::DeletedReply => 'Deleted reply on :name. (Thread ID: :id)',
self::CreatedCategory => 'Created the :name forum category.',
self::ModifiedCategory => 'Modified the :name forum category.',
self::DeletedCategory => 'Deleted the :name forum category.',
self::ToggleStickiedThread => 'Toggled sticky status for thread :name. (Thread ID: :id)',
self::EditedReply => 'Edited a reply on :name. (Thread ID: :id)',
self::EditedThread => 'Edited thread :name. (Thread ID: :id)',
self::PrunedPosts => 'Pruned all forum posts from :name.',
default => $this->name
};
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Enums;
use Spatie\Color\Hex;
use Spatie\Color\Color;
// https://git.tadah.sipr/tadah/arbiter/-/blob/trunk/Tadah.Arbiter/Log.cs
enum ArbiterLogSeverity : int
{
case Error = 0;
case Warning = 1;
case Event = 2;
case Information = 3;
case Debug = 4;
case Boot = 5;
/**
* Gets the logs shorthand type ('information' => 'info', 'warning' => 'warn', etc.)
*
* @return string
*/
public function event(): string
{
return match($this)
{
ArbiterLogSeverity::Error => 'error',
ArbiterLogSeverity::Warning => 'warn',
ArbiterLogSeverity::Event => 'event',
ArbiterLogSeverity::Information => 'info',
ArbiterLogSeverity::Debug => 'debug',
ArbiterLogSeverity::Boot => 'boot',
};
}
/**
* Gets the log color.
*
* @return Color
*/
public function color(): Color
{
return match($this)
{
ArbiterLogSeverity::Error => Hex::fromString('#E74856'),
ArbiterLogSeverity::Warning => Hex::fromString('#F9F1A5'),
ArbiterLogSeverity::Event => Hex::fromString('#3B78FF'),
ArbiterLogSeverity::Information => Hex::fromString('#F2F2F2'),
ArbiterLogSeverity::Debug => Hex::fromString('#0037DA'),
ArbiterLogSeverity::Boot => Hex::fromString('#16C60C'),
};
}
}

40
app/Enums/AssetGenre.php Normal file
View File

@ -0,0 +1,40 @@
<?php
namespace App\Enums;
// https://developer.roblox.com/en-us/api-reference/enum/Genre
enum AssetGenre : int
{
case All = 0;
case TownAndCity = 1;
case Fantasy = 2;
case SciFi = 3;
case Ninja = 4;
case Scary = 5;
case Pirate = 6;
case Adventure = 7;
case Sports = 8;
case Funny = 9;
case WildWest = 10;
case War = 11;
case SkatePark = 12;
case Tutorial = 13;
/**
* Gets the type's name
*
* @return string
*/
public function fullname(): string
{
return match($this)
{
self::TownAndCity => 'Town and City',
self::SciFi => 'Sci-Fi',
self::WildWest => 'Wild West',
self::SkatePark => 'Skate Park',
default => $this->name
};
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace App\Enums;
enum AssetModeration : int
{
case Pending = 0;
case Approved = 1;
case Declined = 2;
}

290
app/Enums/AssetType.php Normal file
View File

@ -0,0 +1,290 @@
<?php
namespace App\Enums;
use App\Rules\IsRobloxXml;
// https://pbs.twimg.com/media/FIECM2bWYAMOPnl?format=png&name=large
enum AssetType : int
{
case Image = 1;
case TShirt = 2;
case Audio = 3;
case Mesh = 4;
case Lua = 5;
case HTML = 6;
case Text = 7;
case Hat = 8;
case Place = 9;
case Model = 10;
case Shirt = 11;
case Pants = 12;
case Decal = 13;
case Avatar = 16;
case Head = 17;
case Face = 18;
case Gear = 19;
case Badge = 21;
case GroupEmblem = 22;
case Animation = 24;
case Arms = 25;
case Legs = 26;
case Torso = 27;
case RightArm = 28;
case LeftArm = 29;
case LeftLeg = 30;
case RightLeg = 31;
case Package = 32;
case YoutubeVideo = 33;
case GamePass = 34;
case App = 35;
case Code = 37;
case Plugin = 38;
case SolidModel = 39;
case MeshPart = 40;
/**
* Gets the asset type's full name
*
* @return string
*/
public function fullname(): string
{
return match($this)
{
self::TShirt => 'T-Shirt',
self::GroupEmblem => 'Group Emblem',
self::RightArm => 'Right Arm',
self::LeftArm => 'Left Arm',
self::LeftLeg => 'Left Leg',
self::RightLeg => 'Right Leg',
self::GamePass => 'Game Pass',
default => $this->name
};
}
public static function sellableTypes(): array
{
return [
self::TShirt,
self::Audio,
self::Hat,
self::Model,
self::Shirt,
self::Pants,
self::Decal,
self::Face,
self::Gear,
self::Badge
];
}
public function isSellable(): bool
{
return in_array($this, self::sellableTypes());
}
public static function freeTypes(): array
{
return [
self::Audio,
self::Model,
self::Decal,
];
}
public function isFree(): bool
{
return in_array($this, self::freeTypes());
}
/**
* Gets the asset types that can be worn by a user.
*
* @return array
*/
public static function wearableTypes(): array
{
return [
self::Head,
self::Face,
self::Gear,
self::Hat,
self::TShirt,
self::Shirt,
self::Pants
];
}
/**
* Checks if the asset type is a wearable type.
*
* @return bool
*/
public function isWearable(): bool
{
return in_array($this, self::wearableTypes());
}
/**
* Gets the asset types that are shown on the inventory sections.
*
* @return array
*/
public static function inventoryTypes(): array
{
return [
self::Head,
self::Face,
self::Gear,
self::Hat,
self::TShirt,
self::Shirt,
self::Pants,
self::Decal,
self::Model,
self::Plugin,
self::Animation,
self::Place,
self::GamePass,
self::Audio,
self::Badge,
self::LeftArm,
self::RightArm,
self::LeftLeg,
self::RightLeg,
self::Torso,
self::Package
];
}
/**
* Checks if the asset type is shown on the inventory selection.
*
* @return bool
*/
public function isInventoryType(): bool
{
return in_array($this, self::inventoryTypes());
}
/**
* Gets the asset types that are shown on the favorites section on user profiles.
*
* @return array
*/
public static function favoriteTypes(): array
{
return [
self::Head,
self::Face,
self::Gear,
self::Hat,
self::TShirt,
self::Shirt,
self::Pants,
self::Decal,
self::Model
];
}
/**
* Checks if the asset type is shown on the favorites selection.
*
* @return bool
*/
public function isFavoriteType(): bool
{
return in_array($this, self::favoriteTypes());
}
/**
* Gets the Font Awesome icon for this asset type.
*
* @return string
*/
public function fontAwesomeIcon(): string
{
return match($this) {
self::Place => 'fa-image-landscape',
self::Model => 'fa-cubes',
self::Decal => 'fa-file-image',
self::Badge => 'fa-certificate',
self::GamePass => 'fa-ticket',
self::Audio => 'fa-volume-high',
self::Animation => 'fa-person-running',
self::Shirt => 'fa-shirt',
self::TShirt => 'fa-shirt-tank-top',
self::Pants => 'fa-clothes-hanger',
self::Plugin => 'fa-puzzle-piece',
};
}
/**
* Gets the asset types that are shown on the develop page.
* Note that not everything here is creatable through the develop page (places, models, etc).
*
* @return array
*/
public static function developTypes(): array
{
return [
self::Place,
self::Model,
self::Decal,
self::Badge,
self::GamePass,
self::Audio,
self::Animation,
self::Shirt,
self::TShirt,
self::Pants,
self::Plugin,
];
}
/**
* Checks if the asset type is shown on the develop page.
*
* @return bool
*/
public function isDevelopType(): bool
{
return in_array($this, self::developTypes());
}
/**
* Checks if the asset type can be uploaded through the develop page
*
* @return bool
*/
public function isDevelopCreatable(): bool
{
return match($this)
{
self::TShirt => true,
self::Decal => true,
self::Audio => true,
self::Animation => true,
default => false
};
}
/**
* Gets the upload validator for the asset type
*
* @return array
*/
public function rules(): array
{
return match($this)
{
self::TShirt => ['file', 'mimes:png,jpeg', 'max:8192'],
self::Decal => ['file', 'mimes:png,jpeg', 'max:8192'],
self::Audio => ['file', 'mimes:mp3,wav,wmv,midi,txt', 'max:8192'],
self::Animation => ['file', 'max:8192', new IsRobloxXml],
default => []
};
}
}

12
app/Enums/ChatStyle.php Normal file
View File

@ -0,0 +1,12 @@
<?php
namespace App\Enums;
// https://anaminus.github.io/api/type/ChatStyle.html
enum ChatStyle : int
{
case Classic = 0;
case Bubble = 1;
case ClassicAndBubble = 2;
}

11
app/Enums/CreatorType.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace App\Enums;
// https://anaminus.github.io/api/type/CreatorType.html
enum CreatorType : int
{
case User = 0;
case Group = 1;
}

35
app/Enums/DevelopPage.php Normal file
View File

@ -0,0 +1,35 @@
<?php
namespace App\Enums;
enum DevelopPage : string
{
case Ads = 'ads';
case Games = 'universes';
/**
* Gets the artificial types that are shown on the develop page.
*
* @return array
*/
public static function developPages(): array
{
return [
// self::Ads,
self::Games
];
}
/**
* Gets the Font Awesome icon for this develop page.
*
* @return string
*/
public function fontAwesomeIcon(): string
{
return match($this) {
self::Ads => 'fa-rectangle-ad',
self::Games => 'fa-gamepad-modern',
};
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Enums;
enum GameServerState : int
{
/**
* The game server is online and is ready to receive job operations.
*/
case Online = 0;
/**
* The game server is offline and is unable to receive any operations.
*/
case Offline = 1;
/**
* The game server has crashed.
*/
case Crashed = 2;
/**
* The game server is online, but does not want to receive job operations.
*/
case Paused = 3;
}

View File

@ -0,0 +1,9 @@
<?php
namespace App\Enums;
enum PlaceAccess : int
{
case Everyone = 1;
case Friends = 2;
}

29
app/Enums/PlaceSort.php Normal file
View File

@ -0,0 +1,29 @@
<?php
namespace App\Enums;
enum PlaceSort : int
{
case MostPopular = 0;
case MostVisited = 1;
case MostFavorited = 2;
case RecentlyUpdated = 3;
case Featured = 4;
/**
* Gets the sort's name
*
* @return string
*/
public function fullname(): string
{
return match($this)
{
self::MostPopular => 'Popular',
self::MostVisited => 'Most Visited',
self::MostFavorited => 'Most Favorited',
self::RecentlyUpdated => 'Recently Updated',
default => $this->name
};
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Enums;
use Illuminate\Support\Facades\Storage;
use \OpenSSLAsymmetricKey;
enum SignatureType : string
{
case Roblox = 'roblox';
case Arbiter = 'arbiter';
/**
* Gets the hash algorithm for this signature type.
*
* @return int
*/
public function algorithm(): int
{
return match($this) {
SignatureType::Roblox => OPENSSL_ALGO_SHA1,
SignatureType::Arbiter => OPENSSL_ALGO_SHA256
};
}
/**
* Gets the key passphrase for this signature type.
*
* @return string
* @throws \Exception
*/
public function getPrivateKeyPassphrase(): string
{
$passphrase = match($this) {
SignatureType::Roblox => env('ROBLOX_PRIVATE_KEY_PASSPHRASE'),
SignatureType::Arbiter => env('ARBITER_PRIVATE_KEY_PASSPHRASE')
};
if (is_null($passphrase))
{
throw new \Exception('No passphrase set for key ' . $this->name);
}
return $passphrase;
}
/**
* Gets the private key for this signature type.
*
* @return \OpenSSLAsymmetricKey
* @throws \Exception
*/
public function getPrivateKey(): \OpenSSLAsymmetricKey
{
$pem = match ($this) {
SignatureType::Roblox => Storage::disk('local')->get('keys/roblox.pem'),
SignatureType::Arbiter => Storage::disk('local')->get('keys/arbiter.pem')
};
$key = openssl_pkey_get_private($pem, $this->getPrivateKeyPassphrase());
if ($key === false)
{
throw new \Exception('Failed to acquire private key');
}
return $key;
}
/**
* Gets the public key for this signature type.
*
* @return string
*/
public function getPublicKey(): string
{
return openssl_pkey_get_details($this->getPrivateKey())['key'];
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace App\Events\GameServer;
use App\Enums\ArbiterLogSeverity;
use App\Models\GameServer;
use Illuminate\Support\Carbon;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
class ConsoleOutput implements ShouldBroadcastNow
{
use Dispatchable;
/**
* Creates a new event instance.
*
* @param GameServer $game_server
* @param ArbiterLogSeverity $severity
* @param Carbon $timestamp
* @param string $output
* @param ?string $blur
*/
public function __construct(
public GameServer $game_server,
public ArbiterLogSeverity $severity,
public Carbon $timestamp,
public string $output,
public ?string $blur
) {}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn(): Channel|array
{
return new PrivateChannel('game-servers.' . $this->game_server->uuid);
}
/**
* Get the data to broadcast.
*
* @return array
*/
public function broadcastWith(): array
{
return [
'severity' => [
'event' => $this->severity->event(),
'color' => (string) $this->severity->color()->toHex()
],
'timestamp' => $this->timestamp->format('n/j/Y g:i:s A'),
'output' => $this->output,
'blur' => $this->blur
];
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Events\GameServer;
use App\Models\GameServer;
use App\Models\PlaceJob;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
class NewPlaceJob implements ShouldBroadcast
{
use Dispatchable, SerializesModels;
/**
* Creates a new event instance.
*
* @param GameServer $game_server
* @param PlaceJob $job
*/
public function __construct(
public GameServer $game_server,
public PlaceJob $job,
) {}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn(): Channel|array
{
return new PrivateChannel('game-servers.' . $this->game_server->uuid);
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Events\GameServer;
use App\Models\GameServer;
use App\Models\ThumbnailJob;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
class NewThumbnailJob implements ShouldBroadcast
{
use Dispatchable, SerializesModels;
/**
* Creates a new event instance.
*
* @param GameServer $game_server
* @param ThumbnailJob $job
*/
public function __construct(
public GameServer $game_server,
public ThumbnailJob $job,
) {}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn(): Channel|array
{
return new PrivateChannel('game-servers.' . $this->game_server->uuid);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Events\GameServer;
use App\Models\GameServer;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
class ResourceReport implements ShouldBroadcastNow
{
use Dispatchable;
/**
* Creates a new event instance.
*
* @param GameServer $game_server
* @param object $resources
*/
public function __construct(
public GameServer $game_server,
public object $resources,
) {}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn(): Channel|array
{
return new PrivateChannel('game-servers.' . $this->game_server->uuid);
}
/**
* Get the data to broadcast.
*
* @return array
*/
public function broadcastWith(): array
{
return (array) $this->resources;
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Events\GameServer;
use App\Models\GameServer;
use App\Enums\GameServerState;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
class StateChange implements ShouldBroadcastNow
{
use Dispatchable;
/**
* Creates a new event instance.
*
* @param GameServer $game_server
* @param GameServerState $state
*/
public function __construct(
public GameServer $game_server,
public GameServerState $state,
) {}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn(): Channel|array
{
return new PrivateChannel('game-servers.' . $this->game_server->uuid);
}
/**
* Get the data to broadcast.
*
* @return array
*/
public function broadcastWith(): array
{
return [
'state' => $this->state->value,
'utc_offset' => $this->game_server->utc_offset,
'friendly_name' => $this->game_server->friendly_name
];
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Events;
use App\Helpers\IpAddressBanManager;
class IpAddressBanModified
{
/**
* Handles an IP address ban's modification by refreshing all IP address bans.
*/
public function handle()
{
IpAddressBanManager::refresh();
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,25 @@
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: resources/tadah.proto
namespace GPBMetadata\Resources;
class Tadah
{
public static $is_initialized = false;
public static function initOnce() {
$pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
if (static::$is_initialized == true) {
return;
}
\GPBMetadata\Google\Protobuf\Timestamp::initOnce();
$pool->internalAddGeneratedFile(hex2bin(
"0ac7060a157265736f75726365732f74616461682e70726f746f1205546164616822f6020a065369676e616c12290a056e6f6e636518012001280b321a2e676f6f676c652e70726f746f6275662e54696d657374616d70120d0a056a6f62496418022001280912230a096f7065726174696f6e18032001280e32102e54616461682e4f7065726174696f6e12250a0776657273696f6e18042001280e32142e54616461682e436c69656e7456657273696f6e12220a05706c61636518052003280b32132e54616461682e5369676e616c2e506c616365122a0a097468756d626e61696c18062003280b32172e54616461682e5369676e616c2e5468756d626e61696c1a450a05506c616365120f0a07706c616365496418012001280d120e0a06736372697074180220012809121b0a1365787069726174696f6e496e5365636f6e647318032001280d1a4f0a095468756d626e61696c121e0a047479706518012001280e32102e54616461682e417373657454797065120f0a076173736574496418022001280d12110a096163636573734b6579180320012809225f0a08526573706f6e736512230a096f7065726174696f6e18012001280e32102e54616461682e4f7065726174696f6e120f0a0773756363657373180220012808120f0a076d657373616765180320012809120c0a04646174611804200128092a99010a094f7065726174696f6e120c0a084f50454e5f4a4f421000120d0a09434c4f53455f4a4f42100112120a0e455845435554455f534352495054100212190a1552454e45575f54414d50415f4a4f425f4c45415345100312120a0e434c4f53455f414c4c5f4a4f42531004121d0a19434c4f53455f414c4c5f54414d50415f50524f4345535345531005120d0a095448554d424e41494c10062a320a0d436c69656e7456657273696f6e12080a044e4f4e451000120b0a0654414950454910db0f120a0a0554414d504110e00f2a590a09417373657454797065120c0a08434c4f5448494e47100012080a0448454144100112080a044d455348100212090a05504c414345100312080a04555345521004120c0a084845414453484f54100512070a03584d4c1006421aaa020b54616461682e50726f746fca02094170705c50726f746f620670726f746f33"
), true);
static::$is_initialized = true;
}
}

33
app/Helpers/Agent.php Normal file
View File

@ -0,0 +1,33 @@
<?php
namespace App\Helpers;
use Jenssegers\Agent\Agent as UserAgent;
class Agent extends UserAgent
{
/**
* The FontAwesome icon of the user agent.
*
* @return string
*/
public function icon(): string
{
if ($this->isDesktop())
{
return 'fa-display';
}
if ($this->isTablet())
{
return 'fa-tablet';
}
if ($this->isPhone())
{
return 'fa-mobile';
}
return 'fa-question';
}
}

82
app/Helpers/Cdn.php Normal file
View File

@ -0,0 +1,82 @@
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Storage;
class Cdn
{
/**
* The algorithm that's being used to calculate file hashes.
*/
private static $algo = 'sha256';
/**
* Shorthand for PHP's hash function with the CDN's configured hash algo
*
* @param string $data
* @return string|false
*/
public static function hash(string $data): string|false
{
return hash(self::$algo, $data);
}
/**
* Shorthand for PHP's hash_file function with the CDN's configured hash algo
*
* @param string $filename
* @return string|false
*/
public static function hash_file(string $filename): string|false
{
return hash_file(self::$algo, $filename);
}
/**
* Uploads a file to the app's configured content delivery system
*
* @param string $folder
* @param string $data
* @param ?string $extension
* @return void
*/
public static function save(string $data, ?string $extension = null): void
{
$filename = self::hash($data);
if (!is_null($extension))
{
$filename = sprintf('%s.%s', $filename, $extension);
}
if (!Storage::disk('content')->exists($filename))
{
Storage::disk('content')->put($filename, $data);
}
}
/**
* Retrieves an accessible URL to a file on the app's configured content delivery system.
* The widescreen parameter is used for the placeholder thumbnail on failure.
*
* @param string $folder
* @param string $filename
* @param bool $widescreen
* @return string
*/
public static function getUrl(string $filename, bool $widescreen = false): string
{
if (Storage::disk('content')->exists($filename))
{
return asset(sprintf('content/%s', $filename));
}
if ($widescreen)
{
return asset('img/placeholder/widescreen.png');
}
return asset('img/placeholder/icon.png');
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Helpers;
use App\Models\IpAddressBan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
class IpAddressBanManager
{
/**
* Loads all IP address bans into cache.
*/
public static function refresh()
{
if (!Schema::hasTable('ip_address_bans'))
{
return;
}
$banned_ip_addresses = [];
foreach (IpAddressBan::all() as $ban)
{
if (!$ban->is_active)
{
continue;
}
$banned_ip_addresses[] = $ban->ip_address;
}
Cache::store('octane')->put('banned_ip_addresses', $banned_ip_addresses);
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace App\Helpers;
use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class PaginationTransformer
{
/**
* Paginates a given collection.
*
* @param \Illuminate\Support\Collection $collection
* @param int $showPerPage
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
public static function paginate(Collection $collection, $showPerPage)
{
$pageNumber = Paginator::resolveCurrentPage('page');
$totalPageNumber = $collection->count();
return self::paginator($collection->forPage($pageNumber, $showPerPage), $totalPageNumber, $showPerPage, $pageNumber, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
}
/**
* Create a new length-aware paginator instance.
*
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
protected static function paginator($items, $total, $perPage, $currentPage, $options)
{
return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers\Account;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
/**
* @var array
*/
private $greetings = ['Hi', 'Howdy', 'Ahoy', 'Bonjour', 'Hola', 'Olá', '您好', 'Привет', 'سلام', 'Hallo', 'Hej', 'Ciao', 'Hello'];
public function __invoke(Request $request)
{
$status = null;
if ($request->has('verified') && !is_null($request->user()->email_verified_at))
{
if ((time() - $request->user()->email_verified_at->timestamp) <= 30)
{
$status = __('Welcome to :project!', ['project' => config('app.name')]);
}
}
$greeting = $this->greetings[mt_rand(0, count($this->greetings) - 1)];
$username = $request->user()->username;
return view('my.dashboard', compact('status', 'greeting', 'username'));
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Http\Controllers\Account;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DisabledAccountController extends Controller
{
public function view(Request $request)
{
$user = $request->user();
if (!$user->isBanned())
{
return redirect()->route('dashboard');
}
$ban = (object) [
'is_termination' => !$user->ban->is_warning && !$user->ban->is_poison_ban && is_null($user->ban->expiry_date),
'is_warning' => $user->ban->is_warning,
'is_poison_ban' => $user->ban->is_poison_ban,
'reviewed' => $user->ban->created_at->format('m/d/Y h:i:s A (T)'),
'offensive_item' => $user->ban->offensive_item,
'moderator_note' => $user->ban->moderator_note,
'is_appealable' => $user->ban->is_appealable,
];
$ban->expired = false;
if (!$ban->is_termination && !$ban->is_warning && !$ban->is_poison_ban)
{
$ban->duration = seconds2human($user->ban->expiry_date->timestamp - $user->ban->created_at->timestamp, true);
$ban->expired = $user->ban->expiry_date->isPast();
$ban->reactivation_date = $user->ban->expiry_date->format('m/d/Y h:i:s A (T)');
}
elseif ($ban->is_warning)
{
$ban->expired = true;
}
return view('auth.account-disabled', compact('ban'));
}
public function store(Request $request)
{
$user = $request->user();
if (!$user->isBanned())
{
return redirect()->route('dashboard');
}
if ($user->ban->is_poison_ban || (!$user->ban->is_warning && !$user->ban->is_poison_ban && is_null($user->ban->expiry_date)))
{
abort(403);
}
if (!$user->ban->is_warning && !$user->ban->expiry_date->isPast())
{
abort(403);
}
$user->ban->lift();
return redirect()->route('dashboard')->with('success', __('Welcome back! Please adhere to the :project Terms of Service this time.', ['project' => config('app.name')]));
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Account;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
class DiscordController extends Controller
{
public function redirect()
{
return Socialite::driver('discord')->redirect();
}
public function callback(Request $request)
{
$request->user()->linkDiscordAccount(Socialite::driver('discord')->user()->id);
return redirect()->route('account')->with('status', __('Successfully linked Discord account!'));
}
public function unlink(Request $request)
{
$request->user()->unlinkDiscordAccount();
return redirect()->route('account')->with('status', __('Your Discord account has been unlinked.'));
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers\Account;
use App\Http\Controllers\Controller;
use App\Roles\Users;
use App\Models\InviteKey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class InviteKeyController extends Controller
{
private function mayPurchaseKey()
{
/** @var \App\Models\User */
$user = Auth::user();
if (!$user->may(Users::roleset(), Users::PURCHASE_INVITE_KEY))
{
return __('You may not purchase an invite key.');
}
if (!$user->hasEnoughMoney(config('tadah.user_invite_key_cost')))
{
return __('You do not have enough :currency to purchase an invite key.', ['currency' => config('tadah.currency_name')]);
}
if (!$user->hasLinkedDiscordAccount() && config('tadah.discord_required'))
{
return __('Please link your Discord account in order to create invite keys.');
}
$our_keys = InviteKey::where('creator_id', $user->id)
->where('created_at', '>', now()->subDays(config('tadah.user_invite_key_cooldown'))->endOfDay())
->get();
if (count($our_keys) >= config('tadah.user_maximum_keys_in_window'))
{
return __("You've already made :maximum invite keys in the past :cooldown days.", ['maximum' => config('tadah.user_maximum_keys_in_window'), 'cooldown' => config('app.user_invite_key_cooldown')]);
}
return true;
}
public function view(Request $request)
{
$keys = InviteKey::where('creator_id', $request->user()->id)
->orderBy('created_at', 'DESC')
->paginate(15);
$disabled = $this->mayPurchaseKey() !== true;
return view('my.invites', compact('keys', 'disabled'));
}
public function purchase(Request $request)
{
$user = $request->user();
if (($reason = $this->mayPurchaseKey()) !== true)
{
return back()->with('error', $reason);
}
$user->spend(config('tadah.user_invite_key_cost'), 'Bought invite key');
InviteKey::generate($user->id, 1);
return back()->with('success', __('New invite key created.'));
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\Account;
use App\Http\Controllers\Controller;
use App\Rules\IsValidSession;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;
class SessionController extends Controller
{
public function __invoke(Request $request)
{
try
{
$data = $request->validate([
'key' => ['required', new IsValidSession($request->user())]
]);
}
catch (ValidationException)
{
return response()->json(['success' => false]);
}
$key = decrypt($data['key']);
if ($key == $request->session()->getId())
{
Auth::logout();
}
else
{
Session::getHandler()->destroy($key);
}
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Http\Controllers\Account;
use App\Http\Controllers\Controller;
use App\Rules\IsCurrentPassword;
use App\Traits\EmailValidationRules;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SettingsController extends Controller
{
use EmailValidationRules;
public function view(Request $request)
{
$current_session = null;
$sessions = [];
DB::table('sessions')->where('user_id', $request->user()->id)->get()->each(function ($session) use ($request, &$sessions, &$current_session) {
if ($session->id == $request->session()->getId())
{
$current_session = (object) [
'agent' => agent($session->user_agent),
'location' => geolocate($session->ip_address),
'last_ping' => time(),
'ip' => $session->ip_address,
];
return;
}
$sessions[] = (object) [
'key' => encrypt($session->id),
'agent' => agent($session->user_agent),
'location' => geolocate($session->ip_address),
'last_ping' => $session->last_activity,
'ip' => $session->ip_address,
];
});
return view('my.account', [
'current_session' => $current_session,
'sessions' => $sessions,
'discord_user' => $request->user()->discordAccount(),
]);
}
public function updateEmail(Request $request)
{
if ($request->isMethod('post'))
{
$user = $request->user();
$data = $request->validate([
'email' => $this->emailRules(),
'current_password' => ['required', new IsCurrentPassword($user)],
]);
$user->updateEmail($data['email'], $request->ip(), $request->userAgent());
return redirect()->route('account')->with('status', __('Your E-Mail address has been succesfully updated!'));
}
return view('auth.update-email');
}
public function heartbeat(Request $request)
{
$user = $request->user();
$activity = $user->activity;
$activity['website'] = time();
$user->update(compact('activity'));
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ActionLogController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->isSuperAdmin())
{
return abort(404);
}
return $next($request);
});
}
public function view()
{
return view('admin.action-log');
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
class AlertController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->isSuperAdmin())
{
return abort(404);
}
return $next($request);
});
}
public function __invoke()
{
return view('admin.alert');
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Roles\Users;
use App\Http\Controllers\Controller;
class BanController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->may(Users::roleset(), Users::MODERATION_GENERAL_BAN))
{
return abort(404);
}
return $next($request);
});
}
public function __invoke()
{
return view('admin.user.ban');
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Ban;
use App\Roles\Users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class BanInformationController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->may(Users::roleset(), Users::MODERATION_VIEW_BAN_LIST))
{
return abort(404);
}
return $next($request);
});
}
public function __invoke(Request $request)
{
$ban = Ban::findOrFail($request->input('id'));
return response()->json([
'success' => true,
'ban' => [
'pardon_internal_reason' => $ban->pardon_internal_reason,
'offensive_item' => $ban->offensive_item,
'internal_reason' => $ban->internal_reason,
'moderator_note' => $ban->moderator_note,
'is_appealable' => $ban->is_appealable,
'has_been_pardoned' => $ban->has_been_pardoned
]
]);
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Roles\GameServers;
use App\Models\GameServer;
use Illuminate\Http\Request;
class GameServerController extends Controller
{
public function all(Request $request)
{
if (!$request->user()->may(GameServers::roleset(), GameServers::VIEW))
{
return abort(404);
}
return view('admin.game-server.all');
}
public function store(Request $request)
{
if (!$request->user()->may(GameServers::roleset(), GameServers::CREATE))
{
return abort(404);
}
return view('admin.game-server.create');
}
public function view(Request $request, $id)
{
if (!$request->user()->may(GameServers::roleset(), GameServers::VIEW))
{
return abort(404);
}
$game_server = GameServer::where('uuid', $id)->firstOrFail();
$data = [
'isSetUp' => $game_server->is_set_up,
'uuid' => $game_server->uuid,
'state' => $game_server->state()->value
];
return view('admin.game-server.view', compact('game_server', 'data'));
}
public function manage(Request $request, $id)
{
if (!$request->user()->may(GameServers::roleset(), GameServers::MANAGE))
{
return abort(404);
}
$game_server = GameServer::where('uuid', $id)->firstOrFail();
return view('admin.game-server.manage', compact('game_server'));
}
public function state(Request $request)
{
if (!$request->has('uuid'))
{
return abort(404);
}
$game_server = GameServer::where('uuid', $request->input('uuid'))->firstOrFail();
return response()->json(['state' => $game_server->state()->value]);
}
public function logs(Request $request, $uuid)
{
if (!$request->user()->may(GameServers::roleset(), GameServers::CONNECT) || !$request->has('key'))
{
return abort(404);
}
$game_server = GameServer::where('uuid', $uuid)->firstOrFail();
$output = [];
if (!GameServer::$logKeys[$request->input('key')])
{
return response()->json(['success' => false]);
}
if ($request->input('key') == 'console')
{
$trunk = $game_server->retrieveCompleteLog('console');
unset($trunk['latest']);
foreach ($trunk as $line)
{
$output[] = [
'severity' => [
'event' => $line[0]->event(),
'color' => (string) $line[0]->color()->toHex()
],
'timestamp' => $line[1]->format('n/j/Y g:i:s A'),
'output' => $line[2],
'blur' => $line[3]
];
}
$trunk = collect($trunk);
$trunk = $trunk->sortBy(function ($line) {
return $line[1]->timestamp;
});
$output = $trunk->toArray();
}
else
{
$output = $game_server->retrieveCompleteLog($request->input('key'));
}
return response()->json([
'success' => true,
'output' => $output
]);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Roles\Users;
class IpAddressBanController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->may(Users::roleset(), Users::MODERATION_IP_ADDRESS_BAN))
{
return abort(404);
}
return $next($request);
});
}
public function __invoke()
{
return view('admin.user.ip-address-ban');
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Roles\Admin;
use Illuminate\Http\Request;
class PanelController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->may(Admin::roleset(), Admin::VIEW_PANEL))
{
return abort(404);
}
return $next($request);
});
}
public function __invoke(Request $request)
{
return view('admin.panel')->with('user', $request->user());
}
}

View File

@ -0,0 +1,172 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Action;
use App\Enums\Actions;
use App\Roles\Roles;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class PermissionsController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->isSuperAdmin())
{
return abort(404);
}
return $next($request);
});
}
public function view()
{
return view('admin.permissions');
}
public function store(Request $request)
{
// 0xbaadc0de
$rolesets = Roles::allRolesets();
$view_rolesets = [];
foreach ($rolesets as $roleset)
{
$view_rolesets[$roleset] = (object) [
'name' => $roleset,
'roles' => Roles::rolesOfRoleset($roleset),
'basename' => basename(str_replace('\\', '/', $roleset)), // WHAT THE FUCK ??
];
}
if ($request->has('username'))
{
$request->validate([
'username' => ['required', 'exists:users,username']
]);
$user = User::select('id', 'username', 'permissions', 'superadmin')->where('username', $request->input('username'))->first();
return view('admin.permissions', [
'user' => $user,
'rolesets' => $view_rolesets,
]);
}
if ($request->has('reset_for'))
{
$user = User::findOrFail($request->input('reset_for'));
$user->forceSetPermissions(User::defaultPermissions());
Session::flash('success', __('Successfully reset permissions for user <b>:username</b>!', ['username' => $user->username]));
return view('admin.permissions', [
'user' => $user,
'rolesets' => $view_rolesets,
]);
}
try
{
$request->validate([
'user' => ['required', 'exists:users,id']
]);
}
catch (ValidationException)
{
return back()->with('error', __('An unexpected error occurred. Please try again.'));
}
/**
* Only permissions that are turned on are sent.
* Additionally, field names are denominated in the format "roleset;role" prefixed with "permission__".
* Example: "permission__App\Roles\Users;MODERATION_GENERAL_BAN"
*/
$data = $request->all();
if (count($data) > (count($rolesets) * 30)) // 30 flags per roleset, impossible to be above this
{
return back()->with('error', __('An unexpected error occurred. Please try again.'));
}
// We are manually recreating the users permissions based on what it sent
$permissions = [];
foreach ($data as $field => $value)
{
// If it doesn't start with permission__, leave it be
if (!str_starts_with($field, 'permission__'))
{
continue;
}
if ($value != 'on')
{
continue;
}
// Has to be formatted per our spec
$field = substr($field, strlen('permission__'));
$flag = explode(';', $field);
if (count($flag) !== 2)
{
return back()->with('error', __('An unexpected error occurred. Please try again.'));
}
$roleset = $flag[0];
$role = $flag[1];
// If the roleset doesn't exist, go away
if (!in_array($roleset, $rolesets) || !class_exists($roleset))
{
return back()->with('error', __('An unexpected error occurred. Please try again.'));
}
// If the role doesn't exist, go away
$roles = Roles::rolesOfRoleset($roleset);
if (is_null($roles[$role]))
{
return back()->with('error', __('An unexpected error occurred. Please try again.'));
}
// If our permissions building array doesn't have this roleset set, set it as 0
if (!isset($permissions[$roleset]))
{
$permissions[$roleset] = 0;
}
// Add this flag to the roleset
$permissions[$roleset] |= $roles[$role];
}
// Fill in the blanks
foreach ($rolesets as $roleset)
{
if (!isset($permissions[$roleset]))
{
$permissions[$roleset] = 0;
}
}
$user = User::findOrFail($request->input('user'));
$user->forceSetPermissions($permissions);
Action::log($request->user(), Actions::ChangedUserPermissions, $user);
Session::flash('success', __('Successfully updated permissions for user <b>:username</b>!', ['username' => $user->username]));
return view('admin.permissions', [
'user' => $user,
'rolesets' => $view_rolesets,
]);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Models\User;
use App\Roles\Users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserProfileController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next)
{
if (!$request->user()->may(Users::roleset(), Users::MODERATION_VIEW_USER_PROFILE))
{
return abort(404);
}
return $next($request);
});
}
public function view()
{
return view('admin.user.profile');
}
public function load(Request $request)
{
$request->validate([
'username' => ['required', 'exists:users,username']
]);
$user = User::where('username', $request->input('username'))->first();
return view('admin.user.profile', compact('user'));
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers\Arbiter;
use App\Models\GameServer;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class IdentificationController extends Controller
{
public function __invoke(Request $request)
{
if (empty($request->bearerToken()) || !$request->has('friendly_name') || !$request->has('utc_offset'))
{
return abort(404);
}
$game_server = GameServer::whereEncrypted('access_key', '=', $request->bearerToken())->firstOrFail();
$game_server->update(['friendly_name' => $request->input('friendly_name'), 'utc_offset' => $request->input('utc_offset')]);
return response()->make($game_server->uuid)->header('Content-Type', 'text/plain');
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace App\Http\Controllers\Arbiter;
use App\Http\Controllers\Controller;
use App\Events\GameServer\ConsoleOutput;
use App\Events\GameServer\ResourceReport;
use App\Enums\ArbiterLogSeverity;
use App\Models\GameServer;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
class LogController extends Controller
{
public function log(Request $request, $uuid)
{
if (!$request->has('severity') || !$request->has('timestamp') || !$request->has('output') || !$request->has('blur'))
{
return abort(404);
}
$game_server = GameServer::where('uuid', $uuid)->firstOrFail();
if (!$game_server->is($request->game_server))
{
return abort(404);
}
ConsoleOutput::dispatch($game_server,
ArbiterLogSeverity::tryFrom($request->input('severity')) ?? null,
Carbon::createFromTimestamp($request->input('timestamp'))->setTimezone($game_server->utc_offset),
$request->input('output'),
$request->input('blur')
);
return response()->json(['success' => true]);
}
public function resources(Request $request, $uuid)
{
if (!$request->has('cpu') || !$request->has('ram') || !$request->has('inbound') || !$request->has('outbound'))
{
return abort(404);
}
$game_server = GameServer::where('uuid', $uuid)->firstOrFail();
if (!$game_server->is($request->game_server))
{
return abort(404);
}
ResourceReport::dispatch($game_server, (object) [
'cpu' => $request->input('cpu'),
'ram' => $request->input('ram'),
'net' => [
'in' => $request->input('inbound'),
'out' => $request->input('outbound')
]
]);
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers\Arbiter;
use App\Enums\GameServerState;
use App\Events\GameServer\StateChange;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class StateController extends Controller
{
public function __invoke(Request $request)
{
if (!$request->has('state'))
{
return abort(404);
}
if (!$request->game_server->is_set_up)
{
$request->game_server->update(['is_set_up' => true]);
}
StateChange::dispatch($request->game_server, GameServerState::tryFrom($request->input('state')) ?? GameServerState::Offline);
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController as BaseController;
class EmailVerificationNotificationController extends BaseController
{
/**
* Send a new email verification notification.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function __invoke(Request $request)
{
$request->validate([
recaptchaFieldName() => ['required', recaptchaRuleName()]
]);
return $this->store($request);
}
}

View File

@ -0,0 +1,108 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Traits\PasswordValidationRules;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Password;
use Illuminate\Http\Request;
class PasswordResetController extends Controller
{
use PasswordValidationRules;
// GET /forgot-password
public function request()
{
return view('auth.request-password');
}
// POST /forgot-password
public function create(Request $request)
{
$request->validate([
'email' => ['required', 'email'],
recaptchaFieldName() => ['required', recaptchaRuleName()]
]);
// Hack, since UserProvider does a traditional ->where and can't search encrypted text
if (!is_null($user = User::whereEncrypted('email', '=', $request->email)->first()))
{
$ciphertext = $user->getRawOriginal('email');
$this->broker()->sendResetLink(['email' => $ciphertext]);
}
return view('auth.request-password')->with('status', __('A password reset link has been sent if the email was valid.'));
}
// GET /reset-password/{token}
public function view(Request $request, $token)
{
if (!$request->has('email') || empty($token))
{
return abort(404);
}
if (!is_null($user = User::whereEncrypted('email', '=', $request->email)->first()))
{
if (is_null($rawUser = $this->broker()->getUser(['email' => $user->getRawOriginal('email')])))
{
return abort(404);
}
if (!$this->broker()->tokenExists($rawUser, $token))
{
return abort(404);
}
}
else
{
return abort(404);
}
return view('auth.reset-password', ['token' => $token, 'email' => $request->email]);
}
// POST /reset-password
public function reset(Request $request)
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => $this->passwordRules(),
'password_confirmation' => $this->passwordConfirmationRules()
]);
$ciphertext = '';
if (!is_null($user = User::whereEncrypted('email', '=', $request->email)->first()))
{
$ciphertext = $user->getRawOriginal('email');
}
/* $status = */ $this->broker()->reset(
array_merge($request->only('password', 'password_confirmation', 'token'), ['email' => $ciphertext]),
function ($user, $password) use ($request) {
$user->updatePassword($password, $request->ip(), $request->userAgent());
event(new PasswordReset($user));
}
);
/*
return $status === Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withErrors(['email' => [__($status)]]);
*/
// ^^^ Traditionally we would do this, but since we already validated, we can assume that all validation is done.
// Therefore we just go back to login with "your password has been reset."
// Otherwise it will say "invalid email" or something; we don't want to expose if actual emails exist or not.
return redirect()->route('login')->with('status', __('Your password has successfully been reset, <b>:name</b>!', ['name' => $user->username]));
}
protected function broker(): mixed
{
return Password::broker(config('fortify.passwords'));
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CatalogController extends Controller
{
public function index(Request $request)
{
return view('catalog.index');
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DevelopController extends Controller
{
public function index(Request $request)
{
return view('develop.index');
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers;
use App\Models\ForumCategory;
use App\Models\ForumThread;
use App\Models\ForumReply;
use Illuminate\Http\Request;
class ForumController extends Controller
{
public function index(Request $request)
{
$categories = ForumCategory::orderBy('priority', 'desc')->get();
return view('forum.index')->with('categories', $categories);
}
public function category(Request $request, $id)
{
$category = ForumCategory::where('id', $id)->first();
$categories = ForumCategory::orderBy('priority', 'desc')->get();
return view('forum.category')->with(['category' => $category, 'categories' => $categories]);
}
public function thread(Request $request, $id)
{
$thread = ForumThread::where('id', $id)->first();
$categories = ForumCategory::orderBy('priority', 'desc')->get();
return view('forum.thread')->with(['thread' => $thread, 'categories' => $categories]);
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class GamesController extends Controller
{
public function list(Request $request)
{
return view('games.index');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Http\Controllers;
class HomeController extends Controller
{
public function landing()
{
return view('landing');
}
public function language($locale)
{
$locales = array_flip(config('app.available_locales')); // English => en_US becomes en_US => English
if (!isset($locales[$locale]))
{
$locale = config('app.fallback_locale');
}
app()->setLocale($locale);
session()->put('locale', $locale);
return redirect()->back();
}
public function document($page)
{
// we can use view()->exists but it's unsafe w/ user input
$documents = ['privacy', 'rules', 'statistics', 'tos'];
if (!in_array($page, $documents))
{
return abort(404);
}
return view("document.{$page}");
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers;
use App\Models\Asset;
use Illuminate\Http\Request;
class ItemController extends Controller
{
public function view(Request $request, $id)
{
$asset = Asset::findOrFail($id);
return view('item.view', compact('asset'));
}
public function configure(Request $request, $id)
{
$asset = Asset::findOrFail($id);
abort_unless($asset->canConfigure(), 404);
return view('item.configure', compact('asset'));
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\Roblox;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
class FastFlagController extends Controller
{
const versions = ["2012", "2016"]; // To prevent ../../../, maybe we could list client versions in /config/tadah.php
public function clientAppSettings(Request $request)
{
$version = $request->version ?? "2016";
if (!in_array($version, self::versions)) {
return abort(400);
}
$flags = Storage::disk('resources')->get((sprintf('flags/ClientAppSettings/%s.json', $version)));
return response()->make($flags)->header('Content-Type', 'application/json');
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Http\Controllers\Roblox;
use App\Http\Controllers\Controller;
use App\Roblox\Script\ScriptBuilder;
class MiscellaneousScriptController extends Controller
{
public function gameserver()
{
return response()->text(ScriptBuilder::from('Gameserver')->sign());
}
}

View File

@ -0,0 +1,120 @@
<?php
namespace App\Http\Controllers\Roblox;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Roblox\Script\ScriptBuilder;
class OnlinePlayController extends Controller
{
public function multiplayer(Request $request)
{
$placeId = $request->input('placeId');
$machineAddress = $request->input('server');
$machinePort = $request->input('serverPort');
$parameters = [
... ScriptBuilder::defaultParameters(),
'PlaceID' => -1
];
// TODO: generate screenshot and video info when placeid parameter is not -1 (@pizzaboxer)
if ($request->has('jobID'))
{
// TODO: we probably won't use job ids for joinscript generation anyway (@pizzaboxer)
// Carrot: why?
$jobId = $request->input('jobID');
}
else
{
if (is_numeric($placeId))
{
$parameters['PlaceID'] = $placeId;
}
// make sure the machine address given is a local ip
// this probably isn't necessary? eh
if (is_ipv4($machineAddress))
{
$parameters['MachineAddress'] = $machineAddress;
}
if (is_port($machinePort))
{
$parameters['MachinePort'] = $machinePort;
}
}
/* "ScreenShotInfo":"Crossroads%0d%0aA+fun+game+by+Player%0d%0aBuilt+in+ROBLOX%2c+the+free+online+building+game.+%0d%0ahttp%3a%2f%2fwww.roblox.com%2fCrossroads-place%3fid%3d1818%0d%0aMore+about+this+level%3a%0d%0aThe+classic+ROBLOX+level+is+back!" */
/* "VideoInfo":"<?xml version=\"1.0\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\"><media:group><media:title type=\"plain\"><![CDATA[Crossroads by ROBLOX]]></media:title><media:description type=\"plain\"><![CDATA[The classic ROBLOX level is back!\\n\\n Visit this place at http://www.roblox.com/Crossroads-place?id=1818\\n\\nFor more games visit http://www.roblox.com]]></media:description><media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">Games</media:category><media:keywords>ROBLOX, video, free game, online virtual world</media:keywords></media:group></entry> */
$scripts = [];
switch ($request->route()->getName())
{
case 'client.online.join':
$scripts[] = 'Join';
break;
case 'client.online.group-build':
$scripts[] = 'GroupBuild';
break;
}
$scripts[] = 'MultiplayerSharedScript';
return response()->text(ScriptBuilder::from($scripts)->render($parameters)->sign());
}
public function singleplayer(Request $request)
{
$placeId = $request->input('placeId');
$uploadingTo = $request->input('upload');
$parameters = ScriptBuilder::defaultParameters();
if (is_numeric($placeId))
{
$parameters['IsVisit'] = true;
$parameters['PlaceID'] = $placeId;
$parameters['AssetUrl'] = $parameters['BaseUrl'] . "/asset/?id=" . $placeId;
}
if (Auth::check())
{
$user = $request->user();
$parameters['PlayerName'] = $request->user()->username;
$parameters['PlayerID'] = $request->user()->id;
$parameters['PlayerAppearance'] = $parameters['BaseUrl'] . '/Asset/CharacterFetch.ashx?userId=' . $parameters['PlayerID'] . '&placeId=' . $parameters['PlaceID'];
$parameters['PlayerSSC'] = 'false';
$parameters['ClientPresenceUrl'] = $parameters['BaseUrl'] . "/Game/ClientPresence.ashx?PlaceID=" . $parameters['PlaceID'];
if (is_numeric($uploadingTo))
{
$parameters['UploadUrl'] = $parameters['BaseUrl'] . "/Data/Upload.ashx?assetid=" . $uploadingTo;
}
}
else
{
$parameters['PlayerName'] = 'Guest ' . rand(0, 9999);
$parameters['PlayerAppearance'] = $parameters['BaseUrl'] . '/Asset/CharacterFetch.ashx?userId=1&placeId=' . $parameters['PlaceID'];
}
$scripts = ['SingleplayerSharedScript'];
switch ($request->route()->getName())
{
case 'client.online.visit':
$scripts[] = 'Visit';
break;
case 'client.online.solo':
$scripts[] = 'PlaySolo';
break;
}
return response()->text(ScriptBuilder::from($scripts)->render($parameters)->sign());
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Http\Controllers\Roblox;
use App\Http\Controllers\Controller;
class StaticAssetController extends Controller
{
public function getScriptState()
{
return response()->text('0 0 0 0');
}
public function chatFilter()
{
return response()->text('True');
}
public function keepAlivePinger()
{
// TODO: make this functional?
// supposedly this is to preserve the user's online presence when the client is open
// i'm not entirely sure what the response is supposed to be? archived pages just show 8 (for logged out users)
// but when you're logged it shows a unique number on each request (presumably random? - https://archive.froast.io/forum/32957261)
return response()->text('8');
}
public function respondWithOK()
{
return response()->text('OK');
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Http\Controllers\Roblox;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Roblox\Script\ScriptBuilder;
class StudioController extends Controller
{
public function edit(Request $request)
{
$placeId = $request->input('PlaceID');
$parameters = ScriptBuilder::defaultParameters();
if (is_numeric($placeId))
{
$parameters['PlaceID'] = $placeId;
$parameters['AssetUrl'] = $parameters['BaseUrl'] . "/asset/?id=" . $placeId;
$parameters['ClientPresenceUrl'] = $parameters['BaseUrl'] . "/Game/ClientPresence.ashx?PlaceID=" . $placeId . "&LocationType=Studio";
}
return response()->text(ScriptBuilder::from(['SingleplayerSharedScript', 'Edit'])->render($parameters)->sign());
}
public function studio(Request $request)
{
$parameters = [
'BaseUrl' => "http://" . $request->getHost(),
'StarterScriptID' => 37801172
];
return response()->text(ScriptBuilder::from('Studio')->render($parameters)->sign());
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UsersController extends Controller
{
public function list()
{
return view('users.list');
}
public function profile(Request $request, $id)
{
$user = User::findOrFail($id);
$num_friends = $user->friends()->count();
return view('users.profile', compact('user', 'num_friends'));
}
}

72
app/Http/Kernel.php Normal file
View File

@ -0,0 +1,72 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
\App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\BlockBannedIpAddresses::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\UpdateCurrentIpAddress::class,
\App\Http\Middleware\Localization::class,
\App\Http\Middleware\IsBanned::class,
\App\Http\Middleware\EnsureEmailIsVerified::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminGuard::class,
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.arbiter' => \App\Http\Middleware\AuthenticateArbiter::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Livewire\Account;
use App\Models\Ban;
use App\Roles\Users;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
use Livewire\WithPagination;
class ModerationHistory extends Component
{
use WithPagination;
/**
* @var string
*/
protected $paginationTheme = 'bootstrap';
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::VIEW_BAN_HISTORY), 401);
}
public function render()
{
$user = Auth::user();
$bans = Ban::where('user_id', $user->id)->get();
$bans = paginate($bans, 15);
return view('livewire.account.moderation-history', [
'bans' => $bans
]);
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Http\Livewire\Account;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class TwoFactorAuthentication extends Component
{
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function render()
{
return view('livewire.account.two-factor-authentication');
}
public function enable()
{
}
public function disable()
{
}
public function confirm()
{
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Http\Livewire\Account;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Component;
class UpdateBlurb extends Component
{
/**
* @var string
*/
public $blurb;
/**
* @var array
*/
protected $rules = [
'blurb' => ['max:1000'],
];
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function mount()
{
$this->blurb = Auth::user()->blurb;
}
public function updated($property)
{
$this->validateOnly($property);
}
public function submit()
{
$this->validate();
/** @var \App\Models\User */
$user = Auth::user();
if (RateLimiter::tooManyAttempts('update-blurb:' . $user->id, 1))
{
$wait = RateLimiter::availableIn('update-blurb:' . $user->id);
return $this->addError('blurb', __('Please wait :time before updating your blurb.', ['time' => seconds2human($wait)]));;
}
RateLimiter::hit('update-blurb:' . $user->id, 300);
$user->update(['blurb' => $this->blurb]);
$this->dispatchBrowserEvent('success', __('Your blurb has been updated.'));
}
public function render()
{
return view('livewire.account.update-blurb');
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace App\Http\Livewire\Account;
use App\Traits\PasswordValidationRules;
use App\Rules\IsCurrentPassword;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
class UpdatePassword extends Component
{
use PasswordValidationRules;
/**
* @var string
*/
public $current_password;
/**
* @var string
*/
public $password;
/**
* @var string
*/
public $password_confirmation;
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function updated($property)
{
if ($property == 'current_password')
{
return;
}
$this->validateOnly($property);
}
/**
* @param User $user
* @return array
*/
public function rules(User $user): array
{
return [
'current_password' => ['required', new IsCurrentPassword($user)],
'password' => $this->passwordRules($user->username, $user->email),
'password_confirmation' => $this->passwordConfirmationRules()
];
}
public function render()
{
return view('livewire.account.update-password');
}
public function submit()
{
/** @var \App\Models\User */
$user = Auth::user();
$data = $this->validate($this->rules($user));
$user->updatePassword($data['password'], Request::ip(), Request::userAgent(), $data['current_password']);
return redirect()->route('account')->with('status', __('Your password has been updated!'));
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace App\Http\Livewire\Account;
use App\Traits\UsernameValidationRules;
use App\Rules\IsCurrentPassword;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
class UpdateUsername extends Component
{
use UsernameValidationRules;
/**
* @var string
*/
public $new_username;
/**
* @var string
*/
public $current_password;
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function updated($property)
{
if ($property == 'current_password')
{
return;
}
$this->validateOnly($property);
}
/**
* @param User $user
* @return array
*/
public function rules(User $user): array
{
return [
'new_username' => $this->usernameRules('username'),
'current_password' => ['required', new IsCurrentPassword($user)],
];
}
public function render()
{
return view('livewire.account.update-username');
}
public function submit()
{
/** @var \App\Models\User */
$user = Auth::user();
$data = $this->validate($this->rules($user));
if (!$user->hasEnoughMoney(config('tadah.username_change_cost')))
{
return $this->dispatchBrowserEvent('alert', __('You do not have enough money to change your username.'));
}
$user->updateUsername($data['new_username'], Request::ip(), Request::userAgent());
return redirect()->route('account')->with('status', __('Your username has been successfully updated!'));
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Http\Livewire\Admin;
use App\Roles\Users;
use App\Models\Ban;
use App\Models\Action;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class ActionLog extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
/**
* @var string
*/
public $search = '';
/**
* @var array
*/
protected $queryString = [
'search' => ['except' => ''],
];
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->isSuperAdmin(), 401);
}
public function updatingSearch()
{
$this->resetPage();
}
public function render()
{
$logs = Action::search($this->search)->get()->sortByDesc('created_at');
return view('livewire.admin.action-log')->with('logs', paginate($logs, 15));
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace App\Http\Livewire\Admin;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use Livewire\Component;
use Illuminate\Support\Facades\Request;
class Alert extends Component
{
/**
* @var string
*/
public $text;
/**
* @var string
*/
public $color;
/**
* @var string
*/
public $expiry;
/**
* @return array
*/
public function rules(): array
{
return [
'text' => ['required', 'max:512'],
'color' => ['required', 'regex:/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/'],
'expiry' => ['date', 'after:today'],
];
}
public function updated($property)
{
$this->validateOnly($property);
}
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->isSuperAdmin(), 401);
}
public function mount()
{
$this->text = Cache::get('alert')?->text ?? '';
$this->color = Cache::get('alert')?->color ?? '';
$this->expiry = Cache::get('expiry')?->expiry->format('m/d/Y') ?? '';
}
public function submit()
{
$data = $this->validate();
if (!empty($data['expiry']))
{
Cache::remember('alert', (Carbon::parse($data['expiry'])->timestamp - Carbon::now()->timestamp), function() use ($data) {
return (object) [
'text' => $data['text'],
'color' => $data['color'],
'expiry' => Carbon::parse($data['expiry']),
];
});
}
else
{
Cache::put('alert', (object) [
'text' => $data['text'],
'color' => $data['color'],
]);
}
Action::log(Request::user(), Actions::SiteAlert);
return $this->dispatchBrowserEvent('reload');
}
public function render()
{
return view('livewire.admin.alert');
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace App\Http\Livewire\Admin\Ban;
use App\Roles\Users;
use App\Models\User;
use App\Models\IpAddressBan;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
use Illuminate\Support\Str;
class IpAddress extends Component
{
/**
* @var string
*/
public $identifier;
/**
* @var string
*/
public $internal_reason;
/**
* @var array
*/
public $rules = [
'identifier' => ['required', 'max:255'],
'internal_reason' => ['max:255'],
];
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_IP_ADDRESS_BAN), 401);
}
public function updated($property)
{
$this->validateOnly($property);
}
public function render()
{
return view('livewire.admin.ban.ip-address');
}
public function submit()
{
$data = $this->validate();
$to_ban = [];
/**
* Identifier whereabout check;
*
* 1. First check if the identifier is a e-mail address by seeing if it contains an '@' character in it. Get the IPs of the users that have this e-mail address and add them to $to_ban.
* 2. If the identifier wasn't an e-mail address, we proceed to check if it is an IPv6 address, by seeing if it contains a period. If it does, return an error.
* 3. If it wasn't an IPv6 address, then we check to see if it is a username (by seeing if it is alphanumeric and less than 20 characters.) If it matches this check but no users exist, we boot them out. We add the IPs of the user to the $to_ban array.
* 4. If it wasn't a username, check if it's an IPv4. If it isn't, boot them out. If it is, add it to $to_ban.
*/
if (Str::contains($data['identifier'], '@'))
{
if (is_null($users = User::whereEncrypted('email', '=', $data['identifier'])->get()))
{
return $this->addError('identifier', __('No users exist with this e-mail address.'));
}
foreach ($users as $user)
{
if ($user->isSuperAdmin())
{
return $this->addError('identifier', __('No users exist with that username.'));
}
$to_ban[] = $user->register_ip;
$to_ban[] = $user->last_ip;
}
}
elseif (Str::contains($data['identifier'], ':'))
{
return $this->addError('identifier', __('IPv6 addresses are not supported.'));
}
elseif (ctype_alnum($data['identifier']))
{
if (is_null($user = User::where('username', $data['identifier'])->first()) )
{
return $this->addError('identifier', __('No users exist with that username.'));
}
if ($user->isSuperAdmin())
{
return $this->addError('identifier', __('You may not ban superadmins.'));
}
$to_ban[] = $user->register_ip;
$to_ban[] = $user->last_ip;
}
else
{
if (!filter_var($data['identifier'], FILTER_VALIDATE_IP))
{
return $this->addError('identifier', __('Please enter a valid IPv4 address.'));
}
$to_ban[] = $data['identifier'];
}
$to_ban = array_unique($to_ban);
if (in_array(Request::ip(), $to_ban))
{
return $this->dispatchBrowserEvent('error', __('You cannot ban yourself.'));
}
$count = 0;
foreach ($to_ban as $banned_ip)
{
if (!is_null($existing = IpAddressBan::whereEncrypted('ip_address', '=', $banned_ip)->first()))
{
if ($existing->is_active)
{
continue;
}
}
$count++;
IpAddressBan::create(array_filter([
'ip_address' => $banned_ip,
'moderator_id' => Request::user()->id,
'internal_reason' => $data['internal_reason'],
'criterium' => $data['identifier']
], null, ARRAY_FILTER_USE_BOTH));
Action::log(Request::user(), Actions::AddIPBan);
}
return $this->dispatchBrowserEvent('success', __(':amount IP(s) have been banned. Please check the ban list to see who got affected.', ['amount' => number_format($count)]));
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Http\Livewire\Admin\Ban;
use App\Roles\Users;
use App\Models\IpAddressBan;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class IpAddressSearch extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
/**
* @var string
*/
public $search = '';
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_VIEW_IP_ADDRESS_BAN_LIST), 401);
}
public function updatingSearch()
{
$this->resetPage();
}
public function render()
{
if (empty(trim($this->search)))
{
$bans = IpAddressBan::orderBy('created_at', 'DESC');
}
else
{
$bans = IpAddressBan::whereEncrypted('ip_address', '=', $this->search);
}
return view('livewire.admin.ban.ip-address-search')->with('bans', paginate($bans->get(), 15));
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Http\Livewire\Admin\Ban;
use App\Models\User;
use App\Roles\Users;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Validation\Rule;
use Livewire\Component;
class Pardon extends Component
{
/**
* @var string
*/
public $username;
/**
* @var string
*/
public $pardon_reason;
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_PARDON_BAN), 401);
}
public function updated($property)
{
$this->validateOnly($property);
}
/**
* @return array
*/
public function rules(): array
{
return [
'username' => ['required', Rule::exists(User::class)],
'pardon_reason' => ['required', 'max:255']
];
}
public function render()
{
return view('livewire.admin.ban.pardon');
}
public function submit()
{
$data = $this->validate();
$user = User::where('username', $data['username'])->first();
if (!$user->isBanned())
{
return $this->addError('username', __('This user is not currently banned.'));
}
Request::user()->pardon($user, $data['pardon_reason']);
Action::log(Request::user(), Actions::PardonedUser, $user);
return $this->dispatchBrowserEvent('success', __('Successfully pardoned ban for user <b>:username</b>!', ['username' => $user->username]));
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace App\Http\Livewire\Admin\Ban;
use App\Roles\Users;
use App\Models\IpAddressBan;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class PardonIpAddress extends Component
{
/**
* @var string
*/
public $ip_address;
/**
* @var string
*/
public $internal_reason;
/**
* @var array
*/
public $rules = [
'ip_address' => ['required', 'ipv4'],
];
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_PARDON_IP_ADDRESS_BAN), 401);
}
public function updated($property)
{
$this->validateOnly($property);
}
public function render()
{
return view('livewire.admin.ban.pardon-ip-address');
}
public function submit()
{
$data = $this->validate();
if (is_null($ban = IpAddressBan::whereEncrypted('ip_address', '=', $data['ip_address'])->where('is_active', true)->first()))
{
return $this->addError('ip_address', __('That IP is not currently banned.'));
}
Request::user()->pardonIpAddressBan($ban);
Action::log(Request::user(), Actions::RemoveIPBan);
return $this->dispatchBrowserEvent('success', __('Successfully pardoned ban for IP <span class="font-monospace">:ip</span>!', ['ip' => $ban->ip_address]));
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Http\Livewire\Admin\Ban;
use App\Roles\Users;
use App\Models\Ban;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class Search extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
/**
* @var string
*/
public $search = '';
/**
* @var array
*/
protected $queryString = [
'search' => ['except' => ''],
];
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_VIEW_BAN_LIST), 401);
}
public function updatingSearch()
{
$this->resetPage();
}
public function render()
{
$bans = Ban::search($this->search)->get();
$this->dispatchBrowserEvent('admin-hook-details');
return view('livewire.admin.ban.search')->with('bans', paginate($bans, 15));
}
}

View File

@ -0,0 +1,165 @@
<?php
namespace App\Http\Livewire\Admin\Ban;
use App\Roles\Users;
use App\Models\User as UserModel;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Support\Carbon;
use Livewire\Component;
class User extends Component
{
/**
* @var string
*/
public $username;
/**
* @var string
*/
public $moderator_note;
/**
* @var string
*/
public $internal_reason;
/**
* @var int
*/
public $duration_preset = 0;
/**
* @var ?string
*/
public $offensive_item = null;
/**
* @var ?string
*/
public $custom_expiry_date = null;
/**
* @var mixed
*/
public $is_appealable = true;
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_GENERAL_BAN), 401);
}
/**
* @return array
*/
public function rules(): array
{
return [
'username' => ['required', Rule::exists(UserModel::class)],
'moderator_note' => ['required', 'max:255'],
'internal_reason' => ['required', 'max:255'],
'duration_preset' => ['required', Rule::in([0, 1, 2, 3, 4, 5, 6, 7])],
'offensive_item' => ['nullable'],
'custom_expiry_date' => ['required_if:duration_preset,6', 'date', 'after:today', 'nullable'],
];
}
public function render()
{
return view('livewire.admin.ban.user');
}
public function updated($property)
{
$this->validateOnly($property);
}
public function submit()
{
$data = $this->validate();
$user = UserModel::where('username', $data['username'])->first();
if ($user->isBanned())
{
return $this->addError('username', __('That user is already banned.'));
}
if ($user->username == Request::user()->username)
{
return $this->addError('username', __('You may not moderate yourself.'));
}
if ($user->isSuperAdmin())
{
return $this->addError('username', __('You may not moderate superadmins.'));
}
$is_warning = $data['duration_preset'] == 0;
$is_poison_ban = $data['duration_preset'] == 7;
$expiry_date = null;
if (!$is_warning && !$is_poison_ban)
{
$expiry_date = match($data['duration_preset'])
{
'1' => Carbon::now()->addDays(1), // 1 day
'2' => Carbon::now()->addDays(3), // 3 days
'3' => Carbon::now()->addDays(7), // 7 days
'4' => Carbon::now()->addDays(14), // 14 days
'5' => null, // Account Deletion
'6' => Carbon::parse($data['custom_expiry_date']) // Custom Date
};
}
if ($is_warning)
{
Request::user()->punish($user, [
'internal_reason' => $data['internal_reason'],
'moderator_note' => $data['moderator_note'],
'offensive_item' => $data['offensive_item'],
'is_warning' => true,
]);
Action::log(Request::user(), Actions::WarnedUser, $user);
}
else
{
$ban = Request::user()->punish($user, [
'internal_reason' => $data['internal_reason'],
'moderator_note' => $data['moderator_note'],
'offensive_item' => $data['offensive_item'],
'expiry_date' => $expiry_date,
'is_appealable' => !empty($this->is_appealable),
]);
if (Request::user()->may(Users::roleset(), Users::MODERATION_POISON_BAN) && $is_poison_ban)
{
$user->ban->poison();
Action::log(Request::user(), Actions::PoisonBannedUser, $user);
}
else
{
if ($expiry_date)
{
Action::log(Request::user(), Actions::TempBannedUser, $ban);
}
else
{
Action::log(Request::user(), Actions::PermBannedUser, $user);
}
}
}
return $this->dispatchBrowserEvent('success', __('Successfully punished user <b>:username</b>!', ['username' => $user->username]));
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace App\Http\Livewire\Admin\GameServer;
use App\Models\GameServer;
use App\Roles\GameServers;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class All extends Component
{
use WithPagination;
/**
* @var \Illuminate\Support\Collection
*/
public $game_servers;
/**
* @var string
*/
protected $paginationTheme = 'bootstrap';
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(GameServers::roleset(), GameServers::VIEW), 401);
}
public function mount($gameServers)
{
$this->game_servers = $gameServers;
}
/**
* @return array
*/
public function getListeners(): array
{
$listeners = [];
foreach ($this->game_servers as $game_server)
{
$listeners["echo-private:game-servers.{$game_server->uuid},GameServer\\StateChange"] = '$refresh';
$listeners["echo-private:game-servers.{$game_server->uuid},GameServer\\NewPlaceJob"] = '$refresh';
$listeners["echo-private:game-servers.{$game_server->uuid},GameServer\\NewThumbnailJob"] = '$refresh';
}
return $listeners;
}
public function render()
{
$servers = paginate($this->game_servers, 15);
return view('livewire.admin.game-server.all', compact('servers'));
}
}

View File

@ -0,0 +1,124 @@
<?php
namespace App\Http\Livewire\Admin\GameServer;
use App\Roles\GameServers;
use App\Models\GameServer;
use App\Models\Action;
use App\Enums\Actions;
use App\Rules\IsSiprNameOrIpAddress;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
class Create extends Component
{
/**
* @var string
*/
public $ip_address;
/**
* @var integer
*/
public $maximum_place_jobs;
/**
* @var integer
*/
public $maximum_thumbnail_jobs;
/**
* @var integer
*/
public $port = 64989;
/**
* @var mixed
*/
public $has_vnc = false;
/**
* @var ?int
*/
public $vnc_port = null;
/**
* @var ?string
*/
public $vnc_password = null;
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(GameServers::roleset(), GameServers::CREATE), 401);
}
public function updated($property)
{
$this->validateOnly($property);
}
/**
* @return array
*/
public function rules(): array
{
return [
'ip_address' => ['required', new IsSiprNameOrIpAddress()], // Rule::unique(GameServer::class)
'maximum_place_jobs' => ['required', 'integer', 'numeric', 'min:5'],
'maximum_thumbnail_jobs' => ['required', 'integer', 'numeric', 'min:5'],
'port' => ['required', 'integer', 'numeric', 'min:0', 'max:65535'],
'vnc_port' => ['min:0', 'max:65535', 'nullable'],
'vnc_password' => ['min:0', 'max:512', 'nullable'],
];
}
public function render()
{
return view('livewire.admin.game-server.create');
}
public function submit()
{
$data = $this->validate();
if (!is_null(GameServer::whereEncrypted('ip_address', '=', $data['ip_address'])->first()))
{
$this->addError('ip_address', __('A game server already exists with that IP address.'));
}
if (!isset($data['vnc_port']) && !empty($this->has_vnc))
{
$this->addError('vnc_port', __('Please specify a VNC port.'));
}
if (!isset($data['vnc_password']) && !empty($this->has_vnc))
{
$this->addError('vnc_password', __('Please specify a VNC password.'));
}
if (!$this->getErrorBag()->isEmpty())
{
return;
}
$game_server = GameServer::create(array_filter([
'uuid' => uuid(),
'ip_address' => $data['ip_address'],
'port' => $data['port'],
'access_key' => GameServer::generateAccessKey(),
'maximum_place_jobs' => $data['maximum_place_jobs'],
'maximum_thumbnail_jobs' => $data['maximum_thumbnail_jobs'],
'has_vnc' => !empty($this->has_vnc),
'vnc_port' => $data['vnc_port'] ?? null,
'vnc_password' => $data['vnc_password'] ?? null,
], null, ARRAY_FILTER_USE_BOTH));
Action::log(Request::user(), Actions::CreatedGameServer, $game_server);
return redirect()->route('admin.game-server.view', $game_server->uuid)->with('success', __('Successfully created game server!'));
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Http\Livewire\Admin\GameServer;
use App\Models\GameServer;
use App\Roles\GameServers;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
class Delete extends Component
{
/**
* @var GameServer
*/
public $gameServer;
/**
* @param GameServer $gameServer
*/
public function mount($gameServer)
{
$this->gameServer = $gameServer;
}
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(GameServers::roleset(), GameServers::MANAGE), 401);
}
public function render()
{
return view('livewire.admin.game-server.delete');
}
public function submit()
{
$this->gameServer->delete();
Action::log(Request::user(), Actions::DeletedGameServer, $this->gameServer);
return redirect()->route('admin.game-server.all')->with('success', __('Successfully deleted game server!'));
}
}

View File

@ -0,0 +1,146 @@
<?php
namespace App\Http\Livewire\Admin\GameServer;
use App\Roles\GameServers;
use App\Rules\IsSiprNameOrIpAddress;
use App\Models\GameServer;
use App\Models\Action;
use App\Enums\Actions;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
class Manage extends Component
{
/**
* @var GameServer
*/
public $gameServer;
/**
* @var string
*/
public $ip_address;
/**
* @var integer
*/
public $maximum_place_jobs;
/**
* @var integer
*/
public $maximum_thumbnail_jobs;
/**
* @var integer
*/
public $port = 64989;
/**
* @var mixed
*/
public $has_vnc = true;
/**
* @var ?int
*/
public $vnc_port = null;
/**
* @var ?string
*/
public $vnc_password = null;
/**
* @param GameServer $gameServer
*/
public function mount($gameServer)
{
$this->gameServer = $gameServer;
$this->ip_address = $this->gameServer->ip_address;
$this->maximum_place_jobs = $this->gameServer->maximum_place_jobs;
$this->maximum_thumbnail_jobs = $this->gameServer->maximum_thumbnail_jobs;
$this->port = $this->gameServer->port;
$this->has_vnc = $this->gameServer->has_vnc;
$this->vnc_port = $this->gameServer->vnc_port;
$this->vnc_password = $this->gameServer->vnc_password;
}
public function updated($property)
{
$this->validateOnly($property);
}
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(GameServers::roleset(), GameServers::MANAGE), 401);
}
public function render()
{
return view('livewire.admin.game-server.manage');
}
/**
* @return array
*/
public function rules(): array
{
return [
'ip_address' => ['required', new IsSiprNameOrIpAddress()], // Rule::unique(GameServer::class)
'maximum_place_jobs' => ['required', 'integer', 'numeric', 'min:5'],
'maximum_thumbnail_jobs' => ['required', 'integer', 'numeric', 'min:5'],
'port' => ['required', 'integer', 'numeric', 'min:0', 'max:65535'],
'vnc_port' => ['min:0', 'max:65535', 'nullable'],
'vnc_password' => ['min:0', 'max:512', 'nullable'],
];
}
public function submit()
{
$data = $this->validate();
if (is_null($server = GameServer::whereEncrypted('ip_address', '=', $data['ip_address'])->first()))
{
if (!$server->is($this->gameServer))
{
$this->addError('ip_address', __('A game server already exists with that IP address.'));
}
}
if (!isset($data['vnc_port']) && !empty($this->has_vnc))
{
$this->addError('vnc_port', __('Please specify a VNC port.'));
}
if (!isset($data['vnc_password']) && !empty($this->has_vnc))
{
$this->addError('vnc_password', __('Please specify a VNC password.'));
}
if (!$this->getErrorBag()->isEmpty())
{
return;
}
$this->gameServer->update(array_filter([
'ip_address' => $this->ip_address,
'maximum_place_jobs' => $this->maximum_place_jobs,
'maximum_thumbnail_jobs' => $this->maximum_thumbnail_jobs,
'port' => $this->port,
'has_vnc' => $this->has_vnc,
'vnc_port' => $data['vnc_port'] ?? null,
'vnc_password' => $data['vnc_password'] ?? null,
], null, ARRAY_FILTER_USE_BOTH));
Action::log(Request::user(), Actions::ModifiedGameServer, $this->gameServer);
return $this->dispatchBrowserEvent('success', __('Successfully updated game server!'));
}
}

View File

@ -0,0 +1,46 @@
<?php
namespace App\Http\Livewire\Admin\User;
use App\Roles\Users;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class AssociatedAccounts extends Component
{
use WithPagination;
/**
* @var string
*/
protected $paginationTheme = 'bootstrap';
/**
* @var mixed
*/
private $accounts;
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_VIEW_ASSOCIATED_ACCOUNTS), 401);
}
/**
* @param mixed $accounts
*/
public function mount(mixed $accounts)
{
$this->accounts = $accounts;
}
public function render()
{
return view('livewire.admin.user.associated-accounts')->with('accounts', $this->accounts->paginate(10));
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Http\Livewire\Admin\User;
use App\Roles\Users;
use App\Models\Ban;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class ModerationHistory extends Component
{
use WithPagination;
/**
* @var string
*/
protected $paginationTheme = 'bootstrap';
/**
* @var \App\Models\User
*/
private $user;
/**
* @param \App\Models\User $user
*/
public function mount(User $user)
{
$this->user = $user;
}
public function __construct()
{
abort_unless(Auth::check(), 401);
/** @var \App\Models\User */
$user = Auth::user();
abort_unless($user->may(Users::roleset(), Users::MODERATION_VIEW_BAN_HISTORY), 401);
}
public function render()
{
$bans = Ban::where('user_id', $this->user->id);
return view('livewire.admin.user.moderation-history')->with('bans', $bans->paginate(15));
}
}

View File

@ -0,0 +1,187 @@
<?php
namespace App\Http\Livewire\Auth;
use App\Models\User;
use App\Models\PoisonedIpAddress;
use App\Rules\IsValidInviteKey;
use App\Traits\PasswordValidationRules;
use App\Traits\UsernameValidationRules;
use App\Traits\EmailValidationRules;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Livewire\Component;
class Register extends Component
{
use PasswordValidationRules, UsernameValidationRules, EmailValidationRules;
/**
* @var string
*/
public $username;
/**
* @var string
*/
public $email;
/**
* @var string
*/
public $password;
/**
* @var string
*/
public $password_confirmation;
/**
* @var string
*/
public $key;
/**
* @var mixed
*/
public $tos;
/**
* @var mixed
*/
public $age;
/**
* @var string
*/
public $captcha;
/**
* @var array
*/
public $input_began = [
'username' => false,
'email' => false,
'password' => false,
'password_confirmation' => false,
'key' => false,
'tos' => false,
'age' => false,
];
public function __construct()
{
abort_if(Auth::check(), 401);
abort_unless(is_null(PoisonedIpAddress::whereEncrypted('ip_address', '=', Request::ip())->first()), 404);
}
/**
* @return array
*/
public function rules(): array
{
$rules = [
'username' => $this->usernameRules(),
'email' => $this->emailRules(),
'password' => $this->passwordRules($this->username, $this->email),
'password_confirmation' => $this->passwordConfirmationRules(),
'tos' => ['required', 'min:1'],
'age' => ['required', 'min:1'],
];
if (config('tadah.invite_keys_required'))
{
$rules['key'] = ['required', 'string', new IsValidInviteKey()];
}
return $rules;
}
public function data()
{
return $this->unwrapDataForValidation($this->prepareForValidation($this->getDataForValidation($this->rules())));
}
public function render()
{
$bag = $this->getErrorBag();
$icon = function ($field) use ($bag) {
if ($field == 'documents')
{
return match (true)
{
$bag->has('tos') || $bag->has('age') => 'fa-xmark',
!$bag->has('tos') && !$bag->has('age') && $this->input_began['tos'] && $this->input_began['age'] => 'fa-check',
default => 'fa-hyphen'
};
}
return match(true)
{
$bag->has($field) && $this->input_began[$field] => 'fa-xmark',
!$bag->has($field) && $this->input_began[$field] => 'fa-check',
default => 'fa-hyphen'
};
};
$status = function ($field) use ($bag) {
return match(true)
{
$bag->has($field) && $this->input_began[$field] => 'is-invalid',
!$bag->has($field) && $this->input_began[$field] && $field != 'tos' && $field != 'age' => 'is-valid',
default => null
};
};
$feedback = function ($field) use ($icon) {
return match($icon($field)) {
'fa-xmark' => 't_error-feedback',
'fa-check' => 't_success-feedback',
'fa-hyphen' => 't_disabled-feedback'
};
};
return view('livewire.auth.register', compact('icon', 'status', 'feedback'));
}
public function updated($property)
{
if ($property == 'captcha')
{
return;
}
$this->input_began[$property] = true;
$validator = validator($this->data(), $this->rules());
$this->dispatchBrowserEvent('validated', !$validator->fails());
$this->validateOnly($property);
}
public function register()
{
$captchaValidation = validator(['captcha' => $this->captcha], ['captcha' => ['required', recaptchaRuleName()]]);
if ($captchaValidation->fails())
{
return $this->dispatchBrowserEvent('fatal', __('The captcha challenge failed. Please try again.'));
}
$primaryValidation = validator($this->data(), $this->rules());
if ($primaryValidation->fails())
{
return $this->dispatchBrowserEvent('fatal', __('An unexpected error occurred. Please try again.'));
}
if (!is_null(PoisonedIpAddress::whereEncrypted('ip_address', '=', Request::ip())->first()))
{
return abort(404);
}
User::register($primaryValidation->validated(), Request::ip());
return $this->dispatchBrowserEvent('register-complete');
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Livewire\Dashboard;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class BestFriends extends Component
{
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function render()
{
return view('livewire.dashboard.best-friends');
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace App\Http\Livewire\Dashboard;
use App\Models\Status;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Component;
class Feed extends Component
{
/**
* @var string
*/
public $status;
/**
* @var bool
*/
public $loading = true;
/**
* @var array
*/
protected $rules = [
'status' => ['required', 'min:3', 'max:140'],
];
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function load()
{
$this->loading = false;
}
public function share()
{
$this->validate();
/** @var \App\Models\User */
$user = Auth::user();
$key = ('create-feed-post:' . $user->id);
if (RateLimiter::tooManyAttempts($key, 1))
{
$wait = RateLimiter::availableIn($key);
return $this->addError('status', __('Please wait :time before updating your status.', ['time' => seconds2human($wait, true)]));;
}
RateLimiter::hit('create-feed-post:' . Auth::user()->id, 300);
$status = Status::create([
'content' => $this->status,
'creator_id' => $user->id
]);
$user->updateStatus($status);
}
public function updated($property)
{
$this->validateOnly($property);
}
public function render()
{
/** @var \App\Models\User */
$user = Auth::user();
$posts = collect([]);
$this->status = $user->status?->content ?? '';
if ($this->loading)
{
return view('livewire.dashboard.feed', compact('posts', 'user'));
}
// ... merge users own posts
$posts = $posts->merge(Status::where('creator_id', $user->id)->get());
// ... merge posts from friends
$friends = $user->friends()->pluck('id')->all();
$posts = $posts->merge(Status::whereIn('creator_id', $friends)->get());
// ... merge posts from groups
// TODO
// ... sort
$posts = $posts->sortByDesc('id');
return view('livewire.dashboard.feed', compact('posts', 'user'));
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Livewire\Dashboard;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class RecentlyPlayedGames extends Component
{
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function render()
{
return view('livewire.dashboard.recently-played-games');
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace App\Http\Livewire\Develop;
use App\Enums\AssetType;
use App\Enums\DevelopPage;
use App\Enums\CreatorType;
use App\Models\Asset;
use App\Models\Universe;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class Assets extends Component
{
use WithPagination;
/**
* @var AssetType
*/
public $selected_type;
/**
* @var DevelopPage
*/
public $selected_page;
protected $listeners = ['assetCreated' => 'render'];
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function render()
{
if ($this->selected_type)
{
abort_unless($this->selected_type->isDevelopType(), 401);
$assets = Asset::where('creator_id', Auth::user()->id)
->where('creator_type', CreatorType::User->value)
->where('type', $this->selected_type->value)
->orderBy('created_at', 'desc')
->get();
}
else
{
abort_unless($this->selected_page, 401);
if ($this->selected_page == DevelopPage::Games)
{
$assets = Universe::where('creator_id', Auth::user()->id)
->where('creator_type', CreatorType::User->value)
->orderBy('created_at', 'desc')
->get();
}
}
return view('livewire.develop.assets', [
'assets' => paginate($assets, 10),
'selected_type' => $this->selected_type,
'selected_page' => $this->selected_page
]);
}
}

View File

@ -0,0 +1,185 @@
<?php
namespace App\Http\Livewire\Develop;
use App\Enums\AssetType;
use App\Models\Asset;
use App\Helpers\Cdn;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\TemporaryUploadedFile;
use Livewire\WithFileUploads;
use claviska\SimpleImage;
class Create extends Component
{
use WithFileUploads;
/**
* @var AssetType
*/
public $selected_type;
/**
* @var TemporaryUploadedFile
*/
public $asset_file;
/**
* @var string
*/
public $asset_name;
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function mount()
{
abort_unless($this->selected_type->isDevelopCreatable(), 404);
}
/**
* @return array
*/
protected function rules(): array
{
return [
'asset_name' => ['required', 'min:3', 'max:50'],
'asset_file' => ['required', ... $this->selected_type->rules()]
];
}
public function upload()
{
$this->validate();
if (RateLimiter::tooManyAttempts('create-asset:' . Auth::user()->id, 1))
{
$wait = RateLimiter::availableIn('create-asset:' . Auth::user()->id);
$this->dispatchBrowserEvent('error', __('Please wait :time before creating a new :asset_type.', ['time' => seconds2human($wait), 'asset_type' => $this->selected_type->fullname()]));
return;
}
// static thumbnail processing
if (in_array($this->selected_type, [AssetType::TShirt, AssetType::Decal]))
{
try
{
$image = new SimpleImage($this->asset_file->getRealPath());
}
catch(\Exception $exception)
{
$this->addError('asset_file', __('Failed to process image, it might be corrupted?'));
return;
}
if ($this->selected_type == AssetType::TShirt)
{
$imageData = new SimpleImage();
$imageData->fromNew($image->getWidth(), $image->getWidth());
$assetThumbnail = new SimpleImage(resource_path('img/tshirt-template.png'));
$assetThumbnail->resize(420, 420);
// fit the image in a 1:1 canvas, 420x420 max
$imageData->resize($image->getWidth());
$imageData->overlay($image, 'top');
if ($image->getWidth() > 420) $imageData->resize(420, 420);
// image thumbnail must be 420x420
$imageThumbnail = clone $imageData;
$imageThumbnail->resize(420, 420);
// asset thumbnail is image thumbnail overlayed onto t-shirt template
$assetThumbnailOverlay = clone $imageThumbnail;
$assetThumbnailOverlay->resize(250, 250);
$assetThumbnail->overlay($assetThumbnailOverlay, 'center', 1);
}
else if ($this->selected_type == AssetType::Decal)
{
// image retains original ratio, original size is retained if under 420x420
$imageData = clone $image;
$imageData->bestFit(420, 420);
// image and asset thumbnails are the image resized to 420x420
$imageThumbnail = clone $image;
$imageThumbnail->resize(420, 420);
$assetThumbnail = clone $imageThumbnail;
}
$imageData = $imageData->toString();
$imageThumbnail = $imageThumbnail->toString();
$assetThumbnail = $assetThumbnail->toString();
RateLimiter::hit('create-asset:' . Auth::user()->id, 30);
$imageAsset = Asset::create([
'name' => $this->asset_name,
'description' => $this->selected_type->fullname() . ' ' . AssetType::Image->name,
'type' => AssetType::Image->value,
'creator_id' => Auth::user()->id
]);
$imageAsset->initialize($imageData, $imageThumbnail);
$document = simplexml_load_file(resource_path(sprintf('xml/%s.xml', $this->selected_type->name)));
$document->xpath("//url")[0][0] = sprintf('%s/asset/?id=%d', config('app.url'), $imageAsset->id);
// we need to remove the first line that contains the XML declaration
$assetData = $document->asXML();
$assetData = preg_replace('/^.+\n/', '', $assetData);
}
else
{
if ($this->selected_type == AssetType::Audio)
{
$assetThumbnail = file_get_contents(resource_path('img/audio.png'));
$assetData = $this->asset_file->get();
}
if ($this->selected_type == AssetType::Animation)
{
$assetThumbnail = file_get_contents(resource_path('img/animation.png'));
$assetData = $this->asset_file->get();
}
RateLimiter::hit('create-asset:' . Auth::user()->id, 30);
}
$asset = Asset::create([
'name' => $this->asset_name,
'description' => $this->selected_type->fullname(),
'type' => $this->selected_type->value,
'image_id' => $imageAsset->id ?? null,
'creator_id' => Auth::user()->id
]);
$asset->initialize($assetData, $assetThumbnail);
if (in_array($this->selected_type, [AssetType::TShirt, AssetType::Decal]))
{
Cdn::save($imageData);
Cdn::save($imageThumbnail, 'png');
}
Cdn::save($assetData);
Cdn::save($assetThumbnail, 'png');
$this->dispatchBrowserEvent('success', __('Successfully created :asset_type.', ["asset_type" => __($this->selected_type->fullname())]));
$this->emitTo('develop.assets', 'assetCreated');
}
public function updated($property)
{
$this->validateOnly($property);
}
public function render()
{
return view('livewire.develop.create')->with('selected_type', $this->selected_type);
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace App\Http\Livewire\Develop;
use App\Enums\AssetType;
use App\Enums\DevelopPage;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Panel extends Component
{
/**
* @var AssetType
*/
public $selected_type = AssetType::Place;
/**
* @var DevelopPage
*/
public $selected_page = false;
public function __construct()
{
abort_unless(Auth::check(), 401);
}
public function setType($enum_value)
{
$type = AssetType::tryFrom($enum_value);
if (is_null($type) || !$type->isDevelopType())
{
$this->reset('selected_type');
$this->reset('selected_page');
}
$this->selected_type = $type;
$this->selected_page = false;
}
public function setPage($enum_value)
{
$page = DevelopPage::tryFrom($enum_value);
if (is_null($page))
{
$this->reset('selected_type');
$this->reset('selected_page');
}
$this->selected_type = false;
$this->selected_page = $page;
}
public function render()
{
return view('livewire.develop.panel', [
'types' => AssetType::developTypes(),
'pages' => DevelopPage::developPages(),
'selected_type' => $this->selected_type,
'selected_page' => $this->selected_page
]);
}
}

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