#!/usr/bin/perl -w use strict; use warnings; use DBI; use DBD::SQLite::Constants qw/:file_open/; use JSON; my $dbpath = "./posts.db"; my $json = JSON->new; sub get_info { my $clientIP = ($ENV{"REMOTE_ADDR"} or "0.0.0.0"); my $proto = ($ENV{"REQUEST_SCHEME"} or "http"); my $query = (split(/\?/,($ENV{"QUERY_STRING"} or "")))[0]; my $referrer = ($ENV{"HTTP_REFERER"} or ""); return ($proto,$clientIP,$query,$referrer); } sub http_status { my ($status,$content,$target) = @_; my $header = ""; $header .= "status: ".$status."\r\n"; $header .= "Location: ".$target."\r\n" if $target; $header .= "Content-Type: ".$content."\r\n" if $content; $header .= "\r\n"; return $header; } sub soft_die { print http_status(500,"text/json"); print '{"error":"'.shift.'"}'; exit; } sub clean_input { my $input = shift; unless ($input) { return ""; } $input =~ s!%(..)!chr hex $1!ge; $input =~ s!\+! !g; $input =~ s!;!\;!g; #antivaxx return $input; } my $db = DBI->connect("DBI:SQLite:dbname=$dbpath", "", "", { RaiseError => 1, sqlite_open_flags => SQLITE_OPEN_READONLY }) or soft_die($DBI::errstr); my $sth; my @request = get_info(); my @get_params = split("&",clean_input($request[2])); my $directive = shift(@get_params); if ( "rand" eq $directive ) { # select a random post $sth = $db->prepare('SELECT * FROM posts ORDER BY RANDOM() LIMIT 1'); } elsif ( "last" eq $directive ) { # select the last post only $sth = $db->prepare('SELECT * FROM posts ORDER BY DATE DESC LIMIT 1'); } elsif ( "range" eq $directive ) { # select range starting with lastest as 1 my $start = $get_params[0]; my $count = $get_params[1]; $sth = $db->prepare('SELECT * FROM posts ORDER BY DATE DESC LIMIT '.$start.', '.$count); } else { # select the last 10 posts $sth = $db->prepare('SELECT * FROM posts ORDER BY DATE DESC LIMIT 10'); } $sth->execute or soft_die($sth->errstr); print http_status(200,"text/json"); print $json->encode( $sth->fetchall_arrayref({}));