<?php
/**
 * Pings a given host and returns a red or green image.
 * Green when the host is online, red when offline.
 *
 * Keywords: http image ping online check
 *
 * @author Christian Weiske <weiske@mogic.com>
 */
if (!isset($_GET['host'])) {
    sendError('Host missing');
}
$host = $_GET['host'];
if ($host == '') {
    sendError('Empty host');
}

if (!isset($_GET['size'])) {
    $size = 100;
} else {
    $size = intval($_GET['size']);
}

exec('ping -c 1 -w 1 -W 1 ' . escapeshellarg($host), $output, $retval);
if ($retval == 0) {
    //all fine
    sendSvg($size, 'fill: green');
} else {
    //error
    sendSvg($size, 'fill: red');
}

function sendSvg($size, $style)
{
    $half = intval($size / 2);
    header('200 OK');
    header('Content-type: image/svg+xml');
    echo <<<XML
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="$size" height="$size">
  <circle cx="$half" cy="$half" r="$half" style="$style"/>
</svg>

XML;
}

function sendError($msg)
{
    header('400 Bad Request');
    header('Content-type: text/plain');
    echo $msg . "\n";
    exit(1);
}
?>
