|
| 1 | +<?php |
| 2 | + require_once('config.php'); |
| 3 | + |
| 4 | + if ($_SERVER['REQUEST_METHOD'] == "POST" && $isAdministrator) { |
| 5 | + $postData = json_decode(file_get_contents("php://input")); |
| 6 | + if ($postData != null) { |
| 7 | + $newPostData = array( |
| 8 | + "author" => $postData->author, |
| 9 | + "title" => $postData->title, |
| 10 | + "content" => $postData->content, |
| 11 | + "date" => date(DATE_ISO8601) |
| 12 | + ); |
| 13 | + $safeAuthor = rawurlencode(substr($newPostData['author'], 0, 10)); |
| 14 | + $newPostFilename = POST_DIR.$newPostData['date'].$safeAuthor.".json"; |
| 15 | + if (!file_put_contents($newPostFilename, json_encode($newPostData))) { |
| 16 | + die('{"error": "Error saving post"}'); |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + $page = 0; |
| 22 | + if (isset($_GET['page'])) { |
| 23 | + $page = (int)$_GET['page']; |
| 24 | + if ($page < 0) { |
| 25 | + $page = 0; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + $jsonData = array( |
| 30 | + "title" => "The Jsonary Blog", |
| 31 | + "page" => $page |
| 32 | + ); |
| 33 | + if ($page > 0) { |
| 34 | + $jsonData['prev'] = "?page=".($page - 1); |
| 35 | + } |
| 36 | + |
| 37 | + $posts = array(); |
| 38 | + $filenames = scandir(POST_DIR); |
| 39 | + sort($filenames); |
| 40 | + $filenames = array_reverse($filenames); |
| 41 | + |
| 42 | + $remainingToSkip = POSTS_PER_PAGE*$page; |
| 43 | + $remainingToShow = POSTS_PER_PAGE; |
| 44 | + foreach ($filenames as $filename) { |
| 45 | + if ($filename[0] == "." || is_dir($filename)) { |
| 46 | + continue; |
| 47 | + } |
| 48 | + if ($remainingToSkip-- > 0) { |
| 49 | + continue; |
| 50 | + } |
| 51 | + if ($remainingToShow-- <= 0) { |
| 52 | + break; |
| 53 | + } |
| 54 | + $postData = json_decode(file_get_contents(POST_DIR.$filename)); |
| 55 | + $posts[] = array( |
| 56 | + "postId" => substr($filename, 0, strlen($filename) - 5), |
| 57 | + "title" => $postData->title, |
| 58 | + "author" => $postData->author, |
| 59 | + "date" => $postData->date |
| 60 | + ); |
| 61 | + } |
| 62 | + $jsonData['posts'] = $posts; |
| 63 | + |
| 64 | + if (count($posts) == POSTS_PER_PAGE) { |
| 65 | + $jsonData["next"] = "?page=".($page + 1); |
| 66 | + } |
| 67 | + |
| 68 | + if ($isAdministrator) { |
| 69 | + header("Content-Type: application/json; profile=schemas/index-administrator.json"); |
| 70 | + } else { |
| 71 | + header("Content-Type: application/json; profile=schemas/index.json"); |
| 72 | + } |
| 73 | + echo (json_encode($jsonData)); |
| 74 | +?> |
0 commit comments