Added full source code

This commit is contained in:
Emmanuel BENOîT 2016-01-10 11:01:49 +01:00
commit 33f8586698
1377 changed files with 123808 additions and 0 deletions

View file

@ -0,0 +1,698 @@
<?php
class page_handler {
var $needsAuth = true;
private function logAdm($text) {
logText("*** ADMIN {$_SESSION['login']} $text");
}
function isAdmin() {
$this->accounts = $this->game->getLib('main/account');
return $this->accounts->call('isAdmin', $_SESSION['userid']);
}
function manualUpdate() {
$this->logAdm("is regenerating the manual");
$manual = $this->game->getLib('main/manual');
$x = $manual->call('readXMLFile', config::$main['scriptdir'] . '/../manual/beta5/en/main.lwdoc');
if (is_array($x)) {
$manual->call('updateSections', $x);
}
}
function handleKickReq(&$input, &$data) {
if (is_null($input['kr'])) {
return false;
} elseif (!is_null($input['cancel'])) {
return true;
}
$data['error'] = 0;
$data['name'] = trim($input['p']);
$data['reason'] = trim($input['r']);
$a = $this->accounts->call('getUser', $data['name']);
if (is_null($a) || $a['status'] == 'KICKED' || $a['admin'] == 't') {
$data['error'] = 1;
} elseif (strlen($data['reason']) < 10) {
$data['error'] = 2;
} else {
$r = $this->accounts->call('requestKick', $_SESSION['userid'], $a['id'], $data['reason']);
$data['error'] = $r ? 0 : 3;
if ($r) {
$this->logAdm("is requesting to kick {$data['name']}");
}
}
return ($data['error'] == 0);
}
function handlePNCommand($command, $id) {
$pd = $this->planets->call('byId', $id);
if (is_null($pd)) {
return;
}
$pLog = "planet '{$pd['name']}' (#$id)";
if (!is_null($pd['owner'])) {
$pLog .= " owned by player {$pd['owner']}";
}
if ($command == "v") {
$this->b5adm->call('validatePlanetName', $id);
$this->logAdm("validated $pLog");
$this->db->query("UPDATE credits SET credits_obtained = credits_obtained + 200 WHERE account = {$_SESSION['userid']}");
} elseif ($command == "r") {
$this->b5adm->call('resetPlanet', $id, $_SESSION[game::sessName()]['player']);
$this->logAdm("reset $pLog");
} elseif ($command == "w") {
$this->b5adm->call('sendPlanetWarning', $id, $_SESSION[game::sessName()]['player']);
$this->logAdm("warned $pLog");
$this->db->query("UPDATE credits SET credits_obtained = credits_obtained + 200 WHERE account = {$_SESSION['userid']}");
}
}
function handlePlanetNames(&$input, &$data) {
$this->db = $this->game->db;
if (!is_null($input['pc'])) {
$this->planets = $this->game->getLib("beta5/planet");
$this->handlePNCommand($input['pc'], (int) $input['id']);
}
list($mode, $q) = $this->b5adm->call('getPlanetsModList', $input['m']);
if ($input['m'] == 'o') {
$this->logAdm("is accessing the complete planet list");
}
$perPage = 30;
$lines = dbCount($q);
$mod = $lines % $perPage;
$pages = ($lines - $mod) / $perPage + ($mod > 0 ? 1 : 0);
$page = (int) $input['p'];
if ($page < 0 || $pages == 0) {
$page = 0;
} elseif ($page >= $pages) {
$page = $pages - 1;
}
$data['list'] = array();
$this->players = $this->game->getLib('beta5/player');
for ($i = 0; $i < ($page + 1) * $perPage && $i < $lines; $i ++) {
$r = dbFetchHash($q);
if ($i >= $page * $perPage) {
if (!is_null($r['owner'])) {
$r['oname'] = $this->players->call('getName', $r['owner']);
}
array_push($data['list'], $r);
}
}
$data['mode'] = $mode;
$data['pages'] = $pages;
$data['page'] = $page;
}
function handleKickList(&$input, &$data) {
if (is_null($input['i']) || is_null($input['a'])) {
$data['lists'] = $this->accounts->call('getKickList');
return;
}
$kr = $this->accounts->call('getKickRequest', (int)$input['i']);
if (is_null($kr) || ($kr['requested_by'] == $_SESSION['userid'] && $input['a'] == 1) || $kr['status'] != 'P') {
return;
}
if ($input['a'] == 1) {
$this->accounts->call('terminate', $kr['to_kick'], 'KICKED', $kr['reason']);
$this->logAdm("accepted request to kick account #{$kr['to_kick']}");
}
$this->accounts->call('kickRequestHandled', $kr['id'], $_SESSION['userid'], $input['a'] == 1);
$data['lists'] = $this->accounts->call('getKickList');
}
function linkMainList() {
$categories = $this->lib->call('getCategories');
for ($i=0;$i<count($categories);$i++) {
$categories[$i]['links'] = $this->lib->call('getLinks', $categories[$i]['id']);
}
return array("lklist", $categories);
}
function checkCat(&$title, &$desc, $id = null) {
$title = preg_replace('/\s+/', ' ', trim($title));
$desc = preg_replace('/\s+/', ' ', trim($desc));
if (strlen($title) < 5) {
return 1;
} elseif (strlen($title) > 64) {
return 2;
} elseif (!$this->lib->call('checkCategoryName', $title, $id)) {
return 3;
} elseif ($desc != '' && strlen($desc) < 10) {
return 4;
}
return 0;
}
function linkMainAddCat(&$input) {
if ($input['cancel'] != "") {
return $this->linkMainList();
}
if ($input['r'] != 1) {
return array('lkcat', array());
}
$title = $input['title'];
$desc = $input['desc'];
$error = $this->checkCat($title, $desc);
if ($error) {
return array('lkcat', array(
'title' => $title,
'desc' => $desc,
'error' => $error,
));
}
$this->lib->call('createCategory', $title, ($desc == "" ? null : $desc));
return $this->linkMainList();
}
function linkMainEditCat(&$input) {
if ($input['cancel'] != "") {
return $this->linkMainList();
}
$id = (int)$input['cid'];
$cat = $this->lib->call('getCategory', $id);
if (is_null($cat)) {
return null;
}
if ($input['r'] != 1) {
return array('lkcat', array(
'id' => $id,
'title' => $cat['title'],
'desc' => $cat['description']
));
}
$title = $input['title'];
$desc = $input['desc'];
$error = $this->checkCat($title, $desc, $id);
if ($error) {
return array('lkcat', array(
'id' => $id,
'title' => $title,
'desc' => $desc,
'error' => $error,
));
}
$this->lib->call('changeCategory', $id, $title, $desc);
return $this->linkMainList();
}
function linkMainDelCat(&$input) {
$id = (int)$input['cid'];
$cat = $this->lib->call('getCategory', $id);
if (!is_null($cat)) {
$this->lib->call('deleteCategory', $id);
}
return $this->linkMainList();
}
function linkMainMoveCat($id, $up) {
$cat = $this->lib->call('getCategory', $id);
if (!is_null($cat)) {
$this->lib->call('moveCategory', $id, $up);
}
return $this->linkMainList();
}
function checkLink(&$title, &$url, &$desc, $id = null) {
$title = preg_replace('/\s+/', ' ', trim($title));
$url = preg_replace('/\s+/', ' ', trim($url));
$desc = preg_replace('/\s+/', ' ', trim($desc));
if (strlen($title) < 5) {
return 1;
} elseif (strlen($title) > 64) {
return 2;
} elseif ($desc != '' && strlen($desc) < 10) {
return 6;
} elseif (!preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/.*)?$/i', $url, $m)) {
return 3;
} else {
list($junk, $proto, $hostname, $port) = $m;
if (!preg_match('/^\d+\.\d+\.\d+\.\d+$/', $hostname)) {
$ip = gethostbyname($hostname);
if ($ip === $hostname) {
return 4;
}
}
if (!$this->lib->call('checkLink', $url, $id)) {
return 5;
}
}
return 0;
}
function linkMainAddLink(&$input) {
if ($input['cancel'] != "") {
return $this->linkMainList();
}
$cid = (int) $input['cid'];
$cat = $this->lib->call('getCategory', $cid);
if (is_null($cat)) {
return $this->linkMainList();
}
if ($input['r'] != 1) {
return array('lklk', array(
'cid' => $cid
));
}
$title = $input['title'];
$url = $input['url'];
$desc = $input['desc'];
$error = $this->checkLink($title, $url, $desc);
if ($error) {
return array('lklk', array(
'cid' => $cid,
'title' => $title,
'url' => $url,
'desc' => $desc,
'error' => $error,
));
}
$this->lib->call('addLink', $cid, $title, ($desc == "" ? null : $desc), $url);
return $this->linkMainList();
}
function linkMainEditLink(&$input) {
if ($input['cancel'] != "") {
return $this->linkMainList();
}
$lid = (int) $input['lid'];
$lnk = $this->lib->call('getLink', $lid);
if (is_null($lnk)) {
return $this->linkMainList();
}
if ($input['r'] != 1) {
return array('lklk', array(
'id' => $lid,
'title' => $lnk['title'],
'url' => $lnk['url'],
'desc' => $lnk['description']
));
}
$title = $input['title'];
$url = $input['url'];
$desc = $input['desc'];
$error = $this->checkLink($title, $url, $desc, $lid);
if ($error) {
return array('lklk', array(
'id' => $lid,
'title' => $title,
'url' => $url,
'desc' => $desc,
'error' => $error,
));
}
$this->lib->call('changeLink', $lid, $title, $url, ($desc == "" ? null : $desc));
return $this->linkMainList();
}
function linkMainDelLink(&$input) {
$id = (int)$input['lid'];
$lnk = $this->lib->call('getLink', $id);
if (!is_null($lnk)) {
$this->lib->call('deleteLink', $id);
}
return $this->linkMainList();
}
function linkMain(&$input) {
$this->lib = $this->game->getLib('main/links');
switch ($input['ac']) :
case '0': return $this->linkMainAddCat($input);
case '1': return $this->linkMainAddLink($input);
case '2': return $this->linkMainEditCat($input);
case '3': return $this->linkMainDelCat($input);
case '4': return $this->linkMainMoveCat((int)$input['cid'], true);
case '5': return $this->linkMainMoveCat((int)$input['cid'], false);
case '10': return $this->linkMainEditLink($input);
case '11': return $this->linkMainDelLink($input);
default: return $this->linkMainList();
endswitch;
}
function linkReports(&$input) {
$lib = $this->game->getLib('main/links');
$acc = $this->game->getLib('main/account');
if ($input['id'] != '') {
$id = (int) $input['id'];
$lnk = $lib->call('getLink', $id);
if (!is_null($lnk)) {
if ($input['dl'] == 1) {
$lib->call('deleteLink', $id);
} elseif ($input['dr'] == 1) {
$lib->call('deleteReports', $id);
}
}
}
$links = array();
$reports = $lib->call('getBrokenReports');
foreach ($reports as $rep) {
if (is_null($links[$rep['link']])) {
$links[$rep['link']] = $lib->call('getLink', $rep['link']);
$links[$rep['link']]['category'] = $lib->call('getCategory', $links[$rep['link']]['category']);
$links[$rep['link']]['reporters'] = array();
}
array_push($links[$rep['link']]['reporters'], utf8entities($acc->call('getUserName', $rep['reported_by'])));
}
return $links;
}
function linkSubmissions(&$input) {
$lib = $this->game->getLib('main/links');
$acc = $this->game->getLib('main/account');
if ($input['su'] != '') {
if ($input['sid'] == '') {
$lib->call('deleteSubmissions', $input['su']);
} elseif ($input['cid'] == '') {
$sub = $lib->call('getSubmission', $input['su'], (int)$input['sid']);
if (!is_null($sub)) {
$cats = $lib->call('getCategories');
return array('lksadd', array(
"sub" => $sub,
"cats" => $cats
));
}
} elseif ($input['cancel'] == '') {
$sub = $lib->call('getSubmission', $input['su'], (int)$input['sid']);
$cat = $lib->call('getCategory', (int)$input['cid']);
if (!(is_null($sub) || is_null($cat))) {
$d = $sub['description'];
$lib->call('addLink', $cat['id'], $sub['title'], $d == "" ? null : $d, $sub['url']);
$lib->call('deleteSubmissions', $sub['url']);
}
}
}
$subs = $lib->call('getSubmissions');
$urls = array();
foreach ($subs as $sub) {
if (!is_array($urls[$sub['url']])) {
$urls[$sub['url']] = array();
}
array_push($urls[$sub['url']], array(
"sid" => $sub['submitted_by'],
"submitter" => utf8entities($acc->call('getUserName', $sub['submitted_by'])),
"title" => utf8entities($sub['title']),
"description" => utf8entities($sub['description'])
));
}
return array('lksub', $urls);
}
function manageAccounts(&$input) {
$aName = $input['an'];
if ($aName == '') {
return array("account" => '');
}
// Get account data
$account = $this->accounts->call('getUser', $aName);
if (is_null($account)) {
return array(
"account" => $aName,
"notfound" => true
);
}
$rv = array(
"account" => $account['name'],
"status" => $account['status'],
"email" => $account['email'],
"admin" => $account['admin'] == 't',
"conf_code" => $account['conf_code'],
"password" => $account['password']
);
if ($input['sa'] || $rv['admin']) {
$this->logAdm("is inspecting account {$account['name']}");
return $rv;
}
$this->db = $this->game->db;
if ($input['mma'] && strcasecmp($input['ma'], $account['email'])) {
// Change email address
$rv['email'] = $nMail = strtolower($input['ma']);
if (!preg_match('/^[A-Za-z0-9_\.\-\+]+@([A-Za-z0-9_\.\-\+]+)+\.[A-Za-z]{2,6}/', $nMail)) {
$rv['mailerr'] = 1;
return $rv;
}
$q = $this->db->query("SELECT name FROM main.account WHERE LOWER(email)='"
. addslashes($nMail) . "'");
if ($q && dbCount($q)) {
$rv['mailerr'] = 2;
list($rv['oacc']) = dbFetchArray($q);
return $rv;
} elseif (!$q) {
$rv['mailerr'] = 3;
return $rv;
}
$q = $this->db->query("UPDATE main.account SET email='" . addslashes($nMail)
. "' WHERE id={$account['id']}");
if (!$q) {
$rv['mailerr'] = 3;
} else {
$this->logAdm("changed email for account {$account['name']}");
$rv['mailerr'] = -1;
}
return $rv;
} elseif ($input['mpw'] && strcmp($input['pw'], $account['password'])) {
// Change password
$rv['password'] = $nPass = strtolower($input['pw']);
if (strlen($nPass) < 4) {
$rv['passerr'] = 1;
return $rv;
}
$q = $this->db->query("UPDATE main.account SET password='" . addslashes($nPass)
. "' WHERE id={$account['id']}");
if (!$q) {
$rv['passerr'] = 2;
} else {
$this->logAdm("changed password for account {$account['name']}");
$rv['passerr'] = -1;
}
return $rv;
}
return $rv;
}
private function getSpamFormData($in) {
$action = is_null($in['e'])
? (is_null($in['p'])
? (is_null($in['cc']) ? 'none' : 'cancel')
: 'preview')
: 'post';
$subject = $in['sub'];
$txt = $in['txt'];
$allGames = ($in['ag'] == '1');
return array($action,$subject,$txt,$allGames);
}
private function checkSpamData($s, &$t) {
$maxNL = 500; $maxNC = 100;
if (strlen($s) < 2) {
$e = 1;
} elseif (strlen($s) > 100) {
$e = 2;
} elseif (strlen($t) < 3) {
$e = 3;
} else {
$ot = $t; $nt = ""; $nl = 0;
while ($ot != '' && $nl < $maxNL) {
$p = strpos($ot, '\n');
if ($p !== false && $p < $maxNC) {
$nt .= substr($ot, 0, $p+1);
$ot = substr($ot, $p+1);
} else if (strlen($ot) < $maxNC) {
$nt .= $ot;
$ot = "";
} else {
$s = substr($ot, 0, $maxNC);
$p = strrpos($s, ' ');
$ot = substr($ot, $maxNC);
$nt .= $s;
if ($p === false) {
$nt .= "\n";
}
}
$nl ++;
}
if ($nl >= $maxNL) {
$e = 4;
} else {
$t = $nt;
$e = 0;
}
}
return $e;
}
private function handleSpam($input) {
list($action, $subject, $text, $allGames) = $this->getSpamFormData($input);
if ($action == 'cancel') {
return array('main', array());
}
$data = array(
'sub' => $subject,
'txt' => $text,
'prev' => '',
'err' => 0,
'ag' => $allGames
);
if ($action == 'none') {
return array('spam', $data);
}
$data['err'] = $err = $this->checkSpamData($subject, $text);
if ($err) {
return array('spam', $data);
}
if ($action == 'preview') {
$fLib = $this->game->getLib('main/forums');
$data['prev'] = $fLib->call('substitute', $text, 't', 'f');
return array('spam', $data);
}
// Send the spam
if ($data['ag']) {
$this->logAdm("is sending spam '$subject' in all games");
foreach (config::getGames() as $game) {
if ($game->name == 'main') {
continue;
}
$status = $game->status();
if ($status == 'FINISHED' || $status == 'PRE') {
continue;
}
$aLib = $game->getLib('admin/beta5');
$aLib->call('sendSpam', $_SESSION['userid'], $subject, $text);
}
} else {
$this->logAdm("is sending spam '$subject' in game {$this->game->text}");
$aLib = $this->game->getLib('admin/beta5');
$aLib->call('sendSpam', $_SESSION['userid'], $subject, $text);
}
return array('main', array());
}
function handle($input) {
if (!$this->isAdmin()) {
$this->logAdm("is a rat bastard who tried to use the admin page!");
$this->output = "rat";
return;
}
$this->b5adm = $this->game->getLib("admin/beta5");
$this->output = "admin";
$d = array();
switch ($input['c']) :
case 'k':
if ($this->handleKickReq($input, $d)) {
$sp = "main";
} else {
$sp = "kickreq";
}
break;
case 'kl':
$this->handleKickList($input, $d);
$sp = "kicklst";
break;
case 'p':
$this->handlePlanetNames($input, $d);
$sp = "pnlist";
break;
case 'lk':
list($sp, $d) = $this->linkMain($input);
break;
case 'lkr':
$d = $this->linkReports($input);
$sp = "lkrep";
break;
case 'lks':
list($sp, $d) = $this->linkSubmissions($input);
break;
case 'a':
$sp = 'acmgmt';
$d = $this->manageAccounts($input);
break;
case 's':
list($sp, $d) = $this->handleSpam($input);
break;
case 'm':
$this->manualUpdate();
default:
$sp = "main";
$d = array();
break;
endswitch;
$this->data = array(
"subpage" => $sp,
"data" => $d
);
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,237 @@
<?php
class page_handler {
public $needsAuth = true;
public $ajax = array(
'init' => "makeAlliesTooltips();\ninitPage();",
'func' => array(
'getTrusted', 'moveAllies', 'removeAllies', 'addAlly',
'removeRAllies', 'removeBanRAllies',
'removeBans', 'addBan'
)
);
/********************
* GETTING THE LIST *
********************/
/** This method generates the AJAX data for the lists returned
* by the getTrustedAllies() action.
*/
private function formatData($taData) {
$result = array();
array_push($result, count($taData['allies']) . "#" . count($taData['reverse'])
. "#" . count($taData['blacklist']));
foreach ($taData['allies'] as $data) {
array_push($result, "{$data['id']}#" . utf8entities($data['name']));
}
foreach ($taData['reverse'] as $id => $data) {
array_push($result, "$id#{$data['level']}#" . utf8entities($data['name']));
}
foreach ($taData['blacklist'] as $id => $name) {
array_push($result, "$id#" . utf8entities($name));
}
return join("\n", $result);
}
/** AJAX callback that returns the list of trusted allies, the
* reverse list as well as the blacklist.
*/
public function getTrusted() {
$taData = $this->game->action('getTrustedAllies', $_SESSION[game::sessName()]['player']);
return $this->formatData($taData);
}
/*******************
* MANAGING ALLIES *
*******************/
/** AJAX callback to add an ally to the player's list.
*/
public function addAlly($name) {
$result = $this->game->action('addTrustedAlly', $_SESSION[game::sessName()]['player'], $name);
if (is_array($result)) {
return $this->formatData($result);
}
switch ($result) :
case beta5_addTrustedAlly::playerNotFound: $error = -1; break;
case beta5_addTrustedAlly::playerOnVacation: $error = 200; break;
case beta5_addTrustedAlly::noAllyName: $error = 1; break;
case beta5_addTrustedAlly::invalidAllyName: $error = 0; break;
case beta5_addTrustedAlly::allyNotFound: $error = 2; break;
case beta5_addTrustedAlly::allyIsPlayer: $error = 3; break;
case beta5_addTrustedAlly::allyIsEnemy: $error = 6; break;
case beta5_addTrustedAlly::playerBlacklisted: $error = 9; break;
case beta5_addTrustedAlly::allyAlreadyListed: $error = 4; break;
case beta5_addTrustedAlly::maxPlayerTrust: $error = 14; break;
case beta5_addTrustedAlly::maxAllyTrust: $error = 5; break;
endswitch;
return "ERR#$error";
}
/*************************
* MANAGING REVERSE LIST *
*************************/
/** AJAX callback to remove a player from his allies' lists.
*/
public function removeRAllies($list) {
$result = $this->game->action('removeTrustingAllies', $_SESSION[game::sessName()]['player'],
explode('#', $list));
if (is_array($result)) {
return $this->formatData($result);
}
switch ($result) :
case beta5_removeTrustingAllies::playerNotFound: $error = -1; break;
case beta5_removeTrustingAllies::playerOnVacation: $error = 200; break;
case beta5_removeTrustingAllies::trustingPlayerNotFound: $error = 7; break;
endswitch;
return "ERR#$error";
}
/**********************
* MANAGING BLACKLIST *
**********************/
public function addBan($name) {
$result = $this->game->action('banTrustingAlly', $_SESSION[game::sessName()]['player'], $name);
if (is_array($result)) {
return $this->formatData($result);
}
switch ($result) :
case beta5_banTrustingAlly::playerNotFound: $error = -1; break;
case beta5_banTrustingAlly::playerOnVacation: $error = 200; break;
case beta5_banTrustingAlly::emptyName: $error = 11; break;
case beta5_banTrustingAlly::invalidName: $error = 15; break;
case beta5_banTrustingAlly::targetNotFound: $error = 2; break;
case beta5_banTrustingAlly::targetIsPlayer: $error = 13; break;
case beta5_banTrustingAlly::alreadyBanned: $error = 12; break;
endswitch;
return "ERR#$error";
}
// ----------------------------------- OLD CODE BELOW!!!!
public function findLevels($list) {
$al = explode('#', $list);
$l = gameAction('getPlayerAllies', $_SESSION[game::sessName()]['player']);
$ll = array();
$i = 0;
$c = count($l);
foreach ($al as $id)
{
for ($j=0;$j<$c&&$l[$j]['id']!=$id;$j++) ;
if ($j<$c)
array_push($ll,$j);
$i ++;
if ($i == 5)
break;
}
return $ll;
}
public function moveAllies($list, $dir) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$levels = $this->findLevels($list);
sort($levels);
if (!count($levels))
return $this->getTrusted();
$pid = $_SESSION[game::sessName()]['player'];
if ($dir == "0")
{
$l = gameAction('getPlayerAllies', $pid);
if ($levels[0] == count($l) - 1)
return $this->getTrusted();
$levels = array_reverse($levels);
}
elseif ($levels[0] == 0)
return $this->getTrusted();
$act = 'moveAlly' . (($dir == "0") ? "Down" : "Up");
foreach ($levels as $l)
gameAction($act, $pid, $l);
return $this->getTrusted();
}
public function removeAllies($list) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$levels = $this->findLevels($list);
if (count($levels)) {
$pid = $_SESSION[game::sessName()]['player'];
foreach ($levels as $l)
gameAction('removeAlly', $pid, $l);
gameAction('reorderPlayerAllies', $pid);
}
return $this->getTrusted();
}
public function removeBanRAllies($list) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$tb = gameAction('getPlayerIsAlly', $_SESSION[game::sessName()]['player']);
$pid = $_SESSION[game::sessName()]['player'];
$al = explode('#', $list);
foreach ($al as $opid) {
if (is_null($tb[$opid]))
return "ERR#7";
elseif (gameAction('checkTAListBan', $pid, $opid))
return "ERR#8";
}
foreach ($al as $opid) {
gameAction('removeAlly', $opid, $tb[$opid]['level']);
gameAction('reorderPlayerAllies', $opid);
gameAction('addTAListBan', $pid, $opid);
}
return $this->getTrusted();
}
public function removeBans($list) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$pid = $_SESSION[game::sessName()]['player'];
$tb = gameAction('getTAListBans', $pid);
$al = explode('#', $list);
foreach ($al as $opid)
if (is_null($tb[$opid]))
return "ERR#10";
foreach ($al as $opid)
gameAction('delTAListBan', $pid, $opid);
return $this->getTrusted();
}
/** Main webpage handler.
*/
public function handle($input) {
$this->data = $this->getTrusted();
$this->output = "allies";
}
}
?>

