Compare commits

...

103 commits

Author SHA1 Message Date
a334b5d7d8 Bumped VERSION. 2025-01-04 02:51:07 +00:00
2a191c5b19 Switched to integrated EEPROM client. 2025-01-04 02:50:21 +00:00
77bfc10475 Updated libraries. 2025-01-04 02:47:54 +00:00
6e229a363e Updated LICENCE year. 2025-01-03 19:15:56 +00:00
a1a3d0d4b1 Update VERSION. 2025-01-03 19:15:21 +00:00
51b6d29a39 Alter output of /v1/me if banned. 2025-01-03 19:14:48 +00:00
07c822c2d7 Bumped VERSION. 2024-12-23 01:49:03 +00:00
53b9a547b3 Fixed PM actions not doing anything. 2024-12-23 01:48:32 +00:00
ac2d99c241 Updated libraries. 2024-12-20 00:40:15 +00:00
68ce58f382 Bumped VERSION. 2024-12-20 00:30:03 +00:00
8569d2b65d Moved topic listing into the router. 2024-12-20 00:29:14 +00:00
504154ac38 p= -> page= for forum categories. 2024-12-20 00:10:20 +00:00
06faf86d05 Moved forum category views into the router. 2024-12-19 23:41:52 +00:00
c061f46a2e Bumped VERSION. 2024-12-19 02:27:51 +00:00
b8687406b8 Shortcut for pagination appending. 2024-12-19 02:27:28 +00:00
5e1d36abac Use nextParameter instead of addParameter and manually counting where possible. 2024-12-19 02:23:05 +00:00
0f1a8886a6 Rewrote the Pagination handler. 2024-12-19 01:22:26 +00:00
706fbe8283 Moved forum index into the router. 2024-12-18 23:58:53 +00:00
e53f7fdc08 Minor design update for roles list in settings. 2024-12-18 03:26:44 +00:00
162ea6ac81 Bumped VERSION. 2024-12-18 03:08:17 +00:00
308ba33377 Replaced confirm pages with dynamic requests on the forum. 2024-12-18 03:07:48 +00:00
3d8d0b7e88 Added global <noscript> notice. 2024-12-17 21:44:48 +00:00
6c723f2ecc Made $x use significantly less ugly. 2024-12-17 21:37:28 +00:00
bc2d7a08d0 Final set of CSRFP -> CSRF renames, use headers instead of POST fields and build CSRF handling into the XHR wrapper. 2024-12-17 21:23:38 +00:00
2e9adf0d06 Fixed migrations being impossible to run on a clean database. 2024-12-17 20:32:09 +00:00
3a0f27011d Updated .gitignore. 2024-12-15 17:14:43 +00:00
5e0a2530a8 Raised checking level from 5 to 6. 2024-12-02 21:33:15 +00:00
5cf2529209 Fixed PHPstan detections. 2024-12-02 02:28:08 +00:00
b76e7ab264 Forgot to remove one of the vs. 2024-12-02 00:37:46 +00:00
51981a3aef Imported tag creation script with VERSION file. 2024-12-02 00:36:27 +00:00
80e76ff15e Fixed oversight on memberlist. 2024-12-02 00:34:00 +00:00
b08ebce214 Fixed omegadumb oversight. 2024-12-01 01:37:53 +00:00
ec2d81a8b1 Fixed oversight... 2024-11-30 15:30:30 +00:00
1f502d83b4 Forgot half of it. 2024-11-30 04:20:20 +00:00
3ed0e50ae1 Removed getter/setter methods in favour of property hooks and asymmetric visibility. 2024-11-30 04:09:29 +00:00
b2301dde45 Added simpler avatar URL field. 2024-11-22 20:57:02 +00:00
39be84fcc0 Reordered output cus it was bothering me. 2024-11-21 20:05:56 +00:00
242e70eabf Added option to include e-mail address in user rpc call. 2024-11-21 19:37:04 +00:00
174ceaa4e7 Count loads of old emote endpoint in case I forgot to replace anywhere. 2024-11-14 04:13:57 +00:00
058b409adf Added RPC for emotes list. 2024-11-14 02:44:02 +00:00
8e006c7003 Updated RPC library. 2024-11-13 23:30:34 +00:00
23d47fa6d2 Ensure content passed to the parse_text filter is escaped. 2024-11-07 00:33:42 +00:00
bdad34e065 Updated libraries. 2024-10-28 18:35:19 +00:00
fc6a899f16 Fixed some URLs not getting registered properly. 2024-10-05 15:28:56 +00:00
1f16de2239 Fixed casing oversight. 2024-10-05 14:39:43 +00:00
1550a5da57 Removed all references to the IPAddress class. 2024-10-05 14:22:14 +00:00
7ef1974c88 Fixed undropkicked I. 2024-10-05 03:36:53 +00:00
0f45a5f60f Updated to latest Index version. 2024-10-05 02:40:29 +00:00
324fe21d73 Use attributes for JSON encoding. 2024-09-30 17:38:08 +00:00
153abde3a2 Updated libraries. 2024-09-30 17:37:41 +00:00
f8aaa71260 Added optional string role IDs for the API. 2024-09-16 21:44:37 +00:00
37a3bc1ee6 Updated libraries. 2024-09-16 20:51:46 +00:00
f547812d5a Added RPC endpoint for fetching user info. 2024-09-05 20:08:31 +00:00
8a06836985 Added auth RPC routes. 2024-08-25 23:03:46 +00:00
34528ae413 Fixed return type. 2024-08-18 20:54:39 +00:00
0bf7ca0d52 Replaced internal Flashii ID routes with RPC library. 2024-08-16 19:29:57 +00:00
cc9fccdf18 Updated Index and switched to Carbon for date handling. 2024-08-04 21:37:12 +00:00
ca77b501e7 Removed stray Jeff. 2024-07-27 20:11:06 +00:00
2439f87df9 Added very preliminary support for Bearer tokens to chat authentication. 2024-07-21 01:50:42 +00:00
400253e04b Added interop endpoints for Hanyuu. 2024-07-20 19:35:50 +00:00
01c60e3027 Updated libraries. 2024-07-18 03:42:16 +00:00
37d8413118 Updated build script. 2024-06-11 00:48:44 +00:00
8cfa07bc8c SharpConfig -> FileConfig 2024-06-03 23:04:59 +00:00
a65579bf9d Updated libraries. 2024-06-03 23:04:21 +00:00
44a4bb6e6f Prevent access to private messages when impersonating a user. 2024-06-02 19:57:58 +00:00
ec00cfa176 Base64 encode PM titles and bodies in the database.
To prevent personal discomfort with having to do database messages and seeing people's personal conversations.
I haven't run into it yet, but I'd rather avoid it altogether.
2024-06-02 19:54:33 +00:00
1d295df8da Added broom closet PM stats. 2024-06-02 19:43:57 +00:00
6a88ed8b11 Updated libraries. 2024-05-30 22:02:09 +00:00
36bcf1ab1d Built Playpen icon updating into Misuzu.
Was previously handled by a stinky script.
2024-05-30 22:00:41 +00:00
5d3e1d4960 Fixed wrong HTTP verb. 2024-03-30 15:22:11 +00:00
9bb943bacf Fixed various oversights. 2024-03-30 03:19:08 +00:00
107d16cf46 Updated Misuzu to new HTTP router. 2024-03-30 03:14:03 +00:00
0afc5186a7 Fixed error when trying to access a topic with no posts associated. 2024-02-24 22:03:32 +00:00
0300bae994 hurr 2024-02-21 00:31:25 +00:00
cb0c64f8ed Stinky fix for impersonation in chat auth. 2024-02-20 23:56:43 +00:00
89ef9d9ad1 Fixed bans no longer working. 2024-02-15 22:55:24 +00:00
c02d922dc6 Fixed Forum Activity section always showing up. 2024-02-13 21:22:56 +00:00
80cd6222c4 Fixed profile fields not showing up anymore. 2024-02-11 02:22:22 +00:00
344a3c9160 Missed one! 2024-02-09 16:07:43 +00:00
df5dbdf3ad Fixed forum/topic breadcrumbs. 2024-02-08 15:20:44 +00:00
c0caceed7b Fixed use of wrong BanInfo constructor. 2024-02-08 15:18:57 +00:00
be54ce2c22 Fixed oversights on landing page. 2024-02-08 00:06:23 +00:00
070dc5e782 Added lazy database object creation. 2024-02-07 00:04:45 +00:00
b89621cb1a Added PMs to data export. 2024-02-05 22:56:51 +00:00
760cca0e5d whoops 2024-02-02 21:53:36 +00:00
fe77f1616c Updated to new EEPROM script. 2024-02-02 21:42:40 +00:00
eb81ed7a82 Added notice when recipient is banned. 2024-02-02 02:16:37 +00:00
8ef11afe02 Check if recipient is actually able to receive messages. 2024-02-02 02:07:29 +00:00
cca016ba10 Prevent banned users from sending messages. 2024-02-02 01:59:21 +00:00
b80151583e Added private messages. 2024-01-30 23:47:02 +00:00
d8cc208a85 Use accent-color and color-scheme CSS directives. 2024-01-25 18:17:54 +00:00
4b2f9a2fec Fixed Ctrl+Enter submission not working anymore either. 2024-01-25 00:18:56 +00:00
ddb255bf32 Fixed forum post form throwing up the navigation confirmation when it isn't supposed to. 2024-01-25 00:12:53 +00:00
5a70e3f3f1 Include SameSite attribute on cookies. 2024-01-24 22:14:48 +00:00
bd3e055323 Rewrote Javascript code. 2024-01-24 21:53:26 +00:00
dba5754ccc Fixed error when trying to add a new change. 2024-01-24 18:28:13 +00:00
ec6ba3f781 Imported new asset build script. 2024-01-24 18:24:40 +00:00
70ec285f99 Added links to Amimami repositories. 2024-01-18 20:31:08 +00:00
77eadd5bde Adjusted CORS handling for emoticon endpoint. 2024-01-17 19:57:46 +00:00
f0fc735975 Updated browserlists. 2024-01-08 13:43:34 +00:00
adb80bad9e Added server side image map support. 2024-01-08 13:42:22 +00:00
f30cf41f86 Ported boolean attribute support. 2024-01-08 13:36:47 +00:00
b4f5dd0660 Removed broken CONSTRAINT from perms table creation. 2023-12-16 18:51:17 +00:00
271 changed files with 12008 additions and 8633 deletions

6
.gitignore vendored
View file

@ -46,6 +46,12 @@
# Google
/public/robots.txt
# Well known
/public/.well-known
# moguu?
/public/moguu.swf
/public/moguu.html
# admin
/public/admin

View file

@ -1,4 +1,4 @@
Copyright (c) 2017-2023, flashwave <me@flash.moe>
Copyright (c) 2017-2025, flashwave <me@flash.moe>
All rights reserved.
Redistribution and use in source and binary forms, with or without

View file

