Продолжение переписывания

This commit is contained in:
Shr3dd3r 2023-11-03 02:38:51 +03:00
parent 12143c148d
commit a573faf5a1
7 changed files with 236 additions and 144 deletions

View File

@ -5,10 +5,10 @@
The newest generation imageboard.
## Remarks
<!--
sudo rm -r /usr/share/nginx/html/testing/E949 && sudo cp -R . /usr/share/nginx/html/testing/E949/ && sudo chown -R http:http /usr/share/nginx/html/testing
- `sudo rm -r /usr/share/nginx/html/testing/E949 && sudo cp -R . /usr/share/nginx/html/testing/E949/ && sudo chown -R http:http /usr/share/nginx/html/testing`
mysql -u e949 -p
- `mysql -u e949 -p`
- `#049e59` -> `#094e59`
#049e59 -> #094e59
-->

View File

@ -31,7 +31,7 @@ function CreateDirIfNotExist ($path) {
mkdir($path, 0755, true);
}
CreateDirIfNotExist("../" . $Config["media"]["pics_path"]);
CreateDirIfNotExist("../" . $Config["media"]["pics_path"]); // TODO: treat path as absolute
CreateDirIfNotExist("../" . $Config["media"]["prevs_path"]);
?>

View File

@ -3,28 +3,31 @@
// Includes
require_once("../_auth.php");
require_once("../_utils.php");
require_once("../_errorslist.php");
require_once("../_types.php");
require_once("../user/index.php");
// Functions
/*
* FUNCTION
* Check if image size properties are valid
*/
function ImageSizeIsValid ($x, $y) {
function Post_ImgResIsValid ($x, $y): bool {
global $Config;
return ($x <= $Config["media"]["max_pic_res"]["x"])
&& ($y <= $Config["media"]["max_pic_res"]["y"])
&& (GetRatio($x, $y) <= $Config["media"]["max_pic_res"]["ratio"]);
&& (Utils_GetRatio($x, $y) <= $Config["media"]["max_pic_res"]["ratio"]);
}
/*
* FUNCTION
* Create preview version of image
*/
function Post_CreatePreviewFromImage ($src, $dst) {
function Post_CreatePreviewFromImage ($src, $dst): ReturnT {
$img = null;
// Reading image from source path
@ -36,18 +39,20 @@ function Post_CreatePreviewFromImage ($src, $dst) {
$img = imagecreatefrompng($src);
break;
default:
throw new Exception("invalid mime type");
return new ReturnT(err_code: E_UIN_FILETYPE, err_desc: "invalid mime type");
}
// Saving it as LQ JPEG
imagejpeg($img, $dst, 30);
return new ReturnT(data: true);
}
/*
* FUNCTION
* Store image
*/
function Post_StoreImage ($path, $preview = true) {
function Post_StoreImage ($path, $preview = true): ReturnT {
global $Config;
// Paths
@ -60,37 +65,105 @@ function Post_StoreImage ($path, $preview = true) {
if ($Config["media"]["previews_enabled"] && $preview) {
$previewDir = "../../" . $Config["media"]["prevs_path"];
$previewPath = JoinPaths($previewDir, $fileName . ".jpg");
Post_CreatePreviewFromImage($path, $previewPath);
$res = Post_CreatePreviewFromImage($path, $previewPath);
if ($res.IsError())
return $res;
}
move_uploaded_file($path, $targetPath);
return new ReturnT(data: true);
}
/*
* FUNCTION
* Create single publication
*/
function Post_Create (
int $author_id,
string $tags,
string $pic_path,
?string $title = null,
?string $prev_path = null,
bool $comms_enabled = false,
bool $edit_lock = false
): ReturnT {
$result = null;
// Author ID should exist
if (!User_IDExist($author_id))
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "specified user id does not exist");
// Performing SQL query
$s = $db->prepare("INSERT INTO posts (author_id,comment_section_id,tags,title,pic_path,preview_path,comments_enabled,edit_lock) VALUES (?,?,?,?,?,?,?,?)");
$s->bind_param("ssssssss", $author_id, null, $tags, $title, $pic_path, $prev_path, $comms_enabled, $edit_lock);
if ($s->execute() === false)
return new ReturnT(err_code: E_DBE_INSERTFAIL, err_desc: "failed to create post record in DB");
return new ReturnT(data: $result);
}
// Methods
/*
* METHOD
* Create single publication
*/
function Post_Create ($author, $tags, $pic_path, $title = null, $prev_path = null, $comms_enabled = false, $edit_lock = false): ReturnT {
global $db;
function Post_Create_Method (array $req, array $files): ReturnT {
global $db, $Config, $LOGGED_IN, $THIS_USER;
$result = null;
$author_id = $THIS_USER;
$tags = null;
$pic_path = null;
$title = null;
$prev_path = null;
$comms_enabled = false;
// Check post params
// Author ID should exist
if (!User_IDExist($author))
// TODO
// Input sanity checks
// Performing SQL query
$s = $db->prepare("INSERT INTO posts (author_id,comment_section_id,tags,title,pic_path,preview_path,comments_enabled,edit_lock) VALUES (?,?,?,?,?,?,?,?)");
$s->bind_param("ssssssss", $author, null, $tags, $title, $pic_path, $prev_path, $comms_enabled, $edit_lock);
// Check if user is authenticated
if (!$LOGGED_IN)
return new ReturnT(err_code: E_AUT_NOTAUTHED, err_desc: "you must be logged in to create posts");
if ($s->execute() !== true) {
return new ReturnT(null, 601, "failed to create post record in DB");
}
// Check if there are necessary input
if (!(isset($req["tags"]) && isset($files["pic"])))
return new ReturnT(err_code: E_UIN_INSUFARGS, err_desc: "tags and picture are necessary");
return new ReturnT($result);
// TODO: add rate-limiting, instead of this
// Check user role
if (User_HasRole($THIS_USER, "newbie").GetData())
return new ReturnT(err_code: E_ACS_INSUFROLE, err_desc: "newbies cant create posts");
// Check image properties
// If size is too large
if ($files["pic"]["size"] > $Config["media"]["max_pic_size"])
return new ReturnT(err_code: E_UIN_FILE2LARGE, err_desc: "picture size is too large");
$TmpFilePath = $_FILES["pic"]["tmp_name"];
$Ext = strtolower(pathinfo($TmpFilePath, PATHINFO_EXTENSION));
// If file extension is not in list of allowed
if (!in_array($Ext, $Config["media"]["allowed_exts"]))
return new ReturnT(err_code: E_UIN_FILETYPE, err_desc: "picture extension is invalid");
// If file mime type is not in list of allowed
if (!in_array(mime_content_type($TmpFilePath), $Config["media"]["allowed_mimetypes"]))
return new ReturnT(err_code: E_UIN_FILETYPE, err_desc: "picture mime type is invalid");
// Check if resolution is bigger than allowed or have unacceptable aspect ratio
list($SzX, $SzY, $Type, $Attr) = getimagesize($TmpFilePath);
if (!Post_ImgResIsValid($SzX, $SzY))
return new ReturnT(err_code: E_UIN_IMGBADRES, err_desc: "image with that resolution or aspect ratio cant be accepted");
// Copy picture to storage folder
$res = Post_StoreImage($TmpFilePath, $Config["media"]["previews_enabled"]);
if ($res.IsError())
return $res;
// TODO
// Actions
return Post_Create($author_id, $tags, $pic_path, $title, $prev_path, $comms_enabled, false);
}
@ -98,43 +171,7 @@ function Post_Create ($author, $tags, $pic_path, $title = null, $prev_path = nul
if (ThisFileIsRequested(__FILE__)) {
require_once("../_json.php");
// Check if there are necessary input
if (!(isset($_POST["tags"]) && isset($_FILES["pic"])))
ReturnJSONError($Err_RDP_InvalidArgs, "not enough arguments");
// TODO: add rate-limiting, instead of this
// Check user privs
if (User_HasRole($THIS_USER, "newbie"))
ReturnJSONError($Err_DP_NotEnoughRole, "newbies cant create posts");
// Check image properties
// If size is too large
if ($_FILES["pic"]["size"] > $Config["media"]["max_pic_size"])
ReturnJSONError($Err_DP_FileTooLarge, "picture is too large");
$TmpFilePath = $_FILES["pic"]["tmp_name"];
$Ext = strtolower(pathinfo($TmpFilePath, PATHINFO_EXTENSION));
// If file extension is not in list of allowed
if (in_array($Ext, $Config["media"]["allowed_exts"]))
ReturnJSONError($Err_DP_FileWrongType, "file extension is invalid");
// If file mime type is not in list of allowed
if (in_array(mime_content_type($TmpFilePath), $Config["media"]["allowed_mimetypes"]))
ReturnJSONError($Err_DP_FileWrongType, "file mime type is invalid");
// Check if resolution is bigger than allowed or have unacceptable aspect ratio
list($SzX, $SzY, $Type, $Attr) = getimagesize($TmpFilePath);
if (!Post_ImageIsValid($SzX, $SzY))
ReturnJSONError($Err_DP_ImageWrongRes, "image with that resolution or aspect ratio cant be accepted");
// TODO: delete image if unacceptable
// Copy picture to storage folder
Post_StoreImage($TmpFilePath, $Config)
// Create post
//$success = Post_Create(
// TODO: cleanup if bad result
}
?>

View File

@ -2,11 +2,18 @@
require_once("../_auth.php");
require_once("../_utils.php");
require_once("../_errorslist.php");
require_once("../_types.php");
// Increment number of views for post
function Post_AddView ($id) {
// Functions
/*
* FUNCTION
* Increment number of views for post
*/
function Post_AddView (int $id): ReturnT {
global $db;
$s = $db->prepare("UPDATE posts SET views = views + 1 WHERE id = ?");
@ -14,14 +21,17 @@ function Post_AddView ($id) {
$s->execute();
$d = $s->get_result()->fetch_assoc();
if (!(bool)$d) {
require_once("../_json.php");
ReturnJSONError($Err_Int_Unexpected, "failed to increment number of views");
}
if (!(bool)$d)
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "failed to increment number of views");
return new ReturnT(data: true);
}
// Get single publication by ID
function Post_GetByID ($id) {
/*
* FUNCTION
* Get post information by ID
*/
function Post_GetByID (int $id): ReturnT {
global $db;
$result = array();
@ -31,9 +41,8 @@ function Post_GetByID ($id) {
$s->execute();
$d = $s->get_result()->fetch_assoc();
if (!(bool)$d) {
return null;
}
if (!(bool)$d)
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "failed to get post");
$result["id"] = $d["id"];
$result["author_id"] = $d["author_id"];
@ -49,29 +58,49 @@ function Post_GetByID ($id) {
$result["preview_path"] = $d["preview_path"];
$result["edit_lock"] = $d["edit_lock"];
Post_AddView($id); // TODO: add rate-limit or completely rework
$r = Post_AddView($id); // TODO: add rate-limit or completely rework
if ($r.IsError())
return $r;
return $result;
return new ReturnT(data: $result);
}
if (ThisFileIsRequested(__FILE__)) {
require_once("../_json.php");
// Methods
if (isset($_REQUEST["id"])) {
if (!ctype_digit($_REQUEST["id"]))
ReturnJSONError($Err_RDP_InvalidID, "id must be numeric");
$UserID = intval($_REQUEST["id"]);
/*
* METHOD
* Get post information by ID
*/
function Post_GetByID_Method (array $req) {
// Input sanity checks
$PostID = null;
if (isset($req["id"])) {
if (!ctype_digit($req["id"]))
return new ReturnT(err_code: E_UIN_BADARGS, "id must be numeric");
$PostID = intval($req["id"]);
} else {
ReturnJSONError($Err_RDP_InvalidID, "id must be specified");
return new ReturnT(err_code: E_UIN_INSUFARGS, "id must be specified");
}
$ResponseData = Post_GetByID($_REQUEST["id"]);
if ($ResponseData)
ReturnJSONData($ResponseData);
// Actions
return Post_GetByID($PostID);
}
if (Utils_ThisFileIsRequested(__FILE__)) {
require_once("../_json.php");
$result = Post_GetByID_Method($_REQUEST);
if ($result->IsError())
$result->ThrowJSONError();
else
ReturnJSONError($Err_DP_IDNotFound, "wrong id");
JSON_ReturnData($result->GetData());
}
?>

View File

@ -9,6 +9,30 @@ require_once("index.php");
// Functions
/*
* FUNCTION
* Create new user account
*/
function User_Create (string $login, string $password, ?string $email = null, ?string $invite_id = null, ?string $avatar_path = null): ReturnT {
$salt = Utils_GenerateRandomString(8);
$pwd_hash = hash("sha256", $password . $salt, true);
// TODO: process invite
$s = $db->prepare("INSERT INTO users (login,email,password_hash,salt,avatar_path,role,invite_id) VALUES (?,?,?,?,?,?,?)");
$role = "newbie"; // TODO: make decision from config
$s->bind_param("sssssss", $login, $email, $pwd_hash, $salt, $avatar_path, $role, $invite_id);
if ($s->execute() === false)
return new ReturnT(err_code: E_DBE_INSERTFAIL, err_desc: "cant insert record to users DB");
return new ReturnT(data: true);
}
// Methods
/*
@ -77,22 +101,7 @@ function User_Create_Method (array $req): ReturnT {
// Actions
$result = null;
$salt = Utils_GenerateRandomString(8);
$pwd_hash = hash("sha256", $password . $salt, true);
// TODO: process invite
$s = $db->prepare("INSERT INTO users (login,email,password_hash,salt,avatar_path,role,invite_id) VALUES (?,?,?,?,?,?,?)");
$role = "newbie";
$s->bind_param("sssssss", $login, $email, $pwd_hash, $salt, $avatar_path, $role, $invite_id);
$result = ($s->execute() !== false);
if (!$result)
return new ReturnT(err_code: E_DBE_INSERTFAIL, err_desc: "cant insert record to users DB");
return new ReturnT(data: $result);
return User_Create($login, $password, $email, $invite_id, $avatar_path);
}

View File

@ -8,6 +8,21 @@ require_once("./index.php");
// Functions
/*
* FUNCTION
* Delete existing account
*/
function User_Delete (int $id): ReturnT {
$s = $db->prepare("delete from users where id = ?");
$s->bind_param("s", $id);
return new ReturnT(data: ($s->execute() !== false));
}
// Methods
/*
@ -32,15 +47,12 @@ function User_Delete_Method (array $req): ReturnT {
}
// If its attempt to delete other account
if (!User_HasRole($THIS_USER, "admin") && $THIS_USER !== $id)
if (!User_HasRole($THIS_USER, "admin").GetData() && $THIS_USER !== $id)
return new ReturnT(err_code: E_ACS_INSUFROLE, err_desc: "you must be admin to delete other accounts");
// Actions
$s = $db->prepare("delete from users where id = ?");
$s->bind_param("s", $id);
return new ReturnT(data: ($s->execute() !== false));
return User_Delete($id);
}

View File

@ -42,7 +42,7 @@ function User_IDExist ($id): bool {
* FUNCTION
* Check if user has specified role
*/
function User_HasRole ($id, $role) {
function User_HasRole ($id, $role): ReturnT {
global $db;
$s = $db->prepare("SELECT * FROM users WHERE id = ?");
@ -51,19 +51,16 @@ function User_HasRole ($id, $role) {
$d = $s->get_result()->fetch_assoc();
if (!(bool)$d)
return null;
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "user not found in database");
if ($d["role"] == $role)
return true;
return false;
return new ReturnT(data: $d["role"] === $role);
}
/*
* FUNCTION
* Check if user is moderator (or higher)
*/
function User_IsMod ($id) {
function User_IsMod ($id): ReturnT {
global $db;
$s = $db->prepare("SELECT * FROM users WHERE id = ?");
@ -71,11 +68,41 @@ function User_IsMod ($id) {
$s->execute();
$d = $s->get_result()->fetch_assoc();
if (!(bool)$d) {
return null;
if (!(bool)$d)
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "user not found in database");
return new ReturnT(data: in_array($d["role"], array("mod", "admin")));
}
/*
* FUNCTION
* Get user information from DB
*/
function User_GetInfoByID (int $id): ReturnT {
global $THIS_USER;
$result = array();
$s = $db->prepare("SELECT * FROM users WHERE id = ?");
$s->bind_param("s", $id);
$s->execute();
$d = $s->get_result()->fetch_assoc();
if (!(bool)$d)
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "user not found in database");
$result["id"] = $d["id"];
$result["created_at"] = $d["created_at"];
$result["login"] = $d["login"];
$result["avatar_path"] = $d["avatar_path"];
$result["role"] = $d["role"];
$result["banned"] = $d["banned"];
if (($id === $THIS_USER) || User_IsMod($THIS_USER).GetData()) { // User himself and mods can see additional info
$result["email"] = $d["email"];
$result["invite_id"] = $d["invite_id"];
}
return in_array($d["role"], array("mod", "admin"));
return new ReturnT(data: $result);
}
@ -91,43 +118,21 @@ function User_GetInfoByID_Method (array $req): ReturnT {
// Input sanity checks
$id = null;
$UserID = null;
if (isset($req["id"])) {
if (!ctype_digit($req["id"]))
return new ReturnT(err_code: E_UIN_BADARGS, err_desc: "id must be numeric");
$id = intval($req["id"]);
$UserID = intval($req["id"]);
} else {
if ($LOGGED_IN)
$id = $THIS_USER;
$UserID = $THIS_USER;
else
return new ReturnT(err_code: E_UIN_BADARGS, err_desc: "id must be specified or valid session must be provided");
}
// Actions
$result = array();
$s = $db->prepare("SELECT * FROM users WHERE id = ?");
$s->bind_param("s", $id);
$s->execute();
$d = $s->get_result()->fetch_assoc();
if (!(bool)$d)
return new ReturnT(err_code: E_UIN_WRONGID, err_desc: "user not found in database");
//return new ReturnT(err_code: E_DBE_SELECTFAIL, err_desc: "failed to get user record");
$result["id"] = $d["id"];
$result["created_at"] = $d["created_at"];
$result["login"] = $d["login"];
$result["avatar_path"] = $d["avatar_path"];
$result["role"] = $d["role"];
$result["banned"] = $d["banned"];
if (($id === $THIS_USER) || User_IsMod($THIS_USER)) { // User himself and mods can see additional info
$result["email"] = $d["email"];
$result["invite_id"] = $d["invite_id"];
}
return new ReturnT(data: $result);
return User_GetInfoByID($UserID);
}