View file

@ -0,0 +1,57 @@
<?php
class page_handler {
public $needsAuth = true;
public $ajax = array(
'func' => array('getCommsData'),
'init' => "makeCommsTooltips();\ninitPage();"
);
public function getCommsData() {
// Get the data
$data = $this->game->action('getCommsOverview', $_SESSION[game::sessName()]['player']);
// Issue first line: nCFolders#nGenCats#nAForums
$result = array();
array_push($result, count($data['folders']['CUS']) . "#" . count($data['forums']['general'])
. "#" . count($data['forums']['alliance']));
// Messages in default folders
$dFld = array('IN', 'INT', 'OUT');
foreach ($dFld as $f) {
array_push($result, join('#', $data['folders'][$f]));
}
// Custom folders
foreach ($data['folders']['CUS'] as $id => $folder) {
$folder[2] = utf8entities($folder[2]);
array_unshift($folder, $id);
array_push($result, join('#', $folder));
}
// Forums
foreach ($data['forums']['general'] as $cat) {
array_push($result, "{$cat['id']}#{$cat['type']}#" . count($cat['forums'])
. "#" . utf8entities($cat['title']));
foreach ($cat['forums'] as $f) {
$f[3] = utf8entities($f[3]);
array_push($result, join('#', $f));
}
}
foreach ($data['forums']['alliance'] as $f) {
$f[3] = utf8entities($f[3]);
array_push($result, join('#', $f));
}
return join("\n", $result);
}
public function handle($input) {
$this->data = $this->getCommsData();
$this->output = "comms";
}
}
?>

View file

@ -0,0 +1,115 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
'func' => array('getInformation'),
'init' => "makeDiplomacyTooltips();\ninitPage();"
);
function getAllianceRanking($tag) {
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', "a_general");
$r = $this->rkLib->call('get', $rt, $tag);
if (!$r) {
return array('','');
}
return $r;
}
function getInformation()
{
$out = array();
$pid = $_SESSION[game::sessName()]['player'];
$pinf = gameAction('getPlayerInfo', $pid);
if (!is_null($pinf['arid']))
{
$ainf = gameAction('getAllianceInfo', $pinf['arid']);
$s = "1#" . $ainf['nplanets'] . '#' . $ainf['avgx'] . '#' . $ainf['avgy'];
list($points,$ranking) = $this->getAllianceRanking($ainf['tag']);
$s .= "#$ranking#$points";
array_push($out, $s);
array_push($out, utf8entities($pinf['alliance_req']));
array_push($out, utf8entities($pinf['aname']));
$alinf = gameAction('getPlayerName', $ainf['leader']);
array_push($out, utf8entities($alinf));
}
elseif (!is_null($pinf['aid']))
{
$ainf = gameAction('getAllianceInfo', $pinf['aid']);
$pr = gameAction('getAlliancePrivileges', $pid);
$s = "2#" . $ainf['nplanets'] . '#' . $ainf['avgx'] . '#' . $ainf['avgy'];
list($points,$ranking) = $this->getAllianceRanking($ainf['tag']);
$s .= "#$ranking#$points#";
$s .= $pr['is_leader'] . "#" . (count($pr['f_read']) + count($pr['f_mod']));
array_push($out, $s);
array_push($out, utf8entities($pinf['alliance']));
array_push($out, utf8entities($pinf['aname']));
if (!$pr['is_leader'])
{
array_push($out, utf8entities(gameAction('getPlayerName', $ainf['leader'])));
if (is_null($pinf['a_grade']))
array_push($out, "-");
else
{
$rkl = gameAction('getAllianceRanks', $pinf['aid']);
array_push($out, $rkl[$pinf['a_grade']]);
}
}
$fl = gameAction('getAllianceForumsComplete', $pinf['aid']);
foreach ($fl as $fd)
{
$fid = $fd['id'];
if (!(in_array($fid, $pr['f_read']) || in_array($fid, $pr['f_mod'])))
continue;
$tot = $fd['topics'];
$unread = $tot - gameAction('getReadTopics', $fid, $pid);
array_push($out, "$fid#$tot#$unread#".utf8entities($fd['title']));
}
}
else
array_push($out, "0");
$pm = gameAction('getAllMessages', $pid, 'IN');
$pmn = gameAction('getNewMessages', $pid, 'IN');
$it = gameAction('getAllMessages', $pid, 'INT');
$itn = gameAction('getNewMessages', $pid, 'INT');
$rook = !gameAction('isPlayerRestrained', $pid);
if ($rook)
{
$rol = gameAction('getResearchOffers', $pid);
$now = time(); $nrec = 0; $sentTo = "";
foreach ($rol as $roffer)
{
if ($now - $roffer['time'] > 86400)
break;
if ($roffer['type'] == "S")
$sentTo = utf8entities($roffer['player']);
elseif ($roffer['status'] == "P")
$nrec ++;
}
}
else
$nrec=$sentTo="";
array_push($out, join('#', gameAction('getDiploSummary', $pid)));
array_push($out, "$pm#$pmn#$it#$itn");
array_push($out, ($rook ? 1 : 0) . "#$nrec#$sentTo");
return join("\n", $out);
}
function handle($input)
{
$this->data = $this->getInformation();
$this->output = "diplomacy";
}
}
?>

View file

@ -0,0 +1,43 @@
<?php
class page_handler {
public $needsAuth = true;
public $ajax = array(
"func" => array("getEmpireData"),
"init" => "makeEmpireTooltips();\nempire_write(document.getElementById('init-data').value);"
);
public function getEmpireData() {
$data = $this->game->action('getEmpireOverview', $_SESSION[game::sessName()]['player']);
if (is_null($data)) {
return;
}
$s = "";
foreach ($data['planets'] as $id => $n) {
$s .= ($s == "" ? "" : "#") . "$id#$n";
}
$str = join('#', $data['planetStats'])
. "\n$s\n{$data['fleetStats']['fleets']}#{$data['fleetStats']['battle']}#"
. "{$data['fleetStats']['power']}#{$data['fleetStats']['upkeep']}#"
. "{$data['fleetStats']['at_home']}#{$data['fleetStats']['home_battle']}#"
. "{$data['fleetStats']['foreign']}#{$data['fleetStats']['foreign_battle']}#"
. "{$data['fleetStats']['moving']}#{$data['fleetStats']['waiting']}#"
. "{$data['fleetStats']['gaships']}#{$data['fleetStats']['fighters']}#"
. "{$data['fleetStats']['cruisers']}#{$data['fleetStats']['bcruisers']}\n"
. "{$data['techStats']['points']}#" . join('#', $data['techStats']['budget'])
. "#{$data['techStats']['new']}#{$data['techStats']['foreseen']}\n"
. "{$data['income']}#{$data['profit']}";
return $str;
}
function handle($input) {
$this->data = $this->getEmpireData();
$this->output = "empire";
}
}
?>

View file

@ -0,0 +1,89 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
'init' => "makeEnemyListTooltips();\ninitList();",
'func' => array('getEnemies', 'removeEnemies', 'addEnemy'),
);
function getEnemies()
{
$pid = $_SESSION[game::sessName()]['player'];
$rs = array();
$epl = gameAction('getEnemyPlayers', $pid);
foreach ($epl as $id => $name)
array_push($rs, "0#$id#".utf8entities($name));
$eal = gameAction('getEnemyAlliances', $pid);
foreach ($eal as $id => $name)
array_push($rs, "1#$id#".utf8entities($name));
return join("\n", $rs);
}
function removeEnemies($type, $list) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$pid = $_SESSION[game::sessName()]['player'];
$l = explode('#', $list);
$action = 'removeEnemy' . ($type == "1" ? 'Alliance' : 'Player');
foreach ($l as $eid) {
gameAction($action, $pid, (int)$eid);
}
return $this->getEnemies();
}
function addEnemy($type, $name) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
if ($type != "0" && $type != "1") {
return "ERR#0";
}
$name = preg_replace('/\s+/', ' ', trim($name));
if ($name == "")
return "ERR#1";
elseif (($type == 0 && strlen($name) > 15) || ($type == 1 && strlen($name) > 5))
return "ERR#0";
$pid = $_SESSION[game::sessName()]['player'];
if ($type == 0 && $this->game->params['victory'] == 0 && strtolower($name) == 'ai>peacekeepers') {
return "ERR#9";
}
$eid = gameAction($type == 0 ? "getPlayer" : "getAlliance", $name);
if (is_null($eid))
return "ERR#" . ($type == 0 ? 2 : 3);
$list = array_keys(gameAction('getEnemy'. ($type == 0 ? 'Players' : 'Alliances'), $pid));
if (in_array($eid, $list))
return "ERR#" . ($type == 0 ? 4 : 5);
if ($type == 0 && $eid == $pid)
return "ERR#6";
elseif ($type == 0 && gameAction('isPlayerAlly', $pid, $eid))
return "ERR#8";
elseif ($type == 1)
{
$pinf = gameAction('getPlayerInfo', $pid);
if (!is_null($pinf['aid']) && $pinf['aid'] == $eid)
return "ERR#7";
}
gameAction('addEnemy' . ($type == 0 ? 'Player' : 'Alliance'), $pid, $eid);
return $this->getEnemies();
}
function handle($input)
{
$this->data = $this->getEnemies();
$this->output = "enemylist";
}
}
?>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,85 @@
<?php
class page_handler {
var $needsAuth = true;
var $ajax = array();
var $lang = null;
var $lib = null;
var $page = null;
var $searchText = "";
function pageNotFound() {
$this->subPage = "notfound";
}
function getFirstPage() {
$fPage = $this->lib->call('getFirstPage', $this->lang);
if (is_null($fPage)) {
$this->pageNotFound();
return;
}
$this->page = $this->lib->call('getPage', $fPage);
if (is_null($this->page)) {
$this->pageNotFound();
return;
}
$this->subPage = "page";
}
function getPage($name) {
$secId = $this->lib->call('getSectionId', $this->lang, $name);
if (is_null($secId)) {
$this->pageNotFound();
return;
}
$pageId = $this->lib->call('getPageId', $secId);
if (is_null($pageId)) {
$this->pageNotFound();
return;
}
$this->page = $this->lib->call('getPage', $pageId);
if (is_null($this->page)) {
$this->pageNotFound();
return;
}
$this->subPage = "page";
}
function getSearchPage($text) {
$this->searchText = $text;
if (is_array(tracking::$data['man_search']) && tracking::$data['man_search']['text'] != $text) {
tracking::$data['man_search'] = null;
}
if (!is_array(tracking::$data['man_search'])) {
tracking::$data['man_search'] = array(
"text" => $text,
"results" => $this->lib->call('search', $text, $this->lang, $this->version)
);
}
$this->data = tracking::$data['man_search'];
$this->subPage = "search";
}
function handle($input) {
$this->lang = getLanguage();
$this->lib = $this->game->getLib('main/manual');
if ($input['ss'] != '') {
$this->getSearchPage($input['ss']);
} elseif ($input['p'] != '') {
$p = preg_replace('/[^A-Za-z0-9_\-]/', '', $input['p']);
$this->getPage($p);
} else {
$this->getFirstPage();
}
$this->output = "manual";
}
}
?>

View file

