<?php
 
###########################################################################
##  Copyright (C) Wizardry and Steamworks 2016 - License: GNU GPLv3      ##
###########################################################################
## This script overlays the number of online players and the cumulative  ##
## mangos server uptime onto a specified image and displays the result.  ##
###########################################################################

###########################################################################
##                            CONFIGURATION                              ##
###########################################################################

# The configuration file for this script containing the settings.
include_once("config.php");
 
###########################################################################
##                               INTERNALS                               ##
###########################################################################

function wasTimeElapsed($secs) {
	$bit = array(
		'y' => $secs / 31556926 % 12,
		'w' => $secs / 604800 % 52,
		'd' => $secs / 86400 % 7,
		'h' => $secs / 3600 % 24,
		'm' => $secs / 60 % 60,
		's' => $secs % 60
	);
 
	foreach($bit as $k => $v)
		if($v > 0)
			$ret[] = $v . $k;
 
	return join(' ', $ret);
}
 
$online = 0;
try {
	$db = new PDO('mysql:host='.$DATABASE_HOSTNAME.';dbname='.$DATABASE_CHARACTERS_NAME.';', $DATABASE_USERNAME, $DATABASE_PASSWORD);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$q = $db->prepare("SELECT online FROM $DATABASE_CHARACTERS_NAME.characters");
	$q->execute();
	$result = $q->fetchAll();
	foreach($result as $row) {
		if($row['online'] == 1)
			$online++;
	}
}
catch(PDOException $e) {
    print $e->getMessage();
    return;
}
 
$uptime = 0;
try {
	$db = new PDO('mysql:host='.$DATABASE_HOSTNAME.';dbname='.$DATABASE_REALM_NAME.';', $DATABASE_USERNAME, $DATABASE_PASSWORD);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$q = $db->prepare("SELECT starttime FROM realmd.uptime ORDER BY starttime DESC LIMIT 1");
	$q->execute();
	$result=$q->fetch();
	$uptime=wasTimeElapsed(
		time()-$result['starttime']
	);
}
catch(PDOException $e) {
	print $e->getMessage();
	return;
}
 
$im = imagecreatefrompng($PATH_TO_IMAGE);
imagealphablending($im, false);
imagesavealpha($im, true);
$black = imagecolorallocate ($im, 0, 0, 0);
imagestring($im, 200, 255, 75, $online.' online', $black);
imagestring($im, 200, 245, 95, $uptime, $black);
header('Content-type: image/png');
imagepng($im);
 
?>