e949/api/post/index.php

106 lines
2.4 KiB
PHP

<?php // Get single post by ID
require_once("../_auth.php");
require_once("../_utils.php");
require_once("../_errorslist.php");
require_once("../_types.php");
// 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 = ?");
$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: "failed to increment number of views");
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("s", $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) {
// 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 {
return new ReturnT(err_code: E_UIN_INSUFARGS, "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());
}
?>