@ -0,0 +1,146 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
"func" => array(
"getMapParams", "updateData", "findName", "getPlayerPlanets"
),
"method"=> array(
"updateData" => "POST",
),
"init" => "makeMapTooltips();\nx_getMapParams(mapInit);"
);
function getMapParams()
{
$s = $_SESSION[game::sessName()]['map'] . "\n" . $this->findName($_SESSION[game::sessName()]['map_ctr']);
$s2 = $this->getPlayerPlanets();
if ($s2 != "")
$s .= "\n$s2";
return $s;
}
function getPlayerPlanets()
{
$as = array();
$pl = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
foreach ($pl as $id => $name)
array_push($as, "$id#$name");
return join("\n", $as);
}
function findName($n)
{
$n = trim($n);
$a = gameAction('getPlanetByName', $n);
if (is_null($a))
return "ERR";
$o = ($a['owner'] == $_SESSION[game::sessName()]['player']) ? 0 : 1;
$i = $o ? $a['name'] : $a['id'];
return $a['x']."#".$a['y']."#$o#$i";
}
function updateData($rlist)
{
if ($rlist == "")
return "";
$pid = $_SESSION[game::sessName()]['player'];
$pinf = gameAction('getPlayerInfo', $pid);
$tag = $pinf['aid'] ? $pinf['alliance'] : "";
$l = explode('#', $rlist);
$rs = array();
foreach ($l as $rdata)
{
list($xt,$yt,$md5) = explode(',', $rdata);
$x = (int)$xt; $y = (int)$yt;
$sys = gameAction('getSystemAt', $x, $y);
if (is_null($sys)) {
if ($md5 != "-") {
array_push($rs, "#$x#$y");
}
continue;
}
if ($sys['nebula'] > 0) {
$mmd5 = md5(serialize($sys));
if ($md5 == $mmd5)
continue;
array_push($rs, "{$sys['id']}#$x#$y#$mmd5#{$sys['nebula']}#0");
$zones = gameAction('getSystemPlanets', $sys['id']);
for ($i = 0; $i < 6; $i++) {
array_push($rs, "{$zones[$i]['id']}#" . ($zones[$i]['status'] - 1)
. "#{$zones[$i]['name']}");
}
continue;
}
switch (input::$game->params['victory']) {
case 0:
$sys['prot'] = ($sys['prot'] > 0) ? 1 : 0;
break;
case 1:
$sys['prot'] = 0;
break;
case 2:
$sys['prot'] = input::$game->getLib('beta5/ctf')->call('isTarget', $sys['id']) ? 1 : 0;
break;
}
$sys['planets'] = gameAction('getSystemPlanets', $sys['id']);
for ($i = 0; $i < 6; $i ++) {
if ($sys['planets'][$i]['owner'] == $pid)
$r = 2;
elseif ($tag != "" && $sys['planets'][$i]['tag'] == $tag)
$r = 1;
else
$r = 0;
$sys['planets'][$i]['relation'] = $r;
}
$mmd5 = md5(serialize($sys));
if ($md5 == $mmd5) {
continue;
}
array_push($rs, "{$sys['id']}#$x#$y#$mmd5#{$sys['nebula']}#{$sys['prot']}");
for ($i = 0; $i < 6; $i ++) {
$p = $sys['planets'][$i];
$s = $p['id']."#".$p['status']."#".$p['relation']."#".$p['tag'];
array_push($rs, $s);
array_push($rs, $p['name']);
}
}
return join("\n", $rs);
}
function handle($input)
{
$ctrMap = null;
switch ($input['menu']):
case 'p':
$_SESSION[game::sessName()]['map'] = 0;
if ($input['ctr'] != '' && !is_null($mc = gameAction('getPlanetById', (int)$input['ctr'])))
$ctrMap = $mc['name'];
break;
case 'a': $_SESSION[game::sessName()]['map'] = 1; break;
case 'l': $_SESSION[game::sessName()]['map'] = 2; break;
endswitch;
if (is_null($_SESSION[game::sessName()]['map']))
$_SESSION[game::sessName()]['map'] = 0;
if (is_null($ctrMap))
$_SESSION[game::sessName()]['map_ctr'] = gameAction('getFirstPlanet', $_SESSION[game::sessName()]['player']);
else
$_SESSION[game::sessName()]['map_ctr'] = $ctrMap;
$this->output = "map";
}
}
?>

View file

@ -0,0 +1,463 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
'func' => array(
'getPublicOffers', 'moveMap', 'cancelSale', 'placeBid',
'buyPublic', 'getPrivateOffers', 'buyPrivate', 'declinePrivate',
'getSentOffers'
),
'init' => 'initMarket();'
);
//--------------------
// Public offers
function findName($n)
{
$n = trim($n);
$a = gameAction('getPlanetByName', $n);
if (is_null($a))
return null;
$o = ($a['owner'] == $_SESSION[game::sessName()]['player']) ? 0 : 1;
$i = $o ? $a['name'] : $a['id'];
return array($o + 1, $i, $a['x'], $a['y']);
}
function getPlayerPlanets()
{
$pl = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$as = array(count($pl));
foreach ($pl as $id => $name)
array_push($as, "$id#$name");
return $as;
}
function getPublicOffers() {
$page = &$this->sessData('page'); $page = 0;
$player = $_SESSION[game::sessName()]['player'];
$pinfo = gameAction('getPlayerInfo', $player);
$result = array();
// Get map configuration
$map = &$this->sessData('po_map');
if (!is_array($map)) {
$pname = gameAction('getFirstPlanet', $player);
list($type,$param,$x,$y) = $this->findName($pname);
$map = array(
'type' => $type,
'x' => $x,
'y' => $y,
'param' => $param,
'dist' => 1
);
} elseif ($map['type'] == 1) {
$pi = gameAction('getPlanetOwner', $map['param']);
if ($pi['owner'] != $player) {
$pi['type'] = 2;
$pi['param'] = $pi['name'];
}
}
// Add map data to the output array
array_push($result, $map['type']."#".$map['x']."#".$map['y']."#".$map['dist'].($map['type'] == 0 ? '' : ('#'.utf8entities($map['param']))));
$result = array_merge($result, $this->getPlayerPlanets());
// Get selected system data
$sys = gameAction('getSystemAt', $map['x'], $map['y']);
if (is_null($sys)) {
array_push($result, "-1#0");
} else {
switch ($this->game->params['victory']) {
case 0:
$sys['prot'] = ($sys['prot'] > 0) ? 1 : 0;
break;
case 1:
$sys['prot'] = 0;
break;
case 2:
$sys['prot'] = input::$game->getLib('beta5/ctf')->call('isTarget', $sys['id']) ? 1 : 0;
break;
}
$pLev = gameAction('getProtectionLevel', $player);
array_push($result, $sys['nebula']."#".$sys['prot']);
$plist = gameAction('getSystemPlanets', $sys['id']);
foreach ($plist as $pi) {
$s = $pi['id']."#".$pi['status']."#".($pi['owner'] == $player ? '1' : '0') . '#';
$s .= ($pinfo['aid'] && $pi['owner'] != $player && $pinfo['alliance'] == $pi['tag']) ? '1' : '0';
array_push($result, $s . "#" . utf8entities($pi['name']));
}
}
// Look for sales
$pIds = gameAction('getPlanetsAround', $map['x'], $map['y'], $map['dist']);
if (count($pIds))
{
$sales = gameAction('getSales', $pIds);
$pSales = $fSales = array();
for ($i=0;$i<count($sales);$i++)
if (is_null($sales[$i]['planet']))
array_push($fSales, $i);
else
array_push($pSales, $i);
array_push($result, count($pSales)."#".count($fSales));
$sellers = array();
// Planet sales, with or without fleets
for ($i=0;$i<count($pSales);$i++)
{
$o = $sales[$pSales[$i]];
$p = $o['planet'];
if (!in_array($o['player'],$sellers))
array_push($sellers, $o['player']);
$s = $o['id']."#".$o['expires']."#".$p['id']."#".$o['player']."#".$p['x']."#".$p['y']."#".($p['orbit']+1)."#".$o['price']."#";
$s .= ($o['auction']=='t'?1:0)."#".$p['pop']."#".$p['turrets']."#".$p['fact']."#".(is_null($o['fleet'])?0:1)."#".utf8entities($p['name']);
array_push($result, $s);
if (is_null($o['fleet']))
continue;
$f = $o['fleet'];
array_push($result, $f['id']."#".$f['sg']."#".$f['sf']."#".$f['sc']."#".$f['sb']);
}
// Fleet sales
for ($i=0;$i<count($fSales);$i++)
{
$o = $sales[$fSales[$i]];
$f = $o['fleet'];
if (!in_array($o['player'],$sellers))
array_push($sellers, $o['player']);
$s = $o['id']."#".$o['expires']."#".$f['id']."#".$o['player']."#".$f['x']."#".$f['y']."#".($f['orbit']+1)."#".$f['pid']."#".$o['price']."#";
$s .= ($o['auction']=='t'?1:0)."#".$f['sg']."#".$f['sf']."#".$f['sc']."#".$f['sb']."#".utf8entities($f['pname']);
array_push($result, $s);
}
// Current owners
foreach ($sellers as $sid)
{
$pinf = gameAction('getPlayerInfo', $sid, true);
array_push($result, "$sid#" . ($player==$sid?1:0) . "#" . $pinf['quit'] . "#" . utf8entities($pinf['name']));
}
}
else
// No sales
array_push($result, "0#0");
return join("\n", $result);
}
function moveMap($type,$parm,$dist) {
$map = &$this->sessData('po_map');
$type = (int)$type;
if ($type < 0 || $type > 2) {
$type = 0;
}
$dist = (int)$dist;
if ($dist < 1 || $dist > 7) {
$dist = 1;
}
$map['dist'] = $dist;
switch ($type) :
case 0:
list($x,$y) = split('#',$parm);
$map['x'] = (int)$x;
$map['y'] = (int)$y;
$map['type'] = 0;
break;
case 1:
$a = gameAction('getPlanetById', (int)$parm);
if (!is_null($a)) {
$map['x'] = $a['x'];
$map['y'] = $a['y'];
$map['param'] = (int)$parm;
$map['type'] = 1;
}
break;
case 2:
$a = $this->findName($parm);
if (!is_null($a)) {
list($map['type'],$map['param'],$map['x'],$map['y']) = $a;
}
break;
endswitch;
return $this->getPublicOffers();
}
function cancelSale($id) {
$player = $_SESSION[game::sessName()]['player'];
$pLib = $this->game->getLib('beta5/player');
if ($pLib->call('isOnVacation', $player)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $player)) {
return "ERR#201";
}
gameAction('cancelSale', $_SESSION[game::sessName()]['player'], (int)$id);
return $this->getMarketData();
}
function placeBid($id, $bid) {
$player = $_SESSION[game::sessName()]['player'];
$pLib = $this->game->getLib('beta5/player');
if ($pLib->call('isOnVacation', $player)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $player)) {
return "ERR#201";
}
$r = gameAction('placeBid', $_SESSION[game::sessName()]['player'], (int)$id, (int)$bid);
if ($r != '')
return "ERR#$r";
return $this->getPublicOffers();
}
function buyPublic($offer) {
$player = $_SESSION[game::sessName()]['player'];
$pLib = $this->game->getLib('beta5/player');
if ($pLib->call('isOnVacation', $player)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $player)) {
return "ERR#201";
}
$r = gameAction('buy', $_SESSION[game::sessName()]['player'], (int)$offer);
if ($r != '')
return "ERR#$r";
return $this->getPublicOffers();
}
//--------------------
// Private offers
function getPrivateOffers() {
$page = &$this->sessData('page'); $page = 1;
$player = $_SESSION[game::sessName()]['player'];
$pinfo = gameAction('getPlayerInfo', $player);
$result = array();
// Get offers and history
$offers = gameAction('getDirectSales', $player);
$history = gameAction('getSalesHistoryTo', $player);
$sellers = array();
array_push($result, count($offers) . "#" . count($history));
// Generate offers list
foreach ($offers as $o)
{
$f = $o['fleet'];
$p = $o['planet'];
if (!in_array($o['player'], $sellers))
array_push($sellers, $o['player']);
$cs = is_null($p) ? $f : $p;
$rs = array($o['id'], $o['player'], $o['price'], $cs['x'], $cs['y'], $cs['orbit']+1);
array_push($rs, is_null($p) ? '' : $p['id']);
array_push($rs, is_null($f) ? '' : $f['id']);
array_push($rs, $o['started']); array_push($rs, $o['expires']);
array_push($rs, utf8entities(is_null($p) ? $f['pname'] : $p['name']));
array_push($result, join('#', $rs));
if (!is_null($f))
{
$rs = array($f['sg'], $f['sf'], $f['sc'], $f['sb']);
array_push($result, join('#', $rs));
}
if (!is_null($p))
{
$rs = array($p['pop'], $p['turrets'], $p['fact']);
array_push($result, join('#', $rs));
}
}
// Generate history list
foreach ($history as $o)
{
if (!in_array($o['from_player'], $sellers))
array_push($sellers, $o['from_player']);
$price = is_null($o['sell_price']) ? $o['price'] : $o['sell_price'];
$hf = ($o['is_planet'] == 'f') || ($o['f_gaships'] + $o['f_fighters'] + $o['f_cruisers'] + $o['f_bcruisers'] != 0);
$pinf = gameAction('getPlanetById', $o['p_id']);
$rs = array(
$o['from_player'], $price, $pinf['x'], $pinf['y'], $pinf['orbit']+1,
($o['is_planet'] == 't' ? 1 : 0), $hf?1:0,
$o['started'], $o['end_mode'], $o['ended'], utf8entities($o['p_name'])
);
array_push($result, join("#", $rs));
if ($hf)
array_push($result, $o['f_gaships']."#".$o['f_fighters']."#".$o['f_cruisers']."#".$o['f_bcruisers']);
if ($o['is_planet'] == 't')
array_push($result, $o['p_pop']."#".$o['p_turrets']."#".$o['p_factories']);
}
// Player names and status
foreach ($sellers as $sid)
{
$pinf = gameAction('getPlayerInfo', $sid, true);
array_push($result, "$sid#" . $pinf['quit'] . "#" . utf8entities($pinf['name']));
}
return join("\n", $result);
}
function buyPrivate($offer) {
$player = $_SESSION[game::sessName()]['player'];
$pLib = $this->game->getLib('beta5/player');
if ($pLib->call('isOnVacation', $player)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $player)) {
return "ERR#201";
}
$r = gameAction('buy', $_SESSION[game::sessName()]['player'], (int)$offer);
if ($r != '')
return "ERR#$r";
return $this->getPrivateOffers();
}
function declinePrivate($offer) {
$player = $_SESSION[game::sessName()]['player'];
$pLib = $this->game->getLib('beta5/player');
if ($pLib->call('isOnVacation', $player)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $player)) {
return "ERR#201";
}
if (!gameAction('isDirectOffer', $_SESSION[game::sessName()]['player'], (int)$offer)) {
return "ERR#0";
}
gameAction('declinePrivate', (int)$offer);
return $this->getPrivateOffers();
}
//--------------------
// Sent offers
function getSentOffers() {
$page = &$this->sessData('page'); $page = 2;
$player = $_SESSION[game::sessName()]['player'];
$pinfo = gameAction('getPlayerInfo', $player);
$result = array();
// Get offers and history
$offers = gameAction('getSentOffers', $player);
$history = gameAction('getSalesHistoryFrom', $player);
$buyers = array();
array_push($result, count($offers) . "#" . count($history));
// Generate offers list
foreach ($offers as $o) {
$f = $o['fleet'];
$p = $o['planet'];
if ($o['to_player'] != '' && !in_array($o['to_player'], $buyers))
array_push($buyers, $o['to_player']);
$cs = is_null($p) ? $f : $p;
$rs = array($o['id'], $o['mode'], $o['price'], $o['to_player'], $cs['x'], $cs['y'], $cs['orbit'] + 1, is_null($p) ? 0 : 1, is_null($f) ? 0 : 1);
array_push($rs, $o['started']); array_push($rs, $o['expires']);
array_push($rs, utf8entities(is_null($p) ? $f['pname'] : $p['name']));
array_push($result, join('#', $rs));
if (!is_null($f)) {
$rs = array($f['sg'], $f['sf'], $f['sc'], $f['sb']);
array_push($result, join('#', $rs));
}
if (!is_null($p)) {
$rs = array($p['pop'], $p['turrets'], $p['fact']);
array_push($result, join('#', $rs));
}
}
// Generate history list
foreach ($history as $o) {
if ($o['to_player'] != '' && !in_array($o['to_player'], $buyers))
array_push($buyers, $o['to_player']);
$price = is_null($o['sell_price']) ? $o['price'] : $o['sell_price'];
$hf = ($o['is_planet'] == 'f') || ($o['f_gaships'] + $o['f_fighters'] + $o['f_cruisers'] + $o['f_bcruisers'] != 0);
$pinf = gameAction('getPlanetById', $o['p_id']);
$rs = array(
$pinf['x'], $pinf['y'], $pinf['orbit'] + 1, $o['mode'], ($o['is_planet'] == 't' ? 1 : 0),
$hf?1:0, $o['to_player'], $price,
$o['started'], $o['end_mode'], $o['ended'], utf8entities($o['p_name'])
);
array_push($result, join("#", $rs));
if ($hf)
array_push($result, $o['f_gaships']."#".$o['f_fighters']."#".$o['f_cruisers']."#".$o['f_bcruisers']);
if ($o['is_planet'] == 't')
array_push($result, $o['p_pop']."#".$o['p_turrets']."#".$o['p_factories']);
}
// Player names and status
foreach ($buyers as $sid) {
$pinf = gameAction('getPlayerInfo', $sid, true);
array_push($result, "$sid#" . $pinf['quit'] . "#" . utf8entities($pinf['name']));
}
return join("\n", $result);
}
//--------------------
// Standard output
function &sessData($name)
{
if (!is_array($_SESSION[game::sessName()]['market']))
$_SESSION[game::sessName()]['market'] = array('page' => 0);
if (!isset($_SESSION[game::sessName()]['market'][$name]))
$_SESSION[game::sessName()]['market'][$name] = null;
return $_SESSION[game::sessName()]['market'][$name];
}
function getMarketData()
{
switch ($this->sessData('page')) :
case 0: $s = $this->getPublicOffers(); break;
case 1: $s = $this->getPrivateOffers(); break;
case 2: $s = $this->getSentOffers(); break;
default: $s = ""; break;
endswitch;
return $s;
}
function handle($input)
{
$page = &$this->sessData('page');
switch ($input['p']) :
case 'p': $page = 0; break;
case 'r': $page = 1; break;
case 's': $page = 2; break;
endswitch;
$r = gameAction('isPlayerRestrained', $_SESSION[game::sessName()]['player']);
if ($r > 0)
$this->data = $r;
else
$this->data = array(
"page" => $page,
"pdata" => $this->getMarketData()
);
$this->output = "market";
}
}
?>

View file

