<?php
/**
 * Pings a given host and returns a red or green image.
 * Green when the host is online, red when offline.
 *
 * Error: ping: socket: Operation not permitted
 *        (raw socket required by specified options).
 *
 * Solution:
 *     $ chmod +s /path/to/ping
 * Alternative:
 *     $ setcap cap_net_raw+ep /path/to/ping
 * Alternative:
 *     make it passwordless sudo
 *
 * 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) . ' 2>&1', $output, $retval);
if ($retval == 0) {
    //all fine
    sendSvg($size, 'fill: green');
} else if ($retval == 1) {
    //no reply
    sendSvg($size, 'fill: red');
} else {
    //some other error, e.g. permissions
    header('HTTP/1.0 500 Internal server error');
    header('Content-type: text/plain');
    echo implode("\n", $output) . "\n";
}

function sendSvg($size, $style)
{
    $half = intval($size / 2);
    header('HTTP/1.0 200 OK');
    header('Content-type: image/svg+xml');
    echo '<' . '?xml version="1.0"?>' . "\n";
    echo <<<XML
<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('HTTP/1.0 400 Bad Request');
    header('Content-type: text/plain');
    echo $msg . "\n";
    exit(1);
}
?>
