<?php
/**
* get targets for a given service.
* log_db.log_t gets periodically checked by
* script whichs tries to submit flowids to gameserver.
* Information about this status can be found in board.php
*
* 2014-15 by Jan "Someone" Vales <someone@somenet.org>
* do not publish!
*/

$GLOBALS['db'] = new PDO('pgsql:host=localhost;port=5432;dbname=flagbot;user=flagbot;password=flagbotpw');
$GLOBALS['db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (strcmp($_SERVER['REQUEST_METHOD'],"GET") === 0 || strcmp($_SERVER['REQUEST_METHOD'],"POST") === 0 ) {
  handleRequest();
} else {
  http_response_code(405); //Method not implemented
  exit("<p><b>what?</b> try GET or POST</p>");
}

function handleRequest() {
  if (isset($_REQUEST['service'])) {
     getTargets($_REQUEST['service']);
  } else {
     echo "<p><b>usage:</b><br>";
     echo "GET /get_targets.php?service=<i>STRING</i> <br>";
     echo "POST<br> service=<i>STRING</i></p>";
  }
}

function getTargets($service) {
  try {
    $stmt = $GLOBALS['db']->prepare("SELECT * FROM flag_ids WHERE (received + INTERVAL '15 minute') > now() and service = ? and status = 0 ORDER BY received DESC");
    $stmt->execute(array($service));
    $targets = $stmt->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($targets);
  }catch(PDOException $ex) {
    echo "{}";
  }
}