@ -0,0 +1,492 @@
<?php
class page_handler {
var $engines = array('page', 'rpc', 'css', 'js', 'redirect');
var $defaultEngine = 'page';
var $needsAuth = true;
var $ajaxPOST = true;
var $ajax = array(
"func" => array(
"sendMessage", "setSortParameters", "setMessagesPerPage",
"getFolderSettings", "getMessageList", "getTargetName",
"getMessageText", "updateFolders", "deleteMessages",
"moveMessages", "renameFolder", "addFolder", "deleteFolders",
"flushFolders", "switchThreaded"
),
"init" => "makeMessagesTooltips();\ninitMessages();"
);
function getFolderSettings($n, $cid)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return "";
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return "";
$pn = $n;
if ($n == "CUS")
$pn .= "!$cid";
$rs = "";
$p = prefs::get("beta5/$pn!nmsg");
$rs .= ($p == "" ? 20 : $p) . "#";
$p = prefs::get("beta5/$pn!orderby");
$rs .= ($p == "" ? "date" : $p) . "#";
$p = prefs::get("beta5/$pn!direction");
$rs .= ($p == "" ? 0 : $p) . "#";
$p = prefs::get("beta5/$pn!threaded");
$rs .= ($p == "" ? 1 : $p);
return $rs;
}
function getMessageList($n, $cid, $alst)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return "";
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return "";
$list = gameAction('getMessageHeaders', $pid, $n, $cid);
$s = "";
$al = array();
if (trim($alst) != "")
{
$alc = explode('#', $alst);
$cmid = array_keys($list);
foreach ($alc as $mid)
{
if ($mid == "" || (int)$mid != $mid)
continue;
array_push($al, $mid);
if (in_array($mid, $cmid))
continue;
if ($s != "")
$s .= "\n";
$s .= "-#$mid";
}
}
foreach ($list as $id => $hdr)
{
if (in_array($id, $al))
continue;
if ($s != "")
$s .= "\n";
$s .= "+#$id#".$hdr['received']."#".$hdr['status']."#";
$s .= $hdr['slink']."#".$hdr['rlink'].'#'.$hdr['replink'];
$s .= "#" . $hdr['replyTo'] . "\n";
$s .= $hdr['from'] . "\n";
$s .= $hdr['to'] . "\n";
$s .= $hdr['subject'];
}
return $s;
}
function sendMessage($t, $rec, $sub, $msg, $replyId)
{
$e = false;
$errs = array(0,0,0);
$rec = trim($rec);
$sub = trim($sub);
$msg = trim($msg);
if ($rec == "")
{
$errs['rec'] = 1;
$e = true;
}
elseif ($t == 0)
{
$rid = gameAction('getPlayer', $rec);
if (is_null($rid))
{
$errs[0] = 2;
$e = true;
}
else
$sendAction = 'Player';
}
elseif ($t == 1)
{
$pinf = gameAction('getPlanetByName', $rec);
if (is_null($pinf))
{
$errs[0] = 2;
$e = true;
}
else
{
$rid = $pinf['id'];
$sendAction = 'Planet';
}
}
else
{
$rid = gameAction('getAlliance', $rec);
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
if (is_null($rid))
{
$errs[0] = 2;
$e = true;
}
elseif ($rid == $pinf['aid'])
$sendAction = 'Alliance';
else
$sendAction = 'Diplomacy';
}
if ($sub == "")
{
$errs[1] = 1;
$e = true;
}
elseif (strlen($sub) > 64)
{
$errs[1] = 2;
$e = true;
}
if ($msg == "")
{
$errs[2] = 1;
$e = true;
}
if ($replyId == -1)
$replyId = null;
if (!$e)
gameAction("sendMessage$sendAction", $_SESSION[game::sessName()]['player'], $rid, $sub, $msg, $replyId);
return $e ? join('#', $errs) : "OK";
}
function getFolderParms($i)
{
$cf = -1;
$ftype = null;
switch ($i['f'])
{
case 'I':
$ftype = 'IN';
break;
case 'O':
$ftype = 'OUT';
break;
case 'T':
$ftype = 'INT';
break;
case 'C':
if (is_null($this->cFolders[$i['cf']]))
$ftype = null;
else
{
$ftype = 'CUS';
$cf = $i['cf'];
}
break;
}
if (is_null($ftype))
return "#-1";
return "#$ftype#$cf";
}
function setSortParameters($n, $cid, $se, $so)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return;
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return;
$seOk = array('st', 'sub', 'date', 'from', 'to');
if (!in_array($se, $seOk))
return;
$pn = $n;
if ($n == "CUS")
$pn .= "!$cid";
prefs::set("beta5/$pn!orderby", $se);
prefs::set("beta5/$pn!direction", ($so=="1")?"1":"0");
}
function setMessagesPerPage($n, $cid, $mpp)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return;
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return;
if ($mpp == "" || (int)$mpp != $mpp || $mpp<1 || $mpp>5)
return;
$pn = $n;
if ($n == "CUS")
$pn .= "!$cid";
prefs::set("beta5/$pn!nmsg", $mpp * 10);
}
function switchThreaded($n, $cid)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return;
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return;
$pn = $n;
if ($n == "CUS")
$pn .= "!$cid";
$p = prefs::get("beta5/$pn!threaded");
prefs::set("beta5/$pn!threaded", ($p == "1") ? "0" : "1");
}
function getTargetName($type, $id)
{
$type = (int)$type;
$id = (int)$id;
$rv = "";
switch ($type) :
case 0:
$rv = gameAction('getPlayerName', $id);
break;
case 1:
$pinf = gameAction('getPlanetById', $id);
if (!is_null($pinf))
$rv = $pinf['name'];
break;
case 2:
$pinf = gameAction('getAllianceInfo', $id);
if (!is_null($pinf))
$rv = $pinf['tag'];
break;
endswitch;
return $rv;
}
function getMessageText($mId)
{
$mId = (int)$mId;
$pl = $_SESSION[game::sessName()]['player'];
$msg = gameAction('getCompleteMessage', $mId, $pl);
if (is_null($mId) || $msg['player'] != $pl)
return "";
$s = $msg['ftype'] . '#' . (is_null($msg['cfid']) ? 0 : $msg['cfid']) . '#' . $msg['id'];
$s .= "\n" . $msg['subject'];
if ($msg['text'])
{
$s .= "\n" . $msg['text'];
gameAction('setMessageRead', $mId);
}
return $s;
}
function updateFolders()
{
$pl = $_SESSION[game::sessName()]['player'];
$flist = "IN##" . gameAction('getNewMessages', $pl, 'IN');
$flist .= "#" . gameAction('getAllMessages', $pl, 'IN') . "\n\n";
$flist .= "INT##" . gameAction('getNewMessages', $pl, 'INT');
$flist .= "#" . gameAction('getAllMessages', $pl, 'INT') . "\n\n";
$flist .= "OUT##" . gameAction('getNewMessages', $pl, 'OUT');
$flist .= "#" . gameAction('getAllMessages', $pl, 'OUT') . "\n";
$fl = gameAction('getCustomFolders', $pl);
foreach ($fl as $id => $name)
{
$flist .= "\nCUS#$id#" . gameAction('getNewMessages', $pl, 'CUS', $id);
$flist .= "#" . gameAction('getAllMessages', $pl, 'CUS', $id);
$flist .= "\n".utf8entities($name);
}
return $flist;
}
function deleteMessages($n, $cid, $dList, $aList)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return;
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return;
$dl = explode("#", $dList);
foreach ($dl as $mid)
{
if ($mid == "" || (int)$mid != $mid)
continue;
gameAction('deleteMessage', $mid, $pid);
}
return $this->getMessageList($n, $cid, $aList);
}
function moveMessages($n, $cid, $tn, $tcid, $mList, $aList)
{
$nok = array('IN','OUT','INT','CUS');
if (!in_array($n, $nok))
return;
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
if ($n=="CUS" && is_null($fl[$cid]))
return;
if ( !in_array($tn, $nok)
|| ($tn=="CUS" && is_null($fl[$tcid]))
)
return $this->getMessageList($n, $cid, $aList);
$dl = explode("#", $mList);
foreach ($dl as $mid)
{
if ($mid == "" || (int)$mid != $mid)
continue;
gameAction('moveMessage', $mid, $pid, $tn, $tcid);
}
return $this->getMessageList($n, $cid, $aList);
}
function renameFolder($fid, $name)
{
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
$name = trim($name);
if (is_null($fl[$fid]) || $name == "" || strlen($name) > 32)
return $this->updateFolders();
gameAction('renameCustomFolder', $fid, $name);
return $this->updateFolders();
}
function addFolder($name)
{
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
$name = trim($name);
if ($name == "" || strlen($name) > 32 || count($fl) >= 15 || in_array($name, array_values($fl)))
return $this->updateFolders();
gameAction('createCustomFolder', $pid, $name);
return $this->updateFolders();
}
function deleteFolders($lst)
{
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
$dl = explode('#', $lst);
foreach ($dl as $id)
{
if (is_null($fl[$id]))
continue;
gameAction('deleteCustomFolder', $pid, $id);
}
return $this->updateFolders();
}
function flushFolders($lst)
{
$pid = $_SESSION[game::sessName()]['player'];
$fl = gameAction('getCustomFolders', $pid);
$dl = explode('#', $lst);
$nok = array('IN','OUT','INT','CUS');
foreach ($dl as $idc)
{
list($n, $id) = explode('!', $idc);
if (!in_array($n, $nok) || ($n == "CUS" && is_null($fl[$id])))
continue;
gameAction('flushFolder', $pid, $n, $id);
}
return $this->updateFolders();
}
function handle($input)
{
$pl = $_SESSION[game::sessName()]['player'];
$this->cFolders = gameAction('getCustomFolders', $pl);
// Generate complete folder list
$flist = "IN##" . gameAction('getNewMessages', $pl, 'IN');
$flist .= "#" . gameAction('getAllMessages', $pl, 'IN') . "\n\n";
$flist .= "INT##" . gameAction('getNewMessages', $pl, 'INT');
$flist .= "#" . gameAction('getAllMessages', $pl, 'INT') . "\n\n";
$flist .= "OUT##" . gameAction('getNewMessages', $pl, 'OUT');
$flist .= "#" . gameAction('getAllMessages', $pl, 'OUT') . "\n";
foreach ($this->cFolders as $id => $name)
{
$flist .= "\nCUS#$id#" . gameAction('getNewMessages', $pl, 'CUS', $id);
$flist .= "#" . gameAction('getAllMessages', $pl, 'CUS', $id);
$flist .= "\n".utf8entities($name);
}
switch ($input['a']) :
case 'c':
$dInit = "Compose";
$type = $input['ct'];
$id = $input['id'];
if ($type != '' && $id != '')
$dInit .= "#$type#$id#";
break;
case 'f':
$dInit = "Browse";
$dInit .= $this->getFolderParms($input);
break;
case 'mf':
$dInit = "Folders";
break;
default:
$dInit = "Compose";
break;
endswitch;
$this->data = array(
"dinit" => $dInit,
"flist" => $flist
);
$this->output = "message";
}
function redirect($input) {
if (is_null($_SESSION['userid'])) {
return "message";
}
$this->msgs = $this->game->getLib('beta5/msg');
$player = $_SESSION[game::sessName()]['player'];
if ($this->msgs->call('getNew', $player, 'IN')) {
return "message?a=f&f=I";
} elseif ($this->msgs->call('getNew', $player, 'INT')) {
return "message?a=f&f=T";
}
l::FIXME("check messages in other folders");
return "message";
}
}
?>

View file

@ -0,0 +1,131 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
"func" => array(
"getCash", "getCashDetails", "transferFunds"
),
"init" => "makeMoneyTooltips();\nx_getCash(displayCash); x_getCashDetails(displayPage);"
);
function getCash() {
$pi = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
return $pi['cash'];
}
function getCashDetails() {
$pr = gameAction('isPlayerRestrained', $_SESSION[game::sessName()]['player']);
$str = "$pr";
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
$str .= "#" . (gameAction('isOnVacation', $_SESSION[game::sessName()]['player']) ? 1 : 0);
$income = $upkeep = 0;
$ppl = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$str .= "#" . count($ppl);
$strp = "";
foreach ($ppl as $id => $name)
{
$info = gameAction('getPlanetById', $id);
if ($strp != "")
$strp .= "\n";
$strp .= "$name\n$id#";
$m = gameAction('getPlanetIncome', $info['owner'], $info['pop'], $info['happiness'], $info['ifact'], $info['mfact'], $info['turrets'], $info['corruption']);
$income += $m[0];
$strp .= join('#', $m);
$strp .= '#' . $info['ifact'];
}
$pfl = gameAction('getPlayerFleets', $_SESSION[game::sessName()]['player']);
$str .= "#" . count($pfl);
$strf = "";
foreach ($pfl as $id => $name)
{
$info = gameAction('getFleet', $id);
if ($strf != "")
$strf .= "\n";
$strf .= "$name\n";
if (is_null($info['move']) && is_null($info['wait']))
{
$pinf = gameAction('getPlanetById', $info['location']);
$strf .= $pinf['name'] . "\n$id#0#0";
}
elseif (is_null($info['move']))
{
$pinf = gameAction('getPlanetById', $info['wait']['drop_point']);
$strf .= $pinf['name'] . "\n$id#0#" . $info['wait']['time_left'];
}
else
{
$pinf = gameAction('getPlanetById', $info['move']['m_to']);
$strf .= $pinf['name'] . "\n$id#" . $info['move']['time_to_arrival'] . "#";
$strf .= (is_null($info['wait']) ? 0 : $info['wait']['time_left']);
}
$u = gameAction('getFleetUpkeep', $_SESSION[game::sessName()]['player'],
$info['gaships'], $info['fighters'], $info['cruisers'], $info['bcruisers']);
$upkeep += $u;
$strf .= "#$u";
}
$profit = $income - $upkeep;
$str .= "#$income#$upkeep#$profit\n$strp\n$strf";
return $str;
}
public function transferFunds($target, $amount) {
if ((int)$amount != $amount || $amount <= 0) {
return 1;
}
if ($target == "") {
return 2;
}
$sid = $_SESSION[game::sessName()]['player'];
$pLib = $this->game->getLib('beta5/player');
$tid = $pLib->call('getPlayerId', $target);
if (is_null($tid)) {
return 3;
}
if ($sid == $tid) {
return 4;
}
if ($pLib->call('isRestrained', $tid)) {
return 5;
}
if ($pLib->call('isRestrained', $sid)) {
return 6;
}
$sourcePLevel = $pLib->call('getProtectionLevel', $sid);
if ($sourcePLevel) {
return 7;
}
$targetPLevel = $pLib->call('getProtectionLevel', $tid);
if ($targetPLevel) {
return 8;
}
$p = gameAction('getPlayerInfo', $sid);
if ($p['cash'] < $amount) {
return 9;
}
$vac = $this->game->getLib('beta5/player');
if ($vac->call('isOnVacation', $sid) || $vac->call('isOnVacation', $tid)) {
return 10;
}
gameAction('transferFunds', $sid, $tid, $amount);
return 0;
}
function handle($input)
{
$this->output = "money";
}
}
?>

View file

@ -0,0 +1,13 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array();
function handle($input) {
$this->output = "norealloc";
}
}
?>

View file

@ -0,0 +1,59 @@
<?php
class page_handler
{
var $needsAuth = true;
function checkName($n)
{
if (strlen($n) > 15)
return 1;
if (preg_match('/[^A-Za-z0-9_\.\-\+@\/'."'".' ]/', $n))
return 2;
if ( preg_match('/^\s/', $n)
|| preg_match('/\s$/', $n)
)
return 3;
if (preg_match('/\s\s+/', $n))
return 4;
if (strlen($n) < 2)
return 5;
return 0;
}
function handle($input) {
if ($this->game->params['norealloc'] == 1) {
$this->output = 'norealloc';
return;
}
$this->output = 'nplanet';
$pl = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
if (count($pl))
{
$this->data = false;
return;
}
if ($input['name'] == '')
{
$this->data = array('ok' => false, 'err' => 0, 'name' => '');
return;
}
$pErr = $this->checkName($input['name']);
if (!$pErr)
{
$p = gameAction('getPlanetByName', $input['name']);
if (!is_null($p))
$pErr = 6;
}
if ($pErr)
{
$this->data = array('ok' => false, 'err' => $pErr, 'name' => $input['name']);
return;
}
$nplanet = gameAction('reassignPlanet', $_SESSION[game::sessName()]['player'], $input['name']);
$this->data = array('ok' => true, 'name' => $input['name'], 'id' => $nplanet);
}
}

View file

@ -0,0 +1,87 @@
<?php
class page_handler {
public $needsAuth = true;
public $ajax = array(
'func' => array('getOverview', 'switchOvMode', 'breakProtection'),
'init' => "makeOverviewTooltips();\ninitPage();"
);
public function getOverview() {
$overview = $this->game->action('getOverview', $_SESSION[game::sessName()]['player'],
getLanguage());
$result = array($_SESSION[game::sessName()]['ov_complete'] ? "1" : "0");
// Protection level
array_push($result, $overview['protection']);
// Communications overview
$data = $overview['comms'];
array_push($result, count($data['folders']['CUS']) . "#" . count($data['forums']['general'])
. "#" . count($data['forums']['alliance']) . "#" . $data['forums']['allianceID']);
// Messages in default folders
$dFld = array('IN', 'INT', 'OUT');
foreach ($dFld as $f) {
array_push($result, join('#', $data['folders'][$f]));
}
// Custom folders
foreach ($data['folders']['CUS'] as $id => $folder) {
$folder[2] = utf8entities($folder[2]);
array_unshift($folder, $id);
array_push($result, join('#', $folder));
}
// Forums
foreach ($data['forums']['general'] as $cat) {
array_push($result, "{$cat['id']}#{$cat['type']}#" . count($cat['forums'])
. "#" . utf8entities($cat['title']));
foreach ($cat['forums'] as $f) {
$f[3] = utf8entities($f[3]);
array_push($result, join('#', $f));
}
}
foreach ($data['forums']['alliance'] as $f) {
$f[3] = utf8entities($f[3]);
array_push($result, join('#', $f));
}
// Empire overview
$data = $overview['empire'];
array_push($result, join('#', $data['planetStats']));
array_push($result, "{$data['fleetStats']['power']}#{$data['fleetStats']['fleets']}"
. "#{$data['fleetStats']['battle']}");
array_push($result, "{$data['income']}#{$data['fleetStats']['upkeep']}");
array_push($result, $data['techStats']['new']);
// Universe overview
$data = $overview['universe'];
array_push($result, $data['summary'][0] . "#" . $data['summary'][2] . "#" . $data['summary'][0]);
array_push($result, join("#", $data['rankings']));
array_push($result, time());
foreach ($data['ticks'] as $tick) {
array_push($result, join('#', $tick));
}
return join("\n", $result);
}
public function breakProtection() {
$pLib = $this->game->getLib('beta5/player');
$pLib->call('breakProtection', $_SESSION[game::sessName()]['player'], 'BRK');
return $this->getOverview();
}
public function switchOvMode() {
$_SESSION[game::sessName()]['ov_complete'] = ! $_SESSION[game::sessName()]['ov_complete'];
}
public function handle($input) {
$this->data = $this->getOverview();;
$this->output = "overview";
}
}
?>

View file

