xref: /web-php/images/elephpants.php (revision 59c070f5)
1<?php
2
3include_once __DIR__ . '/../include/prepend.inc';
4
5$now = $_SERVER["REQUEST_TIME"];
6if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
7    $last = strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]);
8
9    /* Use the same logo for a day */
10    if (strtotime("+1 day", $last) > $now) {
11        header("HTTP/1.1 304 Not Modified");
12        exit;
13    }
14}
15$future = strtotime("+1 day", $now);
16$tsstring = gmdate("D, d M Y H:i:s ", $now) . "GMT";
17header("Last-Modified: " . $tsstring);
18header("Expires: " . date(DATE_RSS, $future));
19
20/*
21
22 Simple script to serve elephpant images in json format.
23 This script is called directly by the browser to feed the
24 javascript generated banner of elephpant images.
25
26 The structure of the response data is:
27
28 [{
29     title: <image title>,
30     url:   <link to image on flickr>,
31     data:  <base64 encoded image>
32 },{
33     ...
34 }]
35*/
36
37// determine how many images to serve.
38if (isset($_REQUEST['count'])) {
39    $count = min((int) $_REQUEST['count'], 50);
40} else {
41    header('HTTP/1.1 400', true, 400);
42    echo json_encode([
43        'error' => "Specify how many elephpants to serve via 'count'.",
44    ]);
45    exit;
46}
47
48// read out photo metadata
49$path = __DIR__ . '/elephpants';
50$json = @file_get_contents($path . '/flickr.json');
51$photos = json_decode($json, true);
52
53// if no photo data, respond with an error.
54if (!$photos || !is_array($photos)) {
55    header('HTTP/1.1 500', true, 500);
56    echo json_encode([
57        'error' => "No elephpant metadata available.",
58    ]);
59    exit;
60}
61
62// prepare requested number of elephpants at random.
63shuffle($photos);
64$elephpants = [];
65$got = 0;
66foreach ($photos as $photo) {
67
68    // stop when we have the requested number of photos.
69    if ($got == $count) {
70        break;
71    }
72
73    // skip photo if file doesn't exist.
74    if (!is_readable($path . '/' . $photo['filename'])) {
75        continue;
76    }
77
78    $got++;
79    // add photo to response array.
80    $elephpants[] = [
81        'title' => $photo['title'],
82        'url' => "http://flickr.com/photos/" . $photo['owner'] . "/" . $photo['id'],
83        'data' => base64_encode(file_get_contents($path . '/' . $photo['filename'])),
84    ];
85}
86
87echo json_encode($elephpants);
88