personal-website/docs/www/blog/generatearticle.php

102 lines
2.4 KiB
PHP

<?php
$COMMONS = $_SERVER['DOCUMENT_ROOT'] . "/../common";
include_once($COMMONS."/header.php");
include_once($COMMONS."/blog_utils.php");
// If request is GET, show request info.
if(strcmp($_SERVER["REQUEST_METHOD"], "GET") == 0)
{
display_header("Generate Article");
printf("
<article>
<h2>Generate Article</h2>
<p>
Request this page with POST supplying following arguments:
</p>
<table>
<tr>
<td>
<b>Argument</b>
</td>
<td>
<b>Comment</b>
</td>
</tr>
<tr>
<td>
blogpost_id
</td>
<td>
GUID of the blogpost in the database.
</td>
</tr>
<tr>
<td>
referer
</td>
<td>
URL, from which this page was requested, after generating
the article, the page will redirect back to the referer.
</td>
</tr>
</table>
</article>
");
include_once($COMMONS."/footer.php");
die();
}
// If request is not GET or POST, throw method not allowed
if(strcmp($_SERVER["REQUEST_METHOD"], "POST") != 0)
{
header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
include_once($_SERVER["DOCUMENT_ROOT"]."/errors/405.php");
die();
}
// Check DB connection
if($conn == null){
header($_SERVER["SERVER_PROTOCOL"]." 503 Service Unavailable", true, 503);
include_once($_SERVER["DOCUMENT_ROOT"]."/errors/503.php");
die();
}
// If one of the needed parameters isn't set, show 400
if(!(isset($_POST["blogpost_id"]) && isset($_POST["referer"])))
{
header($_SERVER["SERVER_PROTOCOL"]." 400: Bad Request", true, 400);
include_once($_SERVER["DOCUMENT_ROOT"]."/errors/400.php");
die;
}
// Get the blogpost id and referer
$blogId = sanitize_input($_POST["blogpost_id"]);
$referer = sanitize_input($_POST["referer"]);
// Get the address of the blogpost
$blogAddress = get_blogpost_address($conn, $blogId);
// Try to open the file to which to render the blogpost.
if (!($fp = fopen("article/".$blogAddress.".php", 'w'))) {
header($_SERVER["SERVER_PROTOCOL"]." 500 Could not open file for writing",
true, 505);
include_once($_SERVER["DOCUMENT_ROOT"]."/errors/500.php");
die();
}
// Attempt to generate the blogpost
$blogRendered = generate_article($conn, $fp, $blogId);
// If blogpost could not be loaded, display warning and die.
if(!$blogRendered) {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Foud", true, 404);
include_once($_SERVER["DOCUMENT_ROOT"]."/errors/404.php");
die();
}
// Redirect back to the referrer.
header("Location: ".$referer);
?>