@ -0,0 +1,670 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
"func" => array(
"getPlanetList", "getPlanetData", "addToQueue",
"factoryAction", "replaceItems", "flushQueue",
"moveItems", "deleteItems", "rename",
"planetSale", "cancelSale", "abandon",
"cancelAbandon", "blowItUp", "cancelDestruction",
"getSellableFleets", "destroyTurrets"
),
"init" => "initPlanetPage();"
);
function getPlanetList() {
$l = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$str = count($l);
foreach ($l as $id => $name)
$str .= "\n$id#$name";
return $str;
}
function getPlanetData($id) {
// Get planet data
$id = (int)$id;
$info = gameAction('getPlanetById', $id);
if (is_null($info)) {
return "";
}
$pid = $_SESSION[game::sessName()]['player'];
// Build result array
$result = array(
"{$info['status']}#$id#{$info['x']}#{$info['y']}#" . ($info['orbit']+1)
. "#" . utf8entities($info['name'])
);
// Get probe report
$probeData = null; // FIXME
// Build fleets summary
$ownFleets = array_keys(gameAction('getFleetsAt', $id, $pid));
$allFleets = array_keys(gameAction('getFleetsAt', $id));
$ownSum = 0;
if (count($ownFleets) || $info['owner'] == $pid)
{
$attSum = 0;
$defSum = 0;
$ownMode = ($info['owner'] == $pid ? 1 : null);
foreach ($allFleets as $fid)
{
$finf = gameAction('getFleet', $fid);
if ($finf['owner'] == $pid)
{
if (is_null($ownMode))
$ownMode = ($finf['attacking'] == 't') ? 2 : 1;
$ownSum += gameAction('getFleetPower', $finf['owner'], 0, $finf['gaships'], $finf['fighters'], $finf['cruisers'], $finf['bcruisers']);
}
elseif ($finf['attacking'] == 't')
$attSum += gameAction('getFleetPower', $finf['owner'], 0, $finf['gaships'], $finf['fighters'], $finf['cruisers'], $finf['bcruisers']);
else
$defSum += gameAction('getFleetPower', $finf['owner'], 0, $finf['gaships'], $finf['fighters'], $finf['cruisers'], $finf['bcruisers']);
}
if (is_null($ownMode))
$ownMode = 0;
array_push($result, "$ownMode#$ownSum#$attSum#$defSum");
}
elseif (!is_null($probeData))
{
// FIXME: get fleets data from probe report
}
else
array_push($result, "0###");
// If the planet has been destroyed or is a nebula, we're done
if ($info['status'] != 0)
return join("\n", $result);
// Get owner and player data
$isOwn = ($info['owner'] == $pid);
$owner = is_null($info['owner']) ? null : gameAction('getPlayerInfo', $info['owner']);
$player = $isOwn ? $owner : gameAction('getPlayerInfo', $pid);
$protected = is_null($owner) ? false : (
$this->game->getLib('beta5/player')->call('getProtectionLevel', $info['owner']) > 0
);
$plPriv = gameAction('getAlliancePrivileges', $pid);
$vacation = ($isOwn && $info['vacation'] != 'NO ')
|| (!$isOwn && $info['vacation'] == 'YES ');
// Build planet summary:
// - isOwner
$s = ($isOwn ? 1 : 0) . "#" . ($vacation ? 1 : 0) . "#" . ($protected ? 1 : 0) . "#";
// - turrets
if ($isOwn || $ownSum || ($player['aid'] == $owner['aid'] && $plPriv['list_access'] == 3))
$s .= $info['turrets'];
elseif (!is_null($probeData))
$s .= ""; //FIXME: use probe report
$s .= "#";
// - population
if ($isOwn || $ownSum)
$s .= $info['pop'];
elseif (!is_null($probeData))
$s .= ""; //FIXME: use probe report
else
$s .= "";
$s .= "#";
// - factories
if (!$isOwn && $player['aid'] == $owner['aid'] && $plPriv['list_access'] == 3)
$s .= ((int)$info['ifact'] + (int)$info['mfact']);
elseif (!is_null($probeData)) // FIXME: don't include it if the probe got the exact amounts
$s .= ""; // FIXME: use probe report
$s .= "#";
if ($isOwn)
$s .= $info['ifact'] . "#" . $info['mfact'];
elseif (!is_null($probeData)) // FIXME: only include it if the probe got the exact amounts
$s .= "#"; // FIXME: use probe report
else
$s .= "#";
$s .= "#";
// - happiness
if ($isOwn)
$s .= $info['happiness'];
elseif (!is_null($probeData))
$s .= ""; // FIXME: use probe report
$s .= "#";
// - corruption
if ($isOwn)
$s .= round($info['corruption'] / 320);
elseif (!is_null($probeData))
$s .= ""; // FIXME: use probe report
$s .= "#";
// - profit
if ($isOwn) {
$m = gameAction('getPlanetIncome', $info['owner'], $info['pop'], $info['happiness'], $info['ifact'], $info['mfact'], $info['turrets'], $info['corruption']);
$s .= $m[0];
}
$s .= "#";
// - alliance tag
$s .= $owner['alliance'];
array_push($result, $s);
// We're done if we're not the owner
if (!$isOwn)
return join("\n", $result);
$rules = gameAction('loadPlayerRules', $pid);
// Current action
if (!is_null($info['bh_prep']))
$s = "2#".($info['bh_prep'] + 1);
elseif (!is_null($info['abandon']))
$s = "3#".($info['abandon']);
else
{
$offer = gameAction('getPlanetSale', $id);
if (is_null($offer))
{
$restr = gameAction('isPlayerRestrained', $pid);
$np = gameAction('getRealPlanetCount', $pid);
$canSell = ($restr == 0) && ($np > 1);
$q = dbQuery("SELECT bh_unhappiness FROM player WHERE id=$pid");
list($bhu) = dbFetchArray($q);
$q = dbQuery("SELECT COUNT(*) FROM planet WHERE owner=$pid AND bh_prep IS NOT NULL");
list($bhp) = dbFetchArray($q);
$canBlow = ($np > 1) && ($rules['planet_destruction'] > 0) && ($bhu < 20) && ($bhp < 4);
if ($canBlow && $this->game->params['victory'] == 2) {
// Prevent planets from being destroyed in CTF games
$ctfLib = $this->game->getLib('beta5/ctf');
$canBlow = !($ctfLib->call('isTarget', $info['system']));
}
$s = "0#" . $info['rename'] . "#" . ($canSell ? 1 : 0) . "#" . ($canBlow ? 1 : 0) . "#" . ($np > 1 ? 1 : 0);
}
else
{
$s = "1#" . (is_null($offer['finalized']) ? 0 : ($info['sale'] + 1));
$s .= "#" . $offer['sold_to'] . "#";
if (!is_null($offer['sold_to']))
$s .= utf8entities(gameAction('getPlayerName', $offer['sold_to']));
}
}
array_push($result, $s);
// Capabilities and prices
$s = $rules['military_level'] . "#" . $rules['if_cost'] . "#" . $rules['mf_cost'] . "#" . $rules['bh_cost'] . "#";
$s .= $rules['build_cost_turret'] . "#" . $rules['build_cost_gaship'] . "#" . $rules['build_cost_fighter'];
$s .= "#" . $rules['build_cost_cruiser'] . "#" . $rules['build_cost_bcruiser'];
array_push($result, $s);
// Build queue
$bq = gameAction('getBuildQueue', $id);
foreach ($bq as $bqi)
array_push($result, $bqi["type"] . "#" . $bqi['quantity'] . "#" . $bqi['time'] . "#" . $bqi['ctime']);
return join("\n", $result);
}
function factoryAction($pid, $act, $nb, $type) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
if ((int)$nb != $nb || $nb <= 0) {
return "ERR#3";
}
$t = ($type == '1') ? "m" : "i";
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
if (!in_array($pid, $ids)) {
return "ERR#-1";
}
if ($act != "1") {
$planets = $this->game->getLib('beta5/planet');
$err = $planets->call('checkBuildFactories', $pid, $nb, $t);
if ($err) {
return "ERR#" . ($err + 23);
}
} else {
$err = gameAction('checkDestroyFactories', $pid, $nb, $t);
if ($err) {
return "ERR#" . ($err + 7);
}
}
gameAction(($act == "1") ? "destroyFactories" : "buildFactories", $pid, $nb, $t);
return $this->getPlanetData($pid);
}
function addToQueue($pid, $nb, $type) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
if ((int)$nb != $nb || $nb <= 0) {
return "ERR#2";
}
$r = gameAction('loadPlayerRules', $_SESSION[game::sessName()]['player']);
$type = (int)$type;
if ($type < 0 || $type > $r['military_level'] + 2)
return "ERR#1";
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
if (!in_array($pid, $ids))
return "ERR#-1";
$types = array('turret', 'gaship', 'fighter', 'cruiser', 'bcruiser');
$cost = $r['build_cost_'.$types[$type]] * $nb;
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
if ($pinf['cash'] < $cost)
return "ERR#0";
gameAction('addToBuildQueue', $pid, $nb, $type);
return $this->getPlanetData($pid);
}
function replaceItems($pid, $items, $nb, $type) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
if ((int)$nb != $nb || $nb <= 0)
return "ERR#2";
$r = gameAction('loadPlayerRules', $_SESSION[game::sessName()]['player']);
if ($type < 0 || $type > $r['military_level'] + 2)
return "ERR#1";
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
if (!in_array($pid, $ids))
return "ERR#-1";
$lst = explode('#', $items);
if (!count($lst))
return "ERR#5";
foreach ($lst as $it)
if (!preg_match('/^[0-9]+$/', $it))
return "ERR#-2";
$types = array('turret', 'gaship', 'fighter', 'cruiser', 'bcruiser');
$icost = $r['build_cost_'.$types[$type]] * $nb;
$sum = gameAction('getReplacementCost', $pid, $lst, $icost);
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
if ($pinf['cash'] < $sum)
return "ERR#0";
gameAction('replaceItems', $pid, $lst, $nb, $type);
return $this->getPlanetData($pid);
}
function moveItems($pid, $items, $dir) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
if (!in_array($pid, $ids))
return "ERR#-1";
$lst = explode('#', $items);
if (!count($lst))
return 5;
foreach ($lst as $li)
if (!preg_match('/^[0-9]+$/', $li))
return "ERR#-2";
sort($lst);
if ($dir != '1')
{
$bql = gameAction('getQueueLength', $pid);
if ($lst[0] >= $bql - 1)
return "ERR#8";
$lst = array_reverse($lst);
}
elseif ($lst[0] == 0)
return "ERR#7";
$ga = ($dir == '1') ? "Up" : "Down";
foreach ($lst as $it)
gameAction('moveItem' . $ga, $pid, $it);
return $this->getPlanetData($pid);
}
function deleteItems($pid, $sel) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
if (!in_array($pid, $ids))
return "ERR#-1";
$items = explode('#', $sel);
if (!count($items))
return "ERR#5";
foreach ($items as $i)
{
if (!preg_match('/^[0-9]+$/', $i))
continue;
gameAction('deleteBuildQueueItem', $pid, $i);
}
gameAction('reorderBuildQueue', $pid);
return $this->getPlanetData($pid);
}
function flushQueue($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
if (!in_array($pid, $ids))
return "ERR#-1";
gameAction('flushBuildQueue', $pid);
return $this->getPlanetData($pid);
}
function rename($pid, $name) {
$player = $_SESSION[game::sessName()]['player'];
$playerLib = $this->game->getLib('beta5/player');
if ($playerLib->call('isOnVacation', $player)) {
return "ERR#200";
}
$plp = $playerLib->call('getPlanets', $player);
$ids = array_keys($plp);
if (!in_array($pid, $ids)) {
return "ERR#-1";
}
$n = trim($name);
$err = $this->game->getLib()->call('checkPlanetName', $n);
if ($err) {
if ($err == 6) {
return "ERR#38";
}
return "ERR#". ($err + 12);
}
$planetLib = $this->game->getLib('beta5/planet');
$salesLib = $this->game->getLib('beta5/sale');
$info = $planetLib->call('byId', $pid);
$offer = $salesLib->call('getPlanetSale', $pid);
if (is_null($info['abandon']) && is_null($info['bh_prep']) && $info['rename'] && is_null($offer)) {
$planetLib->call('rename', $pid, $n);
}
return $this->getPlanetData($pid);
}
function planetSale($pid, $mode, $player, $price, $expires, $fleets) {
$cPlayer = $_SESSION[game::sessName()]['player'];
if (gameAction('isOnVacation', $cPlayer)) {
return "ERR#200";
} elseif (gameAction('getProtectionLevel', $cPlayer)) {
return "ERR#201";
}
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$info = gameAction('getPlanetById', $pid);
$offer = gameAction('getPlanetSale', $pid);
if (!(is_null($info['abandon']) && is_null($info['bh_prep']) && is_null($offer)))
return "ERR#-1";
$restr = gameAction('isPlayerRestrained', $cPlayer);
$np = gameAction('getRealPlanetCount', $cPlayer);
if ($restr > 0 || $np <= 1)
return "ERR#-1";
$mode = (int)$mode;
if ($mode < 0 || $mode > 3)
return "ERR#-1";
if ($mode < 2)
{
$player = trim($player);
if ($player == '')
return "ERR#1";
$tPid = gameAction('getPlayer', $player);
if (is_null($tPid))
return "ERR#4";
elseif ($tPid == $cPlayer) {
return "ERR#6";
} elseif (gameAction('getProtectionLevel', $tPid)) {
return "ERR#5";
}
}
else
$tPid = null;
if ($mode != 0)
{
$price = (int)$price;
if ($price <= 0)
return "ERR#2";
}
else
$price = 0;
$expOk = array(0, 6, 12, 24, 48, 72, 96, 120);
$expires = (int)$expires;
if (!in_array($expires,$expOk))
return "ERR#-1";
elseif ($mode == 3 && $expires == 0)
return "ERR#3";
// Check fleets
if ($fleets != "")
{
$sFleets = split('#', $fleets);
$flist = array_keys(gameAction('getFleetsAt', $pid, $cPlayer));
foreach ($sFleets as $fid)
{
if (!in_array($fid, $flist))
return "ERR#7";
$f = gameAction('getFleet', $fid);
if ($f['can_move'] != 'Y' || !is_null($fleet['sale_info']) || !is_null($fleet['sale']))
return "ERR#8";
}
}
else
$sFleets = array();
// Merge fleets
if (count($sFleets) > 1)
{
$tmp = gameAction('mergeFleets', $sFleets, array($cPlayer), '');
$fleet = $tmp[0];
}
elseif (count($sFleets))
$fleet = $sFleets[0];
else
$fleet = null;
gameAction('newSale', $cPlayer, ($mode>1), ($mode == 3), $expires, $price, $tPid, $pid, $fleet);
return $this->getPlanetData($pid);
}
function abandon($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$info = gameAction('getPlanetById', $pid);
$offer = gameAction('getPlanetSale', $pid);
if (!(is_null($info['abandon']) && is_null($info['bh_prep']) && is_null($offer)))
return "ERR#-1";
$np = gameAction('getRealPlanetCount', $cPlayer);
if ($np <= 1)
return "ERR#-1";
gameAction('setPlanetAbandon', $pid);
return $this->getPlanetData($pid);
}
function cancelAbandon($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$info = gameAction('getPlanetById', $pid);
if (is_null($info['abandon']))
return "ERR#-1";
gameAction('setPlanetAbandon', $pid, false);
return $this->getPlanetData($pid);
}
function cancelSale($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$offer = gameAction('getPlanetSale', $pid);
if (is_null($offer))
return "ERR#-1";
if (is_null($offer['finalized']))
gameAction('cancelSale', $cPlayer, $offer['id']);
elseif (!gameAction('cancelTransfer', $cPlayer, $offer['id']))
return "ERR#18";
return $this->getPlanetData($pid);
}
function blowItUp($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids)) {
return "ERR#-1";
}
$info = gameAction('getPlanetById', $pid);
$offer = gameAction('getPlanetSale', $pid);
if (!(is_null($info['abandon']) && is_null($info['bh_prep']) && is_null($offer))) {
return "ERR#-1";
}
$rules = gameAction('loadPlayerRules', $cPlayer);
$np = gameAction('getRealPlanetCount', $cPlayer);
$q = dbQuery("SELECT bh_unhappiness FROM player WHERE id=$cPlayer");
list($bhu) = dbFetchArray($q);
$q = dbQuery("SELECT COUNT(*) FROM planet WHERE owner=$pid AND bh_prep IS NOT NULL");
list($bhp) = dbFetchArray($q);
$canBlow = ($np > 1) && ($rules['planet_destruction'] > 0) && ($bhu < 20) && ($bhp < 4);
if ($canBlow && $this->game->params['victory'] == 2) {
// Prevent planets from being destroyed in CTF games
$ctfLib = $this->game->getLib('beta5/ctf');
$canBlow = !($ctfLib->call('isTarget', $info['system']));
}
if (! $canBlow) {
return "ERR#-1";
}
gameAction('setPlanetBoom', $pid);
return $this->getPlanetData($pid);
}
function cancelDestruction($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$info = gameAction('getPlanetById', $pid);
if (is_null($info['bh_prep']))
return "ERR#-1";
gameAction('setPlanetBoom', $pid, false);
return $this->getPlanetData($pid);
}
function getSellableFleets($pid)
{
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$fleets = array_keys(gameAction('getFleetsAt', $pid, $cPlayer));
$rv = array();
foreach ($fleets as $fid)
{
$f = gameAction('getFleet', $fid);
if ($f['can_move'] != 'Y' || !is_null($fleet['sale_info']) || !is_null($fleet['sale']))
continue;
$s = "$fid#" . $f['gaships'] . "#" . $f['fighters'] . "#" . $f['cruisers'] . "#" . $f['bcruisers'] . "#";
$s .= gameAction('getFleetPower', $cPlayer, 0, $f['gaships'], $f['fighters'], $f['cruisers'], $f['bcruisers']) . "#";
$s .= utf8entities($f['name']);
array_push($rv, $s);
}
return join("\n", $rv);
}
function destroyTurrets($pid, $turrets) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$cPlayer = $_SESSION[game::sessName()]['player'];
$ids = array_keys(gameAction('getPlayerPlanets', $cPlayer));
if (!in_array($pid, $ids))
return "ERR#-1";
$turrets = (int)$turrets;
if ($turrets <= 0)
return "ERR#19";
$err = gameAction('destroyTurrets', $pid, $turrets);
if ($err > 0)
return "ERR#" . ($err + 19);
return $this->getPlanetData($pid);
}
function handle($input)
{
if (!preg_match('/^[0-9]+$/', $input['id'])) {
logText("****** BUG? Planet not found: '{$input['id']}' (from {$_SERVER['HTTP_REFERER']})", LOG_DEBUG);
$this->output = "planetnf";
return;
}
$info = gameAction('getPlanetById', $input['id']);
if (is_null($info))
{
$this->output = "planetnf";
return;
}
$this->data = array(
'id' => $input['id'],
'plist' => $this->getPlanetList(),
'pdata' => $this->getPlanetData($input['id'])
);
$this->output = "planet";
}
}
?>

View file

@ -0,0 +1,13 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array();
function handle($input) {
$this->output = "planetnf";
}
}
?>

View file

