Make RSS feed
[pics.git] / rss.php
diff --git a/rss.php b/rss.php
new file mode 100644 (file)
index 0000000..0312255
--- /dev/null
+++ b/rss.php
@@ -0,0 +1,45 @@
+<?php
+
+require_once __DIR__ . '/db.php';
+
+function post_to_item(DOMDocument $dom, Array $post) {
+      $mime_type = $post['MIME_TYPE'];
+      $post_id = $post['ID'];
+      $post_body = $post['BODY'];
+      $timestamp = $post['TIMESTAMP'];
+      $item = $dom->createElement('item');
+      $description = $dom->createElement('description', $post_body);
+      $link = $dom->createElement('link', "https://pics.jacobcasper.com/#post-{$post_id}");
+      $guid = $dom->createElement('guid', "https://pics.jacobcasper.com/#post-{$post_id}");
+      $pub_date = $dom->createElement('pubDate', date(DATE_RSS, $timestamp));
+      // TODO write the endpoint for this
+      //$enclosure = $dom->createElement('enclosure');
+      //$enclosure->setAttribute('url', "https://pics.jacobcasper.com/pic/{$post_id}");
+      //$enclosure->setAttribute('length', "9999");
+      //$enclosure->setAttribute('type', $mime_type);
+      $item->appendChild($description);
+      //$item->appendChild($enclosure);
+      $item->appendChild($link);
+      $item->appendChild($guid);
+      $item->appendChild($pub_date);
+      return $item;
+}
+
+$rss_template = file_get_contents('rss.template.xml');
+$rss_dom = new DOMDocument();
+$rss_dom->formatOutput = true;
+$rss_dom->loadXML($rss_template);
+$channel_node = $rss_dom->firstChild->childNodes[1];
+$db = get_db();
+$posts = $db->query('SELECT
+    p.ID, p.TIMESTAMP, pi.MIME_TYPE, c.BODY
+    FROM posts p
+    JOIN pics pi on p.id = pi.post_id
+    JOIN comments c on p.id = c.post_id
+    ORDER BY p.TIMESTAMP DESC');
+while ($post = $posts->fetchArray()) {
+    $item = post_to_item($rss_dom, $post);
+    $channel_node->appendChild($item);
+}
+
+file_put_contents('rss.xml', $rss_dom->saveXML());