@ -2,6 +2,6 @@
> Misuzu can and will steal your lunch money.
## Requirements
- PHP 8.2 (64-bit)
- PHP 8.4
- MariaDB 10.6
- [Composer](https://getcomposer.org/)

1
VERSION Normal file
View file

@ -0,0 +1 @@
20250104

View file

@ -17,15 +17,10 @@ exports.process = async function(root, options) {
return '';
included.push(fullPath);
if(!fullPath.startsWith(root)) {
console.error('INVALID PATH: ' + fullPath);
if(!fullPath.startsWith(root))
return '/* *** INVALID PATH: ' + fullPath + ' */';
}
if(!fs.existsSync(fullPath)) {
console.error('FILE NOT FOUND: ' + fullPath);
if(!fs.existsSync(fullPath))
return '/* *** FILE NOT FOUND: ' + fullPath + ' */';
}
const lines = readline.createInterface({
input: fs.createReadStream(fullPath),
@ -58,6 +53,19 @@ exports.process = async function(root, options) {
break;
}
case 'buildvars':
if(typeof options.buildVars === 'object') {
const bvTarget = options.buildVarsTarget || 'window';
const bvProps = [];
for(const bvName in options.buildVars)
bvProps.push(`${bvName}: { value: ${JSON.stringify(options.buildVars[bvName])}, writable: false }`);
if(Object.keys(bvProps).length > 0)
output += `Object.defineProperties(${bvTarget}, { ${bvProps.join(', ')} });\n`;
}
break;
default:
output += line;
output += "\n";
@ -84,7 +92,7 @@ exports.housekeep = function(assetsPath) {
};
}).sort((a, b) => b.lastMod - a.lastMod).map(info => info.name);
const regex = /^(.+)-([a-f0-9]+)\.(.+)$/i;
const regex = /^(.+)[\-\.]([a-f0-9]+)\.(.+)$/i;
const counts = {};
for(const fileName of files) {

View file

@ -154,6 +154,9 @@
}
.forum__post__action {
background-color: transparent;
border: 0;
display: block;
padding: 5px 10px;
margin: 1px;
color: inherit;
@ -161,6 +164,9 @@
transition: background-color .2s;
border-radius: 3px;
cursor: pointer;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
.forum__post__action:hover,
.forum__post__action:focus {

View file

@ -146,9 +146,14 @@
}
.header__desktop__user__button__count {
position: absolute;
bottom: 1px;
right: 1px;
font-size: 10px;
top: -5px;
right: -3px;
z-index: 1;
font-size: .5em;
line-height: 1.4em;
text-align: right;
padding: 2px 2px 0;
border-radius: 4px;
background-color: var(--header-accent-colour);
opacity: .9;
border-radius: 4px;

View file

@ -3,7 +3,6 @@
padding: 0;
box-sizing: border-box;
position: relative;
outline-style: none;
}
html,
@ -57,6 +56,8 @@ body {
html {
scrollbar-color: var(--accent-colour) var(--background-colour);
accent-color: var(--accent-colour);
color-scheme: dark;
}
.main {
@ -163,6 +164,8 @@ html {
@include manage/_manage.css;
@include messages/messages.css;
@include news/container.css;
@include news/feeds.css;
@include news/list.css;

View file

@ -17,4 +17,5 @@
display: flex;
justify-content: center;
padding: 5px;
gap: 5px;
}

View file

@ -0,0 +1,37 @@
.messages-actions-item {
display: flex;
align-items: center;
height: 30px;
margin: 1px;
font-size: 1.3em;
line-height: 1.4em;
color: #fff;
text-decoration: none;
transition: background-color .1s;
width: 100%;
border: 0;
background-color: inherit;
text-align: left;
}
.messages-actions-item:hover,
.messages-actions-item:focus {
background-color: #444f;
}
.messages-actions-item:active,
.messages-actions-item-current {
background-color: var(--accent-colour) !important;
}
.messages-actions-item[disabled] {
background-color: inherit !important;
opacity: .4;
}
.messages-actions-item-icon {
text-align: center;
width: 30px;
flex-grow: 0;
flex-shrink: 0;
}
.messages-actions-item-label {
flex-grow: 1;
flex-shrink: 1;
}

View file

@ -0,0 +1,26 @@
.messages-columns {
display: flex;
gap: 2px;
}
.messages-columns-sidebar {
width: 200px;
flex-shrink: 0;
flex-grow: 0;
}
.messages-columns-content {
flex-shrink: 1;
flex-grow: 1;
overflow: hidden;
}
@media (max-width: 800px) {
.messages-columns {
flex-direction: column;
}
.messages-columns-sidebar {
width: 100%;
}
}

View file

@ -0,0 +1,80 @@
.messages-entry {
color: inherit;
text-decoration: none;
display: flex;
flex-direction: column;
padding: 2px 4px;
gap: 4px;
overflow: hidden;
cursor: pointer;
}
.messages-entry-header {
display: flex;
font-size: 1.1em;
line-height: 1.6em;
border-bottom: 2px solid #9999;
gap: 2px;
}
.messages-entry-check {
flex-grow: 0;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 20px;
}
.messages-entry-check input {
display: block;
}
.messages-entry-unread {
flex-grow: 0;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 20px;
}
.messages-entry-unread-orb {
width: 8px;
height: 8px;
background-color: var(--accent-colour);
border-radius: 100%;
}
.messages-entry-author {
font-weight: bold;
border-bottom: 2px solid var(--user-colour, currentColor);
margin: 0 0 -2px;
flex-grow: 0;
flex-shrink: 1;
overflow: hidden;
white-space: nowrap;
}
.messages-entry-spacing {
flex-grow: 1;
flex-shrink: 1;
}
.messages-entry-datetime {
flex-grow: 0;
flex-shrink: 0;
color: #aaa;
align-self: flex-end;
}
.messages-entry-subject {
line-height: 1.4em;
color: #fff;
overflow: hidden;
}
.messages-entry-preview {
line-height: 1.4em;
color: #888;
overflow: hidden;
}
.messages-entry-preview .messages-entry-overflow {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.messages-entry-overflow {
overflow: hidden;
text-overflow: ellipsis;
}

View file

@ -0,0 +1,33 @@
.messages-folder {
margin: 1px;
display: flex;
flex-direction: column;
gap: 1px;
padding: 1px;
}
.messages-folder-item {
background-color: #161616;
transition: background-color .1s;
}
.messages-folder-item:nth-child(2n) {
background-color: #1f1f1f;
}
.messages-folder-item:hover,
.messages-folder-item:focus {
background-color: #262626;
}
.messages-folder-item:active,
.messages-folder-item-current {
background-color: var(--accent-colour) !important;
}
.messages-folder-notice {
text-align: center;
margin: 10px;
}
.messages-folder-notice-text {
font-size: 1.4em;
line-height: 1.5em;
}
.messages-folder .pagination {
margin-top: 2px;
}

View file

@ -0,0 +1,135 @@
.messages-message {
display: flex;
flex-direction: column;
gap: 10px;
padding: 10px;
}
.messages-message-snippet {
cursor: pointer;
font-size: .9em;
line-height: 1.5em;
color: #888;
gap: 5px;
opacity: .8;
transition: opacity .1s;
}
.messages-message-snippet:hover,
.messages-message-snippet:focus,
.messages-message-snippet:focus-within {
opacity: 1;
}
.messages-message-draft {
border-top: 2px solid var(--accent-colour) !important;
border-left: 2px solid var(--accent-colour) !important;
border-right: 2px solid var(--accent-colour);
border-bottom: 2px solid var(--accent-colour);
}
.messages-message-deleted {
border-top: 2px solid red;
border-left: 2px solid red;
border-right: 2px solid red !important;
border-bottom: 2px solid red !important;
}
.messages-message-overflow {
display: block;
overflow: hidden;
text-overflow: ellipsis;
}
.messages-message-header {
display: flex;
gap: 10px;
border-bottom: 1px #444 solid;
padding-bottom: 10px;
align-items: center;
}
.messages-message-sender-avatar {
flex-shrink: 0;
flex-grow: 0;
width: 40px;
height: 40px;
}
.messages-message-sender-avatar img {
object-fit: cover;
}
.messages-message-details {
display: flex;
flex-direction: column;
flex-shrink: 1;
flex-grow: 1;
overflow: hidden;
gap: 2px;
}
.messages-message-details-spacing {
flex-grow: 1;
flex-shrink: 1;
}
.messages-message-header-columns {
display: flex;
gap: 2px;
}
.messages-message-sender-name {
flex-grow: 0;
flex-shrink: 1;
overflow: hidden;
white-space: nowrap;
}
.messages-message-sender-name a {
color: inherit;
text-decoration: none;
font-weight: 700;
border-bottom: 2px solid var(--user-colour, currentColor);
}
.messages-message-datetime {
flex-shrink: 0;
flex-grow: 0;
align-self: flex-end;
padding-bottom: 2px;
}
.messages-message-addressee {
display: flex;
gap: 4px;
}
.messages-message-addressee-to {
flex-shrink: 0;
flex-grow: 0;
}
.messages-message-addressee-user {
flex-shrink: 1;
flex-grow: 0;
overflow: hidden;
white-space: nowrap;
}
.messages-message-addressee-user a {
color: inherit;
text-decoration: none;
font-weight: 700;
border-bottom: 2px solid var(--user-colour, currentColor);
}
.messages-message-subject {
line-height: 2em;
}
.messages-message-body {
line-height: 1.4em;
}
.messages-message-body p:first-child {
margin-top: 0 !important;
}
.messages-message-body p:last-child {
margin-bottom: 0 !important;
}
.messages-message-snippet-body {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
line-height: 1.4em;
}

View file

@ -0,0 +1,9 @@
@include messages/actions.css;
@include messages/columns.css;
@include messages/entry.css;
@include messages/folder.css;
@include messages/message.css;
@include messages/recipient.css;
@include messages/reply.css;
@include messages/sidebar.css;
@include messages/thread.css;

View file

@ -0,0 +1,17 @@
.messages-recipient {
display: flex;
flex-direction: column;
}
.messages-recipient-avatar {
display: flex;
justify-content: center;
padding: 10px;
}
.messages-recipient-name {
padding: 5px;
}
.messages-recipient-name-input {
width: 100%;
}

View file

@ -0,0 +1,52 @@
.messages-reply-form {
display: flex;
flex-direction: column;
width: 100%;
gap: 5px;
padding: 5px;
}
.messages-reply-subject-input {
width: 100%;
}
.messages-reply-body-input {
min-width: 100%;
max-width: 100%;
min-height: 100px;
}
.messages-reply-compose .messages-reply-body-input {
min-height: 300px;
}
.messages-reply-actions {
display: flex;
padding: 1px;
gap: 1px;
}
.messages-reply-action {
background-color: transparent;
border: 0;
display: block;
padding: 5px 10px;
color: inherit;
text-decoration: none;
transition: background-color .2s;
border-radius: 3px;
cursor: pointer;
}
.messages-reply-action:hover,
.messages-reply-action:focus {
background-color: rgba(0, 0, 0, .2);
}
.messages-reply-options {
display: flex;
align-items: center;
justify-content: space-between;
}
.messages-reply-settings {
display: flex;
align-items: center;
gap: 5px;
}

View file

@ -0,0 +1,11 @@
.messages-sidebar {
position: sticky;
top: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.messages-sidebar-button {
text-align: center;
padding: 10px;
}

View file

@ -0,0 +1,5 @@
.messages-thread {
display: flex;
flex-direction: column;
gap: 1px;
}

View file

@ -1,6 +1,6 @@
.news__feeds {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-columns: 1fr;
grid-gap: 2px;
padding: 2px;
}

View file

@ -4,13 +4,12 @@
border-radius: 2px;
margin: 2px;
overflow: hidden;
width: 200px;
}
.settings__role__collection {
display: flex;
flex-wrap: wrap;
justify-content: center;
flex-direction: column;
margin: 2px;
}
@ -19,14 +18,25 @@
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.settings__role__name {
font-size: 1.2em;
line-height: 1.7em;
border-bottom: 1px solid var(--accent-colour);
padding: 0 5px;
margin: 2px 0;
min-width: 160px;
text-align: right;
}
.settings__role__separator {
flex-grow: 0;
flex-shrink: 0;
background-color: var(--accent-colour);
width: 1px;
align-self: stretch;
margin: 5px 0;
}
.settings__role__description {

24
assets/misuzu.js/csrf.js Normal file
View file

@ -0,0 +1,24 @@
#include utility.js
const MszCSRF = (() => {
let elem;
const getElement = () => {
if(elem === undefined)
elem = $q('meta[name="csrf-token"]');
return elem;
};
return {
get token() {
return getElement()?.content ?? '';
},
set token(token) {
if(typeof token !== 'string')
throw 'token must be a string';
const elem = getElement();
if(elem instanceof HTMLMetaElement)
elem.content = token;
},
};
})();

View file

@ -1,128 +0,0 @@
#include utils.js
#include uiharu.js
#include aembed.js
#include iembed.js
#include vembed.js
var MszEmbed = (function() {
let uiharu = undefined;
return {
init: function(endPoint) {
uiharu = new Uiharu(endPoint);
},
handle: function(targets) {
if(!Array.isArray(targets))
targets = Array.from(targets);
const filtered = new Map;
for(const target of targets) {
if(!(target instanceof HTMLElement)
|| !('dataset' in target)
|| !('mszEmbedUrl' in target.dataset))
continue;
const cleanUrl = target.dataset.mszEmbedUrl.replace(/ /, '%20');
if(cleanUrl.indexOf('https://') !== 0
&& cleanUrl.indexOf('http://') !== 0
&& cleanUrl.indexOf('//') !== 0) {
target.textContent = target.dataset.mszEmbedUrl;
continue;
}
$rc(target);
target.appendChild($e({
tag: 'i',
attrs: {
className: 'fas fa-2x fa-spinner fa-pulse',
style: {
width: '32px',
height: '32px',
lineHeight: '32px',
textAlign: 'center',
},
},
}));
if(filtered.has(cleanUrl))
filtered.get(cleanUrl).push(target);
else
filtered.set(cleanUrl, [target]);
}
const replaceWithUrl = function(targets, url) {
for(const target of targets) {
let body = $e({
tag: 'a',
attrs: {
className: 'link',
href: url,
target: '_blank',
rel: 'noopener noreferrer',
},
child: url
});
$ib(target, body);
$r(target);
}
};
filtered.forEach(function(targets, url) {
uiharu.lookupOne(url, function(metadata) {
if(metadata.error) {
replaceWithUrl(targets, url);
console.error(metadata.error);
return;
}
if(metadata.title === undefined) {
replaceWithUrl(targets, url);
console.warn('Media is no longer available.');
return;
}
let phc = undefined,
options = {
onembed: console.log,
};
if(metadata.type === 'youtube:video') {
phc = MszVideoEmbedPlaceholder;
options.type = 'youtube';
options.player = MszVideoEmbedYouTube;
} else if(metadata.type === 'niconico:video') {
phc = MszVideoEmbedPlaceholder;
options.type = 'nicovideo';
options.player = MszVideoEmbedNicoNico;
} else if(metadata.is_video) {
phc = MszVideoEmbedPlaceholder;
options.type = 'external';
options.player = MszVideoEmbedPlayer;
//options.frame = MszVideoEmbedFrame;
options.nativeControls = true;
options.autosize = false;
options.maxWidth = 640;
options.maxHeight = 360;
} else if(metadata.is_audio) {
phc = MszAudioEmbedPlaceholder;
options.type = 'external';
options.player = MszAudioEmbedPlayer;
options.nativeControls = true;
} else if(metadata.is_image) {
phc = MszImageEmbed;
options.type = 'external';
}
if(phc === undefined)
return;
for(const target of targets) {
const placeholder = new phc(metadata, options, target);
if(placeholder !== undefined)
placeholder.replaceElement(target);
}
});
});
},
};
})();

View file

@ -1,4 +1,4 @@
#include utils.js
#include utility.js
#include watcher.js
const MszAudioEmbedPlayerEvents = function() {
@ -56,7 +56,7 @@ const MszAudioEmbedPlayer = function(metadata, options) {
if(haveNativeControls)
playerAttrs.controls = 'controls';
const watchers = new MszWatcherCollection;
const watchers = new MszWatchers;
watchers.define(MszAudioEmbedPlayerEvents());
const player = $e({
@ -84,7 +84,8 @@ const MszAudioEmbedPlayer = function(metadata, options) {
getType: function() { return 'external'; },
};
watchers.proxy(pub);
pub.watch = (name, handler) => watchers.watch(name, handler);
pub.unwatch = (name, handler) => watchers.unwatch(name, handler);
player.addEventListener('play', function() { watchers.call('play', pub); });

View file

@ -0,0 +1,135 @@
#include utility.js
#include embed/audio.js
#include embed/image.js
#include embed/video.js
#include ext/uiharu.js
const MszEmbed = (function() {
let uiharu = undefined;
return {
init: function(endPoint) {
uiharu = new MszUiharu(endPoint);
},
handle: function(targets) {
if(!Array.isArray(targets))
targets = Array.from(targets);
const filtered = new Map;
for(const target of targets) {
if(!(target instanceof HTMLElement)
|| !('dataset' in target)
|| !('mszEmbedUrl' in target.dataset))
continue;
const cleanUrl = target.dataset.mszEmbedUrl.replace(/ /, '%20');
if(cleanUrl.indexOf('https://') !== 0
&& cleanUrl.indexOf('http://') !== 0
&& cleanUrl.indexOf('//') !== 0) {
target.textContent = target.dataset.mszEmbedUrl;
continue;
}
$rc(target);
target.appendChild($e({
tag: 'i',
attrs: {
className: 'fas fa-2x fa-spinner fa-pulse',
style: {
width: '32px',
height: '32px',
lineHeight: '32px',
textAlign: 'center',
},
},
}));
if(filtered.has(cleanUrl))
filtered.get(cleanUrl).push(target);
else
filtered.set(cleanUrl, [target]);
}
const replaceWithUrl = function(targets, url) {
for(const target of targets) {
let body = $e({
tag: 'a',
attrs: {
className: 'link',
href: url,
target: '_blank',
rel: 'noopener noreferrer',
},
child: url
});
$ib(target, body);
$r(target);
}
};
filtered.forEach(function(targets, url) {
uiharu.lookupOne(url)
.catch(ex => {
replaceWithUrl(targets, url);
console.error(ex);
})
.then(result => {
const metadata = result.body;
if(metadata.error) {
replaceWithUrl(targets, url);
console.error(metadata.error);
return;
}
if(metadata.title === undefined) {
replaceWithUrl(targets, url);
console.warn('Media is no longer available.');
return;
}
let phc = undefined,
options = {
onembed: console.log,
};
if(metadata.type === 'youtube:video') {
phc = MszVideoEmbedPlaceholder;
options.type = 'youtube';
options.player = MszVideoEmbedYouTube;
} else if(metadata.type === 'niconico:video') {
phc = MszVideoEmbedPlaceholder;
options.type = 'nicovideo';
options.player = MszVideoEmbedNicoNico;
} else if(metadata.is_video) {
phc = MszVideoEmbedPlaceholder;
options.type = 'external';
options.player = MszVideoEmbedPlayer;
//options.frame = MszVideoEmbedFrame;
options.nativeControls = true;
options.autosize = false;
options.maxWidth = 640;
options.maxHeight = 360;
} else if(metadata.is_audio) {
phc = MszAudioEmbedPlaceholder;
options.type = 'external';
options.player = MszAudioEmbedPlayer;
options.nativeControls = true;
} else if(metadata.is_image) {
phc = MszImageEmbed;
options.type = 'external';
}
if(phc === undefined)
return;
for(const target of targets) {
const placeholder = new phc(metadata, options, target);
if(placeholder !== undefined)
placeholder.replaceElement(target);
}
});
});
},
};
})();

View file

@ -1,4 +1,4 @@
#include utils.js
#include utility.js
const MszImageEmbed = function(metadata, options, target) {
options = options || {};

View file

@ -1,5 +1,5 @@
#include utils.js
#include rng.js
#include utility.js
#include uniqstr.js
#include watcher.js
const MszVideoEmbedPlayerEvents = function() {
@ -229,7 +229,7 @@ const MszVideoEmbedPlayer = function(metadata, options) {
videoAttrs.style.width = initialSize[0].toString() + 'px';
videoAttrs.style.height = initialSize[1].toString() + 'px';
const watchers = new MszWatcherCollection;
const watchers = new MszWatchers;
watchers.define(MszVideoEmbedPlayerEvents());
const player = $e({
@ -265,12 +265,13 @@ const MszVideoEmbedPlayer = function(metadata, options) {
getHeight: function() { return height; },
};
watchers.proxy(pub);
pub.watch = (name, handler) => watchers.watch(name, handler);
pub.unwatch = (name, handler) => watchers.unwatch(name, handler);
if(shouldObserveResize)
player.addEventListener('resize', function() { setSize(player.videoWidth, player.videoHeight); });
player.addEventListener('play', function() { watchers.call('play', pub); });
player.addEventListener('play', function() { watchers.call('play'); });
const pPlay = function() { player.play(); };
pub.play = pPlay;
@ -280,7 +281,7 @@ const MszVideoEmbedPlayer = function(metadata, options) {
let stopCalled = false;
player.addEventListener('pause', function() {
watchers.call(stopCalled ? 'stop' : 'pause', pub);
watchers.call(stopCalled ? 'stop' : 'pause');
stopCalled = false;
});
@ -301,9 +302,9 @@ const MszVideoEmbedPlayer = function(metadata, options) {
player.addEventListener('volumechange', function() {
if(lastMuteState !== player.muted) {
lastMuteState = player.muted;
watchers.call('mute', pub, [lastMuteState]);
watchers.call('mute', lastMuteState);
} else
watchers.call('volume', pub, [player.volume]);
watchers.call('volume', player.volume);
});
const pSetMuted = function(state) { player.muted = state; };
@ -319,21 +320,21 @@ const MszVideoEmbedPlayer = function(metadata, options) {
pub.getPlaybackRate = pGetPlaybackRate;
player.addEventListener('ratechange', function() {
watchers.call('rate', pub, [player.playbackRate]);
watchers.call('rate', player.playbackRate);
});
const pSetPlaybackRate = function(rate) { player.playbackRate = rate; };
pub.setPlaybackRate = pSetPlaybackRate;
window.addEventListener('durationchange', function() {
watchers.call('duration', pub, [player.duration]);
watchers.call('duration', player.duration);
});
const pGetDuration = function() { return player.duration; };
pub.getDuration = pGetDuration;
window.addEventListener('timeupdate', function() {
watchers.call('time', pub, [player.currentTime]);
watchers.call('time', player.currentTime);
});
const pGetTime = function() { return player.currentTime; };
@ -374,7 +375,7 @@ const MszVideoEmbedYouTube = function(metadata, options) {
currentTime = undefined,
isPlaying = undefined;
const watchers = new MszWatcherCollection;
const watchers = new MszWatchers;
watchers.define(MszVideoEmbedPlayerEvents());
const player = $e({
@ -410,7 +411,8 @@ const MszVideoEmbedYouTube = function(metadata, options) {
getPlayerId: function() { return playerId; },
};
watchers.proxy(pub);
pub.watch = (name, handler) => watchers.watch(name, handler);
pub.unwatch = (name, handler) => watchers.unwatch(name, handler);
const postMessage = function(data) {
player.contentWindow.postMessage(JSON.stringify(data), ytOrigin);
@ -463,33 +465,33 @@ const MszVideoEmbedYouTube = function(metadata, options) {
lastPlayerState = state;
if(eventName !== undefined && eventName !== lastPlayerStateEvent) {
lastPlayerStateEvent = eventName;
watchers.call(eventName, pub);
watchers.call(eventName);
}
};
const handleMuted = function(muted) {
isMuted = muted;
watchers.call('mute', pub, [isMuted]);
watchers.call('mute', isMuted);
};
const handleVolume = function(value) {
volume = value / 100;
watchers.call('volume', pub, [volume]);
watchers.call('volume', volume);
};
const handleRate = function(rate) {
playbackRate = rate;
watchers.call('rate', pub, [playbackRate]);
watchers.call('rate', playbackRate);
};
const handleDuration = function(time) {
duration = time;
watchers.call('duration', pub, [duration]);
watchers.call('duration', duration);
};
const handleTime = function(time) {
currentTime = time;
watchers.call('time', pub, [currentTime]);
watchers.call('time', currentTime);
};
const handlePresetRates = function(rates) {
@ -574,7 +576,7 @@ const MszVideoEmbedNicoNico = function(metadata, options) {
currentTime = undefined,
isPlaying = false;
const watchers = new MszWatcherCollection;
const watchers = new MszWatchers;
watchers.define(MszVideoEmbedPlayerEvents());
const player = $e({
@ -610,7 +612,8 @@ const MszVideoEmbedNicoNico = function(metadata, options) {
getPlayerId: function() { return playerId; },
};
watchers.proxy(pub);
pub.watch = (name, handler) => watchers.watch(name, handler);
pub.unwatch = (name, handler) => watchers.unwatch(name, handler);
const postMessage = function(name, data) {
if(name === undefined)
@ -660,28 +663,28 @@ const MszVideoEmbedNicoNico = function(metadata, options) {
if(eventName !== undefined && eventName !== lastPlayerStateEvent) {
lastPlayerStateEvent = eventName;
watchers.call(eventName, pub);
watchers.call(eventName);
}
};
const handleMuted = function(muted) {
isMuted = muted;
watchers.call('mute', pub, [isMuted]);
watchers.call('mute', isMuted);
};
const handleVolume = function(value) {
volume = value;
watchers.call('volume', pub, [volume]);
watchers.call('volume', volume);
};
const handleDuration = function(time) {
duration = time / 1000;
watchers.call('duration', pub, [duration]);
watchers.call('duration', duration);
};
const handleTime = function(time) {
currentTime = time / 1000;
watchers.call('time', pub, [currentTime]);
watchers.call('time', currentTime);
};
const metadataHanders = {

View file

@ -1,35 +1,49 @@
#include utils.js
#include utility.js
Misuzu.Events.Christmas2019 = function() {
this.propName = propName = 'msz-christmas-' + (new Date).getFullYear().toString();
const MszChristmas2019EventInfo = function() {
return {
isActive: () => {
const d = new Date;
return d.getMonth() === 11 && d.getDate() > 5 && d.getDate() < 27;
},
dispatch: () => {
const impl = new MszChristmas2019Event;
impl.dispatch();
return impl;
},
};
};
Misuzu.Events.Christmas2019.prototype.changeColour = function() {
var count = parseInt(localStorage.getItem(this.propName));
document.body.style.setProperty('--header-accent-colour', (count++ % 2) ? 'green' : 'red');
localStorage.setItem(this.propName, count.toString());
};
Misuzu.Events.Christmas2019.prototype.isActive = function() {
var d = new Date;
return d.getMonth() === 11 && d.getDate() > 5 && d.getDate() < 27;
};
Misuzu.Events.Christmas2019.prototype.dispatch = function() {
var headerBg = $q('.header__background'),
menuBgs = $qa('.header__desktop__submenu__background');
if(!localStorage.getItem(this.propName))
localStorage.setItem(this.propName, '0');
if(headerBg)
headerBg.style.transition = 'background-color .4s';
setTimeout(function() {
if(headerBg)
headerBg.style.transition = 'background-color 1s';
for(var i = 0; i < menuBgs.length; i++)
menuBgs[i].style.transition = 'background-color 1s';
}, 1000);
this.changeColour();
setInterval(this.changeColour, 10000);
const MszChristmas2019Event = function() {
const propName = 'msz-christmas-' + (new Date).getFullYear().toString();
const headerBg = $q('.header__background');
const menuBgs = Array.from($qa('.header__desktop__submenu__background'));
if(!localStorage.getItem(propName))
localStorage.setItem(propName, '0');
const changeColour = () => {
let count = parseInt(localStorage.getItem(propName));
document.body.style.setProperty('--header-accent-colour', (count++ % 2) ? 'green' : 'red');
localStorage.setItem(propName, count.toString());
};
return {
changeColour: changeColour,
dispatch: () => {
if(headerBg)
headerBg.style.transition = 'background-color .4s';
setTimeout(() => {
if(headerBg)
headerBg.style.transition = 'background-color 1s';
for(const menuBg of menuBgs)
menuBg.style.transition = 'background-color 1s';
}, 1000);
changeColour();
setInterval(changeColour, 10000);
},
};
};

View file

@ -1,15 +1,15 @@
Misuzu.Events = {};
const MszSeasonalEvents = function() {
const events = [];
#include events/christmas2019.js
Misuzu.Events.getList = function() {
return [
new Misuzu.Events.Christmas2019,
];
};
Misuzu.Events.dispatch = function() {
var list = Misuzu.Events.getList();
for(var i = 0; i < list.length; ++i)
if(list[i].isActive())
list[i].dispatch();
return {
add: eventInfo => {
if(!events.includes(eventInfo))
events.push(eventInfo);
},
dispatch: () => {
for(const info of events)
if(info.isActive())
info.dispatch();
},
};
};

View file

@ -0,0 +1,95 @@
#include xhr.js
const MszEEPROM = function(appId, endPoint) {
if(typeof appId !== 'string')
throw 'appId must be a string';
if(typeof endPoint !== 'string')
throw 'endPoint must be a string';
return {
create: fileInput => {
if(!(fileInput instanceof File))
throw 'fileInput must be an instance of window.File';
let userAborted = false;
let abortHandler;
let progressHandler;
const reportProgress = ev => {
if(progressHandler !== undefined)
progressHandler({
loaded: ev.loaded,
total: ev.total,
progress: ev.total <= 0 ? 0 : ev.loaded / ev.total,
});
};
return {
abort: () => {
userAborted = true;
if(typeof abortHandler === 'function')
abortHandler();
},
onProgress: handler => {
if(typeof handler !== 'function')
throw 'handler must be a function';
progressHandler = handler;
},
start: async () => {
if(userAborted)
throw 'File upload was cancelled by the user, it cannot be restarted.';
try {
const formData = new FormData;
formData.append('src', appId);
formData.append('file', fileInput);
const { status, body } = await $x.post(`${endPoint}/uploads`, {
type: 'json',
authed: true,
upload: reportProgress,
abort: handler => abortHandler = handler,
}, formData);
if(body === null)
throw "The upload server didn't return the metadata for some reason.";
if(status !== 201)
throw body.english ?? body.error ?? `Upload failed with status code ${status}`;
body.isImage = () => body.type.startsWith('image/');
body.isVideo = () => body.type.startsWith('video/');
body.isAudio = () => body.type.startsWith('audio/');
body.isMedia = () => body.isImage() || body.isAudio() || body.isVideo();
return Object.freeze(body);
} catch(ex) {
if(userAborted)
throw '';
console.error(ex);
throw ex;
}
},
};
},
delete: async fileInfo => {
if(typeof fileInfo !== 'object')
throw 'fileInfo must be an object';
if(typeof fileInfo.urlf !== 'string')
throw 'fileInfo.urlf must be a string';
const { status, body } = await $x.delete(fileInfo.urlf, {
type: 'json',
authed: true,
});
if(status !== 204) {
if(body === null)
throw `Delete failed with status code ${status}`;
throw body.english ?? body.error ?? `Delete failed with status code ${status}`;
}
},
};
};

View file

@ -1,4 +1,4 @@
const Sakuya = (function() {
const MszSakuya = (function() {
const formatter = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
const divisions = [
{ amount: 60, name: 'seconds' },

View file

@ -0,0 +1,15 @@
#include xhr.js
const MszUiharu = function(apiUrl) {
const maxBatchSize = 4;
const lookupOneUrl = apiUrl + '/metadata';
return {
lookupOne: async targetUrl => {
if(typeof targetUrl !== 'string')
throw 'targetUrl must be a string';
return $x.post(lookupOneUrl, { type: 'json' }, targetUrl);
},
};
};

View file

@ -1,437 +0,0 @@
#include forum/forum.js
Misuzu.Forum.Editor = {};
Misuzu.Forum.Editor.allowWindowClose = false;
Misuzu.Forum.Editor.init = function() {
const postingForm = $q('.js-forum-posting');
if(!postingForm)
return;
const postingButtons = postingForm.querySelector('.js-forum-posting-buttons'),
postingText = postingForm.querySelector('.js-forum-posting-text'),
postingParser = postingForm.querySelector('.js-forum-posting-parser'),
postingPreview = postingForm.querySelector('.js-forum-posting-preview'),
postingMode = postingForm.querySelector('.js-forum-posting-mode'),
previewButton = document.createElement('button'),
bbcodeButtons = $q('.forum__post__actions--bbcode'),
markdownButtons = $q('.forum__post__actions--markdown'),
markupButtons = $qa('.forum__post__action--tag');
// Initialise EEPROM, code sucks ass but it's getting nuked soon again anyway
if(typeof peepPath === 'string')
document.body.appendChild($e({
tag: 'script',
attrs: {
src: peepPath + '/eeprom.js',
charset: 'utf-8',
type: 'text/javascript',
onload: function() {
const eepromClient = new EEPROM(peepApp, peepPath + '/uploads', '');
const eepromHistory = $e({
attrs: {
className: 'eeprom-widget-history-items',
},
});
const eepromHandleFileUpload = function(file) {
const uploadElemNameValue = $e({
attrs: {
className: 'eeprom-widget-file-name-value',
title: file.name,
},
child: file.name,
});
const uploadElemName = $e({
tag: 'a',
attrs: {
className: 'eeprom-widget-file-name',
target: '_blank',
},
child: uploadElemNameValue,
});
const uploadElemProgressText = $e({
attrs: {
className: 'eeprom-widget-file-progress',
},
child: 'Please wait...',
});
const uploadElemProgressBarValue = $e({
attrs: {
className: 'eeprom-widget-file-bar-fill',
style: {
width: '0%',
},
},
});
const uploadElem = $e({
attrs: {
className: 'eeprom-widget-file',
},
child: [
{
attrs: {
className: 'eeprom-widget-file-info',
},
child: [
uploadElemName,
uploadElemProgressText,
],
},
{
attrs: {
className: 'eeprom-widget-file-bar',
},
child: uploadElemProgressBarValue,
},
],
});
if(eepromHistory.children.length > 0)
$ib(eepromHistory.firstChild, uploadElem);
else
eepromHistory.appendChild(uploadElem);
const explodeUploadElem = function() {
$r(uploadElem);
};
const uploadTask = eepromClient.createUpload(file);
uploadTask.onProgress = function(progressInfo) {
const progressValue = progressInfo.progress.toString() + '%';
uploadElemProgressBarValue.style.width = progressValue;
uploadElemProgressText.textContent = progressValue + ' (' + (progressInfo.total - progressInfo.loaded).toString() + ' bytes remaining)';
};
uploadTask.onFailure = function(errorInfo) {
if(!errorInfo.userAborted) {
let errorText = 'Was unable to upload file.';
switch(errorInfo.error) {
case EEPROM.ERR_INVALID:
errorText = 'Upload request was invalid.';
break;
case EEPROM.ERR_AUTH:
errorText = 'Upload authentication failed, refresh and try again.';
break;
case EEPROM.ERR_ACCESS:
errorText = 'You\'re not allowed to upload files.';
break;
case EEPROM.ERR_GONE:
errorText = 'Upload client has a configuration error or the server is gone.';
break;
case EEPROM.ERR_DMCA:
errorText = 'This file has been uploaded before and was removed for copyright reasons, you cannot upload this file.';
break;
case EEPROM.ERR_SERVER:
errorText = 'Upload server returned a critical error, try again later.';
break;
case EEPROM.ERR_SIZE:
if(errorInfo.maxSize < 1)
errorText = 'Selected file is too large.';
else {
const _t = ['bytes', 'KB', 'MB', 'GB', 'TB'],
_i = parseInt(Math.floor(Math.log(errorInfo.maxSize) / Math.log(1024))),
_s = Math.round(errorInfo.maxSize / Math.pow(1024, _i), 2);
errorText = 'Upload may not be larger than %1 %2.'.replace('%1', _s).replace('%2', _t[_i]);
}
break;
}
uploadElem.classList.add('eeprom-widget-file-fail');
uploadElemProgressText.textContent = errorText;
Misuzu.showMessageBox(errorText, 'Upload Error');
}
};
uploadTask.onComplete = function(fileInfo) {
uploadElem.classList.add('eeprom-widget-file-done');
uploadElemName.href = fileInfo.url;
uploadElemProgressText.textContent = '';
const insertTheLinkIntoTheBoxEx2 = function() {
const parserMode = parseInt(postingParser.value);
let insertText = location.protocol + fileInfo.url;
if(parserMode == 1) { // bbcode
if(fileInfo.isImage())
insertText = '[img]' + fileInfo.url + '[/img]';
else if(fileInfo.isAudio())
insertText = '[audio]' + fileInfo.url + '[/audio]';
else if(fileInfo.isVideo())
insertText = '[video]' + fileInfo.url + '[/video]';
} else if(parserMode == 2) { // markdown
if(fileInfo.isMedia())
insertText = '![](' + fileInfo.url + ')';
}
$insertTags(postingText, insertText, '');
postingText.value = postingText.value.trim();
};
uploadElemProgressText.appendChild($e({
tag: 'a',
attrs: {
href: 'javascript:void(0);',
onclick: function() { insertTheLinkIntoTheBoxEx2(); },
},
child: 'Insert',
}));
uploadElemProgressText.appendChild($t(' '));
uploadElemProgressText.appendChild($e({
tag: 'a',
attrs: {
href: 'javascript:void(0);',
onclick: function() {
eepromClient.deleteUpload(fileInfo).start();
explodeUploadElem();
},
},
child: 'Delete',
}));
insertTheLinkIntoTheBoxEx2();
};
uploadTask.start();
};
const eepromFormInput = $e({
tag: 'input',
attrs: {
type: 'file',
multiple: 'multiple',
className: 'eeprom-widget-form-input',
onchange: function(ev) {
const files = this.files;
for(const file of files)
eepromHandleFileUpload(file);
this.value = '';
},
},
});
const eepromForm = $e({
tag: 'label',
attrs: {
className: 'eeprom-widget-form',
},
child: [
eepromFormInput,
{
attrs: {
className: 'eeprom-widget-form-text',
},
child: 'Select Files...',
}
],
});
const eepromWidget = $e({
attrs: {
className: 'eeprom-widget',
},
child: [
eepromForm,
{
attrs: {
className: 'eeprom-widget-history',
},
child: eepromHistory,
},
],
});
postingForm.appendChild(eepromWidget);
postingText.addEventListener('paste', function(ev) {
if(ev.clipboardData && ev.clipboardData.files.length > 0) {
ev.preventDefault();
const files = ev.clipboardData.files;
for(const file of files)
eepromHandleFileUpload(file);
}
});
document.body.addEventListener('dragenter', function(ev) {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('dragover', function(ev) {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('dragleave', function(ev) {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('drop', function(ev) {
ev.preventDefault();
ev.stopPropagation();
if(ev.dataTransfer && ev.dataTransfer.files.length > 0) {
const files = ev.dataTransfer.files;
for(const file of files)
eepromHandleFileUpload(file);
}
});
},
onerror: function(ev) {
console.error('Failed to initialise EEPROM: ', ev);
},
},
}));
// hack: don't prompt user when hitting submit, really need to make this not stupid.
postingButtons.firstElementChild.addEventListener('click', function() {
Misuzu.Forum.Editor.allowWindowClose = true;
});
window.addEventListener('beforeunload', function(ev) {
if(!Misuzu.Forum.Editor.allowWindowClose && postingText.value.length > 0) {
ev.preventDefault();
ev.returnValue = '';
}
});
for(var i = 0; i < markupButtons.length; ++i)
(function(currentBtn) {
currentBtn.addEventListener('click', function(ev) {
$insertTags(postingText, currentBtn.dataset.tagOpen, currentBtn.dataset.tagClose);
});
})(markupButtons[i]);
Misuzu.Forum.Editor.switchButtons(parseInt(postingParser.value));
var lastPostText = '',
lastPostParser = null;
postingParser.addEventListener('change', function() {
var postParser = parseInt(postingParser.value);
Misuzu.Forum.Editor.switchButtons(postParser);
if(postingPreview.hasAttribute('hidden'))
return;
// dunno if this would even be possible, but ech
if(postParser === lastPostParser)
return;
postingParser.setAttribute('disabled', 'disabled');
previewButton.setAttribute('disabled', 'disabled');
previewButton.classList.add('input__button--busy');
Misuzu.Forum.Editor.renderPreview(postParser, lastPostText, function(success, text) {
if(!success) {
Misuzu.showMessageBox(text);
return;
}
postingPreview.classList[postParser == 2 ? 'add' : 'remove']('markdown');
lastPostParser = postParser;
postingPreview.innerHTML = text;
MszEmbed.handle($qa('.js-msz-embed-media'));
previewButton.removeAttribute('disabled');
postingParser.removeAttribute('disabled');
previewButton.classList.remove('input__button--busy');
});
});
previewButton.className = 'input__button';
previewButton.textContent = 'Preview';
previewButton.type = 'button';
previewButton.value = 'preview';
previewButton.addEventListener('click', function() {
if(previewButton.value === 'back') {
postingPreview.setAttribute('hidden', 'hidden');
postingText.removeAttribute('hidden');
previewButton.value = 'preview';
previewButton.textContent = 'Preview';
postingMode.textContent = postingMode.dataset.original;
postingMode.dataset.original = null;
} else {
var postText = postingText.value,
postParser = parseInt(postingParser.value);
if(lastPostText === postText && lastPostParser === postParser) {
postingPreview.removeAttribute('hidden');
postingText.setAttribute('hidden', 'hidden');
previewButton.value = 'back';
previewButton.textContent = 'Edit';
postingMode.dataset.original = postingMode.textContent;
postingMode.textContent = 'Previewing';
return;
}
postingParser.setAttribute('disabled', 'disabled');
previewButton.setAttribute('disabled', 'disabled');
previewButton.classList.add('input__button--busy');
Misuzu.Forum.Editor.renderPreview(postParser, postText, function(success, text) {
if(!success) {
Misuzu.showMessageBox(text);
return;
}
postingPreview.classList[postParser == 2 ? 'add' : 'remove']('markdown');
lastPostText = postText;
lastPostParser = postParser;
postingPreview.innerHTML = text;
MszEmbed.handle($qa('.js-msz-embed-media'));
postingPreview.removeAttribute('hidden');
postingText.setAttribute('hidden', 'hidden');
previewButton.value = 'back';
previewButton.textContent = 'Back';
previewButton.removeAttribute('disabled');
postingParser.removeAttribute('disabled');
previewButton.classList.remove('input__button--busy');
postingMode.dataset.original = postingMode.textContent;
postingMode.textContent = 'Previewing';
});
}
});
postingButtons.insertBefore(previewButton, postingButtons.firstChild);
};
Misuzu.Forum.Editor.switchButtons = function(parser) {
var bbcodeButtons = $q('.forum__post__actions--bbcode'),
markdownButtons = $q('.forum__post__actions--markdown');
bbcodeButtons.hidden = parser != 1;
markdownButtons.hidden = parser != 2;
};
Misuzu.Forum.Editor.renderPreview = function(parser, text, callback) {
if(!callback)
return;
parser = parseInt(parser);
text = text || '';
var xhr = new XMLHttpRequest,
formData = new FormData;
formData.append('post[mode]', 'preview');
formData.append('post[text]', text);
formData.append('post[parser]', parser.toString());
xhr.addEventListener('readystatechange', function() {
if(xhr.readyState !== XMLHttpRequest.DONE)
return;
if(xhr.status === 200)
callback(true, xhr.response);
else
callback(false, 'Failed to render preview.');
});
// need to figure out a url registry system again, current one is too much overhead so lets just do this for now
xhr.open('POST', '/forum/posting.php');
xhr.withCredentials = true;
xhr.send(formData);
};

View file

@ -0,0 +1,286 @@
#include msgbox.jsx
#include parsing.js
#include utility.js
#include xhr.js
#include ext/eeprom.js
let MszForumEditorAllowClose = false;
const MszForumEditor = function(form) {
if(!(form instanceof Element))
throw 'form must be an instance of element';
const buttonsElem = form.querySelector('.js-forum-posting-buttons'),
textElem = form.querySelector('.js-forum-posting-text'),
parserElem = form.querySelector('.js-forum-posting-parser'),
previewElem = form.querySelector('.js-forum-posting-preview'),
modeElem = form.querySelector('.js-forum-posting-mode'),
markupActs = form.querySelector('.js-forum-posting-actions');
let lastPostText = '',
lastPostParser;
const eepromClient = new MszEEPROM(peepApp, peepPath);
const eepromHistory = <div class="eeprom-widget-history-items"/>;
const eepromHandleFileUpload = async file => {
const uploadElemNameValue = <div class="eeprom-widget-file-name-value" title={file.name}>{file.name}</div>;
const uploadElemName = <a class="eeprom-widget-file-name" target="_blank">{uploadElemNameValue}</a>;
const uploadElemProgressText = <div class="eeprom-widget-file-progress">Please wait...</div>;
const uploadElemProgressBarValue = <div class="eeprom-widget-file-bar-fill" style={{ width: '0%' }}/>;
const uploadElem = <div class="eeprom-widget-file">
<div class="eeprom-widget-file-info">
{uploadElemName}
{uploadElemProgressText}
</div>
<div class="eeprom-widget-file-bar">
{uploadElemProgressBarValue}
</div>
</div>;
if(eepromHistory.children.length > 0)
$ib(eepromHistory.firstChild, uploadElem);
else
eepromHistory.appendChild(uploadElem);
const explodeUploadElem = () => $r(uploadElem);
const uploadTask = eepromClient.create(file);
uploadTask.onProgress(prog => {
uploadElemProgressBarValue.style.width = `${Math.ceil(prog.progress * 100)}%`;
uploadElemProgressText.textContent = `${prog.progress.toLocaleString(undefined, { style: 'percent' })} (${prog.total - prog.loaded} bytes remaining)`;
});
try {
const fileInfo = await uploadTask.start();
uploadElem.classList.add('eeprom-widget-file-done');
uploadElemName.href = fileInfo.url;
uploadElemProgressText.textContent = '';
const insertTheLinkIntoTheBoxEx2 = () => {
const parserMode = parseInt(parserElem.value);
let insertText = location.protocol + fileInfo.url;
if(parserMode == 1) { // bbcode
if(fileInfo.isImage())
insertText = `[img]${fileInfo.url}[/img]`;
else if(fileInfo.isAudio())
insertText = `[audio]${fileInfo.url}[/audio]`;
else if(fileInfo.isVideo())
insertText = `[video]${fileInfo.url}[/video]`;
} else if(parserMode == 2) { // markdown
if(fileInfo.isMedia())
insertText = `![](${fileInfo.url})`;
}
$insertTags(textElem, insertText, '');
textElem.value = textElem.value.trim();
};
uploadElemProgressText.appendChild(<a href="javascript:void(0)" onclick={() => insertTheLinkIntoTheBoxEx2()}>Insert</a>);
uploadElemProgressText.appendChild($t(' '));
uploadElemProgressText.appendChild(<a href="javascript:void(0)" onclick={() => {
eepromClient.delete(fileInfo)
.then(() => explodeUploadElem())
.catch(ex => {
console.error(ex);
MszShowMessageBox(ex, 'Upload Error');
});
}}>Delete</a>);
insertTheLinkIntoTheBoxEx2();
} catch(ex) {
let errorText = 'Upload aborted.';
if(!ex.aborted) {
console.error(ex);
errorText = ex.toString();
}
uploadElem.classList.add('eeprom-widget-file-fail');
uploadElemProgressText.textContent = errorText;
await MszShowMessageBox(errorText, 'Upload Error');
}
};
const eepromFormInput = <input type="file" multiple={true} class="eeprom-widget-form-input"
onchange={() => {
const files = eepromFormInput.files;
for(const file of files)
eepromHandleFileUpload(file);
eepromFormInput.value = '';
}}/>;
const eepromForm = <label class="eeprom-widget-form">
{eepromFormInput}
<div class="eeprom-widget-form-text">
Select Files...
</div>
</label>;
const eepromWidget = <div class="eeprom-widget">
{eepromForm}
<div class="eeprom-widget-history">
{eepromHistory}
</div>
</div>;
form.appendChild(eepromWidget);
textElem.addEventListener('paste', ev => {
if(ev.clipboardData && ev.clipboardData.files.length > 0) {
ev.preventDefault();
const files = ev.clipboardData.files;
for(const file of files)
eepromHandleFileUpload(file);
}
});
document.body.addEventListener('dragenter', ev => {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('dragover', ev => {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('dragleave', ev => {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('drop', ev => {
ev.preventDefault();
ev.stopPropagation();
if(ev.dataTransfer && ev.dataTransfer.files.length > 0) {
const files = ev.dataTransfer.files;
for(const file of files)
eepromHandleFileUpload(file);
}
});
// hack: don't prompt user when hitting submit, really need to make this not stupid.
buttonsElem.firstChild.addEventListener('click', () => MszForumEditorAllowClose = true);
window.addEventListener('beforeunload', function(ev) {
if(!MszForumEditorAllowClose && textElem.value.length > 0) {
ev.preventDefault();
ev.returnValue = '';
}
});
const switchButtons = parser => {
$rc(markupActs);
const tags = MszParsing.getTagsFor(parser);
for(const tag of tags)
markupActs.appendChild(<button class={['forum__post__action', 'forum__post__action--tag', `forum__post__action--${tag.name}`]}
type="button" title={tag.summary} onclick={() => $insertTags(textElem, tag.open, tag.close)}>
<i class={tag.icon}/>
</button>);
};
const renderPreview = async (parser, text) => {
if(typeof text !== 'string')
return '';
const formData = new FormData;
formData.append('post[mode]', 'preview');
formData.append('post[text]', text);
formData.append('post[parser]', parseInt(parser));
return (await $x.post('/forum/posting.php', { authed: true }, formData)).body;
};
const previewBtn = <button class="input__button" type="button" value="preview">Preview</button>;
previewBtn.addEventListener('click', function() {
if(previewBtn.value === 'back') {
previewElem.setAttribute('hidden', 'hidden');
textElem.removeAttribute('hidden');
previewBtn.value = 'preview';
previewBtn.textContent = 'Preview';
modeElem.textContent = modeElem.dataset.original;
modeElem.dataset.original = null;
} else {
const postText = textElem.value,
postParser = parseInt(parserElem.value);
if(lastPostText === postText && lastPostParser === postParser) {
previewElem.removeAttribute('hidden');
textElem.setAttribute('hidden', 'hidden');
previewBtn.value = 'back';
previewBtn.textContent = 'Edit';
modeElem.dataset.original = modeElem.textContent;
modeElem.textContent = 'Previewing';
return;
}
parserElem.setAttribute('disabled', 'disabled');
previewBtn.setAttribute('disabled', 'disabled');
previewBtn.classList.add('input__button--busy');
renderPreview(postParser, postText)
.catch(() => {
previewElem.innerHTML = '';
MszShowMessageBox('Failed to render preview.');
})
.then(body => {
previewElem.classList.toggle('markdown', postParser === 2);
lastPostText = postText;
lastPostParser = postParser;
previewElem.innerHTML = body;
MszEmbed.handle($qa('.js-msz-embed-media'));
previewElem.removeAttribute('hidden');
textElem.setAttribute('hidden', 'hidden');
previewBtn.value = 'back';
previewBtn.textContent = 'Back';
previewBtn.removeAttribute('disabled');
parserElem.removeAttribute('disabled');
previewBtn.classList.remove('input__button--busy');
modeElem.dataset.original = modeElem.textContent;
modeElem.textContent = 'Previewing';
});
}
});
buttonsElem.insertBefore(previewBtn, buttonsElem.firstChild);
switchButtons(parserElem.value);
parserElem.addEventListener('change', () => {
const postParser = parseInt(parserElem.value);
switchButtons(postParser);
if(previewElem.hasAttribute('hidden'))
return;
// dunno if this would even be possible, but ech
if(postParser === lastPostParser)
return;
parserElem.setAttribute('disabled', 'disabled');
previewBtn.setAttribute('disabled', 'disabled');
previewBtn.classList.add('input__button--busy');
renderPreview(postParser, lastPostText)
.catch(() => {
previewElem.innerHTML = '';
MszShowMessageBox('Failed to render preview.');
})
.then(body => {
previewElem.classList.add('markdown', postParser === 2);
lastPostParser = postParser;
previewElem.innerHTML = body;
MszEmbed.handle($qa('.js-msz-embed-media'));
previewBtn.removeAttribute('disabled');
parserElem.removeAttribute('disabled');
previewBtn.classList.remove('input__button--busy');
});
});
};

View file

@ -1 +0,0 @@
Misuzu.Forum = {};

View file

@ -1,135 +1,153 @@
#include sakuya.js
var Misuzu = function() {
Sakuya.trackElements($qa('time'));
hljs.initHighlighting();
MszEmbed.init(location.protocol + '//uiharu.' + location.host);
Misuzu.initQuickSubmit(); // only used by the forum posting form
Misuzu.Forum.Editor.init();
Misuzu.Events.dispatch();
Misuzu.initLoginPage();
MszEmbed.handle($qa('.js-msz-embed-media'));
};
#include utils.js
#include embed.js
#include forum/editor.js
#include msgbox.jsx
#include utility.js
#include xhr.js
#include embed/embed.js
#include events/christmas2019.js
#include events/events.js
#include ext/sakuya.js
#include forum/editor.jsx
#include messages/messages.js
Misuzu.showMessageBox = function(text, title, buttons) {
if($q('.messagebox'))
return false;
(async () => {
const initLoginPage = async () => {
const forms = Array.from($qa('.js-login-form'));
if(forms.length < 1)
return;
text = text || '';
title = title || '';
buttons = buttons || [];
var element = document.createElement('div');
element.className = 'messagebox';
var container = element.appendChild(document.createElement('div'));
container.className = 'container messagebox__container';
var titleElement = container.appendChild(document.createElement('div')),
titleBackground = titleElement.appendChild(document.createElement('div')),
titleText = titleElement.appendChild(document.createElement('div'));
titleElement.className = 'container__title';
titleBackground.className = 'container__title__background';
titleText.className = 'container__title__text';
titleText.textContent = title || 'Information';
var textElement = container.appendChild(document.createElement('div'));
textElement.className = 'container__content';
textElement.textContent = text;
var buttonsContainer = container.appendChild(document.createElement('div'));
buttonsContainer.className = 'messagebox__buttons';
var firstButton = null;
if(buttons.length < 1) {
firstButton = buttonsContainer.appendChild(document.createElement('button'));
firstButton.className = 'input__button';
firstButton.textContent = 'OK';
firstButton.addEventListener('click', function() { element.remove(); });
} else {
for(var i = 0; i < buttons.length; i++) {
var button = buttonsContainer.appendChild(document.createElement('button'));
button.className = 'input__button';
button.textContent = buttons[i].text;
button.addEventListener('click', function() {
element.remove();
buttons[i].callback();
});
if(firstButton === null)
firstButton = button;
}
}
document.body.appendChild(element);
firstButton.focus();
return true;
};
Misuzu.initLoginPage = function() {
var updateForm = function(avatarElem, usernameElem) {
var xhr = new XMLHttpRequest;
xhr.addEventListener('readystatechange', function() {
if(xhr.readyState !== 4)
const updateForm = async (avatar, userName) => {
if(!(avatar instanceof Element) || !(userName instanceof Element))
return;
var json = JSON.parse(xhr.responseText);
if(!json)
return;
const { body } = await $x.get(`/auth/login.php?resolve=1&name=${encodeURIComponent(userName.value)}`, { type: 'json' });
if(json.name)
usernameElem.value = json.name;
avatarElem.src = json.avatar;
});
// need to figure out a url registry system again, current one is too much overhead so lets just do this for now
xhr.open('GET', '/auth/login.php?resolve=1&name=' + encodeURIComponent(usernameElem.value));
xhr.send();
};
avatar.src = body.avatar;
if(body.name.length > 0)
userName.value = body.name;
};
var loginForms = $c('js-login-form');
for(const form of forms) {
const avatar = form.querySelector('.js-login-avatar');
const userName = form.querySelector('.js-login-username');
let timeOut;
for(var i = 0; i < loginForms.length; ++i)
(function(form) {
var loginTimeOut = 0,
loginAvatar = form.querySelector('.js-login-avatar'),
loginUsername = form.querySelector('.js-login-username');
await updateForm(avatar, userName);
updateForm(loginAvatar, loginUsername);
loginUsername.addEventListener('keyup', function() {
if(loginTimeOut)
userName.addEventListener('input', function() {
if(timeOut !== undefined)
return;
loginTimeOut = setTimeout(function() {
updateForm(loginAvatar, loginUsername);
clearTimeout(loginTimeOut);
loginTimeOut = 0;
timeOut = setTimeout(() => {
updateForm(avatar, userName)
.finally(() => {
clearTimeout(timeOut);
timeOut = undefined;
});
}, 750);
});
})(loginForms[i]);
};
Misuzu.initQuickSubmit = function() {
var ctrlSubmit = Array.from($qa('.js-quick-submit, .js-ctrl-enter-submit'));
if(!ctrlSubmit)
return;
}
};
for(var i = 0; i < ctrlSubmit.length; ++i)
ctrlSubmit[i].addEventListener('keydown', function(ev) {
if((ev.code === 'Enter' || ev.code === 'NumpadEnter') // i hate this fucking language so much
&& ev.ctrlKey && !ev.altKey && !ev.shiftKey && !ev.metaKey) {
// hack: prevent forum editor from screaming when using this keycombo
// can probably be done in a less stupid manner
Misuzu.Forum.Editor.allowWindowClose = true;
const initQuickSubmit = () => {
const elems = Array.from($qa('.js-quick-submit, .js-ctrl-enter-submit'));
if(elems.length < 1)
return;
this.form.submit();
ev.preventDefault();
}
});
};
for(const elem of elems)
elem.addEventListener('keydown', ev => {
if((ev.code === 'Enter' || ev.code === 'NumpadEnter') && ev.ctrlKey && !ev.altKey && !ev.shiftKey && !ev.metaKey) {
// hack: prevent forum editor from screaming when using this keycombo
// can probably be done in a less stupid manner
MszForumEditorAllowClose = true;
elem.form.submit();
ev.preventDefault();
}
});
};
const initXhrActions = () => {
const targets = Array.from($qa('a[data-url], button[data-url]'));
for(const target of targets) {
target.onclick = async () => {
if(target.disabled)
return;
const url = target.dataset.url;
if(typeof url !== 'string' || url.length < 1)
return;
const disableWithTarget = typeof target.dataset.disableWithTarget === 'string'
? (target.querySelector(target.dataset.disableWithTarget) ?? target)
: target;
const originalText = disableWithTarget.textContent;
try {
target.disabled = true;
if(target.dataset.disableWith)
disableWithTarget.textContent = target.dataset.disableWith;
if(target.dataset.confirm && !await MszShowConfirmBox(target.dataset.confirm, 'Are you sure?'))
return;
const { status, body } = await $x.send(
target.dataset.method ?? 'GET',
url,
{
type: 'json',
authed: target.dataset.withAuth,
csrf: target.dataset.withCsrf,
}
)
if(status >= 400)
await MszShowMessageBox(
body?.error?.text ?? `No additional information was provided. (HTTP ${status})`,
'Failed to complete action'
);
else if(status >= 200 && status <= 299) {
if(target.dataset.refreshOnSuccess)
location.reload();
else {
const redirectUrl = target.dataset.redirectOnSuccess;
if(typeof redirectUrl === 'string' && redirectUrl.startsWith('/') && !redirectUrl.startsWith('//'))
location.assign(redirectUrl);
}
}
} catch(ex) {
console.error(ex);
await MszShowMessageBox(ex, 'Failed to complete action');
} finally {
disableWithTarget.textContent = originalText;
target.disabled = false;
}
};
}
};
try {
MszSakuya.trackElements($qa('time'));
hljs.highlightAll();
MszEmbed.init(`${location.protocol}//uiharu.${location.host}`);
initXhrActions();
// only used by the forum posting form
initQuickSubmit();
const forumPostingForm = $q('.js-forum-posting');
if(forumPostingForm !== null)
MszForumEditor(forumPostingForm);
const events = new MszSeasonalEvents;
events.add(new MszChristmas2019EventInfo);
events.dispatch();
await initLoginPage();
MszMessages();
MszEmbed.handle($qa('.js-msz-embed-media'));
} catch(ex) {
console.error(ex);
}
})();

View file

@ -0,0 +1,89 @@
#include watcher.js
const MszMessagesActionButton = function(button, stateless) {
if(!(button instanceof Element))
throw 'button must be an element';
const stateful = !stateless;
const pub = {};
const icon = button.querySelector('.js-messages-button-icon i');
const label = button.querySelector('.js-messages-button-label');
const update = () => {
if(stateful) {
icon.className = button.dataset[`${button.dataset.state}Ico`];
label.textContent = button.dataset[`${button.dataset.state}Str`];
}
};
pub.update = update;
const stateWatcher = new MszWatcher;
const getState = () => button.dataset.state !== 'inactive';
const setState = state => {
button.dataset.state = state ? 'active' : 'inactive';
update();
stateWatcher.call(getState());
};
if(stateful) {
pub.getState = getState;
pub.setState = setState;
pub.watchState = handler => { stateWatcher.watch(handler, getState()); };
pub.unwatchState = handler => { stateWatcher.unwatch(handler); };
}
let clickAction;
const click = async () => {
if(clickAction !== undefined) {
if(stateful) {
const result = await clickAction(getState());
if(typeof result === 'boolean')
setState(result);
} else
await clickAction();
}
};
pub.click = click;
button.addEventListener('click', () => click());
update();
pub.setAction = action => {
if(typeof action !== 'function')
throw 'action must be a function';
clickAction = action;
};
let preventEnable = false;
pub.getEnabled = () => !button.disabled;
pub.setEnabled = state => {
if(!preventEnable)
button.disabled = !state;
};
pub.disableWith = async callback => {
if(typeof callback !== 'function')
throw 'callback must be a function';
if(preventEnable)
throw 'preventEnable is true';
preventEnable = true;
const wasDisabled = button.disabled;
button.disabled = true;
try {
return await callback();
} finally {
button.disabled = wasDisabled;
preventEnable = false;
}
};
pub.setHidden = state => {
button.hidden = state;
};
return pub;
};

View file

@ -0,0 +1,167 @@
#include utility.js
#include watcher.js
const MsgMessagesList = function(list) {
if(!(list instanceof Element))
throw 'list must be an element';
const watchers = new MszWatchers;
watchers.define(['select']);
let selectedCount = 0;
const items = Array.from(list.querySelectorAll('.js-messages-entry')).map(elem => {
const item = new MsgMessagesEntry(elem);
item.onSelectedChange((state, initial) => {
if(state)
++selectedCount;
else if(!initial)
--selectedCount;
if(!initial)
watchers.call('select', selectedCount, items.length);
});
return item;
});
const recountSelected = () => {
selectedCount = 0;
for(const item of items)
if(item.getSelected())
++selectedCount;
};
const onSelectedChange = handler => {
watchers.watch('select', handler, selectedCount, items.length);
};
onSelectedChange(selectedCount => {
const state = selectedCount > 0;
for(const item of items)
item.setClickIsSelect(state);
});
return {
getItems: () => items,
getItemsCount: () => items.length,
getSelectedItems: () => {
const selected = [];
for(const item of items)
if(item.getSelected())
selected.push(item);
return selected;
},
removeItem: item => {
$ari(items, item);
$r(item.getElement());
recountSelected();
watchers.call('select', selectedCount, items.length);
},
getAllSelected: () => {
if(items.length < 1)
return false;
for(const item of items)
if(!item.getSelected())
return false;
return true;
},
setAllSelected: state => {
for(const item of items)
item.setSelected(state);
selectedCount = state ? items.length : 0;
watchers.call('select', selectedCount, items.length);
},
onSelectedChange: onSelectedChange,
};
};
const MsgMessagesEntry = function(entry) {
if(!(entry instanceof Element))
throw 'entry must be an element';
const msgId = entry.dataset.msgId;
const unreadElem = entry.querySelector('.js-messages-entry-unread');
const isRead = () => entry.dataset.msgRead === 'read';
const setRead = state => {
if(state) {
entry.dataset.msgRead = 'read';
unreadElem.hidden = true;
} else {
entry.dataset.msgRead = 'unread';
unreadElem.hidden = false;
}
};
const isSent = () => entry.dataset.msgSent === 'sent';
const setSent = state => {
entry.dataset.msgRead = state ? 'sent' : 'draft';
};
const checkbox = entry.querySelector('.js-entry-checkbox');
const getSelected = () => checkbox.checked;
const setSelected = state => checkbox.checked = state;
const toggleSelected = () => checkbox.checked = !checkbox.checked;
let clickIsSelect = false;
const watchers = new MszWatchers;
watchers.define(['select']);
checkbox.addEventListener('click', ev => ev.stopPropagation());
checkbox.addEventListener('keydown', ev => ev.stopPropagation());
checkbox.addEventListener('change', () => {
watchers.call('select', getSelected());
});
const navigateToMessage = () => {
const url = entry.dataset.msgUrl;
if(url !== undefined && url.startsWith('/') && !url.startsWith('//'))
location.assign(url);
};
entry.addEventListener('keydown', ev => {
if(ev.key === 'Enter' || ev.key === 'NumpadEnter') {
ev.preventDefault();
entry.click();
}
});
entry.addEventListener('click', ev => {
ev.preventDefault();
if(clickIsSelect)
checkbox.click();
else
navigateToMessage();
});
entry.addEventListener('dblclick', ev => {
ev.preventDefault();
if(clickIsSelect)
navigateToMessage();
});
return {
getId: () => msgId,
getElement: () => entry,
isRead: isRead,
setRead: setRead,
isSent: isSent,
setSent: setSent,
getSelected: getSelected,
setSelected: setSelected,
toggleSelected: toggleSelected,
setClickIsSelect: state => clickIsSelect = state,
onSelectedChange: handler => {
watchers.watch('select', handler, getSelected());
},
};
};

View file

@ -0,0 +1,356 @@
#include msgbox.jsx
#include utility.js
#include xhr.js
#include messages/actbtn.js
#include messages/list.js
#include messages/recipient.js
#include messages/reply.jsx
#include messages/thread.js
const MszMessages = () => {
const extractMsgIds = msg => {
if(typeof msg.getId === 'function')
return msg.getId();
if(typeof msg.toString === 'function')
return msg.toString();
throw 'unsupported message type';
};
const displayErrorMessage = async error => {
let text;
if(typeof error === 'string')
text = error;
else if(typeof error.text === 'string')
text = error.text;
else if(typeof error.toString === 'function')
text = error.toString();
else
text = 'Something indescribable happened.';
await MszShowMessageBox(text, 'Error');
return false;
};
const msgsCreate = async (title, text, parser, draft, recipient, replyTo) => {
const formData = new FormData;
formData.append('title', title);
formData.append('body', text);
formData.append('parser', parser);
formData.append('draft', draft);
formData.append('recipient', recipient);
formData.append('reply', replyTo);
const { body } = await $x.post('/messages/create', { type: 'json', csrf: true }, formData);
if(body.error !== undefined)
throw body.error;
return body;
};
const msgsUpdate = async (messageId, title, text, parser, draft) => {
const formData = new FormData;
formData.append('title', title);
formData.append('body', text);
formData.append('parser', parser);
formData.append('draft', draft);
const { body } = await $x.post(`/messages/${encodeURIComponent(messageId)}`, { type: 'json', csrf: true }, formData);
if(body.error !== undefined)
throw body.error;
return body;
};
const msgsMark = async (msgs, state) => {
const { body } = await $x.post('/messages/mark', { type: 'json', csrf: true }, {
type: state,
messages: msgs.map(extractMsgIds).join(','),
});
if(body.error !== undefined)
throw body.error;
return true;
};
const msgsDelete = async msgs => {
const { body } = await $x.post('/messages/delete', { type: 'json', csrf: true }, {
messages: msgs.map(extractMsgIds).join(','),
});
if(body.error !== undefined)
throw body.error;
return true;
};
const msgsRestore = async msgs => {
const { body } = await $x.post('/messages/restore', { type: 'json', csrf: true }, {
messages: msgs.map(extractMsgIds).join(','),
});
if(body.error !== undefined)
throw body.error;
return true;
};
const msgsNuke = async msgs => {
const { body } = await $x.post('/messages/nuke', { type: 'json', csrf: true }, {
messages: msgs.map(extractMsgIds).join(','),
});
if(body.error !== undefined)
throw body.error;
return true;
};
const msgsUserBtns = Array.from($qa('.js-header-pms-button'));
if(msgsUserBtns.length > 0)
$x.get('/messages/stats', { type: 'json' }).then(result => {
const body = result.body;
if(typeof body === 'object' && typeof body.unread === 'number')
if(body.unread > 0)
for(const msgsUserBtn of msgsUserBtns)
msgsUserBtn.append($e({ child: body.unread.toLocaleString(), attrs: { className: 'header__desktop__user__button__count' } }));
});
const msgsListElem = $q('.js-messages-list');
const msgsList = msgsListElem instanceof Element ? new MsgMessagesList(msgsListElem) : undefined;
const msgsListEmptyNotice = $q('.js-messages-folder-empty');
const msgsThreadElem = $q('.js-messages-thread');
const msgsThread = msgsThreadElem instanceof Element ? new MszMessagesThread(msgsThreadElem) : undefined;
const msgsRecipientElem = $q('.js-messages-recipient');
const msgsRecipient = msgsRecipientElem instanceof Element ? new MszMessagesRecipient(msgsRecipientElem) : undefined;
const msgsReplyElem = $q('.js-messages-reply');
const msgsReply = msgsReplyElem instanceof Element ? new MszMessagesReply(msgsReplyElem) : undefined;
if(msgsReply !== undefined) {
if(msgsRecipient !== undefined)
msgsRecipient.onUpdate(async info => {
msgsReply.setRecipient(typeof info.id === 'string' ? info.id : '');
msgsReply.setWarning(info.ban ? `${(typeof info.name === 'string' ? info.name : 'This user')} has been banned and will be unable to respond to your messages.` : undefined);
});
msgsReply.onSubmit(async form => {
try {
let result;
if(typeof form.message === 'string') {
result = await msgsUpdate(
form.message,
form.title,
form.body,
form.parser,
form.draft
);
} else {
result = await msgsCreate(
form.title,
form.body,
form.parser,
form.draft,
form.recipient,
form.reply || ''
);
}
if(typeof result.url === 'string')
location.assign(result.url);
} catch(ex) {
return await displayErrorMessage(ex);
}
});
}
let actSelectAll, actMarkRead, actMoveTrash, actNuke;
const actSelectAllBtn = $q('.js-messages-actions-select-all');
if(actSelectAllBtn instanceof Element) {
actSelectAll = new MszMessagesActionButton(actSelectAllBtn);
if(msgsList !== undefined) {
actSelectAll.setAction(async state => {
msgsList.setAllSelected(!state);
return !state;
});
msgsList.onSelectedChange((selectedNo, itemNo) => {
actSelectAll.setState(selectedNo >= itemNo);
});
actSelectAll.setState(msgsList.getAllSelected());
}
}
const actMarkReadBtn = $q('.js-messages-actions-mark-read');
if(actMarkReadBtn instanceof Element) {
actMarkRead = new MszMessagesActionButton(actMarkReadBtn);
if(msgsList !== undefined) {
msgsList.onSelectedChange(selectedNo => {
const enabled = selectedNo > 0;
actMarkRead.setEnabled(enabled);
if(enabled) {
const items = msgsList.getSelectedItems();
let readNo = 0, unreadNo = 0;
for(const item of items) {
if(item.isRead())
++readNo;
else
++unreadNo;
}
actMarkRead.setState(readNo > unreadNo);
}
});
actMarkRead.setAction(async state => {
const items = msgsList.getSelectedItems();
const result = await actMarkRead.disableWith(async () => {
try {
return await msgsMark(items, state ? 'unread' : 'read');
} catch(ex) {
return await displayErrorMessage(ex);
}
});
if(result) {
state = !state;
for(const item of items)
item.setRead(state);
return state;
}
});
} else if(msgsThread !== undefined) {
actMarkRead.setAction(async state => {
const items = [msgsThread.getMessage()];
const result = await actMarkRead.disableWith(async () => {
try {
return await msgsMark(items, state ? 'unread' : 'read');
} catch(ex) {
return await displayErrorMessage(ex);
}
});
return result ? !state : state;
});
}
}
const actMoveTrashBtn = $q('.js-messages-actions-move-trash');
if(actMoveTrashBtn instanceof Element) {
actMoveTrash = new MszMessagesActionButton(actMoveTrashBtn);
if(msgsList !== undefined) {
msgsList.onSelectedChange(selectedNo => actMoveTrash.setEnabled(selectedNo > 0));
actMoveTrash.setAction(async state => {
const items = msgsList.getSelectedItems();
if(!state && !await MszShowConfirmBox(`Are you sure you wish to delete ${items.length} item${items.length === 1 ? '' : 's'}?`, 'Confirmation'))
return;
const result = await actMoveTrash.disableWith(async () => {
try {
if(state)
return await msgsRestore(items);
return await msgsDelete(items);
} catch(ex) {
return await displayErrorMessage(ex);
}
});
if(result)
for(const message of items)
msgsList.removeItem(message);
if(msgsListEmptyNotice instanceof Element)
msgsListEmptyNotice.hidden = msgsList.getItemsCount() > 0;
});
} else if(msgsThread !== undefined) {
actMoveTrash.setAction(async state => {
if(!state && !await MszShowConfirmBox('Are you sure you wish to delete this message?', 'Confirmation'))
return;
const items = [msgsThread.getMessage()];
const result = await actMoveTrash.disableWith(async () => {
try {
if(state)
return await msgsRestore(items);
return await msgsDelete(items);
} catch(ex) {
return await displayErrorMessage(ex);
}
});
if(result) {
state = !state;
if(msgsReply !== undefined)
msgsReply.setHidden(state);
const msg = msgsThread.getMessage();
if(msg !== undefined)
msg.setDeleted(state);
return state;
}
});
}
}
const actNukeBtn = $q('.js-messages-actions-nuke');
if(actNukeBtn instanceof Element) {
actNuke = new MszMessagesActionButton(actNukeBtn, true);
if(msgsList !== undefined) {
msgsList.onSelectedChange(selectedNo => actNuke.setEnabled(selectedNo > 0));
actNuke.setAction(async () => {
const items = msgsList.getSelectedItems();
if(!await MszShowConfirmBox(`Are you sure you wish to PERMANENTLY delete ${items.length} item${items.length === 1 ? '' : 's'}?`, 'Confirmation'))
return;
const result = await actNuke.disableWith(async () => {
try {
return await msgsNuke(items);
} catch(ex) {
return await displayErrorMessage(ex);
}
});
if(result)
for(const message of items)
msgsList.removeItem(message);
if(msgsListEmptyNotice instanceof Element)
msgsListEmptyNotice.hidden = msgsList.getItemsCount() > 0;
});
} else if(msgsThread !== undefined) {
actMoveTrash.watchState(state => {
actNuke.setHidden(!state);
});
actNuke.setAction(async () => {
if(!await MszShowConfirmBox('Are you sure you wish to PERMANENTLY delete this message?', 'Confirmation'))
return;
const items = [msgsThread.getMessage()];
const result = await actNuke.disableWith(async () => {
try {
return await msgsNuke(items);
} catch(ex) {
return await displayErrorMessage(ex);
}
});
if(result)
location.assign('/messages');
});
}
}
};

View file

@ -0,0 +1,50 @@
#include xhr.js
const MszMessagesRecipient = function(element) {
if(!(element instanceof Element))
throw 'element must be an instance of Element';
const avatarElem = element.querySelector('.js-messages-recipient-avatar img');
const nameInput = element.querySelector('.js-messages-recipient-name');
let updateHandler = undefined;
const update = async () => {
const { body } = await $x.post(element.dataset.msgLookup, { type: 'json', csrf: true }, {
name: nameInput.value,
});
if(updateHandler !== undefined)
await updateHandler(body);
if(typeof body.avatar === 'string')
avatarElem.src = body.avatar;
if(typeof body.name === 'string')
nameInput.value = body.name;
};
let nameTimeout = null;
nameInput.addEventListener('input', () => {
if(nameTimeout !== undefined)
return;
nameTimeout = setTimeout(() => {
update().finally(() => {
clearTimeout(nameTimeout);
nameTimeout = undefined;
});
}, 750);
});
update().finally(() => nameTimeout = undefined);
return {
getElement: () => element,
onUpdate: handler => {
if(typeof handler !== 'function')
throw 'handler must be a function';
updateHandler = handler;
},
};
};

View file

@ -0,0 +1,167 @@
#include parsing.js
#include ext/eeprom.js
const MszMessagesReply = function(element) {
if(!(element instanceof Element))
throw 'element must be an Element';
const form = element.querySelector('.js-messages-reply-form');
const bodyElem = form.querySelector('.js-messages-reply-body');
const actsElem = form.querySelector('.js-messages-reply-actions');
const parserSelect = form.querySelector('.js-messages-reply-parser');
const saveBtn = form.querySelector('.js-messages-reply-save');
const sendBtn = form.querySelector('.js-messages-reply-send');
const warnElem = form.querySelector('.js-reply-form-warning');
const warnText = warnElem instanceof Element ? warnElem.querySelector('.js-reply-form-warning-text') : undefined;
let submitHandler;
form.addEventListener('submit', ev => {
ev.preventDefault();
if(typeof submitHandler === 'function') {
const fields = Array.from(form.elements);
const result = {};
for(const field of fields) {
if((field instanceof HTMLButtonElement || (field instanceof HTMLInputElement && field.type === 'submit')) && ev.submitter !== field)
continue;
if(typeof field.name === 'string' && field.name.length > 0)
result[field.name] = field.value;
}
submitHandler(result);
}
});
bodyElem.addEventListener('keydown', ev => {
if((ev.code === 'Enter' || ev.code === 'NumpadEnter') && ev.ctrlKey && !ev.altKey && !ev.metaKey) {
ev.preventDefault();
if(ev.shiftKey)
saveBtn.click();
else
sendBtn.click();
}
});
const switchButtons = parser => {
$rc(actsElem);
const tags = MszParsing.getTagsFor(parser);
actsElem.hidden = tags.length < 1;
for(const tag of tags)
actsElem.appendChild(<button class="messages-reply-action" type="button" title={tag.summary} onclick={() => $insertTags(bodyElem, tag.open, tag.close)}>
<i class={tag.icon}/>
</button>);
};
switchButtons(parserSelect.value);
parserSelect.addEventListener('change', () => {
switchButtons(parserSelect.value);
});
// this implementation is godawful but it'll do for now lol
// need to make it easier to share the forum's implementation
const eepromClient = new MszEEPROM(peepApp, peepPath);
const eepromHandleFileUpload = async file => {
const uploadTask = eepromClient.create(file);
try {
const fileInfo = await uploadTask.start();
const parserMode = parseInt(parserSelect.value);
let insertText = location.protocol + fileInfo.url;
if(parserMode == 1) { // bbcode
if(fileInfo.isImage())
insertText = `[img]${fileInfo.url}[/img]`;
else if(fileInfo.isAudio())
insertText = `[audio]${fileInfo.url}[/audio]`;
else if(fileInfo.isVideo())
insertText = `[video]${fileInfo.url}[/video]`;
} else if(parserMode == 2) { // markdown
if(fileInfo.isMedia())
insertText = `![](${fileInfo.url})`;
}
$insertTags(bodyElem, insertText, '');
bodyElem.value = bodyElem.value.trim();
} catch(ex) {
let errorText = 'Upload aborted.';
if(!ex.aborted) {
console.error(ex);
errorText = ex.toString();
}
await MszShowMessageBox(errorText, 'Upload Error');
}
};
bodyElem.addEventListener('paste', ev => {
if(ev.clipboardData && ev.clipboardData.files.length > 0) {
ev.preventDefault();
const files = ev.clipboardData.files;
for(const file of files)
eepromHandleFileUpload(file);
}
});
document.body.addEventListener('dragenter', ev => {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('dragover', ev => {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('dragleave', ev => {
ev.preventDefault();
ev.stopPropagation();
});
document.body.addEventListener('drop', ev => {
ev.preventDefault();
ev.stopPropagation();
if(ev.dataTransfer && ev.dataTransfer.files.length > 0) {
const files = ev.dataTransfer.files;
for(const file of files)
eepromHandleFileUpload(file);
}
});
return {
getElement: () => element,
setWarning: text => {
if(warnElem === undefined || warnText === undefined)
return;
if(text === undefined) {
warnElem.hidden = true;
warnText.textContent = '';
} else {
warnElem.hidden = false;
warnText.textContent = text;
}
},
setRecipient: userId => {
for(const field of form.elements)
if(field.name === 'recipient') {
field.value = userId;
break;
}
},
getHidden: () => element.hidden,
setHidden: state => {
element.hidden = state;
},
onSubmit: handler => {
if(typeof handler !== 'function')
throw 'handler must be a function';
submitHandler = handler;
},
};
};

View file

@ -0,0 +1,78 @@
const MszMessagesThread = function(thread) {
if(!(thread instanceof Element))
throw 'thread must be an element';
const messages = Array.from(thread.querySelectorAll('.js-messages-message')).map(elem => new MszMessagesThreadMessage(elem));
const message = messages.find(msg => msg.isFull());
return {
getMessage: () => message,
getMessages: () => messages,
};
};
const MszMessagesThreadMessage = function(message) {
if(!(message instanceof Element))
throw 'message must be an element';
const msgId = message.dataset.msgId;
const type = message.dataset.msgType;
const url = message.dataset.msgUrl;
if(type === 'snip') {
message.addEventListener('click', ev => {
if(typeof url !== 'string')
return;
let target = ev.target;
while(target !== message) {
if(target instanceof HTMLAnchorElement)
return;
target = target.parentNode;
}
ev.preventDefault();
location.assign(url);
});
} else if(type === 'full') {
message.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
}
const isRead = () => message.dataset.msgRead === 'read';
const setRead = state => {
message.dataset.msgRead = state ? 'read' : 'unread';
};
const isSent = () => message.dataset.msgSent === 'sent';
const setSent = state => {
message.dataset.msgRead = state ? 'sent' : 'draft';
};
const isDeleted = () => message.dataset.msgDeleted === 'yes';
const setDeleted = state => {
if(state) {
message.dataset.msgDeleted = 'yes';
message.classList.add('messages-message-deleted');
} else {
message.dataset.msgDeleted = 'no';
message.classList.remove('messages-message-deleted');
}
};
return {
getId: () => msgId,
getType: () => type,
isFull: () => type === 'full',
isSnippet: () => type === 'snip',
isRead: isRead,
setRead: setRead,
isSent: isSent,
setSent: setSent,
isDeleted: isDeleted,
setDeleted: setDeleted,
};
};

View file

@ -0,0 +1,73 @@
#include utility.js
const MszShowConfirmBox = async (text, title, target) => {
let result = false;
await MszShowMessageBox(text, title, [
{ text: 'Yes', callback: async () => result = true },
{ text: 'No' },
], target);
return result;
};
const MszShowMessageBox = (text, title, buttons, target) => {
if(typeof text !== 'string') {
if(text !== undefined && text !== null && typeof text.toString === 'function')
text = text.toString();
else throw 'text must be a string';
}
if(!(target instanceof Element))
target = document.body;
if(typeof title !== 'string')
title = 'Information';
if(!Array.isArray(buttons))
buttons = [];
return new Promise((resolve, reject) => {
if(target.querySelector('.messagebox')) {
reject();
return;
}
let buttonsElem;
const html = <div class="messagebox">
<div class="container messagebox__container">
<div class="container__title">
<div class="container__title__background"/>
<div class="container__title__text">{title}</div>
</div>
<div class="container__content">{text}</div>
{buttonsElem = <div class="messagebox__buttons"/>}
</div>
</div>;
let firstButton;
if(buttons.length < 1) {
firstButton = <button class="input__button" onclick={() => {
html.remove();
resolve();
}}>OK</button>;
buttonsElem.appendChild(firstButton);
} else {
for(const button of buttons) {
const buttonElem = <button class="input__button" onclick={() => {
html.remove();
if(typeof button.callback === 'function')
button.callback().finally(() => resolve());
else
resolve();
}}>{button.text}</button>;
buttonsElem.appendChild(buttonElem);
if(firstButton === undefined)
firstButton = buttonElem;
}
}
target.appendChild(html);
firstButton.focus();
});
};

View file

@ -0,0 +1,56 @@
// welcome to the shitty temporary file for managing the bbcode/markdown/whatever button
const MszParsing = (() => {
const defineTag = (name, open, close, summary, icon) => {
return {
name: name,
open: open,
close: close,
summary: summary,
icon: icon,
};
};
const bbTags = [
defineTag('bb-bold', '[b]', '[/b]', 'Bold [b]<text>[/b]', 'fas fa-bold fa-fw'),
defineTag('bb-italic', '[i]', '[/i]', 'Italic [i]<text>[/i]', 'fas fa-italic fa-fw'),
defineTag('bb-underline', '[u]', '[/u]', 'Underline [u]<text>[/u]', 'fas fa-underline fa-fw'),
defineTag('bb-strike', '[s]', '[/s]', 'Strikethrough [s]<text>[/s]', 'fas fa-strikethrough fa-fw'),
defineTag('bb-link', '[url=]', '[/url]', 'Link [url]<url>[/url] or [url=<url>]<text>[/url]', 'fas fa-link fa-fw'),
defineTag('bb-image', '[img]', '[/img]', 'Image [img]<url>[/img]', 'fas fa-image fa-fw'),
defineTag('bb-audio', '[audio]', '[/audio]', 'Audio [audio]<url>[/audio]', 'fas fa-music fa-fw'),
defineTag('bb-video', '[video]', '[/video]', 'Video [video]<url>[/video]', 'fas fa-video fa-fw'),
defineTag('bb-code', '[code]', '[/code]', 'Code [code]<code>[/code]', 'fas fa-code fa-fw'),
defineTag('bb-zalgo', '[zalgo]', '[/zalgo]', 'Zalgo [zalgo]<text>[/zalgo]', 'fas fa-frog fa-fw'),
];
const mdTags = [
defineTag('md-bold', '**', '**', 'Bold **<text>**', 'fas fa-bold fa-fw'),
defineTag('md-italic', '*', '*', 'Italic *<text>* or _<text>_', 'fas fa-italic fa-fw'),
defineTag('md-underline', '__', '__', 'Underline __<text>__', 'fas fa-underline fa-fw'),
defineTag('md-strike', '~~', '~~', 'Strikethrough ~~<text>~~', 'fas fa-strikethrough fa-fw'),
defineTag('md-link', '[](', ')', 'Link [<text>](<url>)', 'fas fa-link fa-fw'),
defineTag('md-image', '![](', ')', 'Image ![<alt text>](<url>)', 'fas fa-image fa-fw'),
defineTag('md-audio', '![](', ')', 'Audio ![<alt text>](<url>)', 'fas fa-music fa-fw'),
defineTag('md-video', '![](', ')', 'Video ![<alt text>](<url>)', 'fas fa-video fa-fw'),
defineTag('md-code', '```', '```', 'Code `<code>` or ```<code>```', 'fas fa-code fa-fw'),
];
const getTagsFor = parser => {
if(typeof parser !== 'number')
parser = parseInt(parser);
if(parser === 1)
return bbTags;
if(parser === 2)
return mdTags;
return [];
};
return {
getTagsFor: getTagsFor,
getTagsForPlainText: () => getTagsFor(0),
getTagsForBBcode: () => getTagsFor(1),
getTagsForMarkdown: () => getTagsFor(2),
};
})();

View file

@ -1,58 +0,0 @@
const Uiharu = function(apiUrl) {
const maxBatchSize = 4;
const lookupOneUrl = apiUrl + '/metadata',
lookupManyUrl = apiUrl + '/metadata/batch';
const lookupManyInternal = function(targetUrls, callback) {
const formData = new FormData;
for(const url of targetUrls)
formData.append('url[]', url);
const xhr = new XMLHttpRequest;
xhr.addEventListener('load', function() {
callback(JSON.parse(xhr.responseText));
});
xhr.addEventListener('error', function(ev) {
callback({ status: xhr.status, error: 'xhr', details: ev });
});
xhr.open('POST', lookupManyUrl);
xhr.send(formData);
};
return {
lookupOne: function(targetUrl, callback) {
if(typeof callback !== 'function')
throw 'callback is missing';
targetUrl = (targetUrl || '').toString();
if(targetUrl.length < 1)
return;
const xhr = new XMLHttpRequest;
xhr.addEventListener('load', function() {
callback(JSON.parse(xhr.responseText));
});
xhr.addEventListener('error', function() {
callback({ status: xhr.status, error: 'xhr', details: ex });
});
xhr.open('POST', lookupOneUrl);
xhr.send(targetUrl);
},
lookupMany: function(targetUrls, callback) {
if(!Array.isArray(targetUrls))
throw 'targetUrls must be an array of urls';
if(typeof callback !== 'function')
throw 'callback is missing';
if(targetUrls < 1)
return;
if(targetUrls.length <= maxBatchSize) {
lookupManyInternal(targetUrls, callback);
return;
}
for(let i = 0; i < targetUrls.length; i += maxBatchSize)
lookupManyInternal(targetUrls.slice(i, i + maxBatchSize), callback);
},
};
};

View file

@ -13,6 +13,10 @@ const $ri = function(name) {
$r($i(name));
};
const $rq = function(query) {
$r($q(query));
};
const $ib = function(ref, elem) {
ref.parentNode.insertBefore(elem, ref);
};
@ -79,6 +83,11 @@ const $e = function(info, attrs, child, created) {
}
break;
case 'boolean':
if(attr)
elem.setAttribute(key, '');
break;
default:
if(key === 'className')
key = 'class';
@ -153,17 +162,17 @@ const $as = function(array) {
}
};
var $insertTags = function(target, tagOpen, tagClose) {
const $insertTags = function(target, tagOpen, tagClose) {
tagOpen = tagOpen || '';
tagClose = tagClose || '';
if(document.selection) {
target.focus();
var selected = document.selection.createRange();
const selected = document.selection.createRange();
selected.text = tagOpen + selected.text + tagClose;
target.focus();
} else if(target.selectionStart || target.selectionStart === 0) {
var startPos = target.selectionStart,
const startPos = target.selectionStart,
endPos = target.selectionEnd,
scrollTop = target.scrollTop;
@ -176,7 +185,7 @@ var $insertTags = function(target, tagOpen, tagClose) {
target.focus();
target.selectionStart = startPos + tagOpen.length;
target.selectionEnd = endPos + tagOpen.length;
target.scrollTop + scrollTop;
target.scrollTop = scrollTop;
} else {
target.value += tagOpen + tagClose;
target.focus();

View file

@ -1,83 +1,65 @@
const MszWatcher = function() {
let watchers = [];
const handlers = [];
return {
watch: function(watcher, thisArg, args) {
if(typeof watcher !== 'function')
throw 'watcher must be a function';
if(watchers.indexOf(watcher) >= 0)
return;
const watch = (handler, ...args) => {
if(typeof handler !== 'function')
throw 'handler must be a function';
if(handlers.includes(handler))
throw 'handler already registered';
watchers.push(watcher);
if(thisArg !== undefined) {
if(!Array.isArray(args)) {
if(args !== undefined)
args = [args];
else args = [];
}
// initial call
args.push(true);
watcher.apply(thisArg, args);
}
},
unwatch: function(watcher) {
$ari(watchers, watcher);
},
call: function(thisArg, args) {
if(!Array.isArray(args)) {
if(args !== undefined)
args = [args];
else args = [];
}
args.push(false);
for(const watcher of watchers)
watcher.apply(thisArg, args);
},
};
};
const MszWatcherCollection = function() {
const collection = new Map;
const watch = function(name, watcher, thisArg, args) {
const watchers = collection.get(name);
if(watchers === undefined)
throw 'undefined watcher name';
watchers.watch(watcher, thisArg, args);
handlers.push(handler);
args.push(true);
handler(...args);
};
const unwatch = function(name, watcher) {
const watchers = collection.get(name);
if(watchers === undefined)
throw 'undefined watcher name';
watchers.unwatch(watcher);
const unwatch = handler => {
$ari(handlers, handler);
};
return {
define: function(names) {
if(!Array.isArray(names))
names = [names];
for(const name of names)
collection.set(name, new MszWatcher);
},
call: function(name, thisArg, args) {
const watchers = collection.get(name);
if(watchers === undefined)
throw 'undefined watcher name';
watchers.call(thisArg, args);
},
watch: watch,
unwatch: unwatch,
proxy: function(obj) {
obj.watch = function(name, watcher) {
watch(name, watcher);
};
obj.unwatch = unwatch;
call: (...args) => {
args.push(false);
for(const handler of handlers)
handler(...args);
},
};
};
const MszWatchers = function() {
const watchers = new Map;
const getWatcher = name => {
const watcher = watchers.get(name);
if(watcher === undefined)
throw 'undefined watcher name';
return watcher;
};
const watch = (name, handler, ...args) => {
getWatcher(name).watch(handler, ...args);
};
const unwatch = (name, handler) => {
getWatcher(name).unwatch(handler);
};
return {
watch: watch,
unwatch: unwatch,
define: names => {
if(typeof names === 'string')
watchers.set(names, new MszWatcher);
else if(Array.isArray(names))
for(const name of names)
watchers.set(name, new MszWatcher);
else
throw 'names must be an array of names or a single name';
},
call: (name, ...args) => {
getWatcher(name).call(...args);
},
};
};

117
assets/misuzu.js/xhr.js Normal file
View file

@ -0,0 +1,117 @@
#include csrf.js
const $x = (function() {
const send = function(method, url, options, body) {
if(options === undefined)
options = {};
else if(typeof options !== 'object')
throw 'options must be undefined or an object';
Object.freeze(options);
const xhr = new XMLHttpRequest;
const requestHeaders = new Map;
if('headers' in options && typeof options.headers === 'object')
for(const name in options.headers)
if(options.headers.hasOwnProperty(name))
requestHeaders.set(name.toLowerCase(), options.headers[name]);
if(options.csrf)
requestHeaders.set('x-csrf-token', MszCSRF.token);
if(typeof options.download === 'function') {
xhr.onloadstart = ev => options.download(ev);
xhr.onprogress = ev => options.download(ev);
xhr.onloadend = ev => options.download(ev);
}
if(typeof options.upload === 'function') {
xhr.upload.onloadstart = ev => options.upload(ev);
xhr.upload.onprogress = ev => options.upload(ev);
xhr.upload.onloadend = ev => options.upload(ev);
}
if(options.authed)
xhr.withCredentials = true;
if(typeof options.timeout === 'number')
xhr.timeout = options.timeout;
if(typeof options.type === 'string')
xhr.responseType = options.type;
if(typeof options.abort === 'function')
options.abort(() => xhr.abort());
if(typeof options.xhr === 'function')
options.xhr(() => xhr);
if(typeof body === 'object') {
if(body instanceof URLSearchParams) {
requestHeaders.set('content-type', 'application/x-www-form-urlencoded');
} else if(body instanceof FormData) {
// content-type is implicitly set
} else if(body instanceof Blob || body instanceof ArrayBuffer || body instanceof DataView) {
if(!requestHeaders.has('content-type'))
requestHeaders.set('content-type', 'application/octet-stream');
} else if(!requestHeaders.has('content-type')) {
const bodyParts = [];
for(const name in body)
if(body.hasOwnProperty(name))
bodyParts.push(encodeURIComponent(name) + '=' + encodeURIComponent(body[name]));
body = bodyParts.join('&');
requestHeaders.set('content-type', 'application/x-www-form-urlencoded');
}
}
return new Promise((resolve, reject) => {
xhr.onload = ev => {
const headers = (headersString => {
const headers = new Map;
const raw = headersString.trim().split(/[\r\n]+/);
for(const name in raw)
if(raw.hasOwnProperty(name)) {
const parts = raw[name].split(': ');
headers.set(parts.shift(), parts.join(': '));
}
return headers;
})(xhr.getAllResponseHeaders());
if(options.csrf && headers.has('x-csrf-token'))
MszCSRF.token = headers.get('x-csrf-token');
resolve({
get ev() { return ev; },
get xhr() { return xhr; },
get status() { return xhr.status; },
get headers() { return headers; },
get body() { return xhr.response; },
get text() { return xhr.responseText; },
});
};
xhr.onerror = ev => reject({
xhr: xhr,
ev: ev,
});
xhr.open(method, url);
for(const [name, value] of requestHeaders)
xhr.setRequestHeader(name, value);
xhr.send(body);
});
};
return {
send: send,
get: (url, options, body) => send('GET', url, options, body),
post: (url, options, body) => send('POST', url, options, body),
delete: (url, options, body) => send('DELETE', url, options, body),
patch: (url, options, body) => send('PATCH', url, options, body),
put: (url, options, body) => send('PUT', url, options, body),
};
})();

View file

@ -1,5 +1,9 @@
const crypto = require('crypto');
exports.strtr = (str, replacements) => str.toString().replace(
/{([^}]+)}/g, (match, key) => replacements[key] || match
);
const trim = function(str, chars, flags) {
if(chars === undefined)
chars = " \n\r\t\v\0";

105
build.js
View file

@ -1,89 +1,30 @@
const assproc = require('@railcomm/assproc');
const { join: pathJoin } = require('path');
const fs = require('fs');
const swc = require('@swc/core');
const path = require('path');
const util = require('util');
const postcss = require('postcss');
const utils = require('./assets/utils.js');
const assproc = require('./assets/assproc.js');
const rootDir = __dirname;
const modulesDir = path.join(rootDir, 'node_modules');
const assetsDir = path.join(rootDir, 'assets');
const assetsCSS = path.join(assetsDir, 'misuzu.css');
const assetsJS = path.join(assetsDir, 'misuzu.js');
const assetsInfo = path.join(assetsDir, 'current.json');
const pubDir = path.join(rootDir, 'public');
const pubIndex = path.join(pubDir, 'index.html');
const pubAssets = '/assets';
const pubAssetsFull = path.join(pubDir, pubAssets);
const pubAssetCSSFormat = '%s-%s.css';
const pubAssetJSFormat = '%s-%s.js';
const isDebugBuild = fs.existsSync(path.join(rootDir, '.debug'));
const swcJscOptions = {
target: 'es2016',
loose: false,
externalHelpers: false,
keepClassNames: true,
preserveAllComments: false,
transform: {},
parser: {
syntax: 'ecmascript',
jsx: true,
dynamicImport: false,
privateMethod: false,
functionBind: false,
exportDefaultFrom: false,
exportNamespaceFrom: false,
decorators: false,
decoratorsBeforeExport: false,
topLevelAwait: true,
importMeta: false,
},
transform: {
react: {
runtime: 'classic',
pragma: '$er',
},
},
};
const postcssPlugins = [];
if(!isDebugBuild) postcssPlugins.push(require('cssnano'));
postcssPlugins.push(require('autoprefixer')({
remove: false,
}));
fs.mkdirSync(pubAssetsFull, { recursive: true });
(async () => {
const mszCssName = await assproc.process(assetsCSS, { 'prefix': '@', 'entry': 'main.css' })
.then(output => postcss(postcssPlugins).process(output, { from: assetsCSS }).then(output => {
const mszCssName = path.join(pubAssets, util.format(pubAssetCSSFormat, 'misuzu', utils.shortHash(output.css)));
fs.writeFileSync(path.join(pubDir, mszCssName), output.css);
return mszCssName;
}));
const isDebug = fs.existsSync(pathJoin(__dirname, '.debug'));
const mszJsName = await assproc.process(assetsJS, { 'prefix': '#', 'entry': 'main.js' })
.then(output => swc.transform(output, {
filename: 'misuzu.js',
sourceMaps: false,
isModule: false,
minify: !isDebugBuild,
jsc: swcJscOptions,
}).then(async output => {
const mszJsName = path.join(pubAssets, util.format(pubAssetJSFormat, 'misuzu', utils.shortHash(output.code)));
fs.writeFileSync(path.join(pubDir, mszJsName), output.code);
return mszJsName;
}));
const env = {
root: __dirname,
source: pathJoin(__dirname, 'assets'),
public: pathJoin(__dirname, 'public'),
debug: isDebug,
swc: {
es: 'es2021',
},
};
fs.writeFileSync(assetsInfo, JSON.stringify({
mszjs: mszJsName,
mszcss: mszCssName,
}));
const tasks = {
js: [
{ source: 'misuzu.js', target: '/assets', name: 'misuzu.{hash}.js', },
],
css: [
{ source: 'misuzu.css', target: '/assets', name: 'misuzu.{hash}.css', },
],
};
assproc.housekeep(pubAssetsFull);
const files = await assproc.process(env, tasks);
fs.writeFileSync(pathJoin(__dirname, 'assets/current.json'), JSON.stringify(files));
})();

View file

@ -1,15 +1,14 @@
{
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"flashwave/index": "dev-master",
"flashwave/sasae": "dev-master",
"php": ">=8.4",
"flashwave/index": "^0.2410",
"flashii/rpcii": "^2.0",
"erusev/parsedown": "~1.6",
"chillerlan/php-qrcode": "^4.3",
"symfony/mailer": "^6.0",
"matomo/device-detector": "^6.1",
"sentry/sdk": "^4.0",
"flashwave/syokuhou": "dev-master"
"nesbot/carbon": "^3.7"
},
"autoload": {
"classmap": [
@ -25,15 +24,7 @@
"./tools/cron slow"
]
},
"config": {
"preferred-install": "dist",
"allow-plugins": {
"composer/installers": true,
"wikimedia/composer-merge-plugin": false,
"php-http/discovery": true
}
},
"require-dev": {
"phpstan/phpstan": "^1.10"
"phpstan/phpstan": "^2.0"
}
}

1295
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
// Switching to the Index migration system!!!!!!
final class InitialStructureNdx_20230107_023235 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class InitialStructureNdx_20230107_023235 implements DbMigration {
public function migrate(DbConnection $conn): void {
$hasMszTrack = false;
// check if the old migrations table exists

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class CreateTopicRedirsTable_20230430_001226 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class CreateTopicRedirsTable_20230430_001226 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
CREATE TABLE msz_forum_topics_redirects (
topic_id INT(10) UNSIGNED NOT NULL,

View file

@ -1,10 +1,10 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
use Misuzu\ClientInfo;
final class UpdateUserAgentStorage_20230721_121854 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class UpdateUserAgentStorage_20230721_121854 implements DbMigration {
public function migrate(DbConnection $conn): void {
// convert user agent fields to BLOB and add field for client info storage
$conn->execute('
ALTER TABLE msz_login_attempts
@ -23,8 +23,8 @@ final class UpdateUserAgentStorage_20230721_121854 implements IDbMigration {
while($selectLoginAttempts->next()) {
$updateLoginAttempts->reset();
$userAgent = $selectLoginAttempts->getString(0);
$updateLoginAttempts->addParameter(1, json_encode(ClientInfo::parse($userAgent)));
$updateLoginAttempts->addParameter(2, $userAgent);
$updateLoginAttempts->nextParameter(json_encode(ClientInfo::parse($userAgent)));
$updateLoginAttempts->nextParameter($userAgent);
$updateLoginAttempts->execute();
}
@ -33,8 +33,8 @@ final class UpdateUserAgentStorage_20230721_121854 implements IDbMigration {
while($selectSessions->next()) {
$updateSessions->reset();
$userAgent = $selectSessions->getString(0);
$updateSessions->addParameter(1, json_encode(ClientInfo::parse($userAgent)));
$updateSessions->addParameter(2, $userAgent);
$updateSessions->nextParameter(json_encode(ClientInfo::parse($userAgent)));
$updateSessions->nextParameter($userAgent);
$updateSessions->execute();
}

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class AddModeratorNotesTable_20230724_201010 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class AddModeratorNotesTable_20230724_201010 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
CREATE TABLE msz_users_modnotes (
note_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class AddNewBansTable_20230726_175936 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class AddNewBansTable_20230726_175936 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
CREATE TABLE msz_users_bans (
ban_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class RedoWarningsTable_20230726_210150 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class RedoWarningsTable_20230726_210150 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
CREATE TABLE msz_users_warnings (
warn_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class PluraliseUsersForRoleRelations_20230727_130516 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class PluraliseUsersForRoleRelations_20230727_130516 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('RENAME TABLE msz_user_roles TO msz_users_roles');
}
}

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class CreateCountersTable_20230728_212101 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class CreateCountersTable_20230728_212101 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
CREATE TABLE msz_counters (
counter_name VARBINARY(64) NOT NULL,

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class UpdateCollationsInVariousTables_20230803_114403 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class UpdateCollationsInVariousTables_20230803_114403 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
ALTER TABLE msz_audit_log
CHANGE COLUMN log_action log_action VARCHAR(50) NOT NULL COLLATE "ascii_general_ci" AFTER user_id,

View file

@ -1,9 +1,9 @@
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class NewPermissionsSystem_20230830_213930 implements IDbMigration {
public function migrate(IDbConnection $conn): void {
final class NewPermissionsSystem_20230830_213930 implements DbMigration {
public function migrate(DbConnection $conn): void {
// make sure cron doesn't fuck us over
$conn->execute('DELETE FROM msz_config WHERE config_name = "perms.needsRecalc"');
@ -41,9 +41,7 @@ final class NewPermissionsSystem_20230830_213930 implements IDbMigration {
$conn->execute('
ALTER TABLE msz_perms
ADD CONSTRAINT perms_53bit
CHECK (perms_allow >= 0 AND perms_deny >= 0 AND perms_allow <= 9007199254740991 AND perms_deny <= 9007199254740991),
ADD CONSTRAINT perms_only_user_or_role
CHECK ((user_id IS NULL AND role_id IS NULL) OR (user_id IS NULL AND role_id IS NOT NULL) OR (user_id IS NOT NULL AND role_id IS NULL))
CHECK (perms_allow >= 0 AND perms_deny >= 0 AND perms_allow <= 9007199254740991 AND perms_deny <= 9007199254740991)
');
$conn->execute('
@ -79,12 +77,13 @@ final class NewPermissionsSystem_20230830_213930 implements IDbMigration {
$result = $conn->query('SELECT user_id, role_id, general_perms_allow, general_perms_deny, user_perms_allow, user_perms_deny, changelog_perms_allow, changelog_perms_deny, news_perms_allow, news_perms_deny, forum_perms_allow, forum_perms_deny, comments_perms_allow, comments_perms_deny FROM msz_permissions');
while($result->next()) {
$insert->addParameter(1, $result->isNull(0) ? null : $result->getString(0));
$insert->addParameter(2, $result->isNull(1) ? null : $result->getString(1));
$insert->addParameter(3, null);
$insert->addParameter(4, 'user');
$insert->addParameter(5, $result->getInteger(4));
$insert->addParameter(6, $result->getInteger(5));
$insert->reset();
$insert->nextParameter($result->isNull(0) ? null : $result->getString(0));
$insert->nextParameter($result->isNull(1) ? null : $result->getString(1));
$insert->nextParameter(null);
$insert->nextParameter('user');
$insert->nextParameter($result->getInteger(4));
$insert->nextParameter($result->getInteger(5));
$insert->execute();
$allow = $result->getInteger(2);
@ -107,12 +106,13 @@ final class NewPermissionsSystem_20230830_213930 implements IDbMigration {
$result = $conn->query('SELECT user_id, role_id, forum_id, forum_perms_allow, forum_perms_deny FROM msz_forum_permissions');
while($result->next()) {
$insert->addParameter(1, $result->isNull(0) ? null : $result->getString(0));
$insert->addParameter(2, $result->isNull(1) ? null : $result->getString(1));
$insert->addParameter(3, $result->getString(2));
$insert->addParameter(4, 'forum');
$insert->addParameter(5, $result->getInteger(3));
$insert->addParameter(6, $result->getInteger(4));
$insert->reset();
$insert->nextParameter($result->isNull(0) ? null : $result->getString(0));
$insert->nextParameter($result->isNull(1) ? null : $result->getString(1));
$insert->nextParameter($result->getString(2));
$insert->nextParameter('forum');
$insert->nextParameter($result->getInteger(3));
$insert->nextParameter($result->getInteger(4));
$insert->execute();
}

View file

@ -0,0 +1,48 @@
<?php
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class CreateMessagesTable_20240130_233734 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('
CREATE TABLE msz_messages (
msg_id BINARY(8) NOT NULL,
msg_owner_id INT(10) UNSIGNED NOT NULL,
msg_author_id INT(10) UNSIGNED NULL DEFAULT NULL,
msg_recipient_id INT(10) UNSIGNED NULL DEFAULT NULL,
msg_reply_to BINARY(8) NULL DEFAULT NULL,
msg_title TINYTEXT NOT NULL COLLATE "utf8mb4_unicode_520_ci",
msg_body TEXT NOT NULL COLLATE "utf8mb4_unicode_520_ci",
msg_parser TINYINT(3) UNSIGNED NOT NULL,
msg_created TIMESTAMP NOT NULL DEFAULT current_timestamp(),
msg_sent TIMESTAMP NULL DEFAULT NULL,
msg_read TIMESTAMP NULL DEFAULT NULL,
msg_deleted TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (msg_id, msg_owner_id),
KEY messages_owner_foreign (msg_owner_id),
KEY messages_author_foreign (msg_author_id),
KEY messages_recipient_foreign (msg_recipient_id),
KEY messages_reply_to_index (msg_reply_to),
KEY messages_created_index (msg_created),
KEY messages_sent_index (msg_sent),
KEY messages_read_index (msg_read),
KEY messages_deleted_index (msg_deleted),
CONSTRAINT messages_owner_foreign
FOREIGN KEY (msg_owner_id)
REFERENCES msz_users (user_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
CONSTRAINT messages_author_foreign
FOREIGN KEY (msg_author_id)
REFERENCES msz_users (user_id)
ON UPDATE CASCADE
ON DELETE SET NULL,
CONSTRAINT messages_recipient_foreign
FOREIGN KEY (msg_recipient_id)
REFERENCES msz_users (user_id)
ON UPDATE CASCADE
ON DELETE SET NULL
) ENGINE=InnoDB COLLATE=utf8mb4_bin;
');
}
}

View file

@ -0,0 +1,14 @@
<?php
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class BaseSixtyFourEncodePmsInDb_20240602_194809 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute('UPDATE msz_messages SET msg_title = TO_BASE64(msg_title), msg_body = TO_BASE64(msg_body)');
$conn->execute('
ALTER TABLE `msz_messages`
CHANGE COLUMN `msg_title` `msg_title` TINYBLOB NOT NULL AFTER `msg_reply_to`,
CHANGE COLUMN `msg_body` `msg_body` BLOB NOT NULL AFTER `msg_title`;
');
}
}

View file

@ -0,0 +1,13 @@
<?php
use Index\Db\DbConnection;
use Index\Db\Migration\DbMigration;
final class AddRoleIdString_20240916_205613 implements DbMigration {
public function migrate(DbConnection $conn): void {
$conn->execute(<<<SQL
ALTER TABLE msz_roles
ADD COLUMN role_string VARCHAR(20) NULL DEFAULT NULL COLLATE 'ascii_general_ci' AFTER role_id,
ADD UNIQUE INDEX roles_string_unique (role_string);
SQL);
}
}

View file

@ -6,11 +6,14 @@ Below are a number of links to source code repositories related to Flashii.net a
- [Misuzu](https://patchii.net/flashii/misuzu): Backend of the main website.
- [Sharp Chat](https://patchii.net/flashii/sharp-chat): Chat Server software.
- [Futami](https://patchii.net/flashii/futami): Common data shared between the chat clients.
- [Mami](https://patchii.net/flashii/mami): Web client for chat.
- [Ami](https://patchii.net/flashii/ami): Web client for chat for older browsers.
- [EEPROM](https://patchii.net/flashii/eeprom): Service for file uploading.
- [Uiharu](https://patchii.net/flashii/uiharu): Service for looking up URL metadata.
- [Seria](https://patchii.net/flashii/seria): Software used by the downloads tracker.
- [Mince](https://patchii.net/flashii/mince): Source code for the Minecraft servers subwebsite.
- [Awaki](https://patchii.net/flashii/awaki): Redirect service hosted on fii.moe.
- [Aleister](https://patchii.net/flashii/aleister): Public API gateway.
## Tools & Software
- [SoFii](https://patchii.net/flashii/sofii): Launcher for Soldier of Fortune 2
@ -19,8 +22,7 @@ Below are a number of links to source code repositories related to Flashii.net a
## First-Party Libraries
- [Index](https://patchii.net/flash/index): Base library used in almost any component of the website that uses PHP.
- [Sasae](https://patchii.net/flash/sasae): Extension to the Twig templating library.
- [Syokuhou](https://patchii.net/flash/syokuhou): Configuration library.
- [RPCii](https://patchii.net/flashii/rpcii): Internal RPC extension, mainly used to supply data to the API gateway.
## Historical
- [AJAX Chat (fork)](https://patchii.net/flashii/ajax-chat): Old chat software (2013-2015). Still kept on life support for the nostalgia.

View file

@ -1,10 +1,9 @@
<?php
namespace Misuzu;
use Index\Environment;
use Index\Data\DbTools;
use Syokuhou\DbConfig;
use Syokuhou\SharpConfig;
use Index\Db\DbBackends;
use Index\Config\Db\DbConfig;
use Index\Config\Fs\FsConfig;
define('MSZ_STARTUP', microtime(true));
define('MSZ_ROOT', __DIR__);
@ -19,11 +18,11 @@ define('MSZ_ASSETS', MSZ_ROOT . '/assets');
require_once MSZ_ROOT . '/vendor/autoload.php';
Environment::setDebug(MSZ_DEBUG);
mb_internal_encoding('utf-8');
date_default_timezone_set('utc');
error_reporting(MSZ_DEBUG ? -1 : 0);
mb_internal_encoding('UTF-8');
date_default_timezone_set('GMT');
$cfg = SharpConfig::fromFile(MSZ_CONFIG . '/config.cfg');
$cfg = FsConfig::fromFile(MSZ_CONFIG . '/config.cfg');
if($cfg->hasValues('sentry:dsn'))
(function($cfg) {
@ -38,7 +37,7 @@ if($cfg->hasValues('sentry:dsn'))
});
})($cfg->scopeTo('sentry'));
$db = DbTools::create($cfg->getString('database:dsn', 'null:'));
$db = DbBackends::create($cfg->getString('database:dsn', 'null:'));
$db->execute('SET SESSION time_zone = \'+00:00\', sql_mode = \'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION\';');
$cfg = new DbConfig($db, 'msz_config');

1035
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,5 @@
{
"dependencies": {
"@swc/core": "^1.3.69",
"autoprefixer": "^10.4.14",
"cssnano": "^6.0.1",
"postcss": "^8.4.26"
"@railcomm/assproc": "^1.0.0"
}
}

View file

@ -1,6 +1,38 @@
parameters:
level: 5
level: 6
treatPhpDocTypesAsCertain: false
paths:
- database
- src
- public
- public-legacy
bootstrapFiles:
- misuzu.php
dynamicConstantNames:
- MSZ_CLI
- MSZ_DEBUG
ignoreErrors:
-
identifier: variable.undefined
path: public-legacy/forum/posting.php
-
identifier: variable.undefined
path: public-legacy/forum/topic.php
-
identifier: variable.undefined
path: public-legacy/manage/changelog/tag.php
-
identifier: variable.undefined
path: public-legacy/manage/news/category.php
-
identifier: variable.undefined
path: public-legacy/manage/news/post.php
-
identifier: variable.undefined
path: public-legacy/manage/users/note.php
-
identifier: empty.offset
path: public-legacy/search.php
-
identifier: offsetAccess.notFound
path: public-legacy/search.php

View file

@ -1,6 +1,9 @@
<?php
namespace Misuzu;
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
function ghcb_strip_prefix(string $line): string {
$findColon = mb_strpos($line, ':');
return trim($findColon === false || $findColon >= 10 ? $line : mb_substr($line, $findColon + 1));
@ -54,6 +57,9 @@ if(empty($config['tokens']['token']))
$isGitea = isset($_SERVER['HTTP_X_GITEA_DELIVERY']) && isset($_SERVER['HTTP_X_GITEA_EVENT']);
$rawData = file_get_contents('php://input');
if(!is_string($rawData))
die('no input data');
$sigParts = $isGitea
? ['sha256', $_SERVER['HTTP_X_GITEA_SIGNATURE']]
: explode('=', $_SERVER['HTTP_X_HUB_SIGNATURE'] ?? '', 2);
@ -69,6 +75,9 @@ foreach($config['tokens']['token'] as $repoName => $repoToken) {
}
}
if(!isset($repoName) || !is_string($repoName))
die('no repo name');
if(!$repoAuthenticated)
die('signature check failed');
@ -88,6 +97,11 @@ if($data->repository->full_name !== $repoName)
if($_SERVER['HTTP_X_GITHUB_EVENT'] !== 'push')
die('only push event is supported');
if(!property_exists($data, 'commits'))
die('commits property missing');
if(!property_exists($data, 'ref'))
die('ref property missing');
$commitCount = count($data->commits);
if($commitCount < 1)
die('no commits received');
@ -101,8 +115,6 @@ if(!empty($repoInfo['master']))
if($data->ref !== $repoMaster)
die('only the master branch is tracked');
$changelog = $msz->getChangelog();
$tags = $repoInfo['tags'] ?? [];
$addresses = $config['addresses'] ?? [];
@ -118,7 +130,7 @@ foreach($data->commits as $commit) {
$line = $index === false ? $message : mb_substr($message, 0, $index);
$body = trim($index === false ? '' : mb_substr($message, $index + 1));
$changeInfo = $changelog->createChange(
$changeInfo = $msz->changelog->createChange(
ghcb_changelog_action($line),
$line, $body,
$addresses[$commit->author->email] ?? null,
@ -127,5 +139,5 @@ foreach($data->commits as $commit) {
if(!empty($tags))
foreach($tags as $tag)
$changelog->addTagToChange($changeInfo, $tag);
$msz->changelog->addTagToChange($changeInfo, $tag);
}

View file

@ -4,37 +4,33 @@ namespace Misuzu;
use Exception;
use Misuzu\Auth\AuthTokenCookie;
$urls = $msz->getURLs();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('index'));
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('index'));
return;
}
$authCtx = $msz->getAuthContext();
$users = $msz->getUsersContext()->getUsers();
$sessions = $authCtx->getSessions();
$loginAttempts = $authCtx->getLoginAttempts();
if(!empty($_GET['resolve'])) {
header('Content-Type: application/json; charset=utf-8');
try {
// Only works for usernames, this is by design
$userInfo = $users->getUser((string)filter_input(INPUT_GET, 'name'), 'name');
$userInfo = $msz->usersCtx->users->getUser((string)filter_input(INPUT_GET, 'name'), 'name');
} catch(Exception $ex) {
echo json_encode([
'id' => 0,
'name' => '',
'avatar' => $urls->format('user-avatar', ['res' => 200, 'user' => 0]),
'avatar' => $msz->urls->format('user-avatar', ['res' => 200, 'user' => 0]),
]);
return;
}
echo json_encode([
'id' => (int)$userInfo->getId(),
'name' => $userInfo->getName(),
'avatar' => $urls->format('user-avatar', ['user' => $userInfo->getId(), 'res' => 200]),
'id' => (int)$userInfo->id,
'name' => $userInfo->name,
'avatar' => $msz->urls->format('user-avatar', ['user' => $userInfo->id, 'res' => 200]),
]);
return;
}
@ -44,16 +40,16 @@ $ipAddress = $_SERVER['REMOTE_ADDR'];
$countryCode = $_SERVER['COUNTRY_CODE'] ?? 'XX';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
$siteIsPrivate = $cfg->getBoolean('private.enable');
$siteIsPrivate = $msz->config->getBoolean('private.enable');
if($siteIsPrivate) {
[
'private.perm.cat' => $loginPermCat,
'private.perm.val' => $loginPermVal,
'private.msg' => $sitePrivateMessage,
'private.allow_password_reset' => $canResetPassword,
] = $cfg->getValues([
] = $msz->config->getValues([
'private.perm.cat:s',
'private.perm.val:i',
'private.msg:s',
@ -95,58 +91,58 @@ while(!empty($_POST['login']) && is_array($_POST['login'])) {
$loginFailedError = "Invalid username or password, {$attemptsRemainingError}.";
try {
$userInfo = $users->getUser($_POST['login']['username'], 'login');
$userInfo = $msz->usersCtx->users->getUser($_POST['login']['username'], 'login');
} catch(Exception $ex) {
$loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo);
$msz->authCtx->loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo);
$notices[] = $loginFailedError;
break;
}
if(!$userInfo->hasPasswordHash()) {
if(!$userInfo->hasPasswordHash) {
$notices[] = 'Your password has been invalidated, please reset it.';
break;
}
if($userInfo->isDeleted() || !$userInfo->verifyPassword($_POST['login']['password'])) {
$loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
if($userInfo->deleted || !$userInfo->verifyPassword($_POST['login']['password'])) {
$msz->authCtx->loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$notices[] = $loginFailedError;
break;
}
if($userInfo->passwordNeedsRehash())
$users->updateUser($userInfo, password: $_POST['login']['password']);
if($userInfo->passwordNeedsRehash)
$msz->usersCtx->users->updateUser($userInfo, password: $_POST['login']['password']);
if(!empty($loginPermCat) && $loginPermVal > 0 && !$msz->getPerms()->checkPermissions($loginPermCat, $loginPermVal, $userInfo)) {
if(!empty($loginPermCat) && $loginPermVal > 0 && !$msz->perms->checkPermissions($loginPermCat, $loginPermVal, $userInfo)) {
$notices[] = "Login succeeded, but you're not allowed to browse the site right now.";
$loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
break;
}
if($userInfo->hasTOTPKey()) {
$tfaToken = $authCtx->getTwoFactorAuthSessions()->createToken($userInfo);
Tools::redirect($urls->format('auth-two-factor', ['token' => $tfaToken]));
if($userInfo->hasTOTP) {
$tfaToken = $msz->authCtx->tfaSessions->createToken($userInfo);
Tools::redirect($msz->urls->format('auth-two-factor', ['token' => $tfaToken]));
return;
}
$loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
try {
$sessionInfo = $sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
$sessionInfo = $msz->authCtx->sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
} catch(Exception $ex) {
$notices[] = "Something broke while creating a session for you, please tell an administrator or developer about this!";
break;
}
$tokenBuilder = $authInfo->getTokenInfo()->toBuilder();
$tokenBuilder = $msz->authInfo->tokenInfo->toBuilder();
$tokenBuilder->setUserId($userInfo);
$tokenBuilder->setSessionToken($sessionInfo);
$tokenBuilder->removeImpersonatedUserId();
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
AuthTokenCookie::apply($msz->authCtx->createAuthTokenPacker()->pack($tokenInfo));
if(!Tools::isLocalURL($loginRedirect))
$loginRedirect = $urls->format('index');
$loginRedirect = $msz->urls->format('index');
Tools::redirect($loginRedirect);
return;
@ -156,7 +152,7 @@ $welcomeMode = !empty($_GET['welcome']);
$loginUsername = !empty($_POST['login']['username']) && is_string($_POST['login']['username']) ? $_POST['login']['username'] : (
!empty($_GET['username']) && is_string($_GET['username']) ? $_GET['username'] : ''
);
$loginRedirect = $welcomeMode ? $urls->format('index') : (!empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : null) ?? $_SERVER['HTTP_REFERER'] ?? $urls->format('index');
$loginRedirect = $welcomeMode ? $msz->urls->format('index') : (!empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : null) ?? $_SERVER['HTTP_REFERER'] ?? $msz->urls->format('index');
$canRegisterAccount = !$siteIsPrivate;
Template::render('auth.login', [

View file

@ -3,25 +3,25 @@ namespace Misuzu;
use Misuzu\Auth\AuthTokenCookie;
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if($msz->authInfo->isLoggedIn) {
if(!CSRF::validateRequest()) {
Template::render('auth.logout');
return;
}
$tokenInfo = $authInfo->getTokenInfo();
$authCtx = $msz->getAuthContext();
$authCtx->getSessions()->deleteSessions(sessionTokens: $tokenInfo->getSessionToken());
$tokenInfo = $msz->authInfo->tokenInfo;
$msz->authCtx->sessions->deleteSessions(sessionTokens: $tokenInfo->sessionToken);
$tokenBuilder = $tokenInfo->toBuilder();
$tokenBuilder->removeUserId();
$tokenBuilder->removeSessionToken();
$tokenBuilder->removeImpersonatedUserId();
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($msz->authCtx->createAuthTokenPacker()->pack($tokenInfo));
}
Tools::redirect($msz->getURLs()->format('index'));;
Tools::redirect($msz->urls->format('index'));;

View file

@ -4,18 +4,14 @@ namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
$urls = $msz->getURLs();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('settings-account'));
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('settings-account'));
return;
}
$authCtx = $msz->getAuthContext();
$users = $msz->getUsersContext()->getUsers();
$recoveryTokens = $authCtx->getRecoveryTokens();
$loginAttempts = $authCtx->getLoginAttempts();
$reset = !empty($_POST['reset']) && is_array($_POST['reset']) ? $_POST['reset'] : [];
$forgot = !empty($_POST['forgot']) && is_array($_POST['forgot']) ? $_POST['forgot'] : [];
$userId = !empty($reset['user']) ? (int)$reset['user'] : (
@ -24,18 +20,18 @@ $userId = !empty($reset['user']) ? (int)$reset['user'] : (
if($userId > 0)
try {
$userInfo = $users->getUser((string)$userId, 'id');
$userInfo = $msz->usersCtx->users->getUser((string)$userId, 'id');
} catch(RuntimeException $ex) {
Tools::redirect($urls->format('auth-forgot'));
Tools::redirect($msz->urls->format('auth-forgot'));
return;
}
$notices = [];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$siteIsPrivate = $cfg->getBoolean('private.enable');
$canResetPassword = $siteIsPrivate ? $cfg->getBoolean('private.allow_password_reset', true) : true;
$siteIsPrivate = $msz->config->getBoolean('private.enable');
$canResetPassword = $siteIsPrivate ? $msz->config->getBoolean('private.allow_password_reset', true) : true;
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
while($canResetPassword) {
if(!empty($reset) && $userId > 0) {
@ -47,12 +43,12 @@ while($canResetPassword) {
$verifyCode = !empty($reset['verification']) && is_string($reset['verification']) ? $reset['verification'] : '';
try {
$tokenInfo = $recoveryTokens->getToken(verifyCode: $verifyCode);
$tokenInfo = $msz->authCtx->recoveryTokens->getToken(verifyCode: $verifyCode);
} catch(RuntimeException $ex) {
unset($tokenInfo);
}
if(empty($tokenInfo) || !$tokenInfo->isValid() || $tokenInfo->getUserId() !== (string)$userInfo->getId()) {
if(empty($tokenInfo) || !$tokenInfo->isValid || $tokenInfo->userId !== (string)$userInfo->id) {
$notices[] = 'Invalid verification code!';
break;
}
@ -67,21 +63,21 @@ while($canResetPassword) {
break;
}
$passwordValidation = $users->validatePassword($passwordNew);
$passwordValidation = $msz->usersCtx->users->validatePassword($passwordNew);
if($passwordValidation !== '') {
$notices[] = $users->validatePasswordText($passwordValidation);
$notices[] = $msz->usersCtx->users->validatePasswordText($passwordValidation);
break;
}
// also disables two factor auth to prevent getting locked out of account entirely
// this behaviour should really be replaced with recovery keys...
$users->updateUser($userInfo, password: $passwordNew, totpKey: '');
$msz->usersCtx->users->updateUser($userInfo, password: $passwordNew, totpKey: '');
$msz->createAuditLog('PASSWORD_RESET', [], $userInfo);
$recoveryTokens->invalidateToken($tokenInfo);
$msz->authCtx->recoveryTokens->invalidateToken($tokenInfo);
Tools::redirect($urls->format('auth-login', ['redirect' => '/']));
Tools::redirect($msz->urls->format('auth-login', ['redirect' => '/']));
return;
}
@ -102,39 +98,39 @@ while($canResetPassword) {
}
try {
$forgotUser = $users->getUser($forgot['email'], 'email');
$forgotUser = $msz->usersCtx->users->getUser($forgot['email'], 'email');
} catch(RuntimeException $ex) {
unset($forgotUser);
}
if(empty($forgotUser) || $forgotUser->isDeleted()) {
if(empty($forgotUser) || $forgotUser->deleted) {
$notices[] = "This e-mail address is not registered with us.";
break;
}
try {
$tokenInfo = $recoveryTokens->getToken(userInfo: $forgotUser, remoteAddr: $ipAddress);
$tokenInfo = $msz->authCtx->recoveryTokens->getToken(userInfo: $forgotUser, remoteAddr: $ipAddress);
} catch(RuntimeException $ex) {
$tokenInfo = $recoveryTokens->createToken($forgotUser, $ipAddress);
$tokenInfo = $msz->authCtx->recoveryTokens->createToken($forgotUser, $ipAddress);
$recoveryMessage = Mailer::template('password-recovery', [
'username' => $forgotUser->getName(),
'token' => $tokenInfo->getCode(),
'username' => $forgotUser->name,
'token' => $tokenInfo->code,
]);
$recoveryMail = Mailer::sendMessage(
[$forgotUser->getEMailAddress() => $forgotUser->getName()],
[$forgotUser->emailAddress => $forgotUser->name],
$recoveryMessage['subject'], $recoveryMessage['message']
);
if(!$recoveryMail) {
$notices[] = "Failed to send reset email, please contact the administrator.";
$recoveryTokens->invalidateToken($tokenInfo);
$msz->authCtx->recoveryTokens->invalidateToken($tokenInfo);
break;
}
}
Tools::redirect($urls->format('auth-reset', ['user' => $forgotUser->getId()]));
Tools::redirect($msz->urls->format('auth-reset', ['user' => $forgotUser->id]));
return;
}

View file

@ -4,39 +4,22 @@ namespace Misuzu;
use RuntimeException;
use Misuzu\Users\User;
$urls = $msz->getURLs();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('index'));
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('index'));
return;
}
$authCtx = $msz->getAuthContext();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$config = $msz->getConfig();
$register = !empty($_POST['register']) && is_array($_POST['register']) ? $_POST['register'] : [];
$notices = [];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$countryCode = $_SERVER['COUNTRY_CODE'] ?? 'XX';
// there is currently no ip banning system.
// because people can have a wide variety of ip address
// it doesn't make sense to include a single row for it
// in the user bans table
// add better ip tracking and reintroduce the blacklist
// was thinking of having both a storage table and an expanded table
// with the storage table contains range syntaxes and whatnot
// and the expanded table just having seas of raw ips in it with a primary key
// for fast matching
$restricted = '';
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
$loginAttempts = $authCtx->getLoginAttempts();
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
while(!$restricted && !empty($register)) {
while(!empty($register)) {
if(!CSRF::validateRequest()) {
$notices[] = 'Was unable to verify the request, please try again!';
break;
@ -69,28 +52,28 @@ while(!$restricted && !empty($register)) {
break;
}
$usernameValidation = $users->validateName($register['username']);
$usernameValidation = $msz->usersCtx->users->validateName($register['username']);
if($usernameValidation !== '')
$notices[] = $users->validateNameText($usernameValidation);
$notices[] = $msz->usersCtx->users->validateNameText($usernameValidation);
$emailValidation = $users->validateEMailAddress($register['email']);
$emailValidation = $msz->usersCtx->users->validateEMailAddress($register['email']);
if($emailValidation !== '')
$notices[] = $users->validateEMailAddressText($emailValidation);
$notices[] = $msz->usersCtx->users->validateEMailAddressText($emailValidation);
if($register['password_confirm'] !== $register['password'])
$notices[] = 'The given passwords don\'t match.';
$passwordValidation = $users->validatePassword($register['password']);
$passwordValidation = $msz->usersCtx->users->validatePassword($register['password']);
if($passwordValidation !== '')
$notices[] = $users->validatePasswordText($passwordValidation);
$notices[] = $msz->usersCtx->users->validatePasswordText($passwordValidation);
if(!empty($notices))
break;
$defaultRoleInfo = $roles->getDefaultRole();
$defaultRoleInfo = $msz->usersCtx->roles->getDefaultRole();
try {
$userInfo = $users->createUser(
$userInfo = $msz->usersCtx->users->createUser(
$register['username'],
$register['password'],
$register['email'],
@ -103,14 +86,14 @@ while(!$restricted && !empty($register)) {
break;
}
$users->addRoles($userInfo, $defaultRoleInfo);
$config->setString('users.newest', $userInfo->getId());
$msz->getPerms()->precalculatePermissions(
$msz->getForumContext()->getCategories(),
[$userInfo->getId()]
$msz->usersCtx->users->addRoles($userInfo, $defaultRoleInfo);
$msz->config->setString('users.newest', $userInfo->id);
$msz->perms->precalculatePermissions(
$msz->forumCtx->categories,
[$userInfo->id]
);
Tools::redirect($urls->format('auth-login-welcome', ['username' => $userInfo->getName()]));
Tools::redirect($msz->urls->format('auth-login-welcome', ['username' => $userInfo->name]));
return;
}
@ -118,5 +101,5 @@ Template::render('auth.register', [
'register_notices' => $notices,
'register_username' => !empty($register['username']) && is_string($register['username']) ? $register['username'] : '',
'register_email' => !empty($register['email']) && is_string($register['email']) ? $register['email'] : '',
'register_restricted' => $restricted,
'register_restricted' => '',
]);

View file

@ -3,21 +3,23 @@ namespace Misuzu;
use Misuzu\Auth\AuthTokenCookie;
$urls = $msz->getURLs();
if(CSRF::validateRequest()) {
$tokenInfo = $msz->getAuthInfo()->getTokenInfo();
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if($tokenInfo->hasImpersonatedUserId()) {
$impUserId = $tokenInfo->getImpersonatedUserId();
if(CSRF::validateRequest()) {
$tokenInfo = $msz->authInfo->tokenInfo;
if($tokenInfo->hasImpersonatedUserId) {
$impUserId = $tokenInfo->impersonatedUserId;
$tokenBuilder = $tokenInfo->toBuilder();
$tokenBuilder->removeImpersonatedUserId();
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
Tools::redirect($urls->format('manage-user', ['user' => $impUserId]));
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($msz->authCtx->createAuthTokenPacker()->pack($tokenInfo));
Tools::redirect($msz->urls->format('manage-user', ['user' => $impUserId]));
return;
}
}
Tools::redirect($urls->format('index'));
Tools::redirect($msz->urls->format('index'));

View file

@ -5,43 +5,38 @@ use RuntimeException;
use Misuzu\TOTPGenerator;
use Misuzu\Auth\AuthTokenCookie;
$urls = $msz->getURLs();
$authInfo = $msz->getAuthInfo();
if($authInfo->isLoggedIn()) {
Tools::redirect($urls->format('index'));
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if($msz->authInfo->isLoggedIn) {
Tools::redirect($msz->urls->format('index'));
return;
}
$authCtx = $msz->getAuthContext();
$users = $msz->getUsersContext()->getUsers();
$sessions = $authCtx->getSessions();
$tfaSessions = $authCtx->getTwoFactorAuthSessions();
$loginAttempts = $authCtx->getLoginAttempts();
$ipAddress = $_SERVER['REMOTE_ADDR'];
$countryCode = $_SERVER['COUNTRY_CODE'] ?? 'XX';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$twofactor = !empty($_POST['twofactor']) && is_array($_POST['twofactor']) ? $_POST['twofactor'] : [];
$notices = [];
$remainingAttempts = $loginAttempts->countRemainingAttempts($ipAddress);
$remainingAttempts = $msz->authCtx->loginAttempts->countRemainingAttempts($ipAddress);
$tokenString = !empty($_GET['token']) && is_string($_GET['token']) ? $_GET['token'] : (
!empty($twofactor['token']) && is_string($twofactor['token']) ? $twofactor['token'] : ''
);
$tokenUserId = $tfaSessions->getTokenUserId($tokenString);
$tokenUserId = $msz->authCtx->tfaSessions->getTokenUserId($tokenString);
if(empty($tokenUserId)) {
Tools::redirect($urls->format('auth-login'));
Tools::redirect($msz->urls->format('auth-login'));
return;
}
$userInfo = $users->getUser($tokenUserId, 'id');
$userInfo = $msz->usersCtx->users->getUser($tokenUserId, 'id');
// checking user_totp_key specifically because there's a fringe chance that
// there's a token present, but totp is actually disabled
if(!$userInfo->hasTOTPKey()) {
Tools::redirect($urls->format('auth-login'));
if(!$userInfo->hasTOTP) {
Tools::redirect($msz->urls->format('auth-login'));
return;
}
@ -65,7 +60,7 @@ while(!empty($twofactor)) {
}
$clientInfo = ClientInfo::fromRequest();
$totp = new TOTPGenerator($userInfo->getTOTPKey());
$totp = new TOTPGenerator($userInfo->totpKey);
if(!in_array($twofactor['code'], $totp->generateRange())) {
$notices[] = sprintf(
@ -73,30 +68,30 @@ while(!empty($twofactor)) {
$remainingAttempts - 1,
$remainingAttempts === 2 ? '' : 's'
);
$loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->loginAttempts->recordAttempt(false, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
break;
}
$loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$tfaSessions->deleteToken($tokenString);
$msz->authCtx->loginAttempts->recordAttempt(true, $ipAddress, $countryCode, $userAgent, $clientInfo, $userInfo);
$msz->authCtx->tfaSessions->deleteToken($tokenString);
try {
$sessionInfo = $sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
$sessionInfo = $msz->authCtx->sessions->createSession($userInfo, $ipAddress, $countryCode, $userAgent, $clientInfo);
} catch(RuntimeException $ex) {
$notices[] = "Something broke while creating a session for you, please tell an administrator or developer about this!";
break;
}
$tokenBuilder = $authInfo->getTokenInfo()->toBuilder();
$tokenBuilder = $msz->authInfo->tokenInfo->toBuilder();
$tokenBuilder->setUserId($userInfo);
$tokenBuilder->setSessionToken($sessionInfo);
$tokenBuilder->removeImpersonatedUserId();
$tokenInfo = $tokenBuilder->toInfo();
AuthTokenCookie::apply($tokenPacker->pack($tokenInfo));
AuthTokenCookie::apply($msz->authCtx->createAuthTokenPacker()->pack($tokenInfo));
if(!Tools::isLocalURL($redirect))
$redirect = $urls->format('index');
$redirect = $msz->urls->format('index');
Tools::redirect($redirect);
return;
@ -104,7 +99,7 @@ while(!empty($twofactor)) {
Template::render('auth.twofactor', [
'twofactor_notices' => $notices,
'twofactor_redirect' => !empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : $urls->format('index'),
'twofactor_redirect' => !empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : $msz->urls->format('index'),
'twofactor_attempts_remaining' => $remainingAttempts,
'twofactor_token' => $tokenString,
]);

View file

@ -2,9 +2,12 @@
namespace Misuzu;
use RuntimeException;
use Misuzu\Comments\{CommentsCategoryInfo,CommentsPostInfo};
$usersCtx = $msz->getUsersContext();
$redirect = filter_input(INPUT_GET, 'return') ?? $_SERVER['HTTP_REFERER'] ?? $msz->getURLs()->format('index');
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
$redirect = filter_input(INPUT_GET, 'return') ?? $_SERVER['HTTP_REFERER'] ?? $msz->urls->format('index');
if(!Tools::isLocalURL($redirect))
Template::displayInfo('Possible request forgery detected.', 403);
@ -12,17 +15,13 @@ if(!Tools::isLocalURL($redirect))
if(!CSRF::validateRequest())
Template::displayInfo("Couldn't verify this request, please refresh the page and try again.", 403);
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!$msz->authInfo->isLoggedIn)
Template::displayInfo('You must be logged in to manage comments.', 403);
$currentUserInfo = $authInfo->getUserInfo();
if($usersCtx->hasActiveBan($currentUserInfo))
if($msz->usersCtx->hasActiveBan($msz->authInfo->userInfo))
Template::displayInfo('You have been banned, check your profile for more information.', 403);
$comments = $msz->getComments();
$perms = $authInfo->getPerms('global');
$perms = $msz->authInfo->getPerms('global');
$commentId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$commentMode = (string)filter_input(INPUT_GET, 'm');
@ -30,12 +29,12 @@ $commentVote = (int)filter_input(INPUT_GET, 'v', FILTER_SANITIZE_NUMBER_INT);
if(!empty($commentId)) {
try {
$commentInfo = $comments->getPost($commentId);
$commentInfo = $msz->comments->getPost($commentId);
} catch(RuntimeException $ex) {
Template::displayInfo('Post not found.', 404);
}
$categoryInfo = $comments->getCategory(postInfo: $commentInfo);
$categoryInfo = $msz->comments->getCategory(postInfo: $commentInfo);
}
if($commentMode !== 'create' && empty($commentInfo))
@ -44,77 +43,81 @@ if($commentMode !== 'create' && empty($commentInfo))
switch($commentMode) {
case 'pin':
case 'unpin':
if(!$perms->check(Perm::G_COMMENTS_PIN) && !$categoryInfo->isOwner($currentUserInfo))
if(!isset($categoryInfo) || !($categoryInfo instanceof CommentsCategoryInfo))
Template::displayInfo('Comment category not found.', 404);
if(!$perms->check(Perm::G_COMMENTS_PIN) && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to pin comments.", 403);
if($commentInfo->isDeleted())
if(!isset($commentInfo) || !($commentInfo instanceof CommentsPostInfo) || $commentInfo->deleted)
Template::displayInfo("This comment doesn't exist!", 400);
if($commentInfo->isReply())
if($commentInfo->isReply)
Template::displayInfo("You can't pin replies!", 400);
$isPinning = $commentMode === 'pin';
if($isPinning) {
if($commentInfo->isPinned())
if($commentInfo->pinned)
Template::displayInfo('This comment is already pinned.', 400);
$comments->pinPost($commentInfo);
$msz->comments->pinPost($commentInfo);
} else {
if(!$commentInfo->isPinned())
if(!$commentInfo->pinned)
Template::displayInfo("This comment isn't pinned yet.", 400);
$comments->unpinPost($commentInfo);
$msz->comments->unpinPost($commentInfo);
}
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
case 'vote':
if(!$perms->check(Perm::G_COMMENTS_VOTE) && !$categoryInfo->isOwner($currentUserInfo))
if(!isset($categoryInfo) || !($categoryInfo instanceof CommentsCategoryInfo))
Template::displayInfo('Comment category not found.', 404);
if(!$perms->check(Perm::G_COMMENTS_VOTE) && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to vote on comments.", 403);
if($commentInfo->isDeleted())
if(!isset($commentInfo) || !($commentInfo instanceof CommentsPostInfo) || $commentInfo->deleted)
Template::displayInfo("This comment doesn't exist!", 400);
if($commentVote > 0)
$comments->addPostPositiveVote($commentInfo, $currentUserInfo);
$msz->comments->addPostPositiveVote($commentInfo, $msz->authInfo->userInfo);
elseif($commentVote < 0)
$comments->addPostNegativeVote($commentInfo, $currentUserInfo);
$msz->comments->addPostNegativeVote($commentInfo, $msz->authInfo->userInfo);
else
$comments->removePostVote($commentInfo, $currentUserInfo);
$msz->comments->removePostVote($commentInfo, $msz->authInfo->userInfo);
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
case 'delete':
if(!isset($categoryInfo) || !($categoryInfo instanceof CommentsCategoryInfo))
Template::displayInfo('Comment category not found.', 404);
$canDelete = $perms->check(Perm::G_COMMENTS_DELETE_OWN | Perm::G_COMMENTS_DELETE_ANY);
if(!$canDelete && !$categoryInfo->isOwner($currentUserInfo))
if(!$canDelete && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to delete comments.", 403);
$canDeleteAny = $perms->check(Perm::G_COMMENTS_DELETE_ANY);
if($commentInfo->isDeleted())
if(!isset($commentInfo) || !($commentInfo instanceof CommentsPostInfo) || $commentInfo->deleted)
Template::displayInfo(
$canDeleteAny ? 'This comment is already marked for deletion.' : "This comment doesn't exist.",
400
);
$isOwnComment = $commentInfo->getUserId() === $currentUserInfo->getId();
$isOwnComment = $commentInfo->userId === $msz->authInfo->userInfo->id;
$isModAction = $canDeleteAny && !$isOwnComment;
if(!$isModAction && !$isOwnComment)
Template::displayInfo("You're not allowed to delete comments made by others.", 403);
$comments->deletePost($commentInfo);
$msz->comments->deletePost($commentInfo);
if($isModAction) {
$msz->createAuditLog('COMMENT_ENTRY_DELETE_MOD', [
$commentInfo->getId(),
$commentUserId = $commentInfo->getUserId(),
$commentInfo->id,
$commentUserId = $commentInfo->userId,
'<username>',
]);
} else {
$msz->createAuditLog('COMMENT_ENTRY_DELETE', [$commentInfo->getId()]);
$msz->createAuditLog('COMMENT_ENTRY_DELETE', [$commentInfo->id]);
}
Tools::redirect($redirect);
@ -124,24 +127,27 @@ switch($commentMode) {
if(!$perms->check(Perm::G_COMMENTS_DELETE_ANY))
Template::displayInfo("You're not allowed to restore deleted comments.", 403);
if(!$commentInfo->isDeleted())
if(!isset($commentInfo) || !($commentInfo instanceof CommentsPostInfo))
Template::displayInfo("This comment is probably nuked already.", 404);
if(!$commentInfo->deleted)
Template::displayInfo("This comment isn't in a deleted state.", 400);
$comments->restorePost($commentInfo);
$msz->comments->restorePost($commentInfo);
$msz->createAuditLog('COMMENT_ENTRY_RESTORE', [
$commentInfo->getId(),
$commentUserId = $commentInfo->getUserId(),
$commentInfo->id,
$commentUserId = $commentInfo->userId,
'<username>',
]);
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
case 'create':
if(!$perms->check(Perm::G_COMMENTS_CREATE) && !$categoryInfo->isOwner($currentUserInfo))
if(!isset($categoryInfo) || !($categoryInfo instanceof CommentsCategoryInfo))
Template::displayInfo('Comment category not found.', 404);
if(!$perms->check(Perm::G_COMMENTS_CREATE) && !$categoryInfo->isOwner($msz->authInfo->userInfo))
Template::displayInfo("You're not allowed to post comments.", 403);
if(empty($_POST['comment']) || !is_array($_POST['comment']))
Template::displayInfo('Missing data.', 400);
@ -149,13 +155,13 @@ switch($commentMode) {
$categoryId = isset($_POST['comment']['category']) && is_string($_POST['comment']['category'])
? (int)$_POST['comment']['category']
: 0;
$categoryInfo = $comments->getCategory(categoryId: $categoryId);
$categoryInfo = $msz->comments->getCategory(categoryId: (string)$categoryId);
} catch(RuntimeException $ex) {
Template::displayInfo('This comment category doesn\'t exist.', 404);
}
$canLock = $perms->check(Perm::G_COMMENTS_LOCK);
if($categoryInfo->isLocked() && !$canLock)
if($categoryInfo->locked && !$canLock)
Template::displayInfo('This comment category has been locked.', 403);
$commentText = !empty($_POST['comment']['text']) && is_string($_POST['comment']['text']) ? $_POST['comment']['text'] : '';
@ -164,21 +170,19 @@ switch($commentMode) {
$commentPin = !empty($_POST['comment']['pin']) && $perms->check(Perm::G_COMMENTS_PIN);
if($commentLock) {
if($categoryInfo->isLocked())
$comments->unlockCategory($categoryInfo);
if($categoryInfo->locked)
$msz->comments->unlockCategory($categoryInfo);
else
$comments->lockCategory($categoryInfo);
$msz->comments->lockCategory($categoryInfo);
}
if(strlen($commentText) > 0) {
$commentText = preg_replace("/[\r\n]{2,}/", "\n", $commentText);
} else {
if($canLock) {
if($canLock)
Template::displayInfo('The action has been processed.', 400);
} else {
else
Template::displayInfo('Your comment is too short.', 400);
}
break;
}
if(mb_strlen($commentText) > 5000)
@ -186,22 +190,22 @@ switch($commentMode) {
if($commentReply > 0) {
try {
$parentInfo = $comments->getPost($commentReply);
$parentInfo = $msz->comments->getPost($commentReply);
} catch(RuntimeException $ex) {}
if(!isset($parentInfo) || $parentInfo->isDeleted())
if(!isset($parentInfo) || !($parentInfo instanceof CommentsPostInfo) || $parentInfo->deleted)
Template::displayInfo('The comment you tried to reply to does not exist.', 404);
}
$commentInfo = $comments->createPost(
$commentInfo = $msz->comments->createPost(
$categoryInfo,
$parentInfo ?? null,
$currentUserInfo,
$msz->authInfo->userInfo,
$commentText,
$commentPin
);
Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
Tools::redirect($redirect . '#comment-' . $commentInfo->id);
break;
default:

View file

@ -1,179 +0,0 @@
<?php
namespace Misuzu;
use stdClass;
use RuntimeException;
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$categoryId = (int)filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT);
try {
$categoryInfo = $forumCategories->getCategory(categoryId: $categoryId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$authInfo = $msz->getAuthInfo();
$perms = $authInfo->getPerms('forum', $categoryInfo);
$currentUser = $authInfo->getUserInfo();
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if(!$perms->check(Perm::F_CATEGORY_VIEW))
Template::throwError(403);
if($usersCtx->hasActiveBan($currentUser))
$perms = $perms->apply(fn($calc) => $calc & (Perm::F_CATEGORY_LIST | Perm::F_CATEGORY_VIEW));
if($categoryInfo->isLink()) {
if($categoryInfo->hasLinkTarget()) {
$forumCategories->incrementCategoryClicks($categoryInfo);
Tools::redirect($categoryInfo->getLinkTarget());
return;
}
Template::throwError(404);
}
$forumPagination = new Pagination($forumTopics->countTopics(
categoryInfo: $categoryInfo,
global: true,
deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false
), 20);
if(!$forumPagination->hasValidOffset())
Template::throwError(404);
$children = [];
$topics = [];
if($categoryInfo->mayHaveChildren()) {
$children = $forumCategories->getCategoryChildren($categoryInfo, hidden: false, asTree: true);
foreach($children as $childId => $child) {
$childPerms = $authInfo->getPerms('forum', $child->info);
if(!$childPerms->check(Perm::F_CATEGORY_LIST)) {
unset($category->children[$childId]);
continue;
}
$childUnread = false;
if($child->info->mayHaveChildren()) {
foreach($child->children as $grandChildId => $grandChild) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChild->info);
if(!$grandChildPerms->check(Perm::F_CATEGORY_LIST)) {
unset($child->children[$grandChildId]);
continue;
}
$grandChildUnread = false;
if($grandChild->info->mayHaveTopics()) {
$catIds = [$grandChild->info->getId()];
foreach($grandChild->childIds as $greatGrandChildId) {
$greatGrandChildPerms = $authInfo->getPerms('forum', $greatGrandChildId);
if(!$greatGrandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $greatGrandChildId;
}
$grandChildUnread = $forumCategories->checkCategoryUnread($catIds, $currentUser);
if($grandChildUnread)
$childUnread = true;
}
$grandChild->perms = $grandChildPerms;
$grandChild->unread = $grandChildUnread;
}
}
if($child->info->mayHaveChildren() || $child->info->mayHaveTopics()) {
$catIds = [$child->info->getId()];
foreach($child->childIds as $grandChildId) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChildId);
if($grandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $grandChildId;
}
try {
$lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
} catch(RuntimeException $ex) {
$lastPostInfo = null;
}
if($lastPostInfo !== null) {
$child->lastPost = new stdClass;
$child->lastPost->info = $lastPostInfo;
$child->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) {
$child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
}
}
}
if($child->info->mayHaveTopics() && !$childUnread)
$childUnread = $forumCategories->checkCategoryUnread($child->info, $currentUser);
$child->perms = $childPerms;
$child->unread = $childUnread;
}
}
if($categoryInfo->mayHaveTopics()) {
$topicInfos = $forumTopics->getTopics(
categoryInfo: $categoryInfo,
global: true,
deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false,
pagination: $forumPagination,
);
foreach($topicInfos as $topicInfo) {
$topics[] = $topic = new stdClass;
$topic->info = $topicInfo;
$topic->unread = $forumTopics->checkTopicUnread($topicInfo, $currentUser);
$topic->participated = $forumTopics->checkTopicParticipated($topicInfo, $currentUser);
if($topicInfo->hasUserId()) {
$topic->user = $usersCtx->getUserInfo($topicInfo->getUserId());
$topic->colour = $usersCtx->getUserColour($topic->user);
}
try {
$topic->lastPost = new stdClass;
$topic->lastPost->info = $lastPostInfo = $forumPosts->getPost(
topicInfo: $topicInfo,
getLast: true,
deleted: $topicInfo->isDeleted() ? null : false,
);
if($lastPostInfo->hasUserId()) {
$topic->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
}
} catch(RuntimeException $ex) {
$topic->lastPost = null;
}
}
}
$perms = $perms->checkMany([
'can_create_topic' => Perm::F_TOPIC_CREATE,
]);
Template::render('forum.forum', [
'forum_breadcrumbs' => $forumCategories->getCategoryAncestry($categoryInfo),
'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
'forum_info' => $categoryInfo,
'forum_children' => $children,
'forum_topics' => $topics,
'forum_pagination' => $forumPagination,
'forum_show_mark_as_read' => $currentUser !== null,
'forum_perms' => $perms,
]);

View file

@ -1,191 +0,0 @@
<?php
namespace Misuzu;
use stdClass;
use RuntimeException;
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$mode = (string)filter_input(INPUT_GET, 'm');
$authInfo = $msz->getAuthInfo();
$currentUser = $authInfo->getUserInfo();
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if($mode === 'mark') {
if(!$authInfo->isLoggedIn())
Template::throwError(403);
$categoryId = filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT);
if($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$categoryInfos = $categoryId === null
? $forumCategories->getCategories()
: $forumCategories->getCategoryChildren(parentInfo: $categoryId, includeSelf: true);
foreach($categoryInfos as $categoryInfo) {
$perms = $authInfo->getPerms('forum', $categoryInfo);
if($perms->check(Perm::F_CATEGORY_LIST))
$forumCategories->updateUserReadCategory($userInfo, $categoryInfo);
}
Tools::redirect($msz->getURLs()->format($categoryId ? 'forum-category' : 'forum-index', ['forum' => $categoryId]));
return;
}
Template::render('confirm', [
'title' => 'Mark forum as read',
'message' => 'Are you sure you want to mark ' . ($categoryId < 1 ? 'the entire' : 'this') . ' forum as read?',
'return' => $msz->getURLs()->format($categoryId ? 'forum-category' : 'forum-index', ['forum' => $categoryId]),
'params' => [
'forum' => $categoryId,
]
]);
return;
}
if($mode !== '')
Template::throwError(404);
$categories = $forumCategories->getCategories(hidden: false, asTree: true);
foreach($categories as $categoryId => $category) {
$perms = $authInfo->getPerms('forum', $category->info);
if(!$perms->check(Perm::F_CATEGORY_LIST)) {
unset($categories[$categoryId]);
continue;
}
$unread = false;
if($category->info->mayHaveChildren())
foreach($category->children as $childId => $child) {
$childPerms = $authInfo->getPerms('forum', $child->info);
if(!$childPerms->check(Perm::F_CATEGORY_LIST)) {
unset($category->children[$childId]);
continue;
}
$childUnread = false;
if($category->info->isListing()) {
if($child->info->mayHaveChildren()) {
foreach($child->children as $grandChildId => $grandChild) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChild->info);
if(!$grandChildPerms->check(Perm::F_CATEGORY_LIST)) {
unset($child->children[$grandChildId]);
continue;
}
$grandChildUnread = false;
if($grandChild->info->mayHaveTopics()) {
$catIds = [$grandChild->info->getId()];
foreach($grandChild->childIds as $greatGrandChildId) {
$greatGrandChildPerms = $authInfo->getPerms('forum', $greatGrandChildId);
if($greatGrandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $greatGrandChildId;
}
$grandChildUnread = $forumCategories->checkCategoryUnread($catIds, $currentUser);
if($grandChildUnread)
$childUnread = true;
}
$grandChild->perms = $grandChildPerms;
$grandChild->unread = $grandChildUnread;
}
}
if($child->info->mayHaveChildren() || $child->info->mayHaveTopics()) {
$catIds = [$child->info->getId()];
foreach($child->childIds as $grandChildId) {
$grandChildPerms = $authInfo->getPerms('forum', $grandChildId);
if($grandChildPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $grandChildId;
}
try {
$lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
} catch(RuntimeException $ex) {
$lastPostInfo = null;
}
if($lastPostInfo !== null) {
$child->lastPost = new stdClass;
$child->lastPost->info = $lastPostInfo;
$child->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) {
$child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
}
}
}
}
if($child->info->mayHaveTopics() && !$childUnread) {
$childUnread = $forumCategories->checkCategoryUnread($child->info, $currentUser);
if($childUnread)
$unread = true;
}
$child->perms = $childPerms;
$child->unread = $childUnread;
}
if($category->info->mayHaveTopics() && !$unread)
$unread = $forumCategories->checkCategoryUnread($category->info, $currentUser);
if(!$category->info->isListing()) {
if(!array_key_exists('0', $categories)) {
$categories['0'] = $root = new stdClass;
$root->info = null;
$root->perms = 0;
$root->unread = false;
$root->colour = null;
$root->children = [];
}
$categories['0']->children[$categoryId] = $category;
unset($categories[$categoryId]);
if($category->info->mayHaveChildren() || $category->info->mayHaveTopics()) {
$catIds = [$category->info->getId()];
foreach($category->childIds as $childId) {
$childPerms = $authInfo->getPerms('forum', $childId);
if($childPerms->check(Perm::F_CATEGORY_LIST))
$catIds[] = $childId;
}
try {
$lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
} catch(RuntimeException $ex) {
$lastPostInfo = null;
}
if($lastPostInfo !== null) {
$category->lastPost = new stdClass;
$category->lastPost->info = $lastPostInfo;
$category->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);
if($lastPostInfo->hasUserId()) {
$category->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
$category->lastPost->colour = $usersCtx->getUserColour($category->lastPost->user);
}
}
}
}
$category->perms = $perms;
$category->unread = $unread;
}
Template::render('forum.index', [
'forum_categories' => $categories,
'forum_empty' => empty($categories),
'forum_show_mark_as_read' => $currentUser !== null,
]);

View file

@ -3,12 +3,13 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_FORUM_LEADERBOARD_VIEW))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_FORUM_LEADERBOARD_VIEW))
Template::throwError(403);
$forumCtx = $msz->getForumContext();
$usersCtx = $msz->getUsersContext();
$config = $cfg->getValues([
$config = $msz->config->getValues([
['forum_leader.first_year:i', 2018],
['forum_leader.first_month:i', 12],
'forum_leader.unranked.forum:a',
@ -61,12 +62,12 @@ for($i = $currentYear, $j = $currentMonth;;) {
break;
}
$rankings = $forumCtx->getPosts()->generatePostRankings($year, $month, $unrankedForums, $unrankedTopics);
$rankings = $msz->forumCtx->posts->generatePostRankings($year, $month, $unrankedForums, $unrankedTopics);
foreach($rankings as $ranking) {
$ranking->user = $ranking->colour = null;
if($ranking->userId !== '')
$ranking->user = $usersCtx->getUserInfo($ranking->userId);
$ranking->user = $msz->usersCtx->getUserInfo($ranking->userId);
}
$name = 'All Time';
@ -92,9 +93,9 @@ MD;
foreach($rankings as $ranking) {
$totalPostsCount += $ranking->postsCount;
$markdown .= sprintf("| %s | [%s](%s%s) | %s |\r\n", $ranking->position,
$ranking->user?->getName() ?? 'Deleted User',
$msz->getSiteInfo()->getURL(),
$msz->getURLs()->format('user-profile', ['user' => $ranking->userId]),
$ranking->user?->name ?? 'Deleted User', // @phpstan-ignore-line: no, it can be null
$msz->siteInfo->url,
$msz->urls->format('user-profile', ['user' => $ranking->userId]),
number_format($ranking->postsCount));
}

View file

@ -1,142 +0,0 @@
<?php
namespace Misuzu;
use RuntimeException;
$urls = $msz->getURLs();
$forumCtx = $msz->getForumContext();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$postId = !empty($_GET['p']) && is_string($_GET['p']) ? (int)$_GET['p'] : 0;
$postMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : '';
$submissionConfirmed = !empty($_GET['confirm']) && is_string($_GET['confirm']) && $_GET['confirm'] === '1';
$postRequestVerified = CSRF::validateRequest();
$authInfo = $msz->getAuthInfo();
if(!empty($postMode) && !$authInfo->isLoggedIn())
Template::displayInfo('You must be logged in to manage posts.', 401);
$currentUser = $authInfo->getUserInfo();
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if($postMode !== '' && $usersCtx->hasActiveBan($currentUser))
Template::displayInfo('You have been banned, check your profile for more information.', 403);
try {
$postInfo = $forumPosts->getPost(postId: $postId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$perms = $authInfo->getPerms('forum', $postInfo->getCategoryId());
if(!$perms->check(Perm::F_CATEGORY_VIEW))
Template::throwError(403);
$canDeleteAny = $perms->check(Perm::F_POST_DELETE_ANY);
switch($postMode) {
case 'delete':
if($canDeleteAny) {
if($postInfo->isDeleted())
Template::displayInfo('This post has already been marked as deleted.', 404);
} else {
if($postInfo->isDeleted())
Template::throwError(404);
if(!$perms->check(Perm::F_POST_DELETE_OWN))
Template::displayInfo('You are not allowed to delete posts.', 403);
if($postInfo->getUserId() !== $currentUser->getId())
Template::displayInfo('You can only delete your own posts.', 403);
// posts may only be deleted within a week of creation, this should be a config value
$deleteTimeFrame = 60 * 60 * 24 * 7;
if($postInfo->getCreatedTime() < time() - $deleteTimeFrame)
Template::displayInfo('This post has existed for too long. Ask a moderator to remove if it absolutely necessary.', 403);
}
$originalPostInfo = $forumPosts->getPost(topicInfo: $postInfo->getTopicId());
if($originalPostInfo->getId() === $postInfo->getId())
Template::displayInfo('This is the opening post of the topic it belongs to, it may not be deleted without deleting the entire topic as well.', 403);
if($postRequestVerified && !$submissionConfirmed) {
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
break;
} elseif(!$postRequestVerified) {
Template::render('forum.confirm', [
'title' => 'Confirm post deletion',
'class' => 'far fa-trash-alt',
'message' => sprintf('You are about to delete post #%d. Are you sure about that?', $postInfo->getId()),
'params' => [
'p' => $postInfo->getId(),
'm' => 'delete',
],
]);
break;
}
$forumPosts->deletePost($postInfo);
$msz->createAuditLog('FORUM_POST_DELETE', [$postInfo->getId()]);
Tools::redirect($urls->format('forum-topic', ['topic' => $postInfo->getTopicId()]));
break;
case 'nuke':
if(!$canDeleteAny)
Template::throwError(403);
if($postRequestVerified && !$submissionConfirmed) {
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
break;
} elseif(!$postRequestVerified) {
Template::render('forum.confirm', [
'title' => 'Confirm post nuke',
'class' => 'fas fa-radiation',
'message' => sprintf('You are about to PERMANENTLY DELETE post #%d. Are you sure about that?', $postInfo->getId()),
'params' => [
'p' => $postInfo->getId(),
'm' => 'nuke',
],
]);
break;
}
$forumPosts->nukePost($postInfo->getId());
$msz->createAuditLog('FORUM_POST_NUKE', [$postInfo->getId()]);
Tools::redirect($urls->format('forum-topic', ['topic' => $postInfo->getTopicId()]));
break;
case 'restore':
if(!$canDeleteAny)
Template::throwError(403);
if($postRequestVerified && !$submissionConfirmed) {
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
break;
} elseif(!$postRequestVerified) {
Template::render('forum.confirm', [
'title' => 'Confirm post restore',
'class' => 'fas fa-magic',
'message' => sprintf('You are about to restore post #%d. Are you sure about that?', $postInfo->getId()),
'params' => [
'p' => $postInfo->getId(),
'm' => 'restore',
],
]);
break;
}
$forumPosts->restorePost($postInfo->getId());
$msz->createAuditLog('FORUM_POST_RESTORE', [$postInfo->getId()]);
Tools::redirect($urls->format('forum-topic', ['topic' => $postInfo->getTopicId()]));
break;
default: // function as an alt for topic.php?p= by default
Tools::redirect($urls->format('forum-post', ['post' => $postInfo->getId()]));
break;
}

View file

@ -3,23 +3,20 @@ namespace Misuzu;
use stdClass;
use RuntimeException;
use Index\DateTime;
use Misuzu\Forum\ForumTopicInfo;
use Misuzu\Forum\{ForumCategoryInfo,ForumPostInfo,ForumTopicInfo};
use Misuzu\Parsers\Parser;
use Index\XDateTime;
use Carbon\CarbonImmutable;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->isLoggedIn)
Template::throwError(401);
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$currentUser = $authInfo->getUserInfo();
$currentUserId = $currentUser->getId();
if($usersCtx->hasActiveBan($currentUser))
$currentUser = $msz->authInfo->userInfo;
$currentUserId = $currentUser->id;
if($msz->usersCtx->hasActiveBan($currentUser))
Template::throwError(403);
$forumPostingModes = [
@ -64,16 +61,16 @@ if(empty($postId)) {
$hasPostInfo = false;
} else {
try {
$postInfo = $forumPosts->getPost(postId: $postId);
$postInfo = $msz->forumCtx->posts->getPost(postId: (string)$postId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
if($postInfo->isDeleted())
if($postInfo->deleted)
Template::throwError(404);
// should automatic cross-quoting be a thing? if so, check if $topicId is < 1 first <-- what did i mean by this?
$topicId = $postInfo->getTopicId();
$topicId = $postInfo->topicId;
$hasPostInfo = true;
}
@ -81,16 +78,16 @@ if(empty($topicId)) {
$hasTopicInfo = false;
} else {
try {
$topicInfo = $forumTopics->getTopic(topicId: $topicId);
$topicInfo = $msz->forumCtx->topics->getTopic(topicId: $topicId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
if($topicInfo->isDeleted())
if($topicInfo->deleted)
Template::throwError(404);
$forumId = $topicInfo->getCategoryId();
$originalPostInfo = $forumPosts->getPost(topicInfo: $topicInfo);
$forumId = $topicInfo->categoryId;
$originalPostInfo = $msz->forumCtx->posts->getPost(topicInfo: $topicInfo);
$hasTopicInfo = true;
}
@ -98,7 +95,7 @@ if(empty($forumId)) {
$hasCategoryInfo = false;
} else {
try {
$categoryInfo = $forumCategories->getCategory(categoryId: $forumId);
$categoryInfo = $msz->forumCtx->categories->getCategory(categoryId: $forumId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -106,16 +103,19 @@ if(empty($forumId)) {
$hasCategoryInfo = true;
}
$perms = $authInfo->getPerms('forum', $categoryInfo);
if(!isset($categoryInfo) || !($categoryInfo instanceof ForumCategoryInfo))
Template::throwError(404);
if($categoryInfo->isArchived()
|| (isset($topicInfo) && $topicInfo->isLocked() && !$perms->check(Perm::F_TOPIC_LOCK))
$perms = $msz->authInfo->getPerms('forum', $categoryInfo);
if($categoryInfo->archived
|| (isset($topicInfo) && $topicInfo->locked && !$perms->check(Perm::F_TOPIC_LOCK))
|| !$perms->check(Perm::F_CATEGORY_VIEW)
|| !$perms->check(Perm::F_POST_CREATE)
|| (!isset($topicInfo) && !$perms->check(Perm::F_TOPIC_CREATE)))
Template::throwError(403);
if(!$categoryInfo->mayHaveTopics())
if(!$categoryInfo->mayHaveTopics)
Template::throwError(400);
$topicTypes = [];
@ -132,8 +132,12 @@ if($mode === 'create' || $mode === 'edit') {
}
// edit mode stuff
if($mode === 'edit' && !$perms->check($postInfo->getUserId() === $currentUserId ? Perm::F_POST_EDIT_OWN : Perm::F_POST_EDIT_ANY))
Template::throwError(403);
if($mode === 'edit') {
if(!isset($postInfo) || !($postInfo instanceof ForumPostInfo))
Template::throwError(404);
if(!$perms->check($postInfo->userId === $currentUserId ? Perm::F_POST_EDIT_OWN : Perm::F_POST_EDIT_ANY))
Template::throwError(403);
}
$notices = [];
@ -147,16 +151,16 @@ if(!empty($_POST)) {
if(!CSRF::validateRequest()) {
$notices[] = 'Could not verify request.';
} else {
$isEditingTopic = empty($topicInfo) || ($mode === 'edit' && $originalPostInfo->getId() == $postInfo->getId());
$isEditingTopic = empty($topicInfo) || ($mode === 'edit' && $originalPostInfo->id == $postInfo->id);
if($mode === 'create') {
$postTimeout = $cfg->getInteger('forum.posting.timeout', 5);
if($postTimeout > 0) {
$postTimeoutThreshold = DateTime::now()->modify(sprintf('-%d seconds', $postTimeout));
$lastPostCreatedAt = $forumPosts->getUserLastPostCreatedAt($currentUser);
$postTimeoutThreshold = new CarbonImmutable(sprintf('-%d seconds', $postTimeout));
$lastPostCreatedAt = $msz->forumCtx->posts->getUserLastPostCreatedAt($currentUser);
if($lastPostCreatedAt->isMoreThan($postTimeoutThreshold)) {
$waitSeconds = $postTimeout + ($lastPostCreatedAt->getUnixTimeSeconds() - time());
if(XDateTime::compare($lastPostCreatedAt, $postTimeoutThreshold) > 0) {
$waitSeconds = $postTimeout + ((int)$lastPostCreatedAt->format('U') - time());
$notices[] = sprintf("You're posting too quickly! Please wait %s seconds before posting again.", number_format($waitSeconds));
$notices[] = "It's possible that your post went through successfully and you pressed the submit button twice by accident.";
@ -165,9 +169,9 @@ if(!empty($_POST)) {
}
if($isEditingTopic) {
$originalTopicTitle = $topicInfo?->getTitle() ?? null;
$originalTopicTitle = $topicInfo?->title ?? null; // @phpstan-ignore-line: nope it can be null
$topicTitleChanged = $topicTitle !== $originalTopicTitle;
$originalTopicType = $topicInfo?->getTypeString() ?? 'discussion';
$originalTopicType = $topicInfo?->typeString ?? 'discussion'; // @phpstan-ignore-line: this also
$topicTypeChanged = $topicType !== null && $topicType !== $originalTopicType;
$topicTitleLengths = $cfg->getValues([
@ -206,19 +210,19 @@ if(!empty($_POST)) {
switch($mode) {
case 'create':
if(empty($topicInfo)) {
$topicInfo = $forumTopics->createTopic(
$topicInfo = $msz->forumCtx->topics->createTopic(
$categoryInfo,
$currentUser,
$topicTitle,
$topicType
);
$topicId = $topicInfo->getId();
$forumCategories->incrementCategoryTopics($categoryInfo);
$topicId = $topicInfo->id;
$msz->forumCtx->categories->incrementCategoryTopics($categoryInfo);
} else
$forumTopics->bumpTopic($topicInfo);
$msz->forumCtx->topics->bumpTopic($topicInfo);
$postInfo = $forumPosts->createPost(
$postInfo = $msz->forumCtx->posts->createPost(
$topicId,
$currentUser,
$_SERVER['REMOTE_ADDR'],
@ -228,17 +232,17 @@ if(!empty($_POST)) {
$categoryInfo
);
$postId = $postInfo->getId();
$forumCategories->incrementCategoryPosts($categoryInfo);
$postId = $postInfo->id;
$msz->forumCtx->categories->incrementCategoryPosts($categoryInfo);
break;
case 'edit':
$markUpdated = $postInfo->getUserId() === $currentUserId
&& $postInfo->shouldMarkAsEdited()
&& $postText !== $postInfo->getBody();
$markUpdated = $postInfo->userId === $currentUserId
&& $postInfo->shouldMarkAsEdited
&& $postText !== $postInfo->body;
$forumPosts->updatePost(
$postId,
$msz->forumCtx->posts->updatePost(
(string)$postId,
remoteAddr: $_SERVER['REMOTE_ADDR'],
body: $postText,
bodyParser: $postParser,
@ -247,7 +251,7 @@ if(!empty($_POST)) {
);
if($isEditingTopic && ($topicTitleChanged || $topicTypeChanged))
$forumTopics->updateTopic(
$msz->forumCtx->topics->updateTopic(
$topicId,
title: $topicTitle,
type: $topicType
@ -255,11 +259,11 @@ if(!empty($_POST)) {
break;
}
if(empty($notices)) {
if(empty($notices)) { // @phpstan-ignore-line: i'm guessing it gets the type confused at this point
// does this ternary ever return forum-topic?
$redirect = $msz->getURLs()->format(empty($topicInfo) ? 'forum-topic' : 'forum-post', [
'topic' => $topicId ?? 0,
'post' => $postId ?? 0,
$redirect = $msz->urls->format(empty($topicInfo) ? 'forum-topic' : 'forum-post', [
'topic' => $topicId,
'post' => $postId,
]);
Tools::redirect($redirect);
return;
@ -275,32 +279,32 @@ if($mode === 'edit') { // $post is pretty much sure to be populated at this poin
$post = new stdClass;
$post->info = $postInfo;
if($postInfo->hasUserId()) {
$post->user = $usersCtx->getUserInfo($postInfo->getUserId());
$post->colour = $usersCtx->getUserColour($post->user);
$post->postsCount = $forumCtx->countTotalUserPosts($post->user);
if($postInfo->userId !== null) {
$post->user = $msz->usersCtx->getUserInfo($postInfo->userId);
$post->colour = $msz->usersCtx->getUserColour($post->user);
$post->postsCount = $msz->forumCtx->countTotalUserPosts($post->user);
}
$post->isOriginalPost = $originalPostInfo->getId() == $postInfo->getId();
$post->isOriginalPoster = $originalPostInfo->hasUserId() && $postInfo->hasUserId()
&& $originalPostInfo->getUserId() === $postInfo->getUserId();
$post->isOriginalPost = $originalPostInfo->id == $postInfo->id;
$post->isOriginalPoster = $originalPostInfo->userId !== null && $postInfo->userId !== null
&& $originalPostInfo->userId === $postInfo->userId;
Template::set('posting_post', $post);
}
try {
$lastPostInfo = $forumPosts->getPost(userInfo: $currentUser, getLast: true, deleted: false);
$selectedParser = $lastPostInfo->getParser();
$lastPostInfo = $msz->forumCtx->posts->getPost(userInfo: $currentUser, getLast: true, deleted: false);
$selectedParser = $lastPostInfo->parser;
} catch(RuntimeException $ex) {
$selectedParser = Parser::BBCODE;
}
Template::render('forum.posting', [
'posting_breadcrumbs' => $forumCategories->getCategoryAncestry($categoryInfo),
'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
'posting_breadcrumbs' => iterator_to_array($msz->forumCtx->categories->getCategoryAncestry($categoryInfo)),
'global_accent_colour' => $msz->forumCtx->categories->getCategoryColour($categoryInfo),
'posting_user' => $currentUser,
'posting_user_colour' => $usersCtx->getUserColour($currentUser),
'posting_user_posts_count' => $forumCtx->countTotalUserPosts($currentUser),
'posting_user_colour' => $msz->usersCtx->getUserColour($currentUser),
'posting_user_posts_count' => $msz->forumCtx->countTotalUserPosts($currentUser),
'posting_user_preferred_parser' => $selectedParser,
'posting_forum' => $categoryInfo,
'posting_notices' => $notices,

View file

@ -1,342 +0,0 @@
<?php
namespace Misuzu;
use stdClass;
use RuntimeException;
$urls = $msz->getURLs();
$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumTopicRedirects = $forumCtx->getTopicRedirects();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();
$postId = !empty($_GET['p']) && is_string($_GET['p']) ? (int)$_GET['p'] : 0;
$topicId = !empty($_GET['t']) && is_string($_GET['t']) ? (int)$_GET['t'] : 0;
$categoryId = null;
$moderationMode = !empty($_GET['m']) && is_string($_GET['m']) ? (string)$_GET['m'] : '';
$submissionConfirmed = !empty($_GET['confirm']) && is_string($_GET['confirm']) && $_GET['confirm'] === '1';
$authInfo = $msz->getAuthInfo();
$currentUser = $authInfo->getUserInfo();
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();
if($topicId < 1 && $postId > 0) {
try {
$postInfo = $forumPosts->getPost(postId: $postId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
$categoryId = $postInfo->getCategoryId();
$perms = $authInfo->getPerms('forum', $postInfo->getCategoryId());
$canDeleteAny = $perms->check(Perm::F_POST_DELETE_ANY);
if($postInfo->isDeleted() && !$canDeleteAny)
Template::throwError(404);
$topicId = $postInfo->getTopicId();
$preceedingPostCount = $forumPosts->countPosts(
topicInfo: $topicId,
upToPostInfo: $postInfo,
deleted: $canDeleteAny ? null : false
);
}
try {
$topicIsNuked = $topicIsDeleted = $canDeleteAny = false;
$topicInfo = $forumTopics->getTopic(topicId: $topicId);
} catch(RuntimeException $ex) {
$topicIsNuked = true;
}
if(!$topicIsNuked) {
$topicIsDeleted = $topicInfo->isDeleted();
if($categoryId !== (int)$topicInfo->getCategoryId()) {
$categoryId = (int)$topicInfo->getCategoryId();
$perms = $authInfo->getPerms('forum', $topicInfo->getCategoryId());
}
if($usersCtx->hasActiveBan($currentUser))
$perms = $perms->apply(fn($calc) => $calc & (Perm::F_CATEGORY_LIST | Perm::F_CATEGORY_VIEW));
$canDeleteAny = $perms->check(Perm::F_POST_DELETE_ANY);
}
if($topicIsNuked || $topicIsDeleted) {
if($forumTopicRedirects->hasTopicRedirect($topicId)) {
$topicRedirectInfo = $forumTopicRedirects->getTopicRedirect($topicId);
Template::set('topic_redir_info', $topicRedirectInfo);
if($topicIsNuked || !$canDeleteAny) {
header('Location: ' . $topicRedirectInfo->getLinkTarget());
return;
}
}
if(empty($topicRedirectInfo))
Template::throwError(404);
}
if(!$perms->check(Perm::F_CATEGORY_VIEW))
Template::throwError(403);
// Maximum amount of posts a topic may contain to still be deletable by the author
// this should be in the config
$deletePostThreshold = 1;
$categoryInfo = $forumCategories->getCategory(topicInfo: $topicInfo);
$topicIsLocked = $topicInfo->isLocked();
$topicIsArchived = $categoryInfo->isArchived();
$topicPostsTotal = $topicInfo->getTotalPostsCount();
$topicIsFrozen = $topicIsArchived || $topicIsDeleted;
$canDeleteOwn = !$topicIsFrozen && !$topicIsLocked && $perms->check(Perm::F_POST_DELETE_OWN);
$canBumpTopic = !$topicIsFrozen && $perms->check(Perm::F_TOPIC_BUMP);
$canLockTopic = !$topicIsFrozen && $perms->check(Perm::F_TOPIC_LOCK);
$canNukeOrRestore = $canDeleteAny && $topicIsDeleted;
$canDelete = !$topicIsDeleted && (
$canDeleteAny || (
$topicPostsTotal > 0
&& $topicPostsTotal <= $deletePostThreshold
&& $canDeleteOwn
&& $topicInfo->getUserId() === (string)$currentUserId
)
);
$validModerationModes = [
'delete', 'restore', 'nuke',
'bump', 'lock', 'unlock',
];
if(in_array($moderationMode, $validModerationModes, true)) {
if(!CSRF::validateRequest())
Template::displayInfo("Couldn't verify this request, please refresh the page and try again.", 403);
$authInfo = $authInfo;
if(!$authInfo->isLoggedIn())
Template::displayInfo('You must be logged in to manage posts.', 401);
if($usersCtx->hasActiveBan($currentUser))
Template::displayInfo('You have been banned, check your profile for more information.', 403);
switch($moderationMode) {
case 'delete':
if($canDeleteAny) {
if($topicInfo->isDeleted())
Template::displayInfo('This topic has already been marked as deleted.', 404);
} else {
if($topicInfo->isDeleted())
Template::throwError(404);
if(!$canDeleteOwn)
Template::displayInfo("You aren't allowed to delete topics.", 403);
if($topicInfo->getUserId() !== $currentUser->getId())
Template::displayInfo('You can only delete your own topics.', 403);
// topics may only be deleted within a day of creation, this should be a config value
$deleteTimeFrame = 60 * 60 * 24;
if($topicInfo->getCreatedTime() < time() - $deleteTimeFrame)
Template::displayInfo('This topic has existed for too long. Ask a moderator to remove if it absolutely necessary.', 403);
// deleted posts are intentionally included
$topicPostCount = $forumPosts->countPosts(topicInfo: $topicInfo);
if($topicPostCount > $deletePostThreshold)
Template::displayInfo('This topic already has replies, you may no longer delete it. Ask a moderator to remove if it absolutely necessary.', 403);
}
if(!isset($_GET['confirm'])) {
Template::render('forum.confirm', [
'title' => 'Confirm topic deletion',
'class' => 'far fa-trash-alt',
'message' => sprintf('You are about to delete topic #%d. Are you sure about that?', $topicInfo->getId()),
'params' => [
't' => $topicInfo->getId(),
'm' => 'delete',
],
]);
break;
} elseif(!$submissionConfirmed) {
Tools::redirect($urls->format(
'forum-topic',
['topic' => $topicInfo->getId()]
));
break;
}
$forumTopics->deleteTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_DELETE', [$topicInfo->getId()]);
Tools::redirect($urls->format('forum-category', [
'forum' => $categoryInfo->getId(),
]));
break;
case 'restore':
if(!$canNukeOrRestore)
Template::throwError(403);
if(!isset($_GET['confirm'])) {
Template::render('forum.confirm', [
'title' => 'Confirm topic restore',
'class' => 'fas fa-magic',
'message' => sprintf('You are about to restore topic #%d. Are you sure about that?', $topicInfo->getId()),
'params' => [
't' => $topicInfo->getId(),
'm' => 'restore',
],
]);
break;
} elseif(!$submissionConfirmed) {
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
]));
break;
}
$forumTopics->restoreTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_RESTORE', [$topicInfo->getId()]);
Tools::redirect($urls->format('forum-category', [
'forum' => $categoryInfo->getId(),
]));
break;
case 'nuke':
if(!$canNukeOrRestore)
Template::throwError(403);
if(!isset($_GET['confirm'])) {
Template::render('forum.confirm', [
'title' => 'Confirm topic nuke',
'class' => 'fas fa-radiation',
'message' => sprintf('You are about to PERMANENTLY DELETE topic #%d. Are you sure about that?', $topicInfo->getId()),
'params' => [
't' => $topicInfo->getId(),
'm' => 'nuke',
],
]);
break;
} elseif(!$submissionConfirmed) {
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
]));
break;
}
$forumTopics->nukeTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_NUKE', [$topicInfo->getId()]);
Tools::redirect($urls->format('forum-category', [
'forum' => $categoryInfo->getId(),
]));
break;
case 'bump':
if($canBumpTopic) {
$forumTopics->bumpTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_BUMP', [$topicInfo->getId()]);
}
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
]));
break;
case 'lock':
if($canLockTopic && !$topicIsLocked) {
$forumTopics->lockTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_LOCK', [$topicInfo->getId()]);
}
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
]));
break;
case 'unlock':
if($canLockTopic && $topicIsLocked) {
$forumTopics->unlockTopic($topicInfo->getId());
$msz->createAuditLog('FORUM_TOPIC_UNLOCK', [$topicInfo->getId()]);
}
Tools::redirect($urls->format('forum-topic', [
'topic' => $topicInfo->getId(),
]));
break;
}
return;
}
$topicPosts = $topicInfo->getPostsCount();
if($canDeleteAny)
$topicPosts += $topicInfo->getDeletedPostsCount();
$topicPagination = new Pagination($topicPosts, 10, 'page');
if(isset($preceedingPostCount))
$topicPagination->setPage(floor($preceedingPostCount / $topicPagination->getRange()), true);
if(!$topicPagination->hasValidOffset())
Template::throwError(404);
$postInfos = $forumPosts->getPosts(
topicInfo: $topicInfo,
deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false,
pagination: $topicPagination,
);
if(empty($postInfos))
Template::throwError(404);
$originalPostInfo = $forumPosts->getPost(topicInfo: $topicInfo);
$posts = [];
foreach($postInfos as $postInfo) {
$posts[] = $post = new stdClass;
$post->info = $postInfo;
if($postInfo->hasUserId()) {
$post->user = $usersCtx->getUserInfo($postInfo->getUserId());
$post->colour = $usersCtx->getUserColour($post->user);
$post->postsCount = $forumCtx->countTotalUserPosts($post->user);
}
$post->isOriginalPost = $originalPostInfo->getId() == $postInfo->getId();
$post->isOriginalPoster = $originalPostInfo->hasUserId() && $postInfo->hasUserId()
&& $originalPostInfo->getUserId() === $postInfo->getUserId();
}
$canReply = !$topicIsArchived && !$topicIsLocked && !$topicIsDeleted && $perms->check(Perm::F_POST_CREATE);
if(!$forumTopics->checkUserHasReadTopic($currentUser, $topicInfo))
$forumTopics->incrementTopicViews($topicInfo);
$forumTopics->updateUserReadTopic($currentUser, $topicInfo);
$perms = $perms->checkMany([
'can_create_post' => Perm::F_POST_CREATE,
'can_edit_post' => Perm::F_POST_EDIT_OWN,
'can_edit_any_post' => Perm::F_POST_EDIT_ANY,
'can_delete_post' => Perm::F_POST_DELETE_OWN,
'can_delete_any_post' => Perm::F_POST_DELETE_ANY,
]);
Template::render('forum.topic', [
'topic_breadcrumbs' => $forumCategories->getCategoryAncestry($topicInfo),
'global_accent_colour' => $forumCategories->getCategoryColour($topicInfo),
'topic_info' => $topicInfo,
'category_info' => $categoryInfo,
'topic_posts' => $posts,
'can_reply' => $canReply,
'topic_pagination' => $topicPagination,
'topic_can_delete' => $canDelete,
'topic_can_nuke_or_restore' => $canNukeOrRestore,
'topic_can_bump' => $canBumpTopic,
'topic_can_lock' => $canLockTopic,
'topic_user_id' => $currentUserId,
'topic_perms' => $perms,
]);

View file

@ -3,32 +3,32 @@ namespace Misuzu;
use DateTimeInterface;
use RuntimeException;
use Index\DateTime;
use Index\XArray;
use Misuzu\Changelog\Changelog;
use Carbon\CarbonImmutable;
use Index\{XArray,XDateTime};
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
Template::throwError(403);
$changeActions = [];
foreach(Changelog::ACTIONS as $action)
$changeActions[$action] = Changelog::actionText($action);
$urls = $msz->getURLs();
$changelog = $msz->getChangelog();
$changeId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$changeInfo = null;
$changeTagIds = [];
$tagInfos = $changelog->getTags();
$tagInfos = $msz->changelog->getTags();
if(empty($changeId))
$isNew = true;
else
try {
$isNew = false;
$changeInfo = $changelog->getChange($changeId);
$changeTagIds = XArray::select($changelog->getTags(changeInfo: $changeInfo), fn($tagInfo) => $tagInfo->getId());
$changeInfo = $msz->changelog->getChange($changeId);
$changeTagIds = XArray::select($msz->changelog->getTags(changeInfo: $changeInfo), fn($tagInfo) => $tagInfo->id);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -37,9 +37,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$changelog->deleteChange($changeInfo);
$msz->createAuditLog('CHANGELOG_ENTRY_DELETE', [$changeInfo->getId()]);
Tools::redirect($urls->format('manage-changelog-changes'));
$msz->changelog->deleteChange($changeInfo);
$msz->createAuditLog('CHANGELOG_ENTRY_DELETE', [$changeInfo->id]);
Tools::redirect($msz->urls->format('manage-changelog-changes'));
return;
}
@ -58,26 +58,26 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
if(empty($createdAt))
$createdAt = null;
else {
$createdAt = DateTime::createFromFormat(DateTimeInterface::ATOM, $createdAt . ':00Z');
if($createdAt->getUnixTimeSeconds() < 0)
$createdAt = CarbonImmutable::createFromFormat(DateTimeInterface::ATOM, $createdAt . ':00Z');
if((int)$createdAt->format('U') < 0)
$createdAt = null;
}
if($isNew) {
$changeInfo = $changelog->createChange($action, $summary, $body, $userId, $createdAt);
$changeInfo = $msz->changelog->createChange($action, $summary, $body, $userId, $createdAt);
} else {
if($action === $changeInfo->getAction())
if($action === $changeInfo->action)
$action = null;
if($summary === $changeInfo->getSummary())
if($summary === $changeInfo->summary)
$summary = null;
if($body === $changeInfo->getBody())
if($body === $changeInfo->body)
$body = null;
if($createdAt !== null && $createdAt->equals($changeInfo->getCreatedAt()))
if($createdAt !== null && XDateTime::compare($createdAt, $changeInfo->createdAt) === 0)
$createdAt = null;
$updateUserInfo = $userId !== $changeInfo->getUserId();
$updateUserInfo = $userId !== $changeInfo->userId;
if($action !== null || $summary !== null || $body !== null || $createdAt !== null || $updateUserInfo)
$changelog->updateChange($changeInfo, $action, $summary, $body, $updateUserInfo, $userId, $createdAt);
$msz->changelog->updateChange($changeInfo, $action, $summary, $body, $updateUserInfo, $userId, $createdAt);
}
if(!empty($tags)) {
@ -88,24 +88,24 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
foreach($tCurrent as $tag)
if(!in_array($tag, $tApply)) {
$tRemove[] = $tag;
$changelog->removeTagFromChange($changeInfo, $tag);
$msz->changelog->removeTagFromChange($changeInfo, $tag);
}
$tCurrent = array_diff($tCurrent, $tRemove);
foreach($tApply as $tag)
if(!in_array($tag, $tCurrent)) {
$changelog->addTagToChange($changeInfo, $tag);
$msz->changelog->addTagToChange($changeInfo, $tag);
$tCurrent[] = $tag;
}
}
$msz->createAuditLog(
$isNew ? 'CHANGELOG_ENTRY_CREATE' : 'CHANGELOG_ENTRY_EDIT',
[$changeInfo->getId()]
[$changeInfo->id]
);
Tools::redirect($urls->format('manage-changelog-change', ['change' => $changeInfo->getId()]));
Tools::redirect($msz->urls->format('manage-changelog-change', ['change' => $changeInfo->id]));
return;
}
@ -115,5 +115,5 @@ Template::render('manage.changelog.change', [
'change_info_tags' => $changeTagIds,
'change_tags' => $tagInfos,
'change_actions' => $changeActions,
'change_author_id' => $authInfo->getUserInfo(),
'change_author_id' => $msz->authInfo->userId,
]);

View file

@ -3,32 +3,31 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_CHANGES_MANAGE))
Template::throwError(403);
$changelog = $msz->getChangelog();
$usersCtx = $msz->getUsersContext();
$changelogPagination = new Pagination($changelog->countChanges(), 30);
if(!$changelogPagination->hasValidOffset())
$pagination = Pagination::fromInput($msz->changelog->countChanges(), 30);
if(!$pagination->validOffset)
Template::throwError(404);
$changeInfos = $changelog->getChanges(pagination: $changelogPagination);
$changeInfos = $msz->changelog->getChanges(pagination: $pagination);
$changes = [];
foreach($changeInfos as $changeInfo) {
$userInfo = $changeInfo->hasUserId() ? $usersCtx->getUserInfo($changeInfo->getUserId()) : null;
$userInfo = $changeInfo->userId !== null ? $msz->usersCtx->getUserInfo($changeInfo->userId) : null;
$changes[] = [
'change' => $changeInfo,
'tags' => $changelog->getTags(changeInfo: $changeInfo),
'tags' => $msz->changelog->getTags(changeInfo: $changeInfo),
'user' => $userInfo,
'user_colour' => $usersCtx->getUserColour($userInfo),
'user_colour' => $msz->usersCtx->getUserColour($userInfo),
];
}
Template::render('manage.changelog.changes', [
'changelog_changes' => $changes,
'changelog_pagination' => $changelogPagination,
'changelog_pagination' => $pagination,
]);

View file

@ -3,13 +3,14 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
Template::throwError(403);
$urls = $msz->getURLs();
$changelog = $msz->getChangelog();
$tagId = (string)filter_input(INPUT_GET, 't', FILTER_SANITIZE_NUMBER_INT);
$loadTagInfo = fn() => $changelog->getTag($tagId);
$loadTagInfo = fn() => $msz->changelog->getTag($tagId);
if(empty($tagId))
$isNew = true;
@ -25,9 +26,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$changelog->deleteTag($tagInfo);
$msz->createAuditLog('CHANGELOG_TAG_DELETE', [$tagInfo->getId()]);
Tools::redirect($urls->format('manage-changelog-tags'));
$msz->changelog->deleteTag($tagInfo);
$msz->createAuditLog('CHANGELOG_TAG_DELETE', [$tagInfo->id]);
Tools::redirect($msz->urls->format('manage-changelog-tags'));
return;
}
@ -37,26 +38,26 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$archive = !empty($_POST['ct_archive']);
if($isNew) {
$tagInfo = $changelog->createTag($name, $description, $archive);
$tagInfo = $msz->changelog->createTag($name, $description, $archive);
} else {
if($name === $tagInfo->getName())
if($name === $tagInfo->name)
$name = null;
if($description === $tagInfo->getDescription())
if($description === $tagInfo->description)
$description = null;
if($archive === $tagInfo->isArchived())
if($archive === $tagInfo->archived)
$archive = null;
if($name !== null || $description !== null || $archive !== null)
$changelog->updateTag($tagInfo, $name, $description, $archive);
$msz->changelog->updateTag($tagInfo, $name, $description, $archive);
}
$msz->createAuditLog(
$isNew ? 'CHANGELOG_TAG_CREATE' : 'CHANGELOG_TAG_EDIT',
[$tagInfo->getId()]
[$tagInfo->id]
);
if($isNew) {
Tools::redirect($urls->format('manage-changelog-tag', ['tag' => $tagInfo->getId()]));
Tools::redirect($msz->urls->format('manage-changelog-tag', ['tag' => $tagInfo->id]));
return;
} else $tagInfo = $loadTagInfo();
break;

View file

@ -1,9 +1,12 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CL_TAGS_MANAGE))
Template::throwError(403);
Template::render('manage.changelog.tags', [
'changelog_tags' => $msz->getChangelog()->getTags(),
'changelog_tags' => $msz->changelog->getTags(),
]);

View file

@ -3,11 +3,13 @@ namespace Misuzu;
use Misuzu\Perm;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_FORUM_CATEGORIES_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_FORUM_CATEGORIES_MANAGE))
Template::throwError(403);
$perms = $msz->getPerms();
$permsInfos = $perms->getPermissionInfo(categoryNames: Perm::INFO_FOR_FORUM_CATEGORY);
$permsInfos = $msz->perms->getPermissionInfo(categoryNames: Perm::INFO_FOR_FORUM_CATEGORY);
$permsLists = Perm::createList(Perm::LISTS_FOR_FORUM_CATEGORY);
if(filter_has_var(INPUT_POST, 'perms'))

View file

@ -1,13 +1,11 @@
<?php
namespace Misuzu;
$authInfo = $msz->getAuthInfo();
if(!$authInfo->getPerms('global')->check(Perm::G_FORUM_TOPIC_REDIRS_MANAGE))
Template::throwError(403);
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
$urls = $msz->getURLs();
$forumCtx = $msz->getForumContext();
$forumTopicRedirects = $forumCtx->getTopicRedirects();
if(!$msz->authInfo->getPerms('global')->check(Perm::G_FORUM_TOPIC_REDIRS_MANAGE))
Template::throwError(403);
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(!CSRF::validateRequest())
@ -17,8 +15,8 @@ if($_SERVER['REQUEST_METHOD'] === 'POST') {
$rTopicURL = trim((string)filter_input(INPUT_POST, 'topic_redir_url'));
$msz->createAuditLog('FORUM_TOPIC_REDIR_CREATE', [$rTopicId]);
$forumTopicRedirects->createTopicRedirect($rTopicId, $authInfo->getUserInfo(), $rTopicURL);
Tools::redirect($urls->format('manage-forum-topic-redirs'));
$msz->forumCtx->topicRedirects->createTopicRedirect($rTopicId, $msz->authInfo->userInfo, $rTopicURL);
Tools::redirect($msz->urls->format('manage-forum-topic-redirs'));
return;
}
@ -28,16 +26,16 @@ if(filter_input(INPUT_GET, 'm') === 'explode') {
$rTopicId = (string)filter_input(INPUT_GET, 't');
$msz->createAuditLog('FORUM_TOPIC_REDIR_REMOVE', [$rTopicId]);
$forumTopicRedirects->deleteTopicRedirect($rTopicId);
Tools::redirect($urls->format('manage-forum-topic-redirs'));
$msz->forumCtx->topicRedirects->deleteTopicRedirect($rTopicId);
Tools::redirect($msz->urls->format('manage-forum-topic-redirs'));
return;
}
$pagination = new Pagination($forumTopicRedirects->countTopicRedirects(), 20);
if(!$pagination->hasValidOffset())
$pagination = Pagination::fromInput($msz->forumCtx->topicRedirects->countTopicRedirects(), 20);
if(!$pagination->validOffset)
Template::throwError(404);
$redirs = $forumTopicRedirects->getTopicRedirects(pagination: $pagination);
$redirs = $msz->forumCtx->topicRedirects->getTopicRedirects(pagination: $pagination);
Template::render('manage.forum.redirs', [
'manage_redirs' => $redirs,

View file

@ -4,10 +4,12 @@ namespace Misuzu;
use RuntimeException;
use Index\XArray;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
Template::throwError(403);
$emotes = $msz->getEmotes();
$emoteId = (string)filter_input(INPUT_GET, 'e', FILTER_SANITIZE_NUMBER_INT);
$emoteInfo = [];
$emoteStrings = [];
@ -17,8 +19,8 @@ if(empty($emoteId))
else
try {
$isNew = false;
$emoteInfo = $emotes->getEmote($emoteId);
$emoteStrings = $emotes->getEmoteStrings($emoteInfo);
$emoteInfo = $msz->emotes->getEmote($emoteId);
$emoteStrings = iterator_to_array($msz->emotes->getEmoteStrings($emoteInfo));
} catch(RuntimeException $ex) {
Template::throwError(404);
}
@ -30,8 +32,8 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$url = trim((string)filter_input(INPUT_POST, 'em_url'));
$strings = explode(' ', trim((string)filter_input(INPUT_POST, 'em_strings')));
if($isNew || $url !== $emoteInfo->getUrl()) {
$checkUrl = $emotes->checkEmoteUrl($url);
if($isNew || $url !== $emoteInfo->url) {
$checkUrl = $msz->emotes->checkEmoteUrl($url);
if($checkUrl !== '') {
echo match($checkUrl) {
'empty' => 'URL may not be empty.',
@ -47,36 +49,36 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$order = null;
if($isNew) {
$emoteInfo = $emotes->createEmote($url, $minRank, $order);
$emoteInfo = $msz->emotes->createEmote($url, $minRank, $order);
} else {
if($order === $emoteInfo->getOrder())
if($order === $emoteInfo->order)
$order = null;
if($minRank === $emoteInfo->getMinRank())
if($minRank === $emoteInfo->minRank)
$minRank = null;
if($url === $emoteInfo->getUrl())
if($url === $emoteInfo->url)
$url = null;
if($order !== null || $minRank !== null || $url !== null)
$emotes->updateEmote($emoteInfo, $order, $minRank, $url);
$msz->emotes->updateEmote($emoteInfo, $order, $minRank, $url);
}
$sCurrent = XArray::select($emoteStrings, fn($stringInfo) => $stringInfo->getString());
$sCurrent = XArray::select($emoteStrings, fn($stringInfo) => $stringInfo->string);
$sApply = $strings;
$sRemove = [];
foreach($sCurrent as $string)
if(!in_array($string, $sApply)) {
$sRemove[] = $string;
$emotes->removeEmoteString($string);
$msz->emotes->removeEmoteString($string);
}
$sCurrent = array_diff($sCurrent, $sRemove);
foreach($sApply as $string)
if(!in_array($string, $sCurrent)) {
$checkString = $emotes->checkEmoteString($string);
$checkString = $msz->emotes->checkEmoteString($string);
if($checkString === '') {
$emotes->addEmoteString($emoteInfo, $string);
$msz->emotes->addEmoteString($emoteInfo, $string);
} else {
echo match($checkString) {
'empty' => 'String may not be empty.',
@ -94,10 +96,10 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$msz->createAuditLog(
$isNew ? 'EMOTICON_CREATE' : 'EMOTICON_EDIT',
[$emoteInfo->getId()]
[$emoteInfo->id]
);
Tools::redirect($msz->getURLs()->format('manage-general-emoticon', ['emote' => $emoteInfo->getId()]));
Tools::redirect($msz->urls->format('manage-general-emoticon', ['emote' => $emoteInfo->id]));
return;
}

View file

@ -3,44 +3,45 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
Template::throwError(403);
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
$emotes = $msz->getEmotes();
if(!$msz->authInfo->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
Template::throwError(403);
if(CSRF::validateRequest() && !empty($_GET['emote'])) {
$emoteId = (string)filter_input(INPUT_GET, 'emote', FILTER_SANITIZE_NUMBER_INT);
try {
$emoteInfo = $emotes->getEmote($emoteId);
$emoteInfo = $msz->emotes->getEmote($emoteId);
} catch(RuntimeException $ex) {
Template::throwError(404);
}
if(!empty($_GET['delete'])) {
$emotes->deleteEmote($emoteInfo);
$msz->createAuditLog('EMOTICON_DELETE', [$emoteInfo->getId()]);
$msz->emotes->deleteEmote($emoteInfo);
$msz->createAuditLog('EMOTICON_DELETE', [$emoteInfo->id]);
} else {
if(isset($_GET['order'])) {
$order = filter_input(INPUT_GET, 'order');
$offset = $order === 'i' ? 10 : ($order === 'd' ? -10 : 0);
$emotes->updateEmoteOrderOffset($emoteInfo, $offset);
$msz->createAuditLog('EMOTICON_ORDER', [$emoteInfo->getId()]);
$msz->emotes->updateEmoteOrderOffset($emoteInfo, $offset);
$msz->createAuditLog('EMOTICON_ORDER', [$emoteInfo->id]);
}
if(isset($_GET['alias'])) {
$alias = (string)filter_input(INPUT_GET, 'alias');
if($emotes->checkEmoteString($alias) === '') {
$emotes->addEmoteString($emoteInfo, $alias);
$msz->createAuditLog('EMOTICON_ALIAS', [$emoteInfo->getId(), $alias]);
if($msz->emotes->checkEmoteString($alias) === '') {
$msz->emotes->addEmoteString($emoteInfo, $alias);
$msz->createAuditLog('EMOTICON_ALIAS', [$emoteInfo->id, $alias]);
}
}
}
Tools::redirect($msz->getURLs()->format('manage-general-emoticons'));
Tools::redirect($msz->urls->format('manage-general-emoticons'));
return;
}
Template::render('manage.general.emoticons', [
'emotes' => $emotes->getEmotes(),
'emotes' => $msz->emotes->getEmotes(),
]);

View file

@ -1,8 +1,11 @@
<?php
namespace Misuzu;
$counterInfos = $msz->getCounters()->getCounters(orderBy: 'name');
$counterNamesRaw = $msz->getConfig()->getArray('counters.names');
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
$counterInfos = $msz->counters->getCounters(orderBy: 'name');
$counterNamesRaw = $msz->config->getArray('counters.names');
$counterNamesCount = count($counterNamesRaw);
$counterNames = [];

View file

@ -3,26 +3,26 @@ namespace Misuzu;
use Misuzu\Pagination;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_LOGS_VIEW))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_LOGS_VIEW))
Template::throwError(403);
$usersCtx = $msz->getUsersContext();
$auditLog = $msz->getAuditLog();
$pagination = new Pagination($auditLog->countLogs(), 50);
if(!$pagination->hasValidOffset())
$pagination = Pagination::fromInput($msz->auditLog->countLogs(), 50);
if(!$pagination->validOffset)
Template::throwError(404);
$logs = $auditLog->getLogs(pagination: $pagination);
$logs = iterator_to_array($msz->auditLog->getLogs(pagination: $pagination));
$userInfos = [];
$userColours = [];
foreach($logs as $log)
if($log->hasUserId()) {
$userId = $log->getUserId();
if($log->userId !== null) {
$userId = $log->userId;
if(!array_key_exists($userId, $userInfos)) {
$userInfos[$userId] = $usersCtx->getUserInfo($userId);
$userColours[$userId] = $usersCtx->getUserColour($userId);
$userInfos[$userId] = $msz->usersCtx->getUserInfo($userId);
$userColours[$userId] = $msz->usersCtx->getUserColour($userId);
}
}

View file

@ -1,19 +1,22 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
Template::throwError(403);
$valueName = (string)filter_input(INPUT_GET, 'name');
$valueInfo = $cfg->getValueInfo($valueName);
$valueInfo = $msz->config->getValueInfo($valueName);
if($valueInfo === null)
Template::throwError(404);
if($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$valueName = $valueInfo->getName();
$msz->createAuditLog('CONFIG_DELETE', [$valueName]);
$cfg->removeValues($valueName);
Tools::redirect($msz->getURLs()->format('manage-general-settings'));
$msz->config->removeValues($valueName);
Tools::redirect($msz->urls->format('manage-general-settings'));
return;
}

View file

@ -1,16 +1,19 @@
<?php
namespace Misuzu;
use Syokuhou\DbConfig;
use Index\Config\Db\DbConfig;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
Template::throwError(403);
$isNew = true;
$sName = (string)filter_input(INPUT_GET, 'name');
$sType = (string)filter_input(INPUT_GET, 'type');
$sValue = null;
$loadValueInfo = fn() => $cfg->getValueInfo($sName);
$loadValueInfo = fn() => $msz->config->getValueInfo($sName);
if(!empty($sName)) {
$sInfo = $loadValueInfo();
@ -38,7 +41,7 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
}
if($sType === 'array') {
$applyFunc = $cfg->setArray(...);
$applyFunc = $msz->config->setArray(...);
$sValue = [];
$sRaw = filter_input(INPUT_POST, 'conf_value', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
foreach($sRaw as $rValue) {
@ -58,22 +61,22 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
}
} elseif($sType === 'bool') {
$sValue = !empty($_POST['conf_value']);
$applyFunc = $cfg->setBoolean(...);
$applyFunc = $msz->config->setBoolean(...);
} else {
$sValue = filter_input(INPUT_POST, 'conf_value');
if($sType === 'int') {
$applyFunc = $cfg->setInteger(...);
$applyFunc = $msz->config->setInteger(...);
$sValue = (int)$sValue;
} elseif($sType === 'float') {
$applyFunc = $cfg->setFloat(...);
$applyFunc = $msz->config->setFloat(...);
$sValue = (float)$sValue;
} else
$applyFunc = $cfg->setString(...);
$applyFunc = $msz->config->setString(...);
}
$msz->createAuditLog($isNew ? 'CONFIG_CREATE' : 'CONFIG_UPDATE', [$sName]);
$applyFunc($sName, $sValue);
Tools::redirect($msz->getURLs()->format('manage-general-settings'));
Tools::redirect($msz->urls->format('manage-general-settings'));
return;
}

View file

@ -1,11 +1,14 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_CONFIG_MANAGE))
Template::throwError(403);
$hidden = $cfg->getArray('settings.hidden');
$vars = $cfg->getAllValueInfos();
$hidden = $msz->config->getArray('settings.hidden');
$vars = $msz->config->getAllValueInfos();
Template::render('manage.general.settings', [
'config_vars' => $vars,

View file

@ -1,16 +1,17 @@
<?php
namespace Misuzu;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
Template::throwError(403);
$news = $msz->getNews();
$pagination = new Pagination($news->countCategories(), 15);
if(!$pagination->hasValidOffset())
$pagination = Pagination::fromInput($msz->news->countCategories(), 15);
if(!$pagination->validOffset)
Template::throwError(404);
$categories = $news->getCategories(pagination: $pagination);
$categories = $msz->news->getCategories(pagination: $pagination);
Template::render('manage.news.categories', [
'news_categories' => $categories,

View file

@ -3,13 +3,14 @@ namespace Misuzu;
use RuntimeException;
if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
die('Script must be called through the Misuzu route dispatcher.');
if(!$msz->authInfo->getPerms('global')->check(Perm::G_NEWS_CATEGORIES_MANAGE))
Template::throwError(403);
$urls = $msz->getURLs();
$news = $msz->getNews();
$categoryId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$loadCategoryInfo = fn() => $news->getCategory(categoryId: $categoryId);
$loadCategoryInfo = fn() => $msz->news->getCategory(categoryId: $categoryId);
if(empty($categoryId))
$isNew = true;
@ -25,9 +26,9 @@ if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
if(!CSRF::validateRequest())
Template::throwError(403);
$news->deleteCategory($categoryInfo);
$msz->createAuditLog('NEWS_CATEGORY_DELETE', [$categoryInfo->getId()]);
Tools::redirect($urls->format('manage-news-categories'));
$msz->news->deleteCategory($categoryInfo);
$msz->createAuditLog('NEWS_CATEGORY_DELETE', [$categoryInfo->id]);
Tools::redirect($msz->urls->format('manage-news-categories'));
return;
}
@ -37,26 +38,26 @@ while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
$hidden = !empty($_POST['nc_hidden']);
if($isNew) {
$categoryInfo = $news->createCategory($name, $description, $hidden);
$categoryInfo = $msz->news->createCategory($name, $description, $hidden);
} else {
if($name === $categoryInfo->getName())
if($name === $categoryInfo->name)
$name = null;
if($description === $categoryInfo->getDescription())
if($description === $categoryInfo->description)
$description = null;
if($hidden === $categoryInfo->isHidden())
if($hidden === $categoryInfo->hidden)
$hidden = null;
if($name !== null || $description !== null || $hidden !== null)
$news->updateCategory($categoryInfo, $name, $description, $hidden);
$msz->news->updateCategory($categoryInfo, $name, $description, $hidden);
}
$msz->createAuditLog(
$isNew ? 'NEWS_CATEGORY_CREATE' : 'NEWS_CATEGORY_EDIT',
[$categoryInfo->getId()]
[$categoryInfo->id]
);
if($isNew) {
Tools::redirect($urls->format('manage-news-category', ['category' => $categoryInfo->getId()]));
Tools::redirect($msz->urls->format('manage-news-category', ['category' => $categoryInfo->id]));
return;
} else $categoryInfo = $loadCategoryInfo();
break;

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