@ -0,0 +1,311 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
"func" => array(
"getInitVals", "getPlanetList", "setMode",
"setCumulative", "getMilitaryLevel",
"flushQueues", "addToQueues", "factoryAction",
"deleteItems", "moveItems", "replaceItems"
),
"init" => "makePlanetsTooltips();\nx_getInitVals(initGetMode);"
);
function getPlanetList() {
$str = "";
$l = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
foreach ($l as $id => $name) {
$info = gameAction('getPlanetById', $id);
if ($str != "")
$str .= "\n";
$str .= "$id#" . $info["x"] . "#" . $info["y"] . "#" . ($info['orbit'] + 1);
$str .= "#" . $info["pop"] . '#' . $info['happiness'];
$str .= "#" . $info["ifact"] . '#' . $info['turrets'];
$str .= "#" . $info["mfact"] . '#';
$m = gameAction('getPlanetIncome', $info['owner'], $info['pop'], $info['happiness'], $info['ifact'], $info['mfact'], $info['turrets'], $info['corruption']);
$str .= $m[0] . "#" . round($info['corruption'] / 320);
$str .= "\n$name\n";
$bq = gameAction('getBuildQueue', $id);
$bqs = '';
foreach ($bq as $bqi)
{
if ($bqs != "")
$bqs .= "#";
$bqs .= $bqi["type"] . "#" . $bqi['quantity'] . "#" . $bqi['time'] . "#" . $bqi['ctime'];
}
$str .= $bqs;
}
return $str;
}
function getInitVals() {
$vac = gameAction('isOnVacation', $_SESSION[game::sessName()]['player']);
if (is_null($_SESSION[game::sessName()]['quick_builder']) || $vac) {
$_SESSION[game::sessName()]['quick_builder'] = false;
}
if (is_null($_SESSION[game::sessName()]['plist_cumulative'])) {
$_SESSION[game::sessName()]['plist_cumulative'] = true;
}
return ($_SESSION[game::sessName()]['quick_builder'] ? "1" : "0") . '#' . ($_SESSION[game::sessName()]['plist_cumulative'] ? "1" : "0")
. "#" . ($vac ? 1 : 0);
}
function setMode($val) {
$vac = gameAction('isOnVacation', $_SESSION[game::sessName()]['player']);
$_SESSION[game::sessName()]['quick_builder'] = ($val == "1" && !$vac);
}
function setCumulative($val) {
$_SESSION[game::sessName()]['plist_cumulative'] = ($val == "1");
}
function getMilitaryLevel() {
$r = gameAction('loadPlayerRules', $_SESSION[game::sessName()]['player']);
if (is_null($r))
return "0";
return $r['military_level'];
}
function flushQueues($planets) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return 13;
}
$pl = explode('#', $planets);
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
foreach ($pl as $pid) {
if (!in_array($pid, $ids)) {
continue;
}
gameAction('flushBuildQueue', $pid);
}
return "OK";
}
function addToQueues($planets, $nb, $type) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return 13;
}
if ((int)$nb != $nb || $nb <= 0) {
return 2;
}
$r = gameAction('loadPlayerRules', $_SESSION[game::sessName()]['player']);
if ($type < 0 || $type > $r['military_level'] + 2) {
return -1;
}
$pl = explode('#', $planets);
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
foreach ($pl as $pid) {
if (!in_array($pid, $ids)) {
return -1;
}
}
$types = array('turret', 'gaship', 'fighter', 'cruiser', 'bcruiser');
$cost = $r['build_cost_'.$types[$type]] * $nb * count($pl);
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
if ($pinf['cash'] < $cost) {
return 4;
}
foreach ($pl as $pid) {
gameAction('addToBuildQueue', $pid, $nb, $type);
}
return "OK";
}
function factoryAction($planets, $act, $nb, $type) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return 13;
}
if ((int)$nb != $nb || $nb <= 0) {
return 3;
}
$t = ($type == '1') ? "m" : "i";
$r = gameAction('loadPlayerRules', $_SESSION[game::sessName()]['player']);
$pl = explode('#', $planets);
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
foreach ($pl as $pid) {
if (!in_array($pid, $ids)) {
return -1;
}
}
if ($act != "1") {
// Check cash first
$cost = $nb * $r[$t . 'f_cost'] * count($pl) ;
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
if ($pinf['cash'] < $cost) {
return 4;
}
// Now check other planet details
$planets = $this->game->getLib('beta5/planet');
foreach ($pl as $pid) {
$err = $planets->call('checkBuildFactories', $pid, $nb, $t);
if ($err) {
return $err + 13;
}
}
} else {
foreach ($pl as $pid) {
$err = gameAction('checkDestroyFactories', $pid, $nb, $t);
if ($err) {
return $err + 4;
}
}
}
$ga = ($act == "1") ? "destroyFactories" : "buildFactories";
foreach ($pl as $pid) {
gameAction($ga, $pid, $nb, $t);
}
return "OK";
}
function deleteItems($items) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return 13;
}
$lst = explode('#', $items);
$items = array();
foreach ($lst as $i) {
array_push($items, explode('-', $i));
}
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
$pll = array();
foreach ($items as $i)
{
list($pl, $it) = $i;
if (!(in_array($pl, $ids) && preg_match('/^[0-9]+$/', $it)))
continue;
if (!in_array($pl, $pll))
array_push($pll, $pl);
gameAction('deleteBuildQueueItem', $pl, $it);
}
foreach ($pll as $pid)
gameAction('reorderBuildQueue', $pid);
return "OK";
}
function replaceItems($items, $nb, $type) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return 13;
}
if ((int)$nb != $nb || $nb <= 0)
return 2;
$r = gameAction('loadPlayerRules', $_SESSION[game::sessName()]['player']);
if ($type < 0 || $type > $r['military_level'] + 2)
return -1;
$lst = explode('#', $items);
$rList = array();
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
foreach ($lst as $li)
{
list($pl,$it) = explode('-', $li);
if (!is_array($rList[$pl]))
{
if (!in_array($pl, $ids))
return -1;
$rList[$pl] = array();
}
if (!preg_match('/^[0-9]+$/', $it))
return -1;
array_push($rList[$pl], $it);
}
$types = array('turret', 'gaship', 'fighter', 'cruiser', 'bcruiser');
$icost = $r['build_cost_'.$types[$type]] * $nb;
$ids = array_keys($rList);
$sum = 0;
foreach ($ids as $pl)
$sum += gameAction('getReplacementCost', $pl, $rList[$pl], $icost);
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
if ($pinf['cash'] < $sum)
return 4;
foreach ($ids as $pl)
gameAction('replaceItems', $pl, $rList[$pl], $nb, $type);
return "OK";
}
function moveItems($items, $dir) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return 13;
}
$lst = explode('#', $items);
$rList = array();
$plp = gameAction('getPlayerPlanets', $_SESSION[game::sessName()]['player']);
$ids = array_keys($plp);
foreach ($lst as $li)
{
list($pl,$it) = explode('-', $li);
if (!is_array($rList[$pl]))
{
if (!in_array($pl, $ids))
return -1;
$rList[$pl] = array();
}
if (!preg_match('/^[0-9]+$/', $it))
return -1;
array_push($rList[$pl], $it);
}
$ids = array_keys($rList);
foreach ($ids as $pl)
{
sort($rList[$pl]);
if ($dir != '1')
{
$bql = gameAction('getQueueLength', $pl);
if ($rList[$pl][0] >= $bql - 1)
return 12;
$rList[$pl] = array_reverse($rList[$pl]);
}
elseif ($rList[$pl][0] == 0)
return 11;
}
$ga = ($dir == '1') ? "Up" : "Down";
foreach ($ids as $pl)
{
foreach ($rList[$pl] as $it)
gameAction('moveItem' . $ga, $pl, $it);
}
return "OK";
}
function handle($input) {
$this->output = "planets";
}
}
?>

View file

@ -0,0 +1,245 @@
<?php
class page_handler {
var $engines = array('redirect', 'xml');
var $defaultEngine = 'redirect';
private function getRanking($type, $name) {
$rt = $this->rankings->call('getType', $type);
$r = $this->rankings->call('get', $rt, $name);
return $r;
}
private function player($id) {
$pinf = $this->players->call('get', $id);
// Basic player data
$data = new data_node('Player');
$data->setAttribute('id', $id);
$data->setAttribute('name', $pinf['name']);
$data->setAttribute('cash', $pinf['cash']);
// Alliance
if ($pinf['aid'] || $pinf['arid']) {
$aData = new data_leaf('Alliance');
if ($pinf['aid']) {
$aData->setAttribute('inalliance', 1);
$tag = $pinf['alliance'];
} else {
$aData->setAttribute('inalliance', 0);
$tag = $pinf['alliance_req'];
}
$aData->setAttribute('tag', $tag);
$data->addContents($aData);
}
// Rankings
$data->addContents($rankings = new data_node('Rankings'));
$rankings->setAttribute('players', $this->beta5->call('getPlayerCount'));
$rkTypes = array(
'p_general' => 'General',
'p_civ' => 'Civilian',
'p_financial' => 'Financial',
'p_military' => 'Military',
'p_round' => 'Overall Round',
'p_idr' => 'Inflicted Damage'
);
foreach ($rkTypes as $type => $name) {
$r = $this->getRanking($type, $pinf['name']);
if (!$r) {
continue;
}
$rt = new data_leaf('Ranking', "$name Ranking");
$rt->setAttribute('points', $r['points']);
$rt->setAttribute('rank', $r['ranking']);
$rankings->addContents($rt);
}
return $data;
}
private function empire($pid) {
$empire = new data_node('Empire');
// Planet statistics
$empire->addContents($planets = new data_node('Planets'));
$pld = $this->planets->call('getStats', $pid);
$planets->setAttribute('count', $pld[0]);
$planets->setAttribute('avgHap', $pld[1]);
$planets->setAttribute('totPop', $pld[2]);
$planets->setAttribute('avgPop', $pld[3]);
$planets->setAttribute('totFac', $pld[4]);
$planets->setAttribute('avgFac', $pld[5]);
$planets->setAttribute('totTur', $pld[6]);
$planets->setAttribute('avgTur', $pld[7]);
$planets->setAttribute('siege', $pld[8]);
$planets->setAttribute('avgCor', $pld[9]);
// Planet list and income
$income = 0;
if ($pld[0] > 0) {
$planets->addContents($plist = new data_node('List'));
$l = $this->players->call('getPlanets', $pid);
foreach ($l as $id => $name) {
$p = new data_leaf('Planet', $name);
$p->setAttribute('id', $id);
$plist->addContents($p);
$info = $this->planets->call('byId', $id);
$m = $this->planets->call('getIncome', $pid, $info['pop'], $info['happ'], $info['ifact'], $info['mfact'], $info['turrets'], $info['corruption']);
$income += $m[0];
}
}
// Fleets
$empire->addContents($fleets = new data_node('Fleets'));
$fs = $this->fleets->call('getStats', $pid);
$fleets->setAttribute('count', $fs['fleets']);
$fleets->setAttribute('inBattle', $fs['battle']);
$copy = array('power', 'gaships', 'fighters', 'cruisers', 'bcruisers');
foreach ($copy as $name) {
$fleets->setAttribute($name, $fs[$name]);
}
// Income and upkeep
$empire->addContents($budget = new data_node('Budget'));
$budget->setAttribute('income', $income);
$budget->setAttribute('upkeep', $fs['upkeep']);
$budget->setAttribute('profit', $income - $fs['upkeep']);
// Research
$empire->addContents($research = new data_node('Research'));
$research->setAttribute('points', $this->techs->call('getPoints', $pid));
$research->setAttribute('new', count($this->techs->call('getTopics', $pid, 0)));
$research->setAttribute('foreseen', count($this->techs->call('getTopics', $pid, -1)) / 2);
// Research budget
$research->addContents($rBudget = new data_node('RBudget'));
$rb = $this->techs->call('getBudget', $pid);
$attrs = array('fundamental', 'military', 'civilian');
for ($i=0;$i<count($attrs);$i++) {
$rBudget->setAttribute($attrs[$i], $rb[$i]);
}
return $empire;
}
private function ticks() {
$lib = $this->game->getLib('main');
$tinf = $lib->call('getTicks', getLanguage());
$ticks = new data_node('Ticks');
foreach ($tinf as $tid => $td) {
if (!$td['game']) {
continue;
}
$ticks->addContents($tick = new data_leaf('Tick', $td['name']));
$tick->setAttribute('first', $td['first']);
$tick->setAttribute('interval', $td['interval']);
if ($td['last']) {
$tick->setAttribute('last', $td['last']);
}
}
return $ticks;
}
private function communications($pid) {
$comms = new data_node('Communications');
$comms->addContents($messages = new data_node('Messages'));
$comms->addContents($forums = new data_node('Forums'));
// Get custom folders and forum structure
$cfold = $this->msgs->call('getCustomFolders', $pid);
$cats = $this->forums->call('getStructure', $pid);
// Messages in default folders
$dfld = array('IN', 'INT', 'OUT');
foreach ($dfld as $f) {
$messages->addContents($node = new data_leaf('DefaultFolder'));
$node->setAttribute('id', $f);
$node->setAttribute('all', $this->msgs->call('getAll', $pid, $f));
$node->setAttribute('new', $this->msgs->call('getNew', $pid, $f));
}
// Custom folders
foreach ($cfold as $cfid => $cfn) {
$messages->addContents($node = new data_leaf('CustomFolder', utf8_encode($cfn)));
$node->setAttribute('id', $cfid);
$node->setAttribute('all', $this->msgs->call('getAll', $pid, 'CUS', $cfid));
$node->setAttribute('new', $this->msgs->call('getNew', $pid, 'CUS', $cfid));
}
// Forums
foreach ($cats as $c) {
if (!count($c['forums'])) {
continue;
}
if ($c['type'] == 'A') {
$forums->addContents($category = new data_node('AllianceForums'));
} else {
$forums->addContents($category = new data_node('GeneralForums'));
$category->addContents($cdesc = new data_leaf('Description', utf8_encode($c['title'])));
$cdesc->setAttribute('id', $c['id']);
$cdesc->setAttribute('type', $c['type']);
}
foreach ($c['forums'] as $f) {
$category->addContents($forum = new data_leaf('Forum', utf8_encode($f['title'])));
$forum->setAttribute('id', $f['id']);
$forum->setAttribute('topics', $f['topics']);
$forum->setAttribute('unread', $f['unread']);
}
}
return $comms;
}
function xml($input) {
if (!$_SESSION['authok']) {
return null;
}
$pid = $_SESSION[game::sessName()]['player'];
$this->beta5 = $this->game->getLib('beta5');
$this->forums = $this->game->getLib('beta5/forums');
$this->fleets = $this->game->getLib('beta5/fleet');
$this->msgs = $this->game->getLib('beta5/msg');
$this->planets = $this->game->getLib('beta5/planet');
$this->players = $this->game->getLib('beta5/player');
$this->rankings = $this->game->getLib('main/rankings');
$this->techs = $this->game->getLib('beta5/tech');
$data = new data_node('Overview');
$data->setAttribute('serverTime', time());
$data->addContents($this->player($pid));
$data->addContents($this->empire($pid));
$data->addContents($this->ticks());
$data->addContents($this->communications($pid));
return $data;
}
function redirect($input) {
$this->accounts = $this->game->getLib('main/account');
if (!is_null($_SESSION['userid'])) {
$isAdmin = $this->accounts->call('isAdmin', $_SESSION['userid']);
} else {
$isAdmin = false;
}
return $isAdmin ? "admin" : "overview";
}
}
?>

View file

@ -0,0 +1,142 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array();
function checkMail($a) {
return preg_match(
'/^[A-Za-z0-9_\.\-\+]+@([A-Za-z0-9_\.\-\+]+)+\.[A-Za-z]{2,6}/',
$a
);
}
function checkPassword($op, $np, $cp) {
$q = dbQuery("SELECT password FROM account WHERE id=".$_SESSION['userid']);
if (!$q) {
$this->passError = 1;
return;
}
list($rop) = dbFetchArray($q);
if ($rop != $op)
$this->passError = 2;
elseif ($np != $cp)
$this->passError = 3;
elseif (strlen($np) < 4)
$this->passError = 4;
elseif (strlen($np) > 64)
$this->passError = 5;
elseif ($np == $_SESSION['login'])
$this->passError = 6;
else
{
$p = addslashes($np);
$op = addslashes($rop);
dbQuery(
"INSERT INTO pass_change (account, old_pass, new_pass) "
. "VALUES({$_SESSION['userid']}, '$op', '$p')"
);
$q = dbQuery("UPDATE account SET password='$p' WHERE id=".$_SESSION['userid']);
if (!$q) {
$this->passError = 1;
}
}
}
function checkFormData($input)
{
$pLang = array('fr', 'en');
if (in_array($input['lang'], $pLang))
prefs::set('main/language', $input['lang']);
$pCol = array('red','green','blue','yellow','grey','purple');
if (in_array($input['col'], $pCol))
prefs::set('main/colour', $input['col']);
$themes = array('default','invert','classic','cripes');
if (in_array($input['thm'], $themes)) {
prefs::set('beta5/theme', $input['thm']);
if ($input['thm'] == 'cripes') {
$input['tt'] = 0;
}
}
if (preg_match('/^[0-4]$/', $input['fs']))
prefs::set('main/font_size', $input['fs']);
if ($this->checkMail($input['mail']))
dbQuery("UPDATE account SET email='".$input['mail']."' WHERE id=".$_SESSION['userid']);
else
$this->mailError = preg_replace('/"/', '&quot;', $input['mail']);
$tt = (int)$input['tt'];
if ($tt >= 0 && $tt <= 6)
prefs::set('main/tooltips', $tt);
if (preg_match('/^[1-5]0$/', $input['tpp']))
prefs::set('main/forums_ntopics', $input['tpp']);
if (preg_match('/^[1-5]0$/', $input['mpp']))
prefs::set('main/forums_nitems', $input['mpp']);
prefs::set('main/smileys', ($input['gsm'] == "1")?"1":"0");
prefs::set('main/forum_code', ($input['gft'] == "1")?"1":"0");
prefs::set('main/forums_threaded', ($input['fdm'] == "1")?"1":"0");
prefs::set('main/forums_reversed', ($input['fmo'] == "1")?"1":"0");
$fsig = preg_replace('/ +/', ' ', trim($input['fsig']));
if (strlen($fsig) <= 255)
prefs::set('main/forums_sig', $input['fsig']);
if ($input['opass'] != "")
$this->checkPassword($input['opass'], $input['npass'], $input['cpass']);
}
function handleQuit() {
if (gameAction('isFinished')) {
return;
}
$pid = $_SESSION[game::sessName()]['player'];
$pinf = gameAction('getPlayerInfo', $pid);
if (!is_null($pinf['qts']))
gameAction('cancelPlayerQuit', $pid);
else
gameAction('setPlayerQuit', $pid);
}
function handle($input)
{
if (!is_null($input['quit']))
$this->handleQuit();
elseif ($input['col'] != "")
$this->checkFormData($input);
$q = dbQuery("SELECT email FROM account WHERE id=".$_SESSION['userid']);
list($email) = dbFetchArray($q);
$pinf = gameAction('getPlayerInfo', $_SESSION[game::sessName()]['player']);
$this->data = array(
"lang" => getLanguage(),
"mail" => $email,
"col" => prefs::get('main/colour', 'red'),
"fs" => prefs::get('main/font_size', 2),
"err1" => $this->mailError,
"err2" => $this->passError,
"tpp" => prefs::get('main/forums_ntopics', 20),
"mpp" => prefs::get('main/forums_nitems', 20),
"gsm" => (prefs::get('main/smileys', 1) == 1),
"gft" => (prefs::get('main/forum_code', 1) == 1),
"fdm" => (prefs::get('main/forums_threaded', 1) == 1),
"fmo" => (prefs::get('main/forums_reversed', 1) == 1),
"fsig" => prefs::get('main/forums_sig', ""),
"tt" => prefs::get('main/tooltips', 2),
"thm" => prefs::get('beta5/theme', 'default'),
"quit" => $pinf['qts'],
"name" => $this->game->text,
"lok" => !(gameAction('isFinished') || $this->game->params['victory'])
);
$this->output = "preferences";
}
}
?>

