e949/api/post/index.php

128 lines
2.7 KiB
PHP

<?php
// Get single post by ID
// Includes
if (isset($IS_FRONTEND) && $IS_FRONTEND) {
require_once("api/_auth.php");
require_once("api/_utils.php");
require_once("api/_errorslist.php");
require_once("api/_types.php");
} else {
require_once("../_auth.php");
require_once("../_utils.php");
require_once("../_errorslist.php");
require_once("../_types.php");
}
// Functions
/*
* FUNCTION
* Get total amount of posts
*/
function Post_GetPostsAmount (): int {
global $db;
$qr = $db->query("SELECT COUNT(*) FROM posts");
$row = $qr->fetch_row();
return $row[0];
}
/*
* 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 = ?");
$s->bind_param("i", $id);
if (!$s->execute())
return new ReturnT(err_code: E_DBE_UNKNOWN, err_desc: "failed to execute statement");
return new ReturnT(data: true);
}
/*
* FUNCTION
* Get post information by ID
*/
function Post_GetByID (int $id): ReturnT {
global $db;
$result = array();
$s = $db->prepare("SELECT * FROM posts WHERE id = ?");
$s->bind_param("i", $id);
$s->execute();
$d = $s->get_result()->fetch_assoc();
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"];
if ($d["comments_enabled"])
$result["comment_section_id"] = $d["comment_section_id"];
$result["created_at"] = $d["created_at"];
$result["tags"] = $d["tags"];
$result["title"] = $d["title"];
$result["votes_up"] = $d["votes_up"];
$result["votes_down"] = $d["votes_down"];
$result["views"] = $d["views"] + 1;
$result["pic_path"] = $d["pic_path"];
$result["preview_path"] = $d["preview_path"];
$result["edit_lock"] = $d["edit_lock"];
$r = Post_AddView($id); // TODO: add rate-limit or completely rework
if ($r->IsError())
return $r;
return new ReturnT(data: $result);
}
// Methods
/*
* METHOD
* Get post information by ID
*/
function Post_GetByID_Method (array $req): ReturnT {
// Input sanity checks
$PostID = null;
if (isset($req["id"])) {
if (!ctype_digit($req["id"]))
return new ReturnT(err_code: E_UIN_BADARGS, err_desc: "id must be numeric");
$PostID = intval($req["id"]);
} else {
return new ReturnT(err_code: E_UIN_INSUFARGS, err_desc: "id must be specified");
}
// Actions
return Post_GetByID($PostID);
}
if (Utils_ThisFileIsRequested(__FILE__)) {
require_once("../_json.php");
$result = Post_GetByID_Method($_REQUEST);
if ($result->IsError())
$result->ThrowJSONError();
else
JSON_ReturnData($result->GetData());
}
?>