View file

@ -0,0 +1,260 @@
<?php
class page_handler
{
var $needsAuth = true;
var $bcnCost = 50000;
var $bcnPow = 3;
var $ajax = array(
"func" => array(
'getPageData',
// 'setEmpirePolicy', 'togglePlanetPolicy', 'setPlanetPolicy',
'upgradeBeacon'
),
"init" => "initPage();"
);
//------------------------------------------------------------------------------
// Probes policy control
function setEmpirePolicy($element, $value)
{
$element = (int)$element; $value = (int)$value;
if ($element < 0 || $value < 0 || $element > 3 || $value > 2)
return "ERR#1";
// Get empire policy
$player = $_SESSION[game::sessName()]['player'];
$ePolicy = gameAction('getPlayerPolicy', $player);
if (is_null($ePolicy))
return "ERR#0";
// Set new value
$ePolicy{$element} = $value;
gameAction('setPlayerPolicy', $player, $ePolicy);
return "1\n$ePolicy";
}
function togglePlanetPolicy($planet)
{
// Get planet information
$player = $_SESSION[game::sessName()]['player'];
$planet = (int)$planet;
$pinf = gameAction('getPlanetById', $planet);
if (is_null($pinf))
return "ERR#1";
elseif ($pinf['owner'] != $player)
return "ERR#2";
// Get planet policy
$pPolicy = gameAction('getPlanetPolicy', $planet);
if (is_null($pPolicy))
{
$ePolicy = gameAction('getPlayerPolicy', $player);
if (is_null($ePolicy))
return "ERR#0";
$pPolicy = $ePolicy;
}
else
$pPolicy = null;
gameAction('setPlanetPolicy', $planet, $pPolicy);
return "2\n$planet#$pPolicy";
}
function setPlanetPolicy($planet, $element, $value)
{
// Check parameters
$element = (int)$element; $value = (int)$value;
if ($element < 0 || $value < 0 || $element > 3 || $value > 2)
return "ERR#1";
// Get planet information
$player = $_SESSION[game::sessName()]['player'];
$planet = (int)$planet;
$pinf = gameAction('getPlanetById', $planet);
if (is_null($pinf))
return "ERR#1";
elseif ($pinf['owner'] != $player)
return "ERR#2";
// Get planet policy
$pPolicy = gameAction('getPlanetPolicy', $planet);
if (is_null($pPolicy))
return "ERR#1";
$pPolicy{$element} = $value;
gameAction('setPlanetPolicy', $planet, $pPolicy);
return "2\n$planet#$pPolicy";
}
//------------------------------------------------------------------------------
// Beacon management functions
function getPlanetBeaconData($pid, $maxTech)
{
// Get the planet's data
$pinf = gameAction('getPlanetById', $pid);
$pinf['orbit'] ++;
$mainData = "$pid#{$pinf['x']}#{$pinf['y']}#{$pinf['orbit']}#{$pinf['beacon']}#";
// Compute the price to upgrade if that applies
if ($pinf['beacon'] < $maxTech)
$price = $this->bcnCost * pow($this->bcnPow, $pinf['beacon']);
else
$price = "";
$mainData .= "$price#" . ($pinf['built_probe'] == 't' ? 1 : 0) . "#";
// If the beacon can spot fleets standing by in Hyperspace, check for them
$reqLevel = $this->game->params['fakebeacons'] ? 1 : 2;
$hsFleets = array();
if ($pinf['beacon'] >= $reqLevel) {
$hsFleetsRaw = $this->game->getLib('beta5/planet')->call('getDetectedFleets', $pid);
foreach ($hsFleetsRaw as $fleet) {
$str = "{$fleet['i_level']}#{$fleet['fl_size']}#{$fleet['fl_owner']}#{$fleet['owner']}";
array_push($hsFleets, $str);
}
}
// Generate the return value
$mainData .= count($hsFleets) . "#" . count($mvFleets) . "#" . utf8entities($pinf['name']);
$rv = array($mainData);
if (count($hsFleets)) {
$rv = array_merge($rv, $hsFleets);
}
return $rv;
}
function upgradeBeacon($pid) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$player = $_SESSION[game::sessName()]['player'];
$pid = (int)$pid;
// Check the planet's existance, ownership and beacon/probe status
$pinf = gameAction('getPlanetById', $pid);
if (is_null($pinf) || $pinf['built_probe'] == 't')
return "ERR#0";
else if ($pinf['owner'] != $player)
return "ERR#1";
// Check the player's tech level
$rules = gameAction('loadPlayerRules', $player);
if ($pinf['beacon'] == $rules['hs_beacon_level'])
return "ERR#0";
// Check the player's cash
$plinf = gameAction('getPlayerInfo', $player);
$price = $this->bcnCost * pow($this->bcnPow, $pinf['beacon']);
if ($plinf['cash'] < $price)
return "ERR#2";
// Upgrade the beacon
dbQuery("UPDATE planet SET beacon=beacon+1,built_probe=".dbBool(1)." WHERE id=$pid");
dbQuery("UPDATE player SET cash=cash-$price WHERE id=$player");
// Generate the return value
$rv = $this->getPlanetBeaconData($pid, $rules['hs_beacon_level']);
array_unshift($rv, 1);
return join("\n", $rv);
}
//------------------------------------------------------------------------------
// Complete data generation for sub-pages
function getPageData($name)
{
$page = $this->setPage($name);
switch ($page)
{
//case "policy": return $this->getPolicyData();
case "beacons": return $this->getBeaconsData();
//case "build": return $this->getBuildData();
//case "data": return $this->getProbesData();
}
}
function getPolicyData()
{
$player = $_SESSION[game::sessName()]['player'];
// Get empire policy
$ePolicy = gameAction('getPlayerPolicy', $player);
if (is_null($ePolicy))
return "ERR#0";
// Get the player's planet-specific policies
$pPolicies = gameAction('getPlayerPlanets', $player);
foreach ($pPolicies as $id => $junk)
{
$pinf = gameAction('getPlanetById', $id);
$pPolicies[$id] = array(
$pinf['x'], $pinf['y'], $pinf['orbit'] + 1,
gameAction('getPlanetPolicy', $id),
utf8entities($pinf['name'])
);
}
// Generate output
$rv = array(0, count($pPolicies) . "#" . $ePolicy);
if (count($pPolicies))
{
foreach ($pPolicies as $id => $pPolicy)
array_push($rv, "$id#" . join("#", $pPolicy));
}
return join("\n", $rv);
}
function getBeaconsData()
{
$player = $_SESSION[game::sessName()]['player'];
// Get the player's beacon technology level
$rules = gameAction('loadPlayerRules', $player);
$beaconTech = $rules['hs_beacon_level'];
// Get the data regarding all of the player's planets
$pl = gameAction('getPlayerPlanets', $player);
$rv = array(0, "$beaconTech#" . count($pl));
foreach ($pl as $id => $name) {
$rv = array_merge($rv, $this->getPlanetBeaconData($id, $beaconTech));
}
return join("\n", $rv);
}
//------------------------------------------------------------------------------
// Sub-pages and session
function setPage($name)
{
//$okPages = array('policy', 'beacons', 'build', 'data');
$okPages = array('beacons');
if (!in_array($name, $okPages))
$name = $okPages[0];
return ($_SESSION[game::sessName()]['probe_page'] = $name);
}
function getPage()
{
if (is_null($_SESSION[game::sessName()]['probe_page']))
$_SESSION[game::sessName()]['probe_page'] = 'beacons';
return $_SESSION[game::sessName()]['probe_page'];
}
function handle($input)
{
$this->data = $this->getPage();
$this->output = "probes";
}
}
?>

View file

@ -0,0 +1,266 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
'func' => array(
'setPage', 'getPlayerData',
'getGeneralRankings', 'getDetailedRankings',
'getAllianceRankings', 'getRoundRankings',
'getDamageRankings'
),
'init' => "makeRanksTooltips();\ninitPage();"
);
function getRanking($type,$name) {
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', $type);
$r = $this->rkLib->call('get', $rt, $name);
if (!$r) {
return array('','');
}
return $r;
}
function getPlayerData($md5)
{
$pname = gameAction('getPlayerName', $_SESSION[game::sessName()]['player']);
$gr = $this->getRanking('p_general', $pname);
$cr = $this->getRanking('p_civ', $pname);
$mr = $this->getRanking('p_military', $pname);
$fr = $this->getRanking('p_financial', $pname);
$or = $this->getRanking('p_round', $pname);
$ir = $this->getRanking('p_idr', $pname);
$a = array(
$gr['points'], $gr['ranking'], $cr['points'], $cr['ranking'],
$mr['points'], $mr['ranking'], $fr['points'], $fr['ranking'],
$or['points'], $or['ranking'], $ir['points'], $ir['ranking']
);
$nmd5 = md5(serialize($a));
if ($md5 == $nmd5)
return "KEEP";
array_unshift($a, $nmd5);
return join('#', $a);
}
function setPage($page)
{
$pok = array('Summary','General','Details','Alliance','Round', 'Damage');
if (in_array($page,$pok))
$_SESSION[game::sessName()]['rkpage'] = $page;
return $_SESSION[game::sessName()]['rkpage'];
}
function getGeneralRankings($param, $md5) {
// Listing configuration
$conf = array(
"perPage" => array(5, 10, 15, 20, 25),
"sortable" => array(
"player" => SORT_STRING,
"rank" => SORT_NUMERIC,
),
"searchModes" => array("player"),
"output" => array(
"isMe", "rank", "points", "player_real"
)
);
// Get the data
$players = array();
$myName = gameAction('getPlayerName', $_SESSION[game::sessName()]['player']);
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', "p_general");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r)
array_push($players, array(
"player" => strtolower($r['id']),
"player_real" => $r['id'],
"rank" => $r['ranking'],
"points" => $r['points'],
"isMe" => ($r['id'] == $myName) ? 1 : 0
));
return gameAction('generateListing', $players, $conf, $param, $md5);
}
function getDetailedRankings($param, $md5) {
// Listing configuration
$conf = array(
"perPage" => array(5, 10, 15, 20, 25),
"sortable" => array(
"player" => SORT_STRING,
"civRank" => SORT_NUMERIC,
"milRank" => SORT_NUMERIC,
"finRank" => SORT_NUMERIC,
),
"searchModes" => array("player"),
"output" => array(
"isMe", "civRank", "civPoints",
"milRank", "milPoints", "finRank",
"finPoints", "player_real"
)
);
// Get the data
$players = array();
$myName = gameAction('getPlayerName', $_SESSION[game::sessName()]['player']);
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', "p_civ");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r)
$players[$r['id']] = array(
"player" => strtolower($r['id']),
"player_real" => $r['id'],
"civRank" => $r['ranking'],
"civPoints" => $r['points'],
"isMe" => ($r['id'] == $myName) ? 1 : 0
);
$rt = $this->rkLib->call('getType', "p_military");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r) {
$players[$r['id']]['milRank'] = $r['ranking'];
$players[$r['id']]['milPoints'] = $r['points'];
}
$rt = $this->rkLib->call('getType', "p_financial");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r) {
$players[$r['id']]['finRank'] = $r['ranking'];
$players[$r['id']]['finPoints'] = $r['points'];
}
$data = array();
foreach ($players as $id => $d)
array_push($data, $d);
return gameAction('generateListing', $data, $conf, $param, $md5);
}
function getAllianceRankings($param, $md5) {
// Listing configuration
$conf = array(
"perPage" => array(5, 10, 15, 20, 25),
"sortable" => array(
"alliance" => SORT_STRING,
"rank" => SORT_NUMERIC,
),
"searchModes" => array("alliance"),
"output" => array(
"rank", "points", "alliance_real"
)
);
// Get the data
$data = array();
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', "a_general");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r)
array_push($data, array(
"alliance" => strtolower($r['id']),
"alliance_real" => $r['id'],
"rank" => $r['ranking'],
"points" => $r['points']
));
return gameAction('generateListing', $data, $conf, $param, $md5);
}
function getRoundRankings($param, $md5) {
// Listing configuration
$conf = array(
"perPage" => array(5, 10, 15, 20, 25),
"sortable" => array(
"player" => SORT_STRING,
"rank" => SORT_NUMERIC,
),
"searchModes" => array("player"),
"output" => array(
"isMe", "rank", "points", "player_real"
)
);
// Get the data
$players = array();
$myName = gameAction('getPlayerName', $_SESSION[game::sessName()]['player']);
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', "p_round");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r)
array_push($players, array(
"player" => strtolower($r['id']),
"player_real" => $r['id'],
"rank" => $r['ranking'],
"points" => $r['points'],
"isMe" => ($r['id'] == $myName) ? 1 : 0
));
return gameAction('generateListing', $players, $conf, $param, $md5);
}
function getDamageRankings($param, $md5) {
// Listing configuration
$conf = array(
"perPage" => array(5, 10, 15, 20, 25),
"sortable" => array(
"player" => SORT_STRING,
"rank" => SORT_NUMERIC,
),
"searchModes" => array("player"),
"output" => array(
"isMe", "rank", "points", "player_real"
)
);
// Get the data
$players = array();
$myName = gameAction('getPlayerName', $_SESSION[game::sessName()]['player']);
if (! $this->rkLib) {
$this->rkLib = input::$game->getLib('main/rankings');
}
$rt = $this->rkLib->call('getType', "p_idr");
$rl = $this->rkLib->call('getAll', $rt);
foreach ($rl as $r)
array_push($players, array(
"player" => strtolower($r['id']),
"player_real" => $r['id'],
"rank" => $r['ranking'],
"points" => $r['points'],
"isMe" => ($r['id'] == $myName) ? 1 : 0
));
return gameAction('generateListing', $players, $conf, $param, $md5);
}
function handle($input)
{
switch ($input['p']):
case 's': $_SESSION[game::sessName()]['rkpage'] = 'Summary'; break;
case 'g': $_SESSION[game::sessName()]['rkpage'] = 'General'; break;
case 'd': $_SESSION[game::sessName()]['rkpage'] = 'Details'; break;
case 'a': $_SESSION[game::sessName()]['rkpage'] = 'Alliance'; break;
case 'o': $_SESSION[game::sessName()]['rkpage'] = 'Round'; break;
case 'i': $_SESSION[game::sessName()]['rkpage'] = 'Damage'; break;
default:
if (is_null($_SESSION[game::sessName()]['rkpage']))
$_SESSION[game::sessName()]['rkpage'] = 'Summary';
break;
endswitch;
$this->data = $_SESSION[game::sessName()]['rkpage'];
$this->output = "rank";
}
}
?>

View file

@ -0,0 +1,11 @@
<?php
class page_handler {
var $needsAuth = true;
function handle($input) {
$this->output = "rat";
}
}
?>

View file

@ -0,0 +1,272 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
"func" => array(
'getMode', 'setMode', 'getDescriptions',
'getTopicsData', 'getLawsData', 'getAttributionsData',
'implementTechnology', 'switchLaw', 'validateBudget',
'getDiplomacyData', 'sendOffer', 'acceptOffer',
'declineOffer'
),
"init" => "makeResearchTooltips(); x_getMode(initResearchPage);"
);
function guessResearchMode($i)
{
switch ($i['p']) :
case 't': $_SESSION[game::sessName()]['respage_mode'] = 'Topics'; break;
case 'l': $_SESSION[game::sessName()]['respage_mode'] = 'Laws'; break;
case 'b': $_SESSION[game::sessName()]['respage_mode'] = 'Attributions'; break;
case 'd': $_SESSION[game::sessName()]['respage_mode'] = 'Diplomacy'; break;
endswitch;
if (is_null($_SESSION[game::sessName()]['respage_mode']))
$_SESSION[game::sessName()]['respage_mode'] = 'Topics';
return $_SESSION[game::sessName()]['respage_mode'];
}
function getMode()
{
if (is_null($_SESSION[game::sessName()]['respage_mode']))
return $this->guessResearchMode(array());
return $_SESSION[game::sessName()]['respage_mode'];
}
function setMode($nm)
{
$pm = array('Topics', 'Laws', 'Attributions', 'Diplomacy');
if (!in_array($nm, $pm))
return $this->guessResearchMode(array());
$_SESSION[game::sessName()]['respage_mode'] = $nm;
return $nm;
}
function getDescriptions($lst)
{
$l = getLanguage();
$a = split('#', $lst);
$s = "";
foreach ($a as $id)
{
if ((int)$id != $id)
continue;
$ns = gameAction('getResearchData', $l, $id);
if ($ns == "")
continue;
if ($s != "")
$s .= "\n";
$s .= $ns;
}
return $s;
}
function getTopicsData()
{
$pl = $_SESSION[game::sessName()]['player'];
$impl = gameAction('getResearchTopics', $pl, 1);
$disp = gameAction('getResearchTopics', $pl, 0);
$brkt = gameAction('getResearchTopics', $pl, -1);
return join("#", $impl) . "!" . join("#", $disp) . "!" . join("#", $brkt);
}
function implementTechnology($id) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
if ((int)$id != $id) {
logText("(CHEAT) research/implement received weird ID from user {$_SESSION['userid']}");
return "ERR#1";
}
return (gameAction('implementTechnology', $_SESSION[game::sessName()]['player'], $id) ? "OK" : "ERR#0");
}
function getLawsData() {
return join('#', gameAction('getLaws', $_SESSION[game::sessName()]['player']));
}
function switchLaw($id) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
if ((int)$id != $id) {
return "ERR#1";
}
return (gameAction('switchLaw', $_SESSION[game::sessName()]['player'], $id) ? "OK" : "ERR#0");
}
function getAttributionsData() {
$pl = $_SESSION[game::sessName()]['player'];
$a = array(gameAction('getResearchPoints', $pl));
$b = gameAction('getResearchBudget', $pl);
$a = array_merge($a, $b);
return join('#', $a);
}
function validateBudget($b) {
if (gameAction('isOnVacation', $_SESSION[game::sessName()]['player'])) {
return "ERR#200";
}
$a = split('#', $b);
if (count($a) != 3) {
return "ERR#0";
}
$s = 0;
for ($i=0;$i<count($a);$i++) {
$s += $a[$i];
if ((int)$a[$i] != $a[$i] || $a[$i] < 0 || $s > 100) {
return "ERR#0";
}
}
gameAction('setResearchBudget', $_SESSION[game::sessName()]['player'], $a);
return "OK";
}
function getDiplomacyData()
{
$pl = $_SESSION[game::sessName()]['player'];
$pr = gameAction('isPlayerRestrained', $pl);
if ($pr > 0)
return $pr;
$impl = gameAction('getResearchTopics', $pl, 1);
$impl = array_merge($impl, gameAction('getResearchTopics', $pl, 0));
$time = $this->game->ticks['day']->interval - $this->game->ticks['hour']->interval * 2;
$s1 = $time . "\n" . join('#',$impl);
$laws = gameAction('getLaws', $pl);
for ($i=0;$i<count($laws);$i+=2)
{
if ($s1 != "")
$s1 .= "#";
$s1 .= $laws[$i];
}
$ol = gameAction('getResearchOffers', $pl);
$str = "";
foreach ($ol as $o)
{
$str .= "\n".$o['id']."#".$o['type']."#".$o['status']."#".$o['price']."#".$o['tech']."#".$o['time'];
$str .= "#".$o['pending']."\n".$o['player'];
}
if ($str == "")
$str = "\n";
$str = $s1.$str;
return $str;
}
function sendOffer($ty, $tid, $pname, $pr) {
$pLib = $this->game->getLib('beta5/player');
$cpid = $_SESSION[game::sessName()]['player'];
if ($pLib->call('isOnVacation', $cpid)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $cpid)) {
return "ERR#201";
}
$pname = trim($pname);
if ($pname == "") {
return "ERR#2";
}
$tpid = $pLib->call('getPlayerId', $pname);
if (is_null($tpid)) {
return "ERR#4";
} elseif ($tpid == $cpid) {
return "ERR#6";
}
$tLib = $this->game->getLib('beta5/tech');
if ($ty == 0) {
$tid = null;
} elseif ($ty == 1) {
$tid = (int)$tid;
if (!$tLib->call('has', $cpid, $tid)) {
logText("*** CHEAT? research::sendOffer: player $cpid trying to send tech $tid");
return "ERR#5";
}
} else {
logText("*** CHEAT? research::sendOffer: player $cpid, received invalid status '$ty'");
return "ERR#8";
}
if ("$pr" != (int)$pr || $pr < 0) {
return "ERR#3";
}
if ($tLib->call('checkOffer', $cpid)) {
logText("*** CHEAT? research::sendOffer: player $cpid has already sent an offer");
return "ERR#9";
}
if ($pLib->call('isOnVacation', $tpid)) {
return "ERR#7";
} elseif ($pLib->call('getProtectionLevel', $tpid)) {
return "ERR#10";
}
$tLib->call('makeOffer', $cpid, $tpid, $tid, $pr);
return $this->getDiplomacyData();
}
function acceptOffer($oid) {
$pLib = $this->game->getLib('beta5/player');
$pid = $_SESSION[game::sessName()]['player'];
if ($pLib->call('isOnVacation', $pid)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $pid)) {
return "ERR#201";
}
$oid = (int)$oid;
$a = gameAction('acceptResearchOffer', $pid, $oid);
if ($a)
return "ERR#$a";
return $this->getDiplomacyData();
}
function declineOffer($oid) {
$pLib = $this->game->getLib('beta5/player');
$pid = $_SESSION[game::sessName()]['player'];
if ($pLib->call('isOnVacation', $pid)) {
return "ERR#200";
} elseif ($pLib->call('getProtectionLevel', $pid)) {
return "ERR#201";
}
$oid = (int)$oid;
$a = gameAction('declineResearchOffer', $pid, $oid);
if ($a)
return "ERR#$a";
return $this->getDiplomacyData();
}
function handle($input)
{
switch ($input['mode']) :
case 't':
$this->setMode('Topics');
break;
case 'l':
$this->setMode('Laws');
break;
case 'b':
$this->setMode('Attributions');
break;
case 'd':
$this->setMode('Diplomacy');
break;
default:
$this->guessResearchMode($input);
endswitch;
$this->output = "research";
}
}
?>

View file

@ -0,0 +1,490 @@
<?php
class page_handler {
/* Engine data */
public $needsAuth = true;
public $ajax = array(
"func" => array(
// General information
"getGeneralInfo", "getTechList",
// Main page
"getSubmitPage", "submitList", "sendOffer",
// Requests page
"getRequestsPage", "submitRequests",
// Alliance-wide listing
"getAllianceList", "setListOptions",
// Viewing orders
"getCurrentOrders",
// Changing orders
"getChangeOrdersData", "submitOrders"
),
"init" => "new TechTrade(document.getElementById('init-data').value)"
);
/* Valid pages */
static private $subPages = array(
"Submit", "Req", "ViewList", "SOrders", "VOrders"
);
/* Libraries */
private $pLib;
private $aLib;
private $rLib;
/* Player information */
private $player;
private $pInfo;
private $vacation;
private $alliance;
private $hasRequests;
private $accessLevel;
/** This function initialises the libraries
* and checks the current player's privileges
* with regards to technology trading.
*/
private function init() {
// Get libraries
$this->pLib = $this->game->getLib('beta5/player');
$this->aLib = $this->game->getLib('beta5/alliance');
$this->rLib = $this->game->getLib('beta5/tech');
// Get player information
$this->player = $_SESSION[game::sessName()]['player'];
$this->pInfo = $this->pLib->call('get', $this->player);
$this->vacation = $this->pLib->call('isOnVacation', $this->player);
$this->alliance = $this->pInfo['aid'];
$alInfo = $this->aLib->call('get', $this->alliance);
$this->hasRequests = ($alInfo['enable_tt'] == 'R');
if (is_null($this->alliance)) {
$this->accessLevel = 0;
} else {
$privileges = $this->aLib->call('getPrivileges', $this->player);
$this->accessLevel = $privileges['tech_trade'];
}
}
/** This method tries to set the current sub-page being viewed, accounting for
* the user's privileges.
*/
private function currentPage($page = null) {
// If we're not trying to change page or if we're trying to set an invalid page,
// fetch the current page from the session.
if (is_null($page) || !in_array($page, self::$subPages)) {
$page = $_SESSION[game::sessName()]['tt_page'];
}
// Check privileges
switch ($page) {
case 'Submit': $ok = ($this->accessLevel > 0); break;
case 'Req': $ok = ($this->accessLevel > 1 && $this->hasRequests); break;
case 'ViewList': $ok = ($this->accessLevel > 2); break;
case 'SOrders': $ok = ($this->accessLevel > 3); break;
case 'VOrders': $ok = ($this->accessLevel > 3); break;
default: $ok = false; break;
}
// If the privileges are invalid, set the page
if (!$ok) {
if ($this->accessLevel == 0) {
$page = 'NoAccess';
} else {
$page = 'Submit';
}
}
return ($_SESSION[game::sessName()]['tt_page'] = $page);
}
/***************************************************************************************
* General information retrieval *
***************************************************************************************/
/** This AJAX function reads the information about the player and returns
* it. It allows the page to "know" what to display.
*/
public function getGeneralInfo() {
// Initialise the handler
$this->init();
// Get the current page
$page = $this->currentPage();
$requests = ($this->hasRequests ? 1 : 0);
return "$page#{$this->accessLevel}#$requests#{$this->alliance}#" . ($this->vacation ? 1 : 0);
}
/** This AJAX function returns the complete list of technologies as pairs
* of ID / Name lines.
*/
public function getTechList() {
// Prevent people from loading the list just for the sake of it
if ($_SESSION[game::sessName()]['tt_list']) {
return "";
}
$_SESSION[game::sessName()]['tt_list'] = true;
// Initialise the handler and get the language
$this->init();
$language = getLanguage();
// Get the list
$techList = $this->rLib->call('getAll', $language);
// Create the result
$result = array();
foreach ($techList as $id => $data) {
$line = array($id, count($data['deps']));
$line = array_merge($line, $data['deps']);
array_push($line, utf8entities($data['name']));
array_push($result, join('#', $line));
}
return join("\n", $result);
}
/***************************************************************************************
* Submission / view orders page *
***************************************************************************************/
/** This is the actual method that generates the output for the submission page.
*/
private function __submitPage() {
$result = array();
// Get last submission date
list($canSubmit, $lastSubmission, $nextSubmission) = $this->aLib->call(
'getTechSubmission', $this->player);
array_push($result, ($canSubmit ? 1 : 0) . "#$lastSubmission#$nextSubmission");
// Get orders
list($sendWhat, $toWhom, $sDate, $oDate) = $this->aLib->call('getTechOrder', $this->player, true);
if ($toWhom) {
$toName = $this->pLib->call('getName', $toWhom);
if (!$oDate) {
$canSend = !($this->vacation || $this->rLib->call('checkOffer', $this->player)) ? 1 : 0;
} else {
$canSend = 0;
}
array_push($result, "$sDate#$oDate#$canSend#$sendWhat#$toWhom#" . utf8entities($toName));
} else {
array_push($result, "-");
}
list($getWhat, $fromWhom, $sDate, $oDate) = $this->aLib->call('getTechOrder', $this->player, false);
if ($fromWhom) {
$fromName = $this->pLib->call('getName', $fromWhom);
array_push($result, "$sDate#$oDate#$getWhat#$fromWhom#" . utf8entities($fromName));
} else {
array_push($result, "-");
}
return join("\n", $result);
}
/** This AJAX function returns the contents for the submission page.
*/
public function getSubmitPage() {
// Initialise page
$this->init();
$page = $this->currentPage('Submit');
if ($page != 'Submit') {
return "FU";
}
return $this->__submitPage();
}
/** This AJAX function submits a player's technology list to his alliance
*/
public function submitList() {
// Initialise page
$this->init();
$page = $this->currentPage('Submit');
if ($page != 'Submit') {
return "FU";
}
$result = array();
// Check if the player can submit
list($canSubmit, $lastSubmission, $nextSubmission) = $this->aLib->call(
'getTechSubmission', $this->player);
if ($this->vacation || ! $canSubmit) {
return $this->__submitPage();
}
// Submit the list
$this->aLib->call('submitTechList', $this->player);
return $this->__submitPage();
}
/** This AJAX function causes a player to obey his tech trading order.
*/
public function sendOffer() {
// Initialise page
$this->init();
$page = $this->currentPage('Submit');
if ($page != 'Submit') {
return "FU";
}
$result = array();
// Check if the player can submit
list($sendWhat, $toWhom, $sDate, $oDate) = $this->aLib->call('getTechOrder', $this->player, true);
if ($toWhom) {
$canSend = !($oDate || $this->vacation || $this->rLib->call('checkOffer', $this->player));
if ($canSend) {
$this->rLib->call('makeOffer', $this->player, $toWhom, $sendWhat, 0);
$this->aLib->call('obeyOrder', $this->player);
}
}
return $this->__submitPage();
}
/***************************************************************************************
* Player requests page *
***************************************************************************************/
/** This method generates the actual requests page data.
*/
private function __requestsPage() {
// Get requests
$requests = $this->aLib->call('getTechRequests', $this->player);
// Get techs the player could request
$requestable = $this->rLib->call('getAvailableTechs', $this->player);
return join('#', $requests) . "\n" . join('#', $requestable);
}
/** This AJAX function returns the contents for the requests page.
*/
public function getRequestsPage() {
// Initialise page
$this->init();
$page = $this->currentPage('Req');
if ($page != 'Req') {
return "FU";
}
// Make sure the requests have been updated
$this->aLib->call('updateRequests', $this->player);
return $this->__requestsPage();
}
/** This AJAX function updates a player's technology requests.
*/
public function submitRequests($requests = "") {
// Initialise page
$this->init();
$page = $this->currentPage('Req');
if ($page != 'Req') {
return "FU";
}
// Parse the list
$requestable = $this->rLib->call('getAvailableTechs', $this->player);
$rawList = explode('#', $requests);
$list = array();
foreach ($rawList as $techID) {
$techID = (int) $techID;
if (in_array($techID, $list) || !in_array($techID, $requestable)) {
continue;
}
array_push($list, $techID);
}
// Make sure the requests have been updated
$this->aLib->call('setTechRequests', $this->player, $list);
return $this->__requestsPage();
}
/***************************************************************************************
* Alliance tech list page *
***************************************************************************************/
public function __allianceList() {
// Get the list itself
$aList = $this->aLib->call('getTechList', $this->alliance, $this->hasRequests);
// Generate the output string
$result = array(count($aList));
foreach ($aList as $player => $techData) {
array_push($result, "$player#{$techData['vacation']}#{$techData['submitted']}#"
. "{$techData['restrict']}#" . count($techData['list']) . "#"
. utf8entities($this->pLib->call('getName', $player)));
foreach ($techData['list'] as $tech => $status) {
array_push($result, "$tech#$status");
}
if (is_null($techData['requests'])) {
array_push($result, "");
} else {
array_push($result, join('#', $techData['requests']));
}
}
return join("\n", $result);
}
public function getAllianceList($oldMD5 = "") {
// Initialise page
$this->init();
$page = $this->currentPage('ViewList');
if ($page != 'ViewList') {
return "FU";
}
$rVal = $this->__allianceList();
$newMD5 = md5($rVal);
$nTechs = prefs::get("beta5/ttTechs", 10);
$nPlayers = prefs::get("beta5/ttPlayers", 3);
return ($oldMD5 == $newMD5) ? "NC" : "$newMD5\n$nTechs#$nPlayers\n$rVal";
}
public function setListOptions($playersPerPage, $techsPerPage) {
// Initialise page
$this->init();
$page = $this->currentPage('ViewList');
if ($page != 'ViewList') {
return;
}
$ppp = min(10, max(2, (int) $playersPerPage));
prefs::set("beta5/ttPlayers", $ppp);
$tpp = min(8, max(1, floor((int) $techsPerPage / 10))) * 10;
prefs::set("beta5/ttTechs", $tpp);
}
/***************************************************************************************
* Order viewing and management *
***************************************************************************************/
private function __getOrders() {
// Get list of orders
$orders = $this->aLib->call('getTechOrders', $this->alliance, $this->hasRequests);
// Generate output
$result = array();
foreach ($orders as $player => $pRecord) {
$pName = $this->pLib->call('getName', $player);
array_push($result, "$player#{$pRecord['sendTo']}#{$pRecord['sendTech']}"
."#{$pRecord['sendSub']}#{$pRecord['sendDone']}"
. "#{$pRecord['recvFrom']}#{$pRecord['recvTech']}"
. "#{$pRecord['recvSub']}#{$pRecord['recvDone']}#" . utf8entities($pName));
}
return join("\n", $result);
}
public function getCurrentOrders($oldMD5 = "") {
// Initialise page
$this->init();
$page = $this->currentPage('VOrders');
if ($page != 'VOrders') {
return;
}
$rVal = $this->__getOrders();
$newMD5 = md5($rVal);
return ($oldMD5 == $newMD5) ? "NC" : "$newMD5\n$rVal";
}
public function getChangeOrdersData($oldMD5 = "") {
// Initialise page
$this->init();
$page = $this->currentPage('SOrders');
if ($page != 'SOrders') {
return "FU";
}
list($lastSet, $nextSet) = $this->aLib->call('getLatestTechOrders', $this->alliance);
$rVal = "$lastSet#$nextSet";
if ($nextSet == 0) {
$rVal .= "\n" . $this->__allianceList();
}
$newMD5 = md5($rVal);
return ($oldMD5 == $newMD5) ? "NC" : "$newMD5\n$rVal";
}
public function submitOrders($orderString) {
// Initialise page
$this->init();
$page = $this->currentPage('SOrders');
if ($page != 'SOrders') {
return "FU";
}
// If the order string is not empty, extract orders
$pfx = '';
if ($orderString != '') {
$oList = explode('!', $orderString);
$orders = array();
foreach ($oList as $oText) {
$order = explode('#', $oText);
if (count($order) != 3) {
$pfx = "ERR";
break;
}
$order[0] = (int)$order[0];
$order[1] = (int)$order[1];
$order[2] = (int)$order[2];
$id = array_shift($order);
if (array_key_exists($id, $orders)) {
$pfx = "ERR";
break;
}
$orders[$id] = $order;
}
if ($pfx == '') {
$pfx = $this->aLib->call('submitTechOrders', $this->alliance, $orders) ? '' : 'ERR';
}
} else {
$pfx = 'ERR';
}
list($lastSet, $nextSet) = $this->aLib->call('getLatestTechOrders', $this->alliance);
$rVal = "$lastSet#$nextSet";
if ($nextSet == 0) {
$rVal .= "\n" . $this->__allianceList();
}
$pfx .= md5($rVal);
return "$pfx\n$rVal";
}
/***************************************************************************************
* Main page handler *
***************************************************************************************/
public function handle($input) {
$_SESSION[game::sessName()]['tt_list'] = false;
$this->output = "techtrade";
$this->data = $this->getGeneralInfo();
}
}
?>

View file

@ -0,0 +1,32 @@
<?php
class page_handler
{
var $needsAuth = true;
var $ajax = array(
'init' => 'readInitString()',
'func' => array('updateTicks')
);
function updateTicks()
{
$tickLib = $this->game->getLib('main');
$tinf = $tickLib->call('getTicks', getLanguage());
$now = time();
$dt = array($now);
foreach ($ticks as $tid => $td)
if ($td['game'])
array_push($dt, "$tid#" . $td['last']);
return join('#', $dt);
}
function handle($input)
{
$lang = getLanguage();
$tickLib = $this->game->getLib('main');
$this->data = $tickLib->call('getTicks', getLanguage());
$this->output = "ticks";
}
}
?>

View file

@ -0,0 +1,31 @@
<?php
class page_handler {
public $needsAuth = true;
public $ajax = array(
'func' => array('getInformation'),
'init' => 'initPage();'
);
public function getInformation() {
$universe = $this->game->action('getUniverseOverview',
$_SESSION[game::sessName()]['player'], getLanguage()
);
$ticks = array();
foreach ($universe['ticks'] as $tick) {
array_push($ticks, join('#', $tick));
}
$main = array(join('#', $universe['summary']), join('#', $universe['rankings']), time());
return join("\n", array_merge($main, $ticks));
}
public function handle($input) {
$this->data = $this->getInformation();
$this->output = "universe";
}
}
?>