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
scripts
config.inccontrol.pl
game
admin/beta5
beta5

63
scripts/config.inc Normal file
View file

@ -0,0 +1,63 @@
<?php
// This file contains the main configuration for a LegacyWorlds game
// engine instance
$config = array(
// Database connection parameters
"dbhost" => "localhost",
"dbuser" => "legacy",
"dbpass" => "",
"dbname" => "legacy",
// Path and URL to static contents
"staticdir" => dirname(__FILE__) . "/../site/static",
"staticurl" => "http://www.legacyworlds.com/static",
// Path to game scripts
"scriptdir" => dirname(__FILE__),
// Path to the cache
"cachedir" => "/tmp/lwcache",
// Debugging level
"debug" => 2,
// Maintenance mode
"maintenance" => null,
/*
"maintenance" => array(
// Hour/Minutes/Seconds/Month/Day/Year
"until" => mktime(10, 20, 0, 1, 11, 2007),
"reason" => "Upgrading the MySQL server."
),
*/
// Mac widget version numbers and location
"latestWidget" => 1,
"oldestWidget" => 1,
"widgetURL" => "http://www.legacyworlds.com/downloads/LegacyWorlds-Dashboard-latest.zip",
// Version numbers to make us feel good
"v_engine" => "0.85a",
"v_game" => "Beta 5",
"v_rev" => "2284",
// Control script fifo and directory
"cs_fifo" => "/tmp/.lwFifo",
"cs_path" => "/tmp/.lwControl",
// Trace users?
"trace" => array(),
// Do we need to actually send emails?
"sendmails" => false
);
if (file_exists($config['cachedir'] . "/maintenance.ser")) {
$__maintenanceFile = fopen($config['cachedir'] . "/maintenance.ser", "r");
$config['maintenance'] = unserialize(fgets($__maintenanceFile));
fclose($__maintenanceFile);
}
?>

574
scripts/control.pl Executable file
View file

@ -0,0 +1,574 @@
#!/usr/bin/perl
######################################################################
# LegacyWorlds Beta 5
# System control script
#
# Without arguments:
# should run as root; creates a FIFO from which it reads commands.
#
# With arguments:
# writes arguments to the pipe
######################################################################
###
## Configuration
#
$fifoPath = "/tmp/.lwFifo";
$ctrlPath = "/tmp/.lwControl";
$fsUser = 0;
$fsGroup = 33;
###
## Main code below
#
use IO::File;
require POSIX;
# If we have arguments, write to the FIFO and exit
if (@ARGV > 0) {
if ($ARGV[0] eq '--start') {
&start();
} elsif ($ARGV[0] eq '--stop') {
&stop();
} else {
&sendMessage(@ARGV);
exit(0);
}
}
# Find the script's path
use FindBin qw($Bin);
if (! -f "$Bin/legacyworlds.xml") {
die "$0: could not find 'legacyworlds.xml' in '$Bin'\n";
}
$lwConf = "$Bin/legacyworlds.xml";
# Fork and detach
$pid = fork();
if ($pid < 0) {
die("$0: failed to fork\n");
} elsif ($pid != 0) {
exit(0);
}
# Detach
POSIX::setsid();
close STDIN; close STDOUT; close STDERR;
open(STDIN, "</dev/null"); open(STDOUT, ">/dev/null"); open(STDERR, ">/dev/null");
# First create the pipe if it doesn't exist
if (! -p $fifoPath) {
if (-e $fifoPath) {
die "$0: '$fifoPath' is not a pipe\n";
} else {
POSIX::mkfifo($fifoPath, 0400)
or die "$0: unable to create '$fifoPath'\n";
}
}
# Set the pipe's owner and group
if ($> == 0) {
chown $fsUser, $fsGroup, $fifoPath;
} else {
chown $>, $fsGroup, $fifoPath;
}
chmod 0620, $fifoPath;
# Create the control directory if needed
if (! -d $ctrlPath) {
if (-e $ctrlPath) {
die "$0: '$ctrlPath' is not a directory\n";
} else {
mkdir $ctrlPath, 0700
or die "$0: unable to create '$ctrlPath'\n";
}
}
# Set the owner and group
if ($> == 0) {
chown $fsUser, $fsGroup, $ctrlPath;
} else {
chown $>, $fsGroup, $ctrlPath;
}
chmod 0770, $ctrlPath;
# Define commands
%commands = (
DIE => \&endController,
MERGE => \&mergeConfiguration,
TMPID => \&tickManagerID,
TMINIT => \&tickManagerStart,
TMSTOP => \&tickManagerStop,
READY => \&gameReady,
START => \&gameStart,
SETEND => \&gameEnd,
NOEND => \&gameCancelEnd,
"END" => \&gameChangeEnd,
SETDEF => \&setDefaultGame,
BOTON => \&startBot,
BOTOFF => \&killBot,
PCPID => \&proxyDetectorID,
PCON => \&startProxyDetector,
PCOFF => \&stopProxyDetector
);
# Reader loop
while (1) {
# Wait for someone to write to the pipe
close(FIFO);
open(FIFO, "< $fifoPath")
or die "$0: unable to open '$fifoPath'\n";
# Read it
$command = <FIFO>;
next unless defined $command;
chomp($command);
next if $command =~ /[^A-Za-z0-9\s]/;
# Extract the actual command
my @args = split /\s+/, $command;
$command = shift @args;
# Check if the command is allowed
next unless defined $commands{$command};
#print "Got command $command, arguments = (" . join(', ', @args) . ")\n";
&{$commands{$command}}(@args);
}
###
## Helper functions
#
sub sendMessage {
my @args = @_;
die "$0: FIFO '$fifoPath' doesn't exist\n" unless -p $fifoPath;
open(FIFO, "> $fifoPath") or die "$0: unable to open FIFO '$fifoPath'\n";
print FIFO (join(' ', @args) . "\n");
close(FIFO);
}
sub start {
$pid = fork();
if ($pid == -1) {
die "$0: could not fork\n";
} elsif ($pid) {
print "LegacyWorlds - Initialising game\n";
print " -> Controller\n";
sleep(1);
print " -> Proxy detector\n";
&sendMessage("PCON");
sleep(1);
print " -> Ticks manager\n";
&sendMessage("TMINIT");
sleep(1);
print " -> IRC bot\n";
&sendMessage("BOTON");
exit(0);
}
}
sub stop {
print "LegacyWolrds - Shutting down\n";
print " -> IRC bot\n";
&sendMessage("BOTOFF");
sleep(1);
print " -> Ticks manager\n";
&sendMessage("TMSTOP");
sleep(1);
print " -> Proxy detector\n";
&sendMessage("PCOFF");
sleep(1);
print " -> Controller\n";
&sendMessage("DIE");
exit(0);
}
###
## Command functions
#
#
# Function that terminates the controller
#
sub endController {
exit(0);
}
#
# Function that adds a new game
#
sub mergeConfiguration {
my $sourceFile = shift;
return unless -f "$ctrlPath/config.$sourceFile.xml";
# Read the new snippet
open(NEWCONF, "< $ctrlPath/config.$sourceFile.xml");
my @newConfiguration = <NEWCONF>;
close(NEWCONF);
# Read the old configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Merge it
my @merged = ();
foreach my $oldLine (@oldConfiguration) {
if ($oldLine =~ /^\s+<\/Games>\s*$/) {
@merged = (@merged, @newConfiguration, "\n");
}
@merged = (@merged, $oldLine);
}
# Write the new configuration file
open(OLDCONF, "> $lwConf");
print OLDCONF @merged;
close OLDCONF;
# Remove the source file
unlink "$ctrlPath/config.$sourceFile.xml";
}
#
# Tick manager PID update
#
sub tickManagerID {
my $pid = shift;
return unless $pid;
open(PIDFILE, "> $ctrlPath/tickManager.pid");
print PIDFILE "$pid " . time() . "\n";
close(PIDFILE);
}
#
# Start tick manager
#
sub tickManagerStart {
return if &tickManagerStatus();
return unless -f "$Bin/ticks.php";
if ($> == 0) {
system("su - lwticks");
} else {
system("cd $Bin; php ticks.php");
}
}
#
# Stop tick manager
#
sub tickManagerStop {
my $pid;
return unless ($pid = &tickManagerStatus());
kill 15, $pid;
unlink("$ctrlPath/tickManager.pid");
}
#
# Start IRC bot
#
sub startBot {
&killBot();
if ($> == 0) {
system("su - lwbot");
} else {
system("cd $Bin/../ircbot; (php bot.php &) </dev/null >/dev/null 2>&1");
}
}
#
# Stop IRC bot
#
sub killBot {
return unless -f "$ctrlPath/ircbot.pid";
my $pid = `cat $ctrlPath/ircbot.pid`;
kill 15, $pid;
unlink("$ctrlPath/ircbot.pid");
}
#
# Check tick manager status
#
sub tickManagerStatus {
return 0 unless -f "$ctrlPath/tickManager.pid";
open(PIDFILE, "< $ctrlPath/tickManager.pid");
my $data = <PIDFILE>;
close(PIDFILE);
chomp($data);
my ($pid, $time) = split / /, $data;
return (time() - $time < 22 ? $pid : 0);
}
#
# Make a game ready
#
sub gameReady {
my $gName = shift;
# Read the current configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Generate new configuration
my @newConf = ();
foreach my $line (@oldConfiguration) {
if ($line =~ /<Game\s+id="$gName".*\s+public="0"\s+canjoin="0"/) {
$line =~ s/\spublic="0"\s+canjoin="0"/ public="1" canjoin="1"/;
}
push @newConf, $line;
}
# Write configuration file
open(NEWCONF, "> $lwConf");
print NEWCONF @newConf;
close(NEWCONF);
}
#
# Start the game earlier or later
#
sub gameStart {
my $gName = shift;
my $when = shift;
return if ($when ne "EARLY" && $when ne "LATE");
$when = ($when eq 'EARLY') ? -1 : 1;
$when *= 24 * 60 * 60;
# Read the current configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Generate new configuration
my @newConf = ();
my $state = 0;
foreach my $line (@oldConfiguration) {
if ($state == 0 && $line =~ /<Game\s+id="$gName".*\s+public="1"\s+canjoin="1"/) {
$state = 1;
} elsif ($state == 1) {
if ($line =~ /<\/Game>/) {
$state = 0;
} elsif ($line =~ /<Tick\s+script="[a-z]+"\s+first="([0-9]+)"\s+interval="[0-9]+"\s*\/>/) {
my $fTick = $1;
$fTick += $when;
$line =~ s/\sfirst="[0-9]+"/ first="$fTick"/;
}
}
push @newConf, $line;
}
# Write configuration file
open(NEWCONF, "> $lwConf");
print NEWCONF @newConf;
close(NEWCONF);
}
#
# Set a running game to end
#
sub gameEnd {
my $gName = shift;
my $when = shift;
$when = $when * 60 * 60 + time();
# Read the current configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Generate new configuration
my @newConf = ();
my $state = 0;
foreach my $line (@oldConfiguration) {
if ($state == 0 && $line =~ /<Game\s+id="$gName".*\s+public="1"\s+canjoin="1"/) {
$state = 1;
} elsif ($state == 1) {
if ($line =~ /<\/Game>/) {
$state = 0;
} elsif ($line =~ /<Tick\s+script="[a-z]+"\s+first="([0-9]+)"\s+interval="[0-9]+"\s*\/>/) {
my $fTick = $1;
$line =~ s/\sfirst="[0-9]+"/ first="$fTick" last="$when"/;
}
}
push @newConf, $line;
}
# Write configuration file
open(NEWCONF, "> $lwConf");
print NEWCONF @newConf;
close(NEWCONF);
}
#
# Set an ending game's status back to running/victory
#
sub gameCancelEnd {
my $gName = shift;
# Read the current configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Generate new configuration
my @newConf = ();
my $state = 0;
foreach my $line (@oldConfiguration) {
if ($state == 0 && $line =~ /<Game\s+id="$gName".*\s+public="1"\s+canjoin="1"/) {
$state = 1;
} elsif ($state == 1) {
if ($line =~ /<\/Game>/) {
$state = 0;
} elsif ($line =~ /<Tick\s+script="[a-z]+"\s+/) {
$line =~ s/\slast="[0-9]+"//;
}
}
push @newConf, $line;
}
# Write configuration file
open(NEWCONF, "> $lwConf");
print NEWCONF @newConf;
close(NEWCONF);
}
#
# End the game earlier or later
#
sub gameChangeEnd {
my $gName = shift;
my $when = shift;
return if ($when ne "EARLY" && $when ne "LATE" && $when ne "NOW");
if ($when ne 'NOW') {
$when = ($when eq 'EARLY') ? -1 : 1;
$when *= 24 * 60 * 60;
}
# Read the current configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Generate new configuration
my @newConf = ();
my $state = 0;
foreach my $line (@oldConfiguration) {
if ($state == 0 && $line =~ /<Game\s+id="$gName".*\s+public="1"\s+canjoin="1"/) {
$state = 1;
} elsif ($state == 1) {
if ($line =~ /<\/Game>/) {
$state = 0;
} elsif ($line =~ /<Tick\s+script="[a-z]+".*\slast="([0-9]+)"/) {
my $lTick = $1;
if ($when eq 'NOW') {
$lTick = time();
} else {
$lTick += $when;
}
$line =~ s/\slast="[0-9]+"/ last="$lTick"/;
}
}
push @newConf, $line;
}
# Write configuration file
open(NEWCONF, "> $lwConf");
print NEWCONF @newConf;
close(NEWCONF);
}
#
# Changes the default game
#
sub setDefaultGame {
my $gName = shift;
return if ($gName eq "");
# Read the current configuration
open(OLDCONF, "< $lwConf");
my @oldConfiguration = <OLDCONF>;
close(OLDCONF);
# Generate new configuration
my @newConf = ();
foreach my $line (@oldConfiguration) {
if ($line =~ /<Games\s+default="[a-z0-9]+"/) {
$line =~ s/<Games\s+default="[0-9a-z]+"/<Games default="$gName"/;
}
push @newConf, $line;
}
# Write configuration file
open(NEWCONF, "> $lwConf");
print NEWCONF @newConf;
close(NEWCONF);
}
#
# Proxy detector PID update
#
sub proxyDetectorID {
my $pid = shift;
return unless $pid;
open(PIDFILE, "> $ctrlPath/proxyDetector.pid");
print PIDFILE "$pid " . time() . "\n";
close(PIDFILE);
}
#
# Start proxy detector
#
sub startProxyDetector {
return if &proxyDetectorStatus();
return unless -f "$Bin/proxycheck.php";
if ($> == 0) {
system("su - lwproxy");
} else {
system("cd $Bin; php proxycheck.php");
}
}
#
# Stop proxy detector
#
sub stopProxyDetector {
my $pid;
return unless ($pid = &proxyDetectorStatus());
kill 15, $pid;
unlink("$ctrlPath/proxyDetector.pid");
}
#
# Check proxy detector status
#
sub proxyDetectorStatus {
return 0 unless -f "$ctrlPath/proxyDetector.pid";
open(PIDFILE, "< $ctrlPath/proxyDetector.pid");
my $data = <PIDFILE>;
close(PIDFILE);
chomp($data);
my ($pid, $time) = split / /, $data;
return (time() - $time < 22 ? $pid : 0);
}

View file

@ -0,0 +1,106 @@
<?php
class admin_beta5_library {
var $index = array();
function admin_beta5_library($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->msgs = $this->lib->game->getLib('beta5/msg');
$this->planets = $this->lib->game->getLib('beta5/planet');
}
function getPlanetsModList($mode) {
$modes = array("r", "o", "p", "w");
if (!in_array($mode, $modes)) {
$mode = $modes[0];
}
$queries = array(
"r" => "SELECT id,name,owner FROM planet WHERE status = 0 AND NOT mod_check AND force_rename IS NULL ORDER BY id",
"o" => "SELECT id,name,owner FROM planet WHERE status = 0 AND mod_check AND force_rename IS NULL ORDER BY id",
"p" => "SELECT id,name,owner FROM planet WHERE status = 0 AND mod_check AND force_rename IS NOT NULL AND force_rename>renamed ORDER BY id",
"w" => "SELECT id,name,owner FROM planet WHERE status = 0 AND NOT mod_check AND force_rename IS NOT NULL ORDER BY id",
);
return array($mode,$this->db->query($queries[$mode]));
}
function validatePlanetName($id) {
$this->db->query("UPDATE planet SET mod_check=TRUE,force_rename=NULL WHERE id=$id AND status=0");
}
function resetPlanet($id, $from, $manual = true) {
$q = $this->db->query("SELECT owner,name FROM planet WHERE id=$id AND status=0");
if (!dbCount($q)) {
return;
}
list($owner, $name) = dbFetchArray($q);
do {
$rn = strtoupper(substr(md5(uniqid(rand())), 0, 7));
$q = $this->db->query("SELECT id FROM planet WHERE name='P-[$rn]'");
} while(dbCount($q));
$this->planets->call('rename', $id, "P-[$rn]");
$this->db->query("UPDATE planet SET ifact=3,mfact=3,turrets=3,pop=2000,mod_check=TRUE,force_rename=NULL WHERE id=$id");
if (!is_null($owner)) {
$this->planets->call('ownerChange', $id);
$this->msgs->call('send', $owner, 'warnname', array(
"moderator" => $from,
"planet" => $id,
"p_name" => $name,
"event" => ($manual ? 'NEUT' : 'ANEUT')
));
}
}
function sendPlanetWarning($id, $from) {
$ts = time();
$q = $this->db->query("SELECT owner,name FROM planet WHERE id=$id");
list($owner, $name) = dbFetchArray($q);
$this->db->query("UPDATE planet SET mod_check=TRUE,renamed=$ts-(16*86400),force_rename=$ts WHERE id=$id");
$this->msgs->call('send', $owner, 'warnname', array(
"moderator" => $from,
"planet" => $id,
"p_name" => $name,
"event" => 'WARN'
));
}
function sendSpam($from, $subject, $contents) {
// Create the "spam record"
$spamID = $this->db->query(
"INSERT INTO admin_spam(sent_by, subject, contents) VALUES ("
. "$from, '" . addslashes($subject) . "', '" . addslashes($contents) . "')"
);
if (!$spamID) {
logText("Admin spam '$subject' could not be sent in game " . $this->game->text, LOG_ERR);
return;
}
// Get the list of all active players
$q = $this->db->query(
"SELECT id FROM player WHERE quit IS NULL OR UNIX_TIMESTAMP(NOW()) - quit < 86400"
);
if (!($q && dbCount($q))) {
logText("Could not fetch the list of players while sending admin spam '$subject'", LOG_ERR);
return;
}
// Spam, spam, spam!
while ($r = dbFetchArray($q)) {
$this->msgs->call('send', $r[0], 'admin', array(
"spam" => $spamID
), 'IN');
}
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,120 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/addTrustedAlly.inc
//
// This action adds a player to another player's trusted allies list.
//
// Parameters:
// $player Identifier of the player whose list must be
// changed
// $allyName Name of the new trusted ally
//
// Possible return values:
// an array The trusted allies data for the player; see
// documentation for getTrustedAllies
// an integer Error; check the error codes.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_addTrustedAlly
extends game_action {
/* ERROR CODES */
const playerNotFound = 0; // Player not found
const playerOnVacation = 1; // Player is on vacation
const noAllyName = 2; // No ally name
const invalidAllyName = 3; // Invalid ally name
const allyNotFound = 4; // Ally not found
const allyIsPlayer = 5; // Ally and player are the same
const allyIsEnemy = 6; // New ally is on enemy list
const playerBlacklisted = 7; // Player is banned from the new ally's reverse list
const allyAlreadyListed = 8; // Ally already in the player's list
const maxPlayerTrust = 9; // Player already has 5 trusted allies
const maxAllyTrust = 10; // Ally already is trusted by 5 players
/***************/
public function __construct($game) {
parent::__construct($game, array(
"players" => "beta5/player"
));
}
public function run($player, $allyName) {
// Check if the player ID is not null
if (is_null($player)) {
return self::playerNotFound;
}
$player = (int) $player;
// Check if the player is valid
$playerRecord = $this->players->call('get', $player);
if (is_null($playerRecord)) {
return self::playerNotFound;
}
// Check if the player is on vacation
if ($this->players->call('isOnVacation', $player)) {
return self::playerOnVacation;
}
// Check the ally's name
$allyName = preg_replace('/\s+/', ' ', trim($allyName));
if ($allyName == "") {
return self::noAllyName;
} elseif (strlen($allyName) > 15) {
return self::invalidAllyName;
}
// Check the ally's record
$ally = $this->players->call('getPlayerId', $allyName);
if (is_null($ally)) {
return self::allyNotFound;
} elseif ($ally == $player) {
return self::allyIsPlayer;
}
// Check the enemy list
if ($this->players->call('isEnemy', $player, $ally)) {
return self::allyIsEnemy;
}
// Check the blacklist
if ($this->players->call('checkTAListBan', $ally, $player)) {
return self::playerBlacklisted;
}
// Check the player's current TA list
$taList = $this->players->call('getAllies', $player);
if (count($taList) == 5) {
return self::maxPlayerTrust;
}
foreach ($taList as $id => $data) {
if ($data['id'] == $ally) {
return self::allyAlreadyListed;
}
}
// Check the reverse TA list
$taList = $this->players->call('isAllyOf', $ally);
if (count($taList) == 5) {
return self::maxAllyTrust;
}
// Add to the player's list
$this->players->call('addAlly', $player, $ally);
// Return all trusted allies data
return $this->game->action('getTrustedAllies', $player);
}
}
?>

View file

@ -0,0 +1,101 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/banTrustingAlly.inc
//
// This action removes a player from other players' trusted allies
// lists.
//
// Parameters:
// $player The player to remove from others' lists.
// $removeList An array of the player IDs from whose lists
// the player must be removed
//
// Possible return values:
// an array The trusted allies data for the player; see
// documentation for getTrustedAllies
// an integer Error; check the error codes.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_banTrustingAlly
extends game_action {
/* ERROR CODES */
const playerNotFound = 0; // Player not found
const playerOnVacation = 1; // Player is on vacation
const emptyName = 2; // The name of the player to ban is empty
const invalidName = 3; // The name of the player to ban is invalid
const targetNotFound = 4; // The player to ban could not be found
const targetIsPlayer = 5; // The player is trying to ban himself
const alreadyBanned = 6; // This player has already been banned
/***************/
public function __construct($game) {
parent::__construct($game, array(
"players" => "beta5/player"
));
}
public function run($player, $name) {
// Check if the player ID is not null
if (is_null($player)) {
return self::playerNotFound;
}
$player = (int) $player;
// Check if the player is valid
$playerRecord = $this->players->call('get', $player);
if (is_null($playerRecord)) {
return self::playerNotFound;
}
if ($this->players->call('isOnVacation', $player)) {
return self::playerOnVacation;
}
// Check the name of the player to ban
$name = preg_replace('/\s+/', ' ', trim($name));
if ($name == "") {
return self::emptyName;
} elseif (strlen($name) > 15) {
return self::invalidName;
}
// Examine the player to ban
$toBan = $this->players->call("getPlayerId", $name);
if (is_null($toBan)) {
return self::targetNotFound;
} elseif ($toBan == $player) {
return self::targetIsPlayer;
}
// Check if the target player is already banned
if ($this->players->call('checkTAListBan', $toBan, $player)) {
return self::alreadyBanned;
}
// Remove the current player from the banned player's TA list
$reverseList = $this->players->call('isAllyOf', $player);
foreach ($reverseList as $id => $data) {
if ($id == $toBan) {
$this->players->call('removeAlly', $toBan, $reverseList[$toBan]['level']);
$this->players->call('reorderAllies', $toBan);
break;
}
}
// Add the ban
$this->players->call('addTAListBan', $player, $toBan);
return $this->game->action("getTrustedAllies", $player);
}
}
?>

View file

@ -0,0 +1,91 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/getCommsOverview.inc
//
// This action fetches data associated with the overview of a player's
// communication channels.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_getCommsOverview
extends game_action {
public function __construct($game) {
parent::__construct($game, array(
"forums" => "beta5/forums",
"msgs" => "beta5/msg"
));
}
public function run($player) {
if (is_null($player)) {
return null;
}
// Messages in default folders
$folders = array();
$dfld = array('IN', 'INT', 'OUT');
foreach ($dfld as $f) {
$pm = $this->msgs->call('getAll', $player, $f);
$pmn = $this->msgs->call('getNew', $player, $f);
$folders[$f] = array($pm, $pmn);
}
// Custom folders
$folders["CUS"] = array();
$cFold = $this->msgs->call('getCustomFolders', $player);
foreach ($cFold as $cfid => $cfn) {
$pm = $this->msgs->call('getAll', $player, 'CUS', $cfid);
$pmn = $this->msgs->call('getNew', $player, 'CUS', $cfid);
$folders["CUS"][$cfid] = array($pm, $pmn, $cfn);
}
// Forums
$cats = $this->forums->call('getStructure', $player);
$forums = array(
"general" => array(),
"alliance" => array()
);
foreach ($cats as $c) {
if (!count($c['forums'])) {
continue;
}
if ($c['type'] == 'A') {
$forums['allianceID'] = $c['id'];
foreach ($c['forums'] as $f) {
array_push($forums['alliance'], array(
$f['id'], $f['topics'], $f['unread'], $f['title']
));
}
} else {
$gCat = array(
"id" => $c['id'],
"type" => $c['type'],
"title" => $c['title'],
"forums" => array()
);
foreach ($c['forums'] as $f) {
array_push($gCat['forums'], array(
$f['id'], $f['topics'], $f['unread'], $f['title']
));
}
array_push($forums['general'], $gCat);
}
}
return array(
"folders" => $folders,
"forums" => $forums
);
}
}
?>

View file

@ -0,0 +1,69 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/getEmpireOverview.inc
//
// This action fetches data associated with an empire's overview.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_getEmpireOverview
extends game_action {
public function __construct($game) {
parent::__construct($game, array(
"planets" => "beta5/planet",
"players" => "beta5/player",
"fleets" => "beta5/fleet",
"techs" => "beta5/tech"
));
}
public function run($player) {
if (is_null($player)) {
return null;
}
// Get general statistics
$genStats = $this->planets->call('getStats', $player);
$fleetStats = $this->fleets->call('getStats', $player);
$planets = $this->players->call('getPlanets', $player);
// Additional planet data
$income = 0;
foreach ($planets as $id => $name) {
$pInfo = $this->planets->call('byId', $id);
$pIncome = $this->planets->call('getIncome', $pInfo);
$income += $pIncome[0];
}
// Get research data
$rPoints = $this->techs->call('getPoints', $player);
$rBudget = $this->techs->call('getBudget', $player);
$nNew = count($this->techs->call('getTopics', $player, 0));
$nForeseen = count($this->techs->call('getTopics', $player, -1)) / 2;
// Return data
return array(
"planetStats" => $genStats,
"planets" => $planets,
"fleetStats" => $fleetStats,
"techStats" => array(
"points" => $rPoints,
"budget" => $rBudget,
"new" => $nNew,
"foreseen" => $nForeseen
),
"income" => $income,
"profit" => $income - $fleetStats['upkeep']
);
}
}
?>

View file

@ -0,0 +1,38 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/getOverview.inc
//
// This action fetches data associated with the complete overview.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_getOverview
extends game_action {
public function __construct($game) {
parent::__construct($game, array(
'players' => 'beta5/player'
));
}
public function run($player, $language) {
if (is_null($player)) {
return null;
}
return array(
"protection" => $this->players->call('getProtectionLevel', $player),
"comms" => $this->game->action('getCommsOverview', $player),
"universe" => $this->game->action('getUniverseOverview', $player, $language),
"empire" => $this->game->action('getEmpireOverview', $player)
);
}
}
?>

View file

@ -0,0 +1,54 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/getTrustedAllies.inc
//
// This action returns all data associated with the trusted allies list.
//
// Parameters:
// $player Identifier of the player
//
// Possible return values:
// an array The trusted allies data for the player
// NULL Error, player not found
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_getTrustedAllies
extends game_action {
public function __construct($game) {
parent::__construct($game, array(
"players" => "beta5/player"
));
}
public function run($player) {
// Check if the player ID is not null
if (is_null($player)) {
return null;
}
$player = (int) $player;
// Check if the player is valid
$playerRecord = $this->players->call('get', $player);
if (is_null($playerRecord)) {
return null;
}
// Return data
return array(
"allies" => $this->players->call('getAllies', $player),
"reverse" => $this->players->call('isAllyOf', $player),
"blacklist" => $this->players->call('getTAListBans', $player)
);
}
}
?>

View file

@ -0,0 +1,80 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/getUniverseOverview.inc
//
// This action fetches data associated with the universe's overview.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_getUniverseOverview
extends game_action {
public function __construct($game) {
parent::__construct($game, array(
"main" => "main",
"beta5" => "beta5",
"map" => "beta5/map",
"players" => "beta5/player",
"rankings" => "main/rankings"
));
}
public function run($player, $language) {
if (is_null($player)) {
return null;
}
return array(
"summary" => $this->map->call('getUniverse'),
"ticks" => $this->getTicks($language),
"rankings" => $this->getPlayerRankings($player)
);
}
private function getTicks($language) {
$ticks = array();
$info = $this->main->call('getTicks', $language);
foreach ($info as $tid => $td) {
if (! $td['game']) {
continue;
}
array_push($ticks, array($tid, $td['first'], $td['interval'], $td['last'], $td['name']));
}
return $ticks;
}
private function getRanking($type, $name) {
$rt = $this->rankings->call('getType', $type);
$r = $this->rankings->call('get', $rt, $name);
if (!$r) {
$r = array('','');
}
return $r;
}
private function getPlayerRankings($pid) {
$pc = $this->beta5->call('getPlayerCount');
$pName = $this->players->call('getName', $pid);
$gr = $this->getRanking('p_general', $pName);
$cr = $this->getRanking('p_civ', $pName);
$mr = $this->getRanking('p_financial', $pName);
$fr = $this->getRanking('p_military', $pName);
$or = $this->getRanking('p_round', $pName);
$ir = $this->getRanking('p_idr', $pName);
return array(
$pc, $gr['points'], $gr['ranking'], $cr['points'], $cr['ranking'],
$mr['points'], $mr['ranking'], $fr['points'], $fr['ranking'],
$or['points'], $or['ranking'], $ir['points'], $ir['ranking']
);
}
}
?>

View file

@ -0,0 +1,79 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game actions
//
// beta5/actions/removeTrustingAllies.inc
//
// This action removes a player from other players' trusted allies
// lists.
//
// Parameters:
// $player The player to remove from others' lists.
// $removeList An array of the player IDs from whose lists
// the player must be removed
//
// Possible return values:
// an array The trusted allies data for the player; see
// documentation for getTrustedAllies
// an integer Error; check the error codes.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_removeTrustingAllies
extends game_action {
/* ERROR CODES */
const playerNotFound = 0; // Player not found
const playerOnVacation = 1; // Player is on vacation
const trustingPlayerNotFound = 2; // One of the allies to remove wasn't found
/***************/
public function __construct($game) {
parent::__construct($game, array(
"players" => "beta5/player"
));
}
public function run($player, $removeList) {
// Check if the player ID is not null
if (is_null($player)) {
return self::playerNotFound;
}
$player = (int) $player;
// Check if the player is valid
$playerRecord = $this->players->call('get', $player);
if (is_null($playerRecord)) {
return self::playerNotFound;
}
if ($this->players->call('isOnVacation', $player)) {
return self::playerOnVacation;
}
// Check if the player is listed as an ally for these players
$trustedBy = $this->players->call('isAllyOf', $player);
$removeList = array_unique($removeList);
foreach ($removeList as $removePlayer) {
if (!array_key_exists((int) $removePlayer, $trustedBy)) {
return self::trustingPlayerNotFound;
}
}
// Remove the player from their lists and reorder
foreach ($removeList as $removePlayer) {
$this->players->call('removeAlly', (int) $removePlayer,
$trustedBy[(int) $removePlayer]['level']);
$this->players->call('reorderAllies', $removePlayer);
}
return $this->game->action("getTrustedAllies", $player);
}
}
?>

View file

@ -0,0 +1,94 @@
<?php
class beta5_alliance_library {
var $index = array(
'acceptRequest',
'addCandidate',
'cancelRequest',
'changeRank',
'create',
'createForum',
'createRank',
'deleteForum',
'deleteRank',
'get',
'getCandidates',
'getForums',
'getForumsComplete',
'getId',
'getKeepers',
'getMembers',
'getMilitary',
'getPlanets',
'getPrivileges',
'getRankPrivileges',
'getRankSize',
'getRanks',
'getRequests',
'getTechList',
'getTechOrder',
'getTechOrders',
'getTechRequests',
'getTechSubmission',
'getVoters',
'kick',
'leave',
'modifyForum',
'modifyRank',
'moveForum',
'rejectRequest',
'removeCandidate',
'sendRequest',
'setDemocratic',
'setForumAccess',
'setSuccessor',
'setTechRequests',
'setTechTradeMode',
'stepDown',
'submitTechList',
'submitTechOrders',
'takePresidency',
'updateRequests',
'updateVictory'
);
function beta5_alliance_library($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Changes a player's vote
function setVote($pid,$v) {
$this->db->query("UPDATE player SET a_vote=$v WHERE id=$pid");
$this->players[$pid] = null;
}
// Marks a tech trading order as obeyed
public function obeyOrder($pid) {
$this->db->query("UPDATE tech_trade_order SET obeyed = UNIX_TIMESTAMP( NOW() ) WHERE player = $pid");
}
// Get the timestamp of the latest tech trading orders and the next time it'll be possible to
// change the orders
public function getLatestTechOrders($alliance) {
// Get latest submission, if any
$q = $this->db->query("SELECT MAX(submitted) FROM tech_trade_order WHERE alliance = $alliance");
list($sub) = dbFetchArray($q);
$sub = (int) $sub;
// Get delays
$interval = 2 * $this->lib->game->ticks['battle']->interval;
$now = time();
if ($now - $sub >= $interval) {
$next = 0;
} else {
$next = $sub + $interval;
}
return array($sub, $next);
}
}
?>

View file

@ -0,0 +1,51 @@
<?php
class beta5_alliance_acceptRequest {
function beta5_alliance_acceptRequest($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->msgs = $this->lib->game->getLib('beta5/msg');
}
// Accepts a request to join an alliance
function run($aid, $pid, $kid) {
$q = $this->db->query("SELECT id FROM player WHERE alliance=$aid AND a_status='REQ' AND id=$pid");
if (!($q && dbCount($q) == 1)) {
return;
}
$a = $this->lib->call('get', $aid);
if (is_null($a)) {
return;
}
$tag = addslashes($a['tag']);
$tm = time();
$this->msgs->call('send', $pid, 'alint', array(
"msg_type" => 10,
"alliance" => $aid,
"tag" => $a['tag'],
"player" => $pid,
));
$l = $this->lib->call('getKeepers', $aid);
foreach ($l as $id) {
if ($id == $kid) {
continue;
}
$this->msgs->call('send', $id, 'alint', array(
"msg_type" => 11,
"alliance" => $aid,
"tag" => $a['tag'],
"player" => $pid,
));
}
$this->db->query("UPDATE player SET a_status='IN',a_vote=NULL,a_grade=NULL WHERE id=$pid");
}
}
?>

View file

@ -0,0 +1,35 @@
<?php
class beta5_alliance_addCandidate {
function beta5_alliance_addCandidate($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Adds a new candidate for an alliance's presidency
function run($aid,$pid) {
$this->db->query("INSERT INTO alliance_candidate(alliance,candidate) VALUES($aid,$pid)");
$q = $this->db->query("SELECT id FROM alliance_candidate WHERE candidate=$pid");
list($id) = dbFetchArray($q);
$this->db->query("UPDATE player SET a_vote=$id WHERE id=$pid");
$a = $this->lib->call('get', $aid);
$tag = addslashes($a['tag']);
$tm = time();
$vl = $this->lib->call('getVoters', $aid);
foreach ($vl as $id) {
if ($id == $pid) {
continue;
}
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',$pid,16)");
}
}
}
?>

View file

@ -0,0 +1,29 @@
<?php
class beta5_alliance_cancelRequest {
function beta5_alliance_cancelRequest($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Cancels a request to join an alliance
function run($p, $a) {
$this->db->query("UPDATE player SET alliance=NULL,a_status=NULL,a_vote=NULL WHERE id=$p");
$ainf = $this->lib->call('get', $a);
$tag = addslashes($ainf['tag']);
$l = $this->lib->call('getKeepers', $a);
$tm = time();
foreach ($l as $id) {
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT'");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$a,'$tag',$p,1)");
}
}
}
?>

View file

@ -0,0 +1,35 @@
<?php
class beta5_alliance_changeRank {
function beta5_alliance_changeRank($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
}
// Change an alliance member's rank
function run($pid, $rid) {
$this->db->query("UPDATE player SET a_grade=$rid WHERE alliance IS NOT NULL AND a_status='IN' AND id=$pid");
$q = $this->db->query(
"SELECT r.can_vote,r.can_be_cand,a.leader FROM player p,alliance a,alliance_grade r "
. "WHERE p.id=$pid AND r.alliance=p.alliance AND a.id=p.alliance AND "
. "((p.a_grade IS NOT NULL AND p.a_grade=r.id) OR (p.a_grade IS NULL AND r.id=a.default_grade))"
);
list($cv,$cc,$lid) = dbFetchArray($q);
$lockedAlliances = (int) $this->game->params['lockalliances'];
$lockedAlliances = ($lockedAlliances > 1) ? 1 : 0;
if ($pid != $lid && ! $lockedAlliances) {
if ($cv == 0) {
$this->db->query("UPDATE player SET a_vote=NULL WHERE id=$pid");
}
if ($cc == 0) {
$this->db->query("DELETE FROM alliance_candidate WHERE candidate=$pid");
}
}
// FIXME: message
}
}
?>

View file

@ -0,0 +1,39 @@
<?php
class beta5_alliance_create {
function beta5_alliance_create($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Create an alliance
function run($tag, $name, $founder) {
$t = addslashes($tag);
$this->db->query("INSERT INTO alliance_grade(name) VALUES ('DEFGRADE-$t')");
$q = $this->db->query("SELECT id FROM alliance_grade WHERE name='DEFGRADE-$t' AND alliance IS NULL");
list($gid) = dbFetchArray($q);
$this->db->query(
"INSERT INTO alliance(tag,name,leader,successor,default_grade) VALUES('$t','"
. addslashes($name) . "',$founder,NULL,$gid)"
);
$i = $this->lib->call('getId', $tag);
if (is_null($i)) {
return null;
}
$this->db->query("UPDATE alliance_grade SET name=NULL,alliance=$i WHERE name='DEFGRADE-$t' AND alliance IS NULL");
$this->db->query("UPDATE player SET alliance=$i,a_status='IN',a_vote=NULL WHERE id=$founder");
$rkLib =& $this->lib->game->getLib('main/rankings');
$rt = $rkLib->call('getType', 'a_general');
$rkLib->call('append', $rt, $tag);
return $i;
}
}
?>

View file

@ -0,0 +1,29 @@
<?php
class beta5_alliance_createForum {
function beta5_alliance_createForum($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Creates an alliance forum
function run($aid, $name, $userPost, $after, $description) {
if ($after == -1) {
$ao = -1;
} else {
$q = $this->db->query("SELECT forder FROM af_forum WHERE id=$after");
list($ao) = dbFetchArray($q);
}
$this->db->query("UPDATE af_forum SET forder=forder+1 WHERE forder>$ao AND alliance=$aid");
$ao ++;
$this->db->query(
"INSERT INTO af_forum(alliance,forder,title,description,user_post) VALUES("
. "$aid,$ao,'" . addslashes($name) . "','". addslashes($description) . "',"
. ($userPost?'TRUE':'FALSE') . ")"
);
}
}
?>

View file

@ -0,0 +1,47 @@
<?php
class beta5_alliance_createRank {
function beta5_alliance_createRank($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Creates a new rank within the alliance
function run($aid, $name, $privs, $kick, $change, $fread, $fmod) {
$n = addslashes($name);
$ll = array('NO', 'PY', 'PL', 'PLD');
$lt = array('NO', 'SL', 'SR', 'VL', 'MR');
$this->db->query(
"INSERT INTO alliance_grade(alliance,name,list_access,attacks,can_set_grades,"
. "can_kick,can_accept,forum_admin,dipl_contact,can_vote,can_be_cand,tech_trade)"
. " VALUES($aid,'$n','".$ll[$privs['list_access']]."',".dbBool($privs['attacks'])
. ",".dbBool($privs['can_set_grades']).",".dbBool($privs['can_kick']).","
. dbBool($privs['can_accept']).','.dbBool($privs['forum_admin']).","
. dbBool($privs['dipl_contact']).",".dbBool($privs['can_vote']).","
. dbBool($privs['can_be_cand']).",'".$lt[$privs['tech_trade']] . "')"
);
$q = $this->db->query("SELECT id FROM alliance_grade WHERE alliance=$aid AND name='$n'");
if (!($q && dbCount($q))) {
return;
}
list($rid) = dbFetchArray($q);
foreach ($kick as $id) {
$this->db->query("INSERT INTO algr_kick VALUES($rid,$id)");
}
foreach ($change as $id) {
$this->db->query("INSERT INTO algr_chgrade VALUES($rid,$id)");
}
foreach ($fread as $id) {
$this->db->query("INSERT INTO algr_forums VALUES($rid,$id,FALSE)");
}
foreach ($fmod as $id) {
$this->db->query("INSERT INTO algr_forums VALUES($rid,$id,TRUE)");
}
}
}
?>

View file

@ -0,0 +1,20 @@
<?php
class beta5_alliance_deleteForum {
function beta5_alliance_deleteForum($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Destroys an alliance forum
function run($id) {
$q = $this->db->query("SELECT alliance,forder FROM af_forum WHERE id=$id");
list($aid,$o) = dbFetchArray($q);
$this->db->query("DELETE FROM af_forum WHERE id=$id");
$this->db->query("UPDATE af_forum SET forder=forder-1 WHERE alliance=$aid AND forder>$o");
}
}
?>

View file

@ -0,0 +1,18 @@
<?php
class beta5_alliance_deleteRank {
function beta5_alliance_deleteRank($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Deletes a rank from an alliance's ACL
function run($aid, $rId, $nrId) {
$this->db->query("UPDATE player SET a_grade=$nrId WHERE alliance=$aid AND a_status='IN' AND a_grade=$rId");
$this->db->query("DELETE FROM alliance_grade WHERE alliance=$aid AND id=$rId");
}
}
?>

View file

@ -0,0 +1,30 @@
<?php
class beta5_alliance_get {
function beta5_alliance_get($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get alliance data
function run($id) {
$q = $this->db->query("SELECT * FROM alliance WHERE id = $id");
if (!($q && dbCount($q) == 1)) {
return null;
}
$r = dbFetchHash($q);
$q = $this->db->query(
"SELECT COUNT(*),ROUND(AVG(s.x)),ROUND(AVG(s.y)) FROM player y,planet p,system s "
. "WHERE y.alliance=$id AND y.a_status='IN' AND p.owner=y.id AND s.id=p.system"
);
list($r['nplanets'],$r['avgx'],$r['avgy']) = dbFetchArray($q);
if (is_null($r['avgx'])) {
$r['avgx'] = $r['avgy'] = 0;
}
return $r;
}
}
?>

View file

@ -0,0 +1,29 @@
<?php
class beta5_alliance_getCandidates {
function beta5_alliance_getCandidates($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get the list of alliance candidates as well as the number of votes they have
function run($aid) {
$l = array();
$q = $this->db->query("SELECT c.id,c.candidate,COUNT(*) FROM alliance_candidate c,"
. "player p WHERE c.alliance=$aid AND p.a_vote=c.id GROUP BY c.id, c.candidate");
while ($r = dbFetchArray($q)) {
$q2 = $this->db->query("SELECT p.name,a.name FROM player p,account a WHERE p.id={$r[1]} AND p.userid=a.id");
$r2 = dbFetchArray($q2);
$l[$r[0]] = array(
"votes" => $r[2],
"pid" => $r[1],
"name" => is_null($r2[0]) ? $r2[1] : $r2[0]
);
}
return $l;
}
}
?>

View file

@ -0,0 +1,27 @@
<?php
class beta5_alliance_getForums {
function beta5_alliance_getForums($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Reads the list of an alliance's forums
function run($aid) {
$q = $this->db->query("SELECT id,forder,title,description,user_post FROM af_forum WHERE alliance=$aid ORDER BY forder");
$rs = array();
while ($r = dbFetchArray($q)) {
$rs[$r[0]] = array(
"order" => $r[1],
"title" => $r[2],
"description" => $r[3],
"user_post" => ($r[4] == 't')
);
}
return $rs;
}
}
?>

View file

@ -0,0 +1,34 @@
<?php
class beta5_alliance_getForumsComplete {
function beta5_alliance_getForumsComplete($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
}
// Reads the list of an alliance's forums, with details
function run($aid) {
$q = $this->db->query("SELECT * FROM af_forum WHERE alliance=$aid ORDER BY forder");
$a = array();
while ($rs = dbFetchHash($q)) {
if ($rs['last_post'] != "") {
$q2 = $this->db->query("SELECT author,moment FROM af_post WHERE id=".$rs['last_post']);
list($au,$mo) = dbFetchArray($q2);
$au = $this->players->call('getName', $au);
$rs['last'] = array(
"moment" => $mo,
"author" => $au
);
} else {
$rs['last'] = null;
}
array_push($a, $rs);
}
return $a;
}
}
?>

View file

@ -0,0 +1,21 @@
<?php
class beta5_alliance_getId {
function beta5_alliance_getId($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get alliance identifier by tag
function run($tag) {
$q = $this->db->query("SELECT id FROM alliance WHERE LOWER(tag)='" . addslashes(strtolower($tag)) . "'");
if (!($q && dbCount($q) == 1)) {
return null;
}
list($id) = dbFetchArray($q);
return $id;
}
}
?>

View file

@ -0,0 +1,46 @@
<?php
class beta5_alliance_getKeepers {
function beta5_alliance_getKeepers($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get a list of IDs for the players that can accept new members into an alliance
function run($a) {
$q = $this->db->query("SELECT leader FROM alliance WHERE id=$a");
list($id) = dbFetchArray($q);
if (!is_null($id)) {
$l = array($id);
} else {
$l = array();
}
$q = $this->db->query("SELECT id FROM alliance_grade WHERE alliance=$a AND can_accept");
if (!$q || dbCount($q) == 0) {
return $l;
}
$gl = array();
while ($r = dbFetchArray($q)) {
list($g) = $r;
array_push($gl, $g);
}
$q = $this->db->query(
"SELECT p.id FROM player p, alliance a WHERE a.id=$a AND p.alliance=a.id AND p.a_status='IN' "
. "AND (p.a_grade IN (" . join(',',$gl) . ") OR (p.a_grade IS NULL AND a.default_grade IN (".join(',',$gl).")))"
);
while ($r = dbFetchArray($q)) {
list($p) = $r;
if (is_null($id) || $p != $id) {
array_push($l, $p);
}
}
return $l;
}
}
?>

View file

@ -0,0 +1,27 @@
<?php
class beta5_alliance_getMembers {
function beta5_alliance_getMembers($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Reads the list of alliance members and their ranks
function run($aid) {
$q = $this->db->query(
"SELECT p.id,p.name,a.name,p.a_grade FROM player p,account a "
. "WHERE p.alliance=$aid AND p.a_status='IN' AND a.id=p.userid");
$rs = array();
while ($r = dbFetchArray($q)) {
$rs[$r[0]] = array(
"name" => is_null($r[1]) ? $r[2] : $r[1],
"rank" => $r[3]
);
}
return $rs;
}
}
?>

View file

@ -0,0 +1,34 @@
<?php
class beta5_alliance_getMilitary {
function beta5_alliance_getMilitary($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get the list of planets under attack in an alliance
function run($aid) {
$q = $this->db->query(
"SELECT p.id AS id,p.name AS name,l.id AS owner,a.v_players AS pllist,"
. "a.v_friendly AS friendly,a.v_enemy AS enemy,s.x AS x,s.y AS y,p.orbit AS orbit "
. " FROM planet p,attacks a,player l,system s "
. "WHERE l.alliance=$aid AND l.a_status='IN' AND p.owner=l.id AND a.planet=p.id AND s.id=p.system"
);
$rs = array();
while ($r = dbFetchHash($q)) {
$r['f_list'] = $r['e_list'] = array();
if ($r['pllist'] == 't') {
$q2 = $this->db->query("SELECT DISTINCT owner,attacking FROM fleet WHERE location=".$r['id']);
while ($r2=dbFetchArray($q2)) {
array_push($r[($r2[1] == 't' ? "e" : "f").'_list'], $r2[0]);
}
}
$rs[$r['id']] = $r;
}
return $rs;
}
}
?>

View file

@ -0,0 +1,42 @@
<?php
class beta5_alliance_getPlanets {
function beta5_alliance_getPlanets($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->planets = $this->lib->game->getLib('beta5/planet');
$this->players = $this->lib->game->getLib('beta5/player');
}
// Returns the list of planets belonging to players of the alliance
function run($aid) {
$rs = array();
$q = $this->db->query("SELECT p.id,p.name,a.name FROM player p,account a WHERE a.id=p.userid AND p.alliance=$aid AND p.a_status='IN'");
while ($r = dbFetchArray($q)) {
$oid = $r[0]; $oname = ($r[1] == "") ? $r[2] : $r[1];
$ppl = $this->players->call('getPlanets', $oid);
foreach ($ppl as $pid => $pname) {
$pinf = $this->planets->call('byId', $pid);
$rs[$pid] = array(
"name" => $pname,
"ownerId" => $oid,
"owner" => $oname,
"x" => $pinf['x'],
"y" => $pinf['y'],
"orbit" => $pinf['orbit'] + 1,
"fact" => $pinf['ifact'] + $pinf['mfact'],
"turrets" => $pinf['turrets'],
);
$q2 = $this->db->query("SELECT COUNT(*) FROM fleet WHERE location=$pid AND attacking");
list($ua) = dbFetchArray($q2);
$rs[$pid]['attack'] = ($ua != 0);
}
}
return $rs;
}
}
?>

View file

@ -0,0 +1,79 @@
<?php
class beta5_alliance_getPrivileges {
function beta5_alliance_getPrivileges($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
}
// Returns the list of privileges a player has inside an alliance
function run($p) {
$nr = array(
'list_access' => 0,
'tech_trade' => 0,
'attacks' => 0,
'can_set_grades' => 0,
'can_kick' => 0,
'can_accept' => 0,
'forum_admin' => 0,
'dipl_contact' => 0,
'can_vote' => 0,
'can_be_cand' => 0,
'is_leader' => 0
);
$pi = $this->players->call('get', $p);
if (is_null($pi['aid'])) {
return $nr;
}
$a = $this->lib->call('get', $pi['aid']);
if (is_null($a)) {
return $nr;
}
if ($a['leader'] == $p) {
$pr = array(
'list_access' => 3,
'tech_trade' => ($a['enable_tt'] == 'N' ? 0 : 4),
'attacks' => 1,
'can_set_grades' => 1,
'can_kick' => 1,
'can_accept' => 1,
'forum_admin' => 1,
'dipl_contact' => 1,
'can_vote' => 0,
'can_be_cand' => 1,
'is_leader' => 1
);
// Get all ranks (-> kick, change)
$q = $this->db->query("SELECT id FROM alliance_grade WHERE alliance=".$a['id']);
$ar = array();
while ($r = dbFetchArray($q)) {
array_push($ar, $r[0]);
}
$pr['kick_ranks'] = $pr['change_ranks'] = $ar;
// Forums
$pr['f_read'] = $pr['f_mod'] = array();
$q = $this->db->query("SELECT id FROM af_forum WHERE alliance=".$a['id']);
while ($r = dbFetchArray($q)) {
array_push($pr['f_mod'], $r[0]);
}
} elseif (is_null($pi['a_grade'])) {
$pr = $this->lib->call('getRankPrivileges', $a['default_grade']);
} else {
$pr = $this->lib->call('getRankPrivileges', $pi['a_grade']);
}
if ($a['democracy'] == "f") {
$pr['can_vote'] = $pr['can_be_cand'] = 'f';
}
return $pr;
}
}
?>

View file

@ -0,0 +1,96 @@
<?php
class beta5_alliance_getRankPrivileges {
function beta5_alliance_getRankPrivileges($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Returns the privileges associated with a rank
function run($id) {
$q = $this->db->query("SELECT * FROM alliance_grade WHERE id=$id");
$pr = dbFetchHash($q);
$pr['is_leader'] = 0;
// Transform list access
switch ($pr['list_access']) :
case 'NO ': $pr['list_access'] = 0; break;
case 'PY ': $pr['list_access'] = 1; break;
case 'PL ': $pr['list_access'] = 2; break;
case 'PLD': $pr['list_access'] = 3; break;
endswitch;
// Transform tech trade tool access
$q = $this->db->query("SELECT enable_tt FROM alliance WHERE id = {$pr['alliance']}");
list($enableTT) = dbFetchArray($q);
switch ($pr['tech_trade']) :
case 'NO': $pr['tech_trade'] = 0; break;
case 'SL': $pr['tech_trade'] = ($enableTT != 'N' ? 1 : 0); break;
case 'SR': $pr['tech_trade'] = ($enableTT == 'N' ? 0 : ($enableTT == 'S' ? 1 : 2)); break;
case 'VL': $pr['tech_trade'] = ($enableTT != 'N' ? 3 : 0); break;
case 'MR': $pr['tech_trade'] = ($enableTT != 'N' ? 4 : 0); break;
endswitch;
// Transform PostgreSQL booleans into something usable by the current scripts
$fields = array("attacks", "can_set_grades", "can_kick", "can_accept",
"can_be_kicked", "forum_admin", "dipl_contact", "can_vote", "can_be_cand");
foreach ($fields as $f) {
$pr[$f] = ($pr[$f] == 't') ? 1 : 0;
}
// Get kickable ranks
$a = array();
if ($pr['can_kick']) {
$q = $this->db->query("SELECT kick FROM algr_kick WHERE grade = $id AND kick <> $id");
if (!dbCount($q)) {
$q = $this->db->query(
"SELECT id FROM alliance_grade "
. "WHERE alliance = {$pr['alliance']} AND id <> $id"
);
}
while ($r = dbFetchArray($q)) {
array_push($a, $r[0]);
}
}
$pr['kick_ranks'] = $a;
// Get changeable ranks
$a = array();
if ($pr['can_set_grades']) {
$q = $this->db->query("SELECT can_change FROM algr_chgrade WHERE grade=$id AND can_change!=$id");
if (!dbCount($q)) {
$q = $this->db->query(
"SELECT id FROM alliance_grade "
. "WHERE alliance={$pr['alliance']} AND id <> $id"
);
}
while ($r = dbFetchArray($q)) {
array_push($a, $r[0]);
}
}
$pr['change_ranks'] = $a;
// Forum privileges
$pr['f_read'] = $pr['f_mod'] = array();
if ($pr['forum_admin'] == 0) {
$q = $this->db->query("SELECT forum,is_mod FROM algr_forums WHERE grade=$id");
while ($r = dbFetchArray($q)) {
array_push($pr[($r[1] == 't') ? "f_mod" : "f_read"], $r[0]);
}
} else {
$q = $this->db->query(
"SELECT f.id FROM af_forum f,alliance_grade r "
. "WHERE r.id = $id AND f.alliance = r.alliance"
);
while ($r = dbFetchArray($q)) {
array_push($pr['f_mod'], $r[0]);
}
}
return $pr;
}
}
?>

View file

@ -0,0 +1,32 @@
<?php
class beta5_alliance_getRankSize {
function beta5_alliance_getRankSize($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get the number of alliance members at a certain rank
function run($aid, $rId) {
$a = $this->lib->call('get', $aid);
$qs = "SELECT COUNT(*) FROM player WHERE alliance=$aid AND a_status='IN' AND ";
if ($rId == $a['default_grade']) {
$qs .= "(a_grade=$rId OR a_grade IS NULL)";
} else {
$qs .= "a_grade=$rId";
}
if (!is_null($a['leader'])) {
$qs .= " AND id<>" . $a['leader'];
}
$q = $this->db->query($qs);
if (!($q && dbCount($q))) {
return 0;
}
list($r) = dbFetchArray($q);
return $r;
}
}
?>

View file

@ -0,0 +1,22 @@
<?php
class beta5_alliance_getRanks {
function beta5_alliance_getRanks($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Reads the list of ranks associated with an alliance
function run($aid) {
$q = $this->db->query("SELECT id,name FROM alliance_grade WHERE alliance=$aid");
$rs = array();
while ($r = dbFetchArray($q)) {
$rs[$r[0]] = is_null($r[1]) ? "-" : $r[1];
}
return $rs;
}
}
?>

View file

@ -0,0 +1,22 @@
<?php
class beta5_alliance_getRequests {
function beta5_alliance_getRequests($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get the list of pending requests for an alliance
function run($aid) {
$q = $this->db->query("SELECT p.id,p.name,a.name FROM player p, account a WHERE p.alliance=$aid AND p.a_status='REQ' AND a.id=p.userid");
$rs = array();
while ($r = dbFetchArray($q)) {
$rs[$r[0]] = ($r[1] == "") ? $r[2] : $r[1];
}
return $rs;
}
}
?>

View file

@ -0,0 +1,93 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/getTechList.inc
//
// This function retrieves the technology list for an alliance.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_getTechList {
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
$this->players = $this->game->getLib('beta5/player');
}
public function run($alliance, $hasRequests) {
// Get tech trading privileges for all players in the alliance
$players = $this->getPlayers($alliance, $hasRequests);
// Get the technology list for each player that is authorized to submit it,
// and get requests for players who can submit requests
$techList = array();
foreach ($players as $player => $priv) {
// Ignore unprivileged players
if ($priv == 0) {
continue;
}
// Get list and player status
list($lastSub, $list) = $this->getPlayerList($player);
$techList[$player] = array(
"submitted" => $lastSub,
"list" => $list,
"vacation" => $this->players->call('isOnVacation', $player) ? 1 : 0,
"restrict" => $this->players->call('isRestrained', $player) ? 1 : 0
);
// Ignore players who can't submit requess
if ($priv == 1) {
continue;
}
$techList[$player]['requests'] = $this->lib->call('getTechRequests', $player);
}
return $techList;
}
private function getPlayers($alliance, $hasRequests) {
$q = $this->db->query(
"SELECT p.id, (CASE p.id = a.leader WHEN TRUE THEN 'MR' ELSE r.tech_trade END) "
. "FROM player p, alliance a, alliance_grade r "
. "WHERE p.alliance = $alliance AND p.a_status = 'IN' AND r.alliance = p.alliance "
. "AND (p.a_grade = r.id OR p.a_grade IS NULL AND r.name IS NULL) "
. "AND a.id = p.alliance"
);
$players = array();
while ($r = dbFetchArray($q)) {
switch ($r[1]) {
case 'NO': $priv = 0; break;
case 'SL': $priv = 1; break;
default: $priv = $hasRequests ? 2 : 1; break;
}
$players[$r[0]] = $priv;
}
return $players;
}
private function getPlayerList($player) {
$list = array();
$subAt = 0;
$q = $this->db->query("SELECT tech, status, submitted FROM tech_trade_list WHERE member = $player");
while ($r = dbFetchArray($q)) {
$list[$r[0]] = $r[1];
$subAt = $r[2];
}
return array($subAt, $list);
}
}
?>

View file

@ -0,0 +1,36 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/getTechOrder.inc
//
// This function retrieves technology trading orders from the database.
// Depending on the $send parameter, it can fetch either orders to send
// technologies or orders to receive technologies.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_getTechOrder {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($player, $send) {
$q = $this->db->query(
"SELECT tech, " . ($send ? "send_to" : "player") . ", submitted, obeyed FROM tech_trade_order "
. "WHERE " . ($send ? "player" : "send_to") . " = $player "
. "FOR UPDATE"
);
if (!dbCount($q)) {
return array(null, null, null, null);
}
return dbFetchArray($q);
}
}
?>

View file

@ -0,0 +1,58 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/getTechOrders.inc
//
// This function retrieves all technology trading orders for an alliance
// from the database.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_getTechOrders {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($alliance) {
// Get the orders for all players
$q = $this->db->query(
"SELECT player, send_to, tech, submitted, obeyed FROM tech_trade_order "
. "WHERE alliance = $alliance"
);
// Create the list of orders
$orders = array();
while ($r = dbFetchArray($q)) {
if (is_null($r[4])) {
$r[4] = 0;
}
if (!is_array($orders[$r[0]])) {
$orders[$r[0]] = array();
}
$orders[$r[0]]['sendTo'] = $r[1];
$orders[$r[0]]['sendTech'] = $r[2];
$orders[$r[0]]['sendSub'] = $r[3];
$orders[$r[0]]['sendDone'] = $r[4];
if (!is_array($orders[$r[1]])) {
$orders[$r[1]] = array();
}
$orders[$r[1]]['recvFrom'] = $r[0];
$orders[$r[1]]['recvTech'] = $r[2];
$orders[$r[1]]['recvSub'] = $r[3];
$orders[$r[1]]['recvDone'] = $r[4];
}
return $orders;
}
}
?>

View file

@ -0,0 +1,38 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/getTechRequests.inc
//
// This function returns the list of technology requests for a player.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_getTechRequests {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($player) {
// Get the player's current requests, if any
$q = $this->db->query(
"SELECT tech FROM tech_trade_request "
. "WHERE player = $player ORDER BY priority"
);
$requests = array();
while ($r = dbFetchArray($q)) {
array_push($requests, $r[0]);
}
return $requests;
}
}
?>

View file

@ -0,0 +1,38 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/getTechSubmission.inc
//
// This function retrieves technology list submission data from the
// tech trading database and determines whether a player can submit his
// list again.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_getTechSubmission {
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
}
public function run($player) {
$q = $this->db->query(
"SELECT submitted FROM tech_trade_list WHERE member = $player LIMIT 1"
);
if (!dbCount($q)) {
return array(true, null, null);
}
list($when) = dbFetchArray($q);
$nextSubmission = $when + $this->game->ticks['battle']->interval;
return array($nextSubmission <= time(), $when, $nextSubmission);
}
}
?>

View file

@ -0,0 +1,46 @@
<?php
class beta5_alliance_getVoters {
function beta5_alliance_getVoters($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get the list of all people in an alliance that can vote, as well as the current leader
function run($a) {
$q = $this->db->query("SELECT leader FROM alliance WHERE id=$a");
list($id) = dbFetchArray($q);
if (!is_null($id)) {
$l = array($id);
} else {
$l = array();
}
$q = $this->db->query("SELECT id FROM alliance_grade WHERE alliance=$a AND can_vote");
if (!$q || dbCount($q) == 0) {
return $l;
}
$gl = array();
while ($r = dbFetchArray($q)) {
list($g) = $r;
array_push($gl, $g);
}
$q = $this->db->query(
"SELECT p.id FROM player p, alliance a WHERE a.id=$a AND p.alliance=a.id AND p.a_status='IN' "
. "AND (p.a_grade IN (" . join(',',$gl) . ") OR (p.a_grade IS NULL AND a.default_grade IN (".join(',',$gl).")))"
);
while ($r = dbFetchArray($q)) {
list($p) = $r;
if (is_null($id) || $p != $id) {
array_push($l, $p);
}
}
return $l;
}
}
?>

View file

@ -0,0 +1,18 @@
<?php
class beta5_alliance_kick {
function beta5_alliance_kick($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Kick an alliance member
function run($pid) {
$this->lib->call('leave', $pid, true);
// FIXME: message
}
}
?>

View file

@ -0,0 +1,84 @@
<?php
class beta5_alliance_leave {
function beta5_alliance_leave($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
$this->rankings = $this->lib->game->getLib('main/rankings');
}
// Leave an alliance
function run($pid, $isKick = false) {
$p = $this->players->call('get', $pid);
if (is_null($p) || is_null($p['aid'])) {
return;
}
$aid = $p['aid'];
$a = $this->lib->call('get', $aid);
if (is_null($a)) {
return;
}
// Delete tech trading data
$this->db->query("DELETE FROM tech_trade_list WHERE member = $pid");
$this->db->query("DELETE FROM tech_trade_request WHERE player = $pid");
$this->db->query("DELETE FROM tech_trade_order WHERE player = $pid OR send_to = $pid");
$msgId = 9;
$mpid = $pid;
if ($pid == $a['leader']) {
if (!is_null($a['successor'])) {
$this->lib->call('stepDown', $aid, true);
$msgId = 14;
$mpid = $a['successor'];
} else {
$this->db->query("UPDATE alliance SET leader=NULL,democracy=TRUE WHERE id=$aid");
$this->db->query("UPDATE alliance_grade SET can_vote=TRUE,can_be_cand=TRUE WHERE alliance=$aid");
$msgId = 15;
}
} elseif ($pid == $a['successor']) {
$this->db->query("UPDATE alliance SET successor=NULL WHERE id=$aid");
}
if ($a['democracy'] == 't') {
$this->db->query("DELETE FROM alliance_candidate WHERE alliance=$aid AND candidate=".$pid);
}
$this->db->query("UPDATE player SET alliance=NULL,a_vote=NULL,a_status=NULL,a_grade=NULL WHERE id=$pid");
$q = $this->db->query("SELECT COUNT(*) FROM player WHERE alliance=$aid AND a_status='IN'");
list($pc) = dbFetchArray($q);
if ($pc == 0) {
$this->db->query("UPDATE player SET alliance=NULL,a_vote=NULL,a_status=NULL,a_grade=NULL WHERE alliance=$aid");
$rt = $this->rankings->call('getType', 'a_general');
$this->rankings->call('delete', $rt, $a['tag']);
$this->db->query("DELETE FROM alliance WHERE id=$aid");
return;
}
if ($isKick) {
return;
}
if ($msgId == 9) {
$l = $this->lib->call('getKeepers', $aid);
} else {
$l = array_keys($this->lib->call('getMembers', $aid));
}
$tag = addslashes($a['tag']);
$tm = time();
l::FIXME("Use message API"); // FIXME
foreach ($l as $id) {
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',$mpid,$msgId)");
}
}
}
?>

View file

@ -0,0 +1,20 @@
<?php
class beta5_alliance_modifyForum {
function beta5_alliance_modifyForum($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Modifies an alliance forum
function run($id, $name, $userPost, $description) {
$this->db->query(
"UPDATE af_forum SET title='".addslashes($name)."',user_post=".($userPost?'TRUE':'FALSE').",description='".addslashes($description)
."' WHERE id=$id"
);
}
}
?>

View file

@ -0,0 +1,77 @@
<?php
class beta5_alliance_modifyRank {
function beta5_alliance_modifyRank($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Modifies a new rank within the alliance
function run($rid, $name, $privs, $kick, $change, $fread, $fmod) {
$ll = array('NO ','PY ','PL ','PLD');
$lt = array('NO', 'SL', 'SR', 'VL', 'MR');
if (is_null($name)) {
$n = "NULL";
} else {
$n = "'".addslashes($name)."'";
}
$qs = "UPDATE alliance_grade SET name=$n";
foreach ($privs as $p => $v) {
$qs .= ",$p=";
if ($p == "list_access") {
$qs .= "'" . $ll[$v] . "'";
} elseif ($p == "tech_trade") {
$qs .= "'" . $lt[$v] . "'";
} else {
$qs .= dbBool($v);
}
}
$qs .= " WHERE id=$rid";
$this->db->query($qs);
$q = $this->db->query("SELECT alliance FROM alliance_grade WHERE id=$rid");
list($aid) = dbFetchArray($q);
$q = $this->db->query("SELECT default_grade,leader FROM alliance WHERE id=$aid");
list($did, $lid) = dbFetchArray($q);
if ($rid == $did) {
$n = " IS NULL";
} else {
$n = "=$rid";
}
if ($privs['can_vote'] == 0) {
$this->db->query("UPDATE player SET a_vote=NULL WHERE a_grade$n AND alliance=$aid AND a_status='IN'" . (is_null($lid) ? "": " AND id<>$lid"));
}
if ($privs['can_be_cand'] == 0) {
$q = $this->db->query("SELECT id FROM player WHERE a_grade$n AND alliance=$aid AND a_status='IN'" . (is_null($lid) ? "": " AND id<>$lid"));
$a = array();
while ($r = dbFetchArray($q)) {
array_push($a, $r[0]);
}
if (count($a)) {
$this->db->query("DELETE FROM alliance_candidate WHERE candidate IN (".join(',',$a).")");
}
}
$this->db->query("DELETE FROM algr_kick WHERE grade=$rid");
foreach ($kick as $id) {
$this->db->query("INSERT INTO algr_kick VALUES($rid,$id)");
}
$this->db->query("DELETE FROM algr_chgrade WHERE grade=$rid");
foreach ($change as $id) {
$this->db->query("INSERT INTO algr_chgrade VALUES($rid,$id)");
}
$this->db->query("DELETE FROM algr_forums WHERE grade=$rid");
foreach ($fread as $id) {
$this->db->query("INSERT INTO algr_forums VALUES($rid,$id,".dbBool(0).")");
}
foreach ($fmod as $id) {
$this->db->query("INSERT INTO algr_forums VALUES($rid,$id,".dbBool(1).")");
}
}
}
?>

View file

@ -0,0 +1,36 @@
<?php
class beta5_alliance_moveForum {
function beta5_alliance_moveForum($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Moves an alliance forum up or down in the list
function run($id, $up) {
$q = $this->db->query("SELECT alliance,forder FROM af_forum WHERE id=$id");
list($aid,$o) = dbFetchArray($q);
if ($o == 0 && $up) {
return;
}
$q = $this->db->query("SELECT MAX(forder) FROM af_forum WHERE alliance=$aid");
list($mo) = dbFetchArray($q);
if ($o == $mo && !$up) {
return;
}
$this->db->query("UPDATE af_forum SET forder=" . ($mo+1) . " WHERE id=$id");
if ($up) {
$this->db->query("UPDATE af_forum SET forder=forder+1 WHERE alliance=$aid AND forder=".($o-1));
$this->db->query("UPDATE af_forum SET forder=".($o-1)." WHERE id=$id");
} else {
$this->db->query("UPDATE af_forum SET forder=forder-1 WHERE alliance=$aid AND forder=".($o+1));
$this->db->query("UPDATE af_forum SET forder=".($o+1)." WHERE id=$id");
}
}
}
?>

View file

@ -0,0 +1,51 @@
<?php
class beta5_alliance_rejectRequest {
function beta5_alliance_rejectRequest($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->msgs = $this->lib->game->getLib('beta5/msg');
}
// Rejects a request to join an alliance
function run($aid, $pid, $kid) {
$q = $this->db->query("SELECT id FROM player WHERE alliance=$aid AND a_status='REQ' AND id=$pid");
if (!($q && dbCount($q) == 1)) {
return;
}
$a = $this->lib->call('get', $aid);
if (is_null($a)) {
return;
}
$tag = addslashes($a['tag']);
$tm = time();
$this->msgs->call('send', $pid, 'alint', array(
"msg_type" => 12,
"alliance" => $aid,
"tag" => $tag,
"player" => $pid,
));
$l = $this->lib->call('getKeepers', $aid);
foreach ($l as $id) {
if ($id == $kid) {
continue;
}
$this->msgs->call('send', $id, 'alint', array(
"msg_type" => 13,
"alliance" => $aid,
"tag" => $tag,
"player" => $pid,
));
}
$this->db->query("UPDATE player SET a_status=NULL,alliance=NULL,a_vote=NULL,a_grade=NULL WHERE id=$pid");
}
}
?>

View file

@ -0,0 +1,32 @@
<?php
class beta5_alliance_removeCandidate {
function beta5_alliance_removeCandidate($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Removes a candidate for an alliance's presidency
function run($aid,$pid) {
$this->db->query("DELETE FROM alliance_candidate WHERE candidate=$pid");
$a = $this->lib->call('get', $aid);
$tag = addslashes($a['tag']);
$tm = time();
$vl = $this->lib->call('getVoters', $aid);
foreach ($vl as $id) {
if ($id == $pid) {
continue;
}
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',$pid,17)");
}
}
}
?>

View file

@ -0,0 +1,29 @@
<?php
class beta5_alliance_sendRequest {
function beta5_alliance_sendRequest($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Sends a request to join an alliance
function run($p, $a) {
$this->db->query("UPDATE player SET alliance=$a,a_status='REQ',a_vote=NULL WHERE id=$p");
$ainf = $this->lib->call('get', $a);
$tag = addslashes($ainf['tag']);
$l = $this->lib->call('getKeepers', $a);
$tm = time();
foreach ($l as $id) {
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT'");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$a,'$tag',$p,0)");
}
}
}
?>

View file

@ -0,0 +1,47 @@
<?php
class beta5_alliance_setDemocratic {
function beta5_alliance_setDemocratic($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Switches an alliance's government mode
function run($aid, $demo) {
$a = $this->lib->call('get', $aid);
if (is_null($a)) {
return null;
}
$ad = ($a['democracy'] != "f");
if ($ad == $demo) {
return;
}
$this->db->query("UPDATE alliance SET democracy=".dbBool($demo)." WHERE id=$aid");
if ($demo) {
$this->db->query("INSERT INTO alliance_candidate(alliance,candidate) VALUES ($aid,".$a['leader'].")");
$q = $this->db->query("SELECT id FROM alliance_candidate WHERE candidate=".$a['leader']." AND alliance=$aid");
list($cid) = dbFetchArray($q);
$this->db->query("UPDATE player SET a_vote=$cid WHERE id=".$a['leader']);
$msId = 4;
} else {
$this->db->query("DELETE FROM alliance_candidate WHERE alliance=$aid");
$msId = 5;
}
$q = $this->db->query("SELECT id FROM player WHERE alliance=$aid AND a_status='IN' AND id<>".$a['leader']);
$tm = time();
$tag = addslashes($a['tag']);
while ($r = dbFetchArray($q)) {
$id = $r[0];
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q2 = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' AND mtype='alint' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q2);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',".$a['leader'].",$msId)");
}
}
}
?>

View file

@ -0,0 +1,23 @@
<?php
class beta5_alliance_setForumAccess {
function beta5_alliance_setForumAccess($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Modifies the access list for an alliance forum
function run($id, $readers, $mods) {
$this->db->query("DELETE FROM algr_forums WHERE forum=$id");
foreach ($readers as $rid) {
$this->db->query("INSERT INTO algr_forums VALUES($rid,$id,false)");
}
foreach ($mods as $rid) {
$this->db->query("INSERT INTO algr_forums VALUES($rid,$id,true)");
}
}
}
?>

View file

@ -0,0 +1,38 @@
<?php
class beta5_alliance_setSuccessor {
function beta5_alliance_setSuccessor($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Changes the successor for the current leader
function run($aid, $sid) {
$a = $this->lib->call('get', $aid);
if (is_null($a) || $a['successor'] == $sid) {
return;
}
$tag = addslashes($a['tag']);
$tm = time();
if (!is_null($a['successor'])) {
$id = $a['successor'];
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' AND mtype='alint' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',".$a['leader'].",2)");
}
$this->db->query("UPDATE alliance SET successor=".(is_null($sid)?"NULL":$sid) . " WHERE id=$aid");
if (!is_null($sid)) {
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($sid,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$sid AND sent_on=$tm AND ftype='INT' AND mtype='alint' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',".$a['leader'].",3)");
}
}
}
?>

View file

@ -0,0 +1,46 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/setTechRequests.inc
//
// This function updates the list of requests made by a player. It
// should only be called after it has been made sure that the player is
// a member of an alliance, that he can submit requests and that his
// list of requested technologies is valid.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_setTechRequests {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($player, $requests) {
// Delete the player's requests
$this->db->query("DELETE FROM tech_trade_request WHERE player = $player");
// Get the player's alliance; if we're here, then the player *is* in an alliance
$q = $this->db->query("SELECT alliance FROM player WHERE id = $player");
list($alliance) = dbFetchArray($q);
// Delete the player's requests and reinserts them while removing any tech that is now "seen"
$this->db->query("DELETE FROM tech_trade_request WHERE player = $player");
$prio = 0;
foreach ($requests as $req) {
$this->db->query(
"INSERT INTO tech_trade_request (alliance, player, priority, tech) "
. "VALUES ($alliance, $player, $prio, $req)"
);
$prio ++;
}
}
}
?>

View file

@ -0,0 +1,34 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/setTechTradeMode.inc
//
// This function allows the alliance president to change the tech trade
// mode for the alliance.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_setTechTradeMode {
static private $okModes = array('N', 'S', 'R');
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($alliance, $mode) {
if (!in_array($mode, self::$okModes)) {
return false;
}
$x = $this->db->query("UPDATE alliance SET enable_tt = '$mode' WHERE id = $alliance");
return !!$x;
}
}
?>

View file

@ -0,0 +1,58 @@
<?php
class beta5_alliance_stepDown {
function beta5_alliance_stepDown($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Makes the alliance leader step down from power
function run($aid, $isLeave = false) {
$a = $this->lib->call('get', $aid);
if (is_null($a) || is_null($a['successor'])) {
return;
}
$this->db->query("UPDATE alliance SET leader=".$a['successor'].",successor=NULL WHERE id=$aid");
if ($a['democracy'] == 't') {
$q = $this->db->query("SELECT id FROM alliance_candidate WHERE candidate=".$a['successor']);
if (dbCount($q) == 1) {
$q2 = $this->db->query("SELECT id FROM alliance_candidate WHERE candidate=".$a['leader']);
list($r1) = dbFetchArray($q);
list($r2) = dbFetchArray($q2);
$this->db->query("UPDATE player SET a_vote=$r2 WHERE a_vote=$r1");
$this->db->query("DELETE FROM alliance_candidate WHERE candidate=".$a['successor']);
} else {
$q = $this->db->query("SELECT id FROM alliance_candidate WHERE candidate={$a['leader']}");
list($id) = dbFetchArray($q);
$this->db->query("UPDATE player SET a_vote=$id WHERE id={$a['successor']}");
}
$this->db->query("UPDATE alliance_candidate SET candidate=".$a['successor']." WHERE candidate=".$a['leader']);
}
if ($isLeave) {
return;
}
$tm = time();
$tag = addslashes($a['tag']);
$qm = $this->db->query("SELECT id FROM player WHERE alliance=$aid AND a_status='IN'");
while ($r = dbFetchArray($qm)) {
$id = $r[0];
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' AND mtype='alint' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
if ($id == $a['leader']) {
$st = $a['successor'].",6";
} elseif ($id == $a['successor']) {
$st = $a['leader'].",7";
} else {
$st = $a['successor'].",8";
}
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',$st)");
}
}
}
?>

View file

@ -0,0 +1,69 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/submitTechList.inc
//
// This function stores a player's technology list in his alliance's
// tech trading database.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_submitTechList {
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
}
public function run($player) {
// Get alliance
$pInfo = $this->game->getLib('beta5/player')->call('get', $player);
$alliance = $pInfo['aid'];
// Get the player's technologies
$techLib = $this->game->getLib('beta5/tech');
$implemented = $techLib->call('getTopics', $player, 1);
$completed = $techLib->call('getTopics', $player, 0);
$foreseen = $techLib->call('getTopics', $player, -1);
$laws = $techLib->call('getLaws', $player);
// Delete previous tech submission
$this->db->query("DELETE FROM tech_trade_list WHERE member = $player");
// Insert technologies
for ($i = 0; $i < count($laws) / 2; $i ++) {
$this->db->query(
"INSERT INTO tech_trade_list (alliance, member, tech, status) "
. "VALUES ($alliance, $player, {$laws[$i * 2]}, 'L')"
);
}
for ($i = 0; $i < count($completed); $i ++) {
$this->db->query(
"INSERT INTO tech_trade_list (alliance, member, tech, status) "
. "VALUES ($alliance, $player, {$completed[$i]}, 'N')"
);
}
for ($i = 0; $i < count($implemented); $i ++) {
$this->db->query(
"INSERT INTO tech_trade_list (alliance, member, tech, status) "
. "VALUES ($alliance, $player, {$implemented[$i]}, 'I')"
);
}
for ($i = 0; $i < count($foreseen) / 2; $i ++) {
$this->db->query(
"INSERT INTO tech_trade_list (alliance, member, tech, status) "
. "VALUES ($alliance, $player, {$foreseen[$i * 2]}, 'F')"
);
}
// Update request list
$this->lib->call('updateRequests', $player);
}
}
?>

View file

@ -0,0 +1,119 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/submitTechOrders.inc
//
// This function updates the alliance's orders for the next 24 hours.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_submitTechOrders {
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
$this->msgs = $this->game->getLib('beta5/msg');
}
public function run($alliance, $orders) {
// List all players included in the orders
$players = array_keys($orders);
foreach ($orders as $oPid => $order) {
if (!in_array($order[1], $players)) {
array_push($players, $order[1]);
}
}
// Check if the players are in the alliance
$q = $this->db->query(
"SELECT id FROM player WHERE id IN (" . join(',', $players) . ") "
. "AND (alliance <> $alliance OR a_status <> 'IN ')"
);
if (dbCount($q)) {
return false;
}
// Get the tech lists for all players
$techList = $this->lib->call('getTechList', $alliance, false);
// Get all dependencies
$dependencies = $this->getDependencies();
// For each order, check if the sender had submitted the technology as
// either New, Implemented or Law, and whether he can actually send
// technologies. Also check if the receiver had submitted his list, if
// he can receive techs and if the list doesn't contain the technology
// to be sent. Oh, and if he has the dependencies.
foreach ($orders as $sender => $order) {
list($tech, $receiver) = $order;
if (!is_array($techList[$sender]) || !is_array($techList[$receiver])
|| $sender == $receiver || !$techList[$sender]['submitted']
|| $techList[$sender]['vacation'] || $techList[$sender]['restrict']
|| !$techList[$receiver]['submitted'] || $techList[$receiver]['vacation']
|| $techList[$receiver]['restrict']
|| !array_key_exists($tech, $techList[$sender]['list'])
|| $techList[$sender]['list'][$tech] == 'F'
|| array_key_exists($tech, $techList[$receiver]['list']) ) {
return false;
}
if (is_array($dependencies[$tech])) {
foreach ($dependencies[$tech] as $dep) {
if (!array_key_exists($dep, $techList[$receiver]['list'])) {
l::trace("dep $dep not found");
return false;
}
$dStatus = $techList[$receiver]['list'][$dep];
if ($dStatus != 'I' && $dStatus != 'L') {
return false;
}
}
}
}
// Delete current orders
$this->db->query("DELETE FROM tech_trade_order WHERE alliance = $alliance");
// Insert new orders
foreach ($orders as $sender => $order) {
list($tech, $receiver) = $order;
$this->db->query(
"INSERT INTO tech_trade_order (alliance, player, send_to, tech) "
. "VALUES($alliance, $sender, $receiver, $tech)"
);
}
// Send private message to all players included in the exchange
$q = $this->db->query("SELECT tag FROM alliance WHERE id = $alliance");
list($tag) = dbFetchArray($q);
foreach ($players as $player) {
$this->msgs->call('send', $player, 'alint', array(
"msg_type" => 20,
"tag" => $tag,
"alliance" => $alliance
));
}
return true;
}
private function getDependencies() {
$q = $this->db->query("SELECT research, depends_on FROM research_dep");
$deps = array();
while ($r = dbFetchArray($q)) {
if (!is_array($deps[$r[0]])) {
$deps[$r[0]] = array();
}
array_push($deps[$r[0]], $r[1]);
}
return $deps;
}
}
?>

View file

@ -0,0 +1,34 @@
<?php
class beta5_alliance_takePresidency {
function beta5_alliance_takePresidency($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Makes a player the new president for an alliance
function run($aid, $pid) {
$this->db->query("UPDATE alliance SET leader=$pid,successor=NULL WHERE id=$aid");
$a = $this->lib->call('get', $aid);
$tag = addslashes($a['tag']);
$tm = time();
$l = array_keys($this->lib->call('getMembers', $aid));
foreach ($l as $id) {
$this->db->query("INSERT INTO message(player,sent_on,mtype,ftype,is_new) VALUES($id,$tm,'alint','INT',TRUE)");
$q = $this->db->query("SELECT id FROM message WHERE player=$id AND sent_on=$tm AND ftype='INT' ORDER BY id DESC LIMIT 1");
list($mid) = dbFetchArray($q);
if ($id == $pid) {
$mt = 18;
} else {
$mt = 19;
}
$this->db->query("INSERT INTO msg_alint VALUES($mid,$aid,'$tag',$pid,$mt)");
}
}
}
?>

View file

@ -0,0 +1,75 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/alliance/library/updateRequests.inc
//
// This function checks whether a player's tech trading requests are ok.
// If they are not, it either deletes or re-arranges them.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_alliance_updateRequests {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($player) {
// Get the player's alliance
$q = $this->db->query("SELECT alliance,a_status FROM player WHERE id = $player");
list($alliance, $aStat) = dbFetchArray($q);
// If the player is not a member of any alliance, remove all requests and leave
if (is_null($alliance) || $aStat != 'IN ') {
$this->db->query("DELETE FROM tech_trade_request WHERE player = $player");
return;
}
// Get the player's current requests, if any
$q = $this->db->query(
"SELECT alliance, tech FROM tech_trade_request "
. "WHERE player = $player ORDER BY priority"
);
$requests = array();
while ($r = dbFetchArray($q)) {
if ($r[0] != $alliance) {
// Requests are from another alliance; delete them and leave
$this->db->query("DELETE FROM tech_trade_request WHERE player = $player");
return;
}
array_push($requests, $r[1]);
}
// Get all technologies or laws that are at least foreseen
$q = $this->db->query(
"SELECT r.id FROM research_player p, research r "
. "WHERE r.id = p.research AND p.points >= 75 * r.points / 100 AND p.player = $player"
);
$seenTechs = array();
while ($r = dbFetchArray($q)) {
array_push($seenTechs, $r[0]);
}
// Delete the player's requests and reinserts them while removing any tech that is now "seen"
$this->db->query("DELETE FROM tech_trade_request WHERE player = $player");
$prio = 0;
foreach ($requests as $req) {
if (in_array($req, $seenTechs)) {
continue;
}
$this->db->query(
"INSERT INTO tech_trade_request (alliance, player, priority, tech) "
. "VALUES ($alliance, $player, $prio, $req)"
);
$prio ++;
}
}
}
?>

View file

@ -0,0 +1,54 @@
<?php
class beta5_alliance_updateVictory {
function beta5_alliance_updateVictory($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Compute victory conditions for an alliance
function run($aid) {
// Get the total amount of planets
$q = $this->db->query("SELECT COUNT(*) FROM planet WHERE status = 0");
list($pCount) = dbFetchArray($q);
// Get the amount of planets the alliance controls
$q = $this->db->query("SELECT COUNT(*) FROM planet WHERE owner IN ("
. "SELECT id FROM player WHERE alliance = $aid AND a_status='IN')");
list($aCount) = dbFetchArray($q);
// Compute the ratio
$pRatio = $aCount / $pCount;
if ($pRatio > 0.75) {
$pRatio = 0.75;
// Check if the alliance was already scheduled for victory
$q = $this->db->query("SELECT time_of_victory FROM alliance_victory WHERE alliance=$aid");
if (dbCount($q)) {
list($tov) = dbFetchArray($q);
if (time() > $tov) {
$tValue = 0.25;
} else {
$diff = $tov - time();
if ($diff > 604800) {
$diff = 604800;
}
$tValue = (604800 - $diff) / 2419200; // 7*24*3600*4
}
logText("tov = $tov, diff = $diff, tval = $tValue");
} else {
$this->db->query("INSERT INTO alliance_victory(alliance, time_of_victory)"
. " VALUES ($aid, UNIX_TIMESTAMP(NOW()) + 604800)");
$tValue = 0;
}
} else {
$tValue = 0;
$this->db->query("DELETE FROM alliance_victory WHERE alliance=$aid");
}
return round(($pRatio + $tValue) * 100);
}
}
?>

View file

@ -0,0 +1,50 @@
<?php
class beta5_bq_library {
var $types = array('turret', 'gaship', 'fighter', 'cruiser', 'bcruiser');
var $qLen = array();
var $index = array (
'append',
'flush',
'get',
'getReplacementCost',
'remove',
'reorder',
'replace'
);
function beta5_bq_library($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Returns the length of a planet's build queue
function getLength($pl) {
if (is_null($this->qLen[$pl])) {
$q = $this->db->query("SELECT COUNT(*) FROM buildqueue WHERE planet = $pl");
list($this->qLen[$pl]) = dbFetchArray($q);
}
return $this->qLen[$pl];
}
// Moves an item down the build queue
function moveDown($pl, $it) {
$bql = $this->lib->call('getLength', $pl);
$np = $it + 1;
$this->db->query("UPDATE buildqueue SET bq_order = $bql WHERE planet = $pl AND bq_order = $it");
$this->db->query("UPDATE buildqueue SET bq_order = $it WHERE planet = $pl AND bq_order = $np");
$this->db->query("UPDATE buildqueue SET bq_order = $np,workunits=0 WHERE planet = $pl AND bq_order = $bql");
}
// Moves an item up the build queue
function moveUp($pl, $it) {
$bql = $this->lib->call('getLength', $pl);
$np = $it - 1;
$this->db->query("UPDATE buildqueue SET bq_order = $bql WHERE planet = $pl AND bq_order = $it");
$this->db->query("UPDATE buildqueue SET bq_order = $it WHERE planet = $pl AND bq_order = $np");
$this->db->query("UPDATE buildqueue SET bq_order = $np,workunits=0 WHERE planet = $pl AND bq_order = $bql");
}
}
?>

View file

@ -0,0 +1,35 @@
<?php
class beta5_bq_append {
function beta5_bq_append($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Add items to a planet's build queue
function run($id, $nb, $type) {
$q = $this->db->query("SELECT owner FROM planet WHERE id = $id");
list($uid) = dbFetchArray($q);
$ru = $this->rules->call('get', $uid);
$q = $this->db->query("SELECT MAX(bq_order) FROM buildqueue WHERE planet = $id");
if (dbCount($q)) {
list($o) = dbFetchArray($q);
if (is_null($o)) {
$o = -1;
}
} else {
$o = -1;
}
$o ++;
$this->db->query("INSERT INTO buildqueue VALUES($id, $o, $type, $nb, 0)");
$cost = $ru['build_cost_'.$this->lib->mainClass->types[$type]] * $nb;
$this->db->query("UPDATE player SET cash = cash - $cost WHERE id = $uid");
}
}
?>

View file

@ -0,0 +1,32 @@
<?php
class beta5_bq_flush {
function beta5_bq_flush($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Flush a planet's build queue
function run($id) {
$q = $this->db->query("SELECT owner FROM planet WHERE id = $id");
list($uid) = dbFetchArray($q);
if (is_null($uid)) {
return;
}
$ru = $this->rules->call('get', $uid);
$sum = 0;
$q = $this->db->query("SELECT item,quantity FROM buildqueue WHERE planet = $id");
while ($r = dbFetchArray($q)) {
$sum += $r[1] * $ru['build_cost_'.$this->lib->mainClass->types[$r[0]]];
}
$this->db->query("DELETE FROM buildqueue WHERE planet = $id");
$this->db->query("UPDATE player SET cash = cash + $sum WHERE id = $uid");
}
}
?>

View file

@ -0,0 +1,52 @@
<?php
class beta5_bq_get {
function beta5_bq_get($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Returns the contents of a planet's build queue
function run($id) {
$q = $this->db->query("SELECT owner,mfact,corruption FROM planet WHERE id=$id");
list($uid, $mf, $cl) = dbFetchArray($q);
$ru = $this->rules->call('get', $uid);
$mp = $ru['mf_productivity'] * $ru['mf_productivity_factor'] * $mf;
if ($mp == 0) {
$mp = 1;
}
$cl = $cl / 32000;
if ($cl > .1) {
$mp = floor($mp * (1.1 - $cl));
}
$q = $this->db->query("SELECT item,quantity,workunits FROM buildqueue WHERE planet = $id ORDER BY bq_order ASC");
$bq = array();
$cwu = 0;
while ($r = dbFetchArray($q)) {
$i = array(
"type" => $r[0],
"quantity" => $r[1],
"workunits" => $r[2]
);
$units = $ru['workunits_'.$this->lib->mainClass->types[$r[0]]] * $r[1] - $r[2];
$i['units'] = $units;
$cwu += $units;
$mod = $units % $mp;
$ttb = ($units - $mod) / $mp + ($mod ? 1 : 0);
$i['time'] = $ttb;
$mod = $cwu % $mp;
$ttb = ($cwu - $mod) / $mp + ($mod ? 1 : 0);
$i['ctime'] = $ttb;
$i['cost'] = $r[1] * $ru['build_cost_'.$this->lib->mainClass->types[$r[0]]];
array_push($bq, $i);
}
return $bq;
}
}
?>

View file

@ -0,0 +1,41 @@
<?php
class beta5_bq_getReplacementCost {
function beta5_bq_getReplacementCost($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Computes the cost of replacing a set of build queue items
function run($pid, $items, $rCost) {
if (count($items) == 0) {
return 0;
}
$q = $this->db->query("SELECT owner FROM planet WHERE id = $pid");
list($uid) = dbFetchArray($q);
$ru = $this->rules->call('get', $uid);
if (count($items) == 1) {
$wc = "=".$items[0];
} else {
$wc = "IN (" . join(',', $items) . ")";
}
$q = $this->db->query("SELECT item,quantity FROM buildqueue WHERE planet = $pid AND bq_order $wc");
if (!dbCount($q)) {
return 0;
}
$sum = 0;
while ($r = dbFetchArray($q)) {
$sum -= $r[1] * $ru['build_cost_'.$this->lib->mainClass->types[$r[0]]];
$sum += $rCost;
}
return $sum;
}
}
?>

View file

@ -0,0 +1,30 @@
<?php
class beta5_bq_remove {
function beta5_bq_remove($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Removes an item from a build queue
function run($pid, $item) {
$q = $this->db->query("SELECT owner FROM planet WHERE id = $pid");
list($uid) = dbFetchArray($q);
$ru = $this->rules->call('get', $uid);
$q = $this->db->query("SELECT item,quantity FROM buildqueue WHERE planet = $pid AND bq_order = $item");
if (!dbCount($q)) {
return;
}
list($t,$n) = dbFetchArray($q);
$cost = $n * $ru['build_cost_'.$this->lib->mainClass->types[$t]];
$this->db->query("DELETE FROM buildqueue WHERE planet = $pid AND bq_order = $item");
$this->db->query("UPDATE player SET cash = cash + $cost WHERE id = $uid");
}
}
?>

View file

@ -0,0 +1,24 @@
<?php
class beta5_bq_reorder {
function beta5_bq_reorder($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Reorders the build queue
function run($pid) {
$q = $this->db->query("SELECT bq_order FROM buildqueue WHERE planet = $pid ORDER BY bq_order ASC");
$i = 0;
while ($r = dbFetchArray($q)) {
if ($r[0] != $i) {
$this->db->query("UPDATE buildqueue SET bq_order = $i WHERE planet = $pid AND bq_order = ".$r[0]);
}
$i ++;
}
}
}
?>

View file

@ -0,0 +1,43 @@
<?php
class beta5_bq_replace {
function beta5_bq_replace($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Replaces items in a build queue
function run($pid, $items, $nb, $type) {
if (count($items) == 0) {
return;
}
$q = $this->db->query("SELECT owner FROM planet WHERE id = $pid");
list($uid) = dbFetchArray($q);
$ru = $this->rules->call('get', $uid);
if (count($items) == 1) {
$wc = "=".$items[0];
} else {
$wc = "IN (" . join(',', $items) . ")";
}
$q = $this->db->query("SELECT item,quantity FROM buildqueue WHERE planet = $pid AND bq_order $wc");
if (!dbCount($q)) {
return;
}
$rCost = $nb * $ru['build_cost_'.$this->lib->mainClass->types[$type]];
$sum = 0;
while ($r = dbFetchArray($q)) {
$sum += $r[1] * $ru['build_cost_'.$this->lib->mainClass->types[$r[0]]];
$sum -= $rCost;
}
$this->db->query("UPDATE buildqueue SET item=$type,quantity=$nb,workunits=0 WHERE planet = $pid AND bq_order $wc");
$this->db->query("UPDATE player SET cash = cash + ($sum) WHERE id = $uid");
}
}
?>

View file

@ -0,0 +1,99 @@
<?
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/ctf/library.inc
//
// This library handles everything specific to Kings of the Hill (CTF)
// matches.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_ctf_library {
var $index = array (
'assign',
'checkTargets',
'joinMessage',
'resetGame'
);
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
}
// This function sends a CTF-specific message to a player
public function message($player, $mType, $team, $timestamp = null) {
if (! $this->msgs) {
$this->msgs = $this->game->getLib('beta5/msg');
}
$this->msgs->call('send', $player, 'ctf', array(
'msg_type' => $mType,
'team' => $team,
'time_stamp' => $timestamp
), $mType ? 'INT' : 'IN');
}
// This function checks whether a specific system is a target
public function isTarget($system) {
// Cache the targets as this function tends to be called several
// times in a row
if (! $this->targets) {
$q = $this->db->query("SELECT system FROM ctf_target");
if (!($q && dbCount($q))) {
return;
}
$this->targets = array();
while ($r = dbFetchArray($q)) {
array_push($this->targets, $r[0]);
}
}
return in_array($system, $this->targets);
}
// This function returns the amount of points a team has
public function getTeamPoints($team) {
$q = $this->db->query("SELECT points FROM ctf_points WHERE team = $team");
if (!($q && dbCount($q))) {
return 0;
}
list($points) = dbFetchArray($q);
return $points;
}
// This function checks for victory
public function checkVictory() {
// Get the target count
$q = $this->db->query("SELECT COUNT(*) FROM ctf_target");
list($tCount) = dbFetchArray($q);
// For each team, get the count of targets held without grace
// for more than <v2time> hours
$time = $this->game->params['v2time'] * 3600;
$q = $this->db->query(
"SELECT held_by, COUNT(*) FROM ctf_target "
. "WHERE held_by IS NOT NULL AND grace_expires IS NULL "
. "AND held_since <= UNIX_TIMESTAMP(NOW()) - $time "
. "GROUP BY held_by"
);
// If there's only one result and if the count is the same as
// the target count, we got a winner
if (dbCount($q) == 1) {
list($team, $hCount) = dbFetchArray($q);
if ($hCount == $tCount) {
return $team;
}
}
return null;
}
}
?>

View file

@ -0,0 +1,88 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/ctf/library/assign.inc
//
// This function assigns a planet to a player in a CTF game.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_ctf_assign {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->planets = $this->lib->game->getLib('beta5/planet');
}
public function run($player, $planetName, $team) {
logText("Assigning planet $planetName for player #$player in team #$team");
// Find unassigned systems marked as spawning area for the team
$system = $this->findFreeSystem($team);
// Assign a random planet in the system
$planet = $this->assignPlanet($player, $system, $planetName);
// Mark the system as the player's spawning point
$this->markSystem($player, $system);
return $planet;
}
private function findFreeSystem($team) {
$q = $this->db->query(
"SELECT s.id FROM system s, ctf_alloc a "
. "WHERE s.id = a.system AND a.alliance = $team "
. "AND a.spawn_point AND NOT s.assigned "
. "FOR UPDATE OF s, a"
);
$n = rand(0, dbCount($q) - 2);
while ($n) {
dbFetchArray($q);
$n --;
}
list($system) = dbFetchArray($q);
return $system;
}
private function assignPlanet($player, $system, $name) {
// Randomize orbit
$npl = 6;
$porb = rand(0, $npl - 1);
// Give the planet to the player
$tm = time();
$this->db->query("UPDATE planet SET name='$name', owner=$player,renamed=$tm,mod_check=FALSE "
. "WHERE system = $system AND orbit = $porb");
// Get planet ID and population
$q = $this->db->query("SELECT id, pop FROM planet WHERE system = $system AND orbit = $porb FOR UPDATE");
list($plid, $cPop) = dbFetchArray($q);
// Update happiness and maximum population
$this->planets->call('updateHappiness', $plid);
$this->planets->call('updateMaxPopulation', $plid, null, $player);
return $plid;
}
private function markSystem($player, $system) {
// Mark the system itself
$this->db->query("UPDATE system SET assigned = TRUE WHERE id = $system");
// Mark the allocation record
$this->db->query("UPDATE ctf_alloc SET player = $player WHERE system = $system");
}
}
?>

View file

@ -0,0 +1,279 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/ctf/library/checkTargets.inc
//
// This function checks the targets' status and sends messages if needed.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_ctf_checkTargets {
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
}
public function run() {
// Get the current status (used later to send messages)
$initialStatus = $this->getStatus();
$this->grace = ($initialStatus[0] != 'nohold') ? (3600 * $this->game->params['v2grace']) : 0;
// Get the list of all target systems
$q = $this->db->query("SELECT * FROM ctf_target");
$targets = array();
while ($r = dbFetchHash($q)) {
array_push($targets, $r);
}
// For each target, check the system's status
foreach ($targets as $target) {
$this->checkTargetStatus($target);
}
// Get the new status
$newStatus = $this->getStatus();
// Check status changes
$this->checkStatusChanges($initialStatus, $newStatus);
}
private function getStatus() {
// Get the target count
$q = $this->db->query("SELECT COUNT(*) FROM ctf_target");
list($tCount) = dbFetchArray($q);
// For each team, get the count of targets held without grace
$q = $this->db->query(
"SELECT held_by, COUNT(*) FROM ctf_target "
. "WHERE held_by IS NOT NULL AND grace_expires IS NULL "
. "GROUP BY held_by"
);
if (dbCount($q) == 1) {
list($team, $hCount) = dbFetchArray($q);
if ($hCount == $tCount) {
$q = $this->db->query("SELECT MAX(held_since) FROM ctf_target");
list($heldSince) = dbFetchArray($q);
return array('held', $team, $heldSince);
}
}
// For each team, get the count of targets held
$q = $this->db->query(
"SELECT held_by, COUNT(*) FROM ctf_target "
. "WHERE held_by IS NOT NULL "
. "GROUP BY held_by"
);
if (dbCount($q) == 1) {
list($team, $gCount) = dbFetchArray($q);
if ($gCount == $tCount) {
$q = $this->db->query("SELECT MIN(grace_expires) FROM ctf_target");
list($graceExpires) = dbFetchArray($q);
return array('grace', $team, $graceExpires);
}
}
return array('nohold');
}
private function checkTargetStatus($target) {
// Get the team for each planet in the system
$q = $this->db->query(
"SELECT y.alliance FROM planet p, player y "
. "WHERE y.id = p.owner AND p.system = {$target['system']}"
);
// If all planets are being held, list the alliances
$teams = array();
$teamPlanets = array();
while ($r = dbFetchArray($q)) {
if (array_key_exists($r[0], $teamPlanets)) {
$teamPlanets[$r[0]] ++;
} else {
$teamPlanets[$r[0]] = 1;
array_push($teams, $r[0]);
}
}
if (count($teams) == 1 && $teamPlanets[$teams[0]] == 6) {
// One team is holding the whole system
$this->heldByTeam($target, $teams[0]);
} else {
// The system is not being held by any particular team
$this->notHeld($target);
}
}
private function heldByTeam($target, $team) {
$tid = $target['system'];
if (is_null($target['held_by'])) {
// If only one team is holding the planets and the system was
// not marked as being held, mark it
logText("Target #$tid now held by team #$team");
$this->assignTarget($target['system'], $team);
} elseif ($target['held_by'] == $team && ! is_null($target['grace_expires'])) {
// If the target was being held by the team but had a grace expiration,
// cancel grace period expiration and increase held_by accordingly
logText("Target #$tid held by team #$team again, grace cancelled");
$gracePeriod = time() - $target['grace_expires'] + $this->grace;
$this->db->query(
"UPDATE ctf_target "
. "SET grace_expires = NULL, held_since = held_since + $gracePeriod "
. "WHERE system = {$target['system']}"
);
} elseif ($target['held_by'] != $team && $this->grace > 0) {
// The target is now being held by another team and the game
// has support for grace periods
if (is_null($target['grace_expires'])) {
// No grace was set - set it
logText("Target #$tid held by team #$team, setting grace for previous holder #"
. $target['held_by']);
$this->setGrace($target['system'], $this->grace);
} elseif ($target['grace_expires'] <= time()) {
// Grace has expired, but a new team is holding the system
logText("Target #$tid now held by team #$team, grace ended for previous holder #"
. $target['held_by']);
$this->assignTarget($target['system'], $team);
}
} elseif ($target['held_by'] != $team) {
// The target is now being held by another team, and there is no
// grace period
logText("Target #$tid now held by team #$team, no grace for previous holder #"
. $target['held_by']);
$this->assignTarget($target['system'], $team);
}
}
private function notHeld($target) {
// If the target wasn't being held before, we're done
if (is_null($target['held_by'])) {
return;
}
$tid = $target['system'];
if ($this->grace > 0) {
// If there is support for grace periods
if (is_null($target['grace_expires'])) {
// Grace period wasn't set - set it
$this->setGrace($target['system'], $this->grace);
logText("Target #$tid no longer held by team #{$target['held_by']}, setting grace");
} elseif ($target['grace_expires'] <= time()) {
// Grace period expired, no-one's holding the system
logText("Target #$tid no longer held by team #{$target['held_by']}, grace ended");
$this->unassignTarget($target['system']);
}
} else {
// No grace periods, no-one's holding the system
logText("Target #$tid no longer held by team #{$target['held_by']}, no grace");
$this->unassignTarget($target['system']);
}
}
private function assignTarget($target, $team) {
$this->db->query(
"UPDATE ctf_target "
. "SET held_by = $team, "
. "held_since = UNIX_TIMESTAMP(NOW()), "
. "grace_expires = NULL "
. "WHERE system = $target"
);
}
private function setGrace($target, $grace) {
$this->db->query(
"UPDATE ctf_target SET grace_expires = UNIX_TIMESTAMP(NOW()) + $grace WHERE system = $target"
);
}
private function unassignTarget($target) {
$this->db->query(
"UPDATE ctf_target "
. "SET held_by = NULL, held_since = NULL, grace_expires = NULL "
. "WHERE system = $target"
);
}
private function checkStatusChanges($initialStatus, $newStatus) {
$winTime = $this->game->params['v2time'] * 3600;
// Status hasn't changed
if ($initialStatus[0] == $newStatus[0] && $initialStatus[1] == $newStatus[1]) {
// Check for victory / halfway to victory
if ($initialStatus[0] == 'held') {
$halfWay = $initialStatus[2] + $winTime / 2;
$victory = $initialStatus[2] + $winTime;
$now = time();
if ($now >= $halfWay && $now < $halfWay + 21) {
$this->statusMessage(10, 11, $newStatus[1], $victory);
} elseif ($now >= $victory) {
// If the game is finished, we shouldn't be here anyways
$this->lib->call('resetGame', $newStatus[1]);
}
}
return;
}
// Status changed, send messages
logText("CTF Status: (" . join(',',$initialStatus) . ") -> (" . join(',',$newStatus) . ")");
if ($initialStatus[0] == 'nohold' && $newStatus[0] == 'held') {
// The targets are now being held by a team
$this->statusMessage(2, 3, $newStatus[1], $newStatus[2] + $winTime);
} elseif ($initialStatus[0] == 'grace' && $newStatus[0] == 'nohold') {
// Targets are no longer being held (no grace period)
$this->statusMessage(6, 9, $initialStatus[1]);
$this->cancelAllGraces();
} elseif ($initialStatus[0] == 'held' && $newStatus[0] == 'nohold') {
// Targets are no longer being held (no grace period)
$this->statusMessage(5, 8, $initialStatus[1]);
} elseif ($initialStatus[0] == 'held' && $newStatus[0] == 'grace') {
// Targets are no longer being held (with grace period)
$this->statusMessage(4, 7, $initialStatus[1], $newStatus[2]);
} elseif ($initialStatus[0] == 'held' && $newStatus[0] == 'held') {
// Targets are now held by another team
$this->statusMessage(5, 8, $initialStatus[1]);
$this->statusMessage(2, 3, $newStatus[1], $newStatus[2] + $winTime);
} elseif ($initialStatus[0] == 'grace' && $newStatus[0] == 'held') {
if ($initialStatus[1] != $newStatus[1]) {
// Other team gained control
$this->statusMessage(6, 9, $initialStatus[1]);
}
$this->statusMessage(2, 3, $newStatus[1], $newStatus[2] + $winTime);
}
}
private function statusMessage($toTeam, $toOthers, $team, $timestamp = null) {
$q = $this->db->query("SELECT id,alliance FROM player");
while ($r = dbFetchArray($q)) {
$this->lib->call('message', $r[0], $r[1] == $team ? $toTeam : $toOthers, $team, $timestamp);
}
}
private function cancelAllGraces() {
$this->db->query("UPDATE ctf_target SET grace_expires = NULL");
}
}
?>

View file

@ -0,0 +1,38 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/ctf/library/joinMessage.inc
//
// This function sends messages to members of a team when another player
// is assigned to it.
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_ctf_joinMessage {
public function __construct($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
public function run($team, $player) {
// List all players in the team
$q = $this->db->query(
"SELECT id FROM player WHERE alliance=$team AND id <> $player"
);
if (!($q && dbCount($q))) {
return;
}
// Send a message to each player
while ($r = dbFetchArray($q)) {
$this->lib->call('message', $r[0], 1, $team, $player);
}
}
}
?>

View file

@ -0,0 +1,349 @@
<?php
//-----------------------------------------------------------------------
// LegacyWorlds Beta 5
// Game libraries
//
// beta5/ctf/library/resetGame.inc
//
// This function is called when a team wins a round.
//
// It first increases the team's victory status. If the game is finished
// it sends messages, updates the rankings and stops there.
//
// FIXME: incomplete explanation
//
// Copyright(C) 2004-2008, DeepClone Development
//-----------------------------------------------------------------------
class beta5_ctf_resetGame {
private static $ftFields = array('gaships', 'fighters', 'cruisers', 'bcruisers');
public function __construct($lib) {
$this->lib = $lib;
$this->game = $this->lib->game;
$this->db = $this->game->db;
$this->fleets = $this->game->getLib('beta5/fleet');
$this->planets = $this->game->getLib('beta5/planet');
$this->players = $this->game->getLib('beta5/player');
}
public function run($winningTeam) {
// Starts by increasing the team's score
$cPoints = $this->increaseScore($winningTeam);
// Did the team win the whole game ?
if ($cPoints == 100) {
$this->endGame($winningTeam);
return;
}
// Neutralize all planets that are owned by players of a team in an area allocated to another team
// as well as planets owned by players in other players' spawning systems
$this->neutralizeColonies();
// Reset all planets that had been WHSN'd
$this->resetWHSN();
// Remove all WHSN penalties
$this->removePenalties();
// Neutralize and consolidate planets in target systems
$this->neutralizeTargets();
// And the dead shall rise again ...
$this->respawnPlayers();
// Equalize fleet sizes and send the fleets home
$this->equalizeFleets();
// Update corruption, happiness and attack status for all planets
$this->updatePlanets();
// Send messages
$this->sendRoundMessages($winningTeam);
}
private function increaseScore($winningTeam) {
$q = $this->db->query("SELECT points FROM ctf_points WHERE team = $winningTeam FOR UPDATE");
if (dbCount($q)) {
list($cPoints) = dbFetchArray($q);
$cPoints = min(100, $cPoints + $this->game->params['v2points']);
$this->db->query("UPDATE ctf_points SET points = $cPoints WHERE team = $winningTeam");
} else {
$cPoints = $this->game->params['v2points'];
$this->db->query("INSERT INTO ctf_points (team, points) VALUES ($winningTeam, $cPoints)");
}
return $cPoints;
}
private function endGame($winningTeam) {
// Fetch the list of players and their teams
$q = $this->db->query("SELECT id,alliance FROM player");
while ($r = dbFetchArray($q)) {
$this->lib->call('message', $r[0], ($r[1] == $winningTeam ? 14 : 15), $winningTeam);
}
// Update the rankings
$this->game->getLib()->call('updateRankings');
}
private function neutralizeColonies() {
// Get the list of all planets to neutralize
$q = $this->db->query(
"SELECT p.id, y.id FROM planet p, ctf_alloc a, player y "
. "WHERE p.owner = y.id AND p.system = a.system "
. "AND a.alliance <> y.alliance "
. "UNION SELECT p.id, y.id FROM planet p, ctf_alloc a, player y "
. "WHERE p.system = a.system AND y.id = p.owner AND a.alliance = y.alliance "
. "AND a.spawn_point AND a.player <> y.id"
);
// Neutralize the planets
while ($r = dbFetchArray($q)) {
$this->planets->call('ownerChange', $r[0]);
$this->players->call('losePlanet', $r[1], $r[0]);
}
}
private function resetWHSN() {
// Get the list of WHSN'd planets
$q = $this->db->query(
"SELECT p.id FROM planet p, system s WHERE s.nebula = 0 AND p.status <> 0 AND p.system = s.id"
);
// Recreate planets instead
while ($r = dbFetchArray($q)) {
$this->regenPlanet($r[0]);
}
}
private function regenPlanet($id) {
$ttn = rand(3, 12);
do {
$rn = strtoupper(substr(md5(uniqid(rand())), 0, 7));
$q = $this->db->query("SELECT id FROM planet WHERE name='P-[$rn]'");
} while (dbCount($q));
$q = $this->db->query("SELECT max_pop FROM planet_max_pop WHERE planet = $id AND tech_level = 0");
list($maxPop) = dbFetchArray($q);
$this->db->query(
"UPDATE planet SET status = 0, pop = 2000, ifact = 3, mfact = 3, "
. "turrets = $ttn, name = 'P-[$rn]', max_pop = $maxPop "
. "WHERE id = $id"
);
}
private function removePenalties() {
$this->db->query("UPDATE planet SET bh_unhappiness = 0");
$this->db->query("UPDATE player SET bh_unhappiness = 0");
}
private function neutralizeTargets() {
// Reset target status
$this->db->query("UPDATE ctf_target SET held_by = NULL, held_since = NULL, grace_expires = NULL");
// Get the list of all planets to neutralize
$q = $this->db->query(
"SELECT p.id, y.id, p.pop FROM planet p, ctf_target t, player y "
. "WHERE p.owner = y.id AND p.system = t.system"
);
while ($r = dbFetchArray($q)) {
// Neutralize the planet
$this->planets->call('ownerChange', $r[0]);
$this->players->call('losePlanet', $r[1], $r[0]);
// Compute factories and turrets for the planet
$x = ($r[2] - 2000) / 48000;
$facts = floor((($r[2] / 30) - 754 * $x * $x) / 2);
$turrets = floor(($r[2] / 22) - 510 * $x * $x);
// Set the planet's factories and turrets, reset its corruption
$this->db->query(
"UPDATE planet SET ifact = $facts, mfact = $facts, turrets = $turrets, corruption = 0 "
. "WHERE id = {$r[0]}"
);
}
}
private function respawnPlayers() {
// Get the list of players who don't have planets
$q = $this->db->query(
"SELECT id FROM player WHERE NOT hidden AND id NOT IN ("
. "SELECT DISTINCT owner FROM planet WHERE owner IS NOT NULL)"
);
while ($r = dbFetchArray($q)) {
$this->respawn($r[0]);
}
}
private function respawn($player) {
// Get the player's initial system
$q = $this->db->query("SELECT system FROM ctf_alloc WHERE player = $player");
list($system) = dbFetchArray($q);
// Choose a random planet
$orbit = rand(0, 5);
$q = $this->db->query("SELECT id FROM planet WHERE system = $system AND orbit = $orbit");
list($planet) = dbFetchArray($q);
// Assign the planet
$this->planets->call('ownerChange', $planet, $player);
$this->players->call('takePlanet', $player, $planet);
}
private function equalizeFleets() {
// Get the list of fleets
list($pFleets, $aFleets) = $this->getAllFleets();
// Compute fleet reduction based on alliance fleets
$fleetReductions = $this->computeReductions($aFleets);
// Compute the reductions for each player
foreach ($pFleets as $player => $fleets) {
$team = array_shift($fleets);
$pFleets[$player] = $this->playerReduction($fleets, $aFleets[$team], $fleetReductions[$team]);
}
// Reinsert each player's fleet at one of his planets
foreach ($pFleets as $player => $fleet) {
$this->insertFleet($player, $fleet);
}
}
private function getAllFleets() {
// Get the list of all fleets
$q = $this->db->query(
"SELECT f.id, p.id, p.alliance FROM fleet f, player p WHERE f.owner = p.id"
);
// Compute totals and disband the fleets as we go
$playerFleets = array();
$allianceFleets = array();
while ($r = dbFetchArray($q)) {
list($fleetID, $player, $alliance) = $r;
if (is_null($playerFleets[$player])) {
$playerFleets[$player] = array($alliance,0,0,0,0);
}
if (is_null($allianceFleets[$alliance])) {
$allianceFleets[$alliance] = array(0,0,0,0);
}
$fleet = $this->fleets->call('get', $fleetID);
for ($i = 0; $i < 4; $i ++) {
$playerFleets[$player][$i + 1] += $fleet[self::$ftFields[$i]];
$allianceFleets[$alliance][$i] += $fleet[self::$ftFields[$i]];
}
$this->fleets->call('disband', $fleetID);
}
return array($playerFleets, $allianceFleets);
}
private function computeReductions($fleets) {
// Find the smallest values for each type of ship
$smallest = null;
foreach ($fleets as $team => $tFleets) {
if (is_null($smallest)) {
$smallest = $tFleets;
continue;
}
for ($i = 0; $i < 4; $i ++) {
if ($tFleets[$i] < $smallest[$i]) {
$smallest[$i] = $tFleets[$i];
}
}
}
// Compute reductions for each team
$reductions = array();
foreach ($fleets as $team => $tFleets) {
$reductions[$team] = array();
for ($i = 0; $i < 4; $i ++) {
if ($tFleets[$i] == $smallest[$i]) {
$nAmount = 0;
} else {
$rnd = ($smallest == 0) ? rand(101, 105) : rand(98, 105);
$nAmount = $tFleets[$i] - floor($rnd * $smallest[$i] / 100);
}
$reductions[$team][$i] = $nAmount;
}
}
return $reductions;
}
private function playerReduction($pFleets, $aFleets, $aReduction) {
$reduc = array();
for ($i = 0; $i < 4; $i ++) {
if ($aFleets[$i] == 0) {
continue;
}
$ratio = $pFleets[$i] / $aFleets[$i];
$reduction = floor($aReduction[$i] * $ratio);
$reduc[$i] = $pFleets[$i] - $reduction;
}
return $reduc;
}
private function insertFleet($player, $fleet) {
if ($fleet[0] + $fleet[1] + $fleet[2] + $fleet[3] == 0) {
return;
}
// Get a planet belonging to the player
$q = $this->db->query("SELECT id FROM planet WHERE owner = $player LIMIT 1");
list($planet) = dbFetchArray($q);
$qString1 = "INSERT INTO fleet (owner, location";
$qString2 = ") VALUES ($player, $planet";
for ($i = 0; $i < 4; $i ++) {
if ($fleet[$i] == 0) {
continue;
}
$qString1 .= ", " . self::$ftFields[$i];
$qString2 .= ", {$fleet[$i]}";
}
$this->db->query("$qString1$qString2)");
}
private function updatePlanets() {
$this->db->query("UPDATE planet SET corruption = corruption / 2");
$q = $this->db->query(
"SELECT p.id FROM planet p, system s "
. "WHERE s.id = p.system AND s.nebula = 0"
);
while ($r = dbFetchArray($q)) {
$this->planets->call('updateHappiness', $r[0]);
$this->planets->call('updateMilStatus', $r[0]);
}
}
private function sendRoundMessages($winningTeam) {
$q = $this->db->query("SELECT id,alliance FROM player");
while ($r = dbFetchArray($q)) {
$this->lib->call('message', $r[0], ($r[1] == $winningTeam ? 12 : 13), $winningTeam);
}
}
}

View file

@ -0,0 +1,99 @@
<?php
class beta5_ecm_library {
var $index = array();
var $ecmTable = array();
var $eccmTable = array();
var $probTables = array();
function beta5_ecm_library($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
function getInformationLevel($ecm, $eccm) {
// Get the probability table
$probTable = $this->getProbabilityTable($ecm, $eccm);
// Randomly selects an information level
$p = rand(0,9999) / 10000;
$i = 0;
while ($p > $probTable[$i]) {
$p -= $probTable[$i];
$i ++;
}
return $i;
}
function getProbabilityTable($ecm, $eccm) {
if (is_null($this->probTables[$ecm.','.$eccm])) {
// Read ECM probability table
$ecmTable = $this->getECMTable($ecm);
// Read ECCM probability table
$eccmTable = $this->getECCMTable($eccm);
// Create combined probabilities
$probTable = array();
$tot = 0;
for ($i=0;$i<4;$i++) {
$probTable[$i] = 0;
for ($j=0;$j<=$i;$j++) {
$probTable[$i] += $ecmTable[$i-$j] * $eccmTable[$j];
}
$tot += $probTable[$i];
}
$probTable[4] = 1 - $tot;
$this->probTables[$ecm.','.$eccm] = $probTable;
}
return $this->probTables[$ecm.','.$eccm];
}
function getECMTable($level) {
if (is_null($this->ecmTable[$level])) {
$qEcm = $this->db->query("SELECT probability FROM ecm WHERE ecm_level=$level ORDER BY info_level ASC");
if (!($qEcm && dbCount($qEcm))) {
return -1;
}
$this->ecmTable[$level] = array();
while ($r = dbFetchArray($qEcm)) {
array_push($this->ecmTable[$level], $r[0] / 100);
}
}
return $this->ecmTable[$level];
}
function getECCMTable($level) {
if (is_null($this->eccmTable[$level])) {
$qEccm = $this->db->query("SELECT probability FROM eccm WHERE eccm_level=$level ORDER BY gain ASC");
if (!($qEccm && dbCount($qEccm))) {
return -1;
}
$this->eccmTable[$level] = array();
while ($r = dbFetchArray($qEccm)) {
array_push($this->eccmTable[$level], $r[0] / 100);
}
}
return $this->eccmTable[$level];
}
function scrambleFleetPower($level, $power) {
switch ($level) :
case 0: return 'NULL';
case 1: $rand = rand(0,49) - 25; break;
case 2: $rand = rand(0,19) - 10; break;
case 3: case 4: $rand = 0; break;
endswitch;
return $power + ($power * $rand / 100);
}
}
?>

View file

@ -0,0 +1,50 @@
<?php
class beta5_fleet_library {
var $fleets = array();
var $fleetDepartures = array();
var $fleetArrivals = array();
var $index = array (
"arrival",
"autoSplit",
"disband",
"get",
"getLocation",
"getPlayerLocations",
"getPower",
"getStats",
"getUpkeep",
"merge",
"sendMoveMessages",
"setOrders",
"split",
"switchStatus"
);
function beta5_fleet_library($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Invalidates the fleet cache
function invCache($id = null) {
if (is_null($id)) {
$this->fleets = array();
} else {
$this->fleets[$id] = null;
}
}
// Renames a fleet
function rename($fid, $name) {
$n = addslashes($name);
$this->db->query("UPDATE fleet SET name='$n' WHERE id=$fid");
$this->fleets[$fid] = null;
}
}
?>

View file

@ -0,0 +1,151 @@
<?php
class beta5_fleet_arrival {
function beta5_fleet_arrival($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->move = $this->lib->game->getLib('beta5/moving');
$this->planets = $this->lib->game->getLib('beta5/planet');
$this->players = $this->lib->game->getLib('beta5/player');
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Handles a fleet's arrival
function run($fid, $dest, $from, $nStatus = null) {
// Get complete fleet data
$q = $this->db->query("SELECT * FROM fleet WHERE id=$fid");
$f = dbFetchHash($q);
if (is_null($f['owner'])) {
logText("beta5/fleetArrival($fid,$dest,$from): BUG! Fleet has no owner!", LOG_ERR);
return;
}
if (is_null($nStatus)) {
$nStatus = ($f['attacking'] == 't');
}
// Get destination planet owner
$po = $this->planets->call('getOwner', $dest);
if (!is_null($po) && $po != $f['owner']) {
// Is the fleet owner an enemy of the planet owner?
$isEnemy = $this->players->call('isEnemy', $po, $f['owner']);
if (!$isEnemy) {
// Get fleet owner data
$foi = $this->players->call('get', $f['owner']);
// Check for enemy alliance
$isEnemy = (!is_null($foi['aid']) && $this->players->call('isAllianceEnemy', $po, $foi['aid']));
}
} else {
$isEnemy = false;
}
// Check whether the player already has fleets at that location,
// and if he does, get their current status
if (!$isEnemy) {
$q = $this->db->query("SELECT attacking FROM fleet WHERE location=$dest AND owner=".$f['owner']." LIMIT 1");
if ($q && dbCount($q)) {
list($aa) = dbFetchArray($q);
$isEnemy = ($aa == 't');
}
}
// Set attack status
$att = ($po != $f['owner']) && ($isEnemy || $nStatus);
logText("beta5/fleetArrival($fid,$dest,$from,{$f['owner']}): Attack=".($att?1:0), LOG_DEBUG);
if (is_array($_SESSION[game::sessName()])) {
logText("Fleet $fid was being controlled by player #{$_SESSION[game::sessName()]['player']}");
}
if ($att) {
if (($split = $this->hsWindowCollapsing($po, $f, $dest, $from)) === true) {
return;
}
// Switch the player's fleets to attack at that location if the fleet arriving is attacking
$this->db->query("UPDATE fleet SET attacking=TRUE,can_move='B' WHERE location=$dest AND NOT attacking AND owner=".$f['owner']);
} else {
$split = "";
}
// Update the fleet's record
$this->db->query("UPDATE fleet SET location=$dest,time_spent=0,attacking=".dbBool($att).",can_move='".($att?'B':'H')."'$split WHERE id=$fid");
// Make sure the system the fleet has arrived in can't be assigned to a new player
$pinf = $this->planets->call('byId', $dest);
$this->db->query("UPDATE system SET assigned=TRUE WHERE id=".$pinf['system']);
// Add a fleet arrival entry to the list
if (!is_array($this->lib->mainClass->fleetArrivals[$dest])) {
$this->lib->mainClass->fleetArrivals[$dest] = array(array(), array());
}
array_push($this->lib->mainClass->fleetArrivals[$dest][$att?1:0], array($fid, $from));
// Clear the fleet cache
$this->lib->call('invCache', $fid);
}
function hsWindowCollapsing($po, $f, $dst, $ori) {
// Apply HS window collapsing
$r = $this->rules->call('get', $po);
$rnd = rand(0,$r['prevent_hs_exit']*10);
$splitG = floor($rnd * $f['gaships'] / 100);
$splitF = floor($rnd * $f['fighters'] / 100);
$splitC = ceil($rnd * $f['cruisers'] / 100);
$splitB = ceil($rnd * $f['bcruisers'] / 100);
if (!($rnd && ($splitC || $splitB))) {
return "";
}
// WE HAVE A WINNER!
if (is_null($f['moving'])) {
$or = $this->rules->call('get', $f['owner']);
}
if ($f['gaships'] == $splitG && $f['fighters'] == $splitF && $f['cruisers'] == $splitC && $f['bcruisers'] == $splitB) {
// The complete fleet has to be delayed
logText("Fleet #{$f['id']} was prevented from dropping out of HS", LOG_DEBUG);
if (is_null($f['moving'])) {
// The fleet dropped out of Hyperspace, create a move order
$fmo = $this->move->call('newObject', $ori, $dst, $or['capital_ship_speed'], ($f['cruisers'] > 0), null);
$this->db->query("UPDATE moving_object SET changed=60,time_left=1 WHERE id=$fmo");
$this->db->query("UPDATE fleet SET moving=$fmo,waiting=NULL WHERE id={$f['id']}");
logText("Fleet #{$f['id']} -> created new moving object", LOG_DEBUG);
} else {
// The fleet was moving, just modify the order
$this->db->query("UPDATE moving_object SET changed=60,time_left=1 WHERE id={$f['moving']}");
logText("Fleet #{$f['id']} -> modified existing moving object", LOG_DEBUG);
}
$fullFleet = true;
} else {
logText("Fleet {$f['id']} got split by HS windows collapsing ($splitG/$splitF/$splitC/$splitB out of {$f['gaships']}/{$f['fighters']}/{$f['cruisers']}/{$f['bcruisers']})", LOG_DEBUG);
// Split fleet
$fullFleet = ",gaships=" . ($f['gaships'] - $splitG);
$fullFleet .= ",fighters=" . ($f['fighters'] - $splitF);
$fullFleet .= ",cruisers=" . ($f['cruisers'] - $splitC);
$fullFleet .= ",bcruisers=" . ($f['bcruisers'] - $splitB);
if (is_null($f['moving'])) {
// The fleet dropped out of Hyperspace, create a move order
$fmo = $this->move->call('newObject', $ori, $dst, $or['capital_ship_speed'], ($f['cruisers'] > 0), null);
logText("Fleet #{$f['id']} -> created new moving object", LOG_DEBUG);
} else {
// The fleet was moving, duplicate the order
$fmo = $this->move->call('cloneObject', $f['moving']);
logText("Fleet #{$f['id']} -> cloned existing moving object", LOG_DEBUG);
}
$this->db->query("UPDATE moving_object SET changed=60,time_left=1 WHERE id=$fmo");
// Generate new fleet
$this->db->query("INSERT INTO fleet(owner,gaships,fighters,cruisers,bcruisers,attacking,moving) VALUES ("
. $f['owner'] . ",$splitG,$splitF,$splitC,$splitB,TRUE,$fmo)");
}
return $fullFleet;
}
}
?>

View file

@ -0,0 +1,83 @@
<?php
class beta5_fleet_autoSplit {
function beta5_fleet_autoSplit($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->standby = $this->lib->game->getLib('beta5/standby');
$this->moving = $this->lib->game->getLib('beta5/moving');
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Automatically split a fleet
function run($fid, $newName, $count) {
// Get fleet data
$f = $this->lib->call('get', $fid, true);
if (is_null($f) || $f['can_move'] != 'Y' || !is_null($f['sale_info'])) {
return 1;
}
// Get player rules
$rules = $this->rules->call('get', $f['owner']);
// Generate new ship counts
$sg = floor($f['gaships'] / $count); $sf = floor($f['fighters'] / $count);
$sc = floor($f['cruisers'] / $count); $sb = floor($f['bcruisers'] / $count);
$count --;
$mg = $count * $sg; $mf = $count * $sf;
$mc = $count * $sc; $mb = $count * $sb;
// If we're moving or standing by in Hyperspace, we need to make sure both
// the new and old fleets are HS-capable
if ((!is_null($f['move']) && $f['move']['hyperspace'] == 't') || !is_null($f['wait'])) {
$nu = $rules['gaship_space'] * $sg + $rules['fighter_space'] * $sf;
$na = $rules['cruiser_haul'] * $sc + $rules['bcruiser_haul'] * $sb;
$ou = $rules['gaship_space'] * ($f['gaships'] - $mg) + $rules['fighter_space'] * ($f['fighters'] - $mf);
$oa = $rules['cruiser_haul'] * ($f['cruisers'] - $mc) + $rules['bcruiser_haul'] * ($f['bcruisers'] - $mb);
if ($nu > $na || $ou > $oa) {
return 3;
}
}
// Generate code that will set the new fleets' orders
if (is_null($f['location'])) {
$location = "NULL";
if (is_null($f['moving'])) {
$moving = "NULL";
$oCode = '$waiting = $this->standby->call("create",'.$f['wait']['time_left'].",".$f['wait']['drop_point']
. ','.$f['wait']['origin'].','.$f['wait']['time_spent'].');';
} else {
$waiting = "NULL";
$oCode = '$moving = $this->moving->call("cloneObject", '.$f['moving'].');';
}
} else {
$location = $f['location'];
$moving = $waiting = 'NULL';
$oCode = null;
}
// Generate new fleets
$nn = addslashes($newName == "" ? preg_replace('/ [0-9]+$/', '', $f['name']) : $newName);
for ($i=0;$i<$count;$i++) {
if ($oCode != "") {
eval($oCode);
}
$nnb = $count > 1 ? (" " . ($i + 1)) : "";
$this->db->query("INSERT INTO fleet(owner,name,location,gaships,fighters,cruisers,bcruisers,attacking,moving,waiting,time_spent) VALUES("
.$f['owner'].",'$nn$nnb',$location,$sg,$sf,$sc,$sb,"
.dbBool($f['attacking'] == 't').",$moving,$waiting,{$f['time_spent']})");
}
// Update original fleet
$this->db->query("UPDATE fleet SET gaships=gaships-$mg,fighters=fighters-$mf,cruisers=cruisers-$mc,bcruisers=bcruisers-$mb "
."WHERE id=$fid");
$this->db->query("DELETE FROM beacon_detection WHERE fleet = $fid");
$this->lib->call('invCache', $fid);
return 0;
}
}
?>

View file

@ -0,0 +1,58 @@
<?php
class beta5_fleet_disband {
function beta5_fleet_disband($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->planets = $this->lib->game->getLib('beta5/planet');
$this->sales = $this->lib->game->getLib('beta5/sale');
}
// Disbands a fleet and removes any sales / movement / stand-by
// entries associated with it
function run($fId, $final = false) {
// Get fleet data
$f = $this->lib->call('get', $fId);
if (is_null($f)) {
return 1;
}
if (!is_null($f['sale_info'])) {
// It is for sale
$r = $this->sales->call('cancel', $f['owner'], $f['sale_info']['sale']['id']);
if (!($r || $final)) {
return 2;
} elseif (!$r) {
// Sale was finalized and we can't cancel; assume no planet is for sale.
// FIXME: send message
$this->db->query("UPDATE fleet SET sale=NULL,owner=".$f['sale_info']['sale']['sold_to']." WHERE id=$fId");
// FIXME: add history
$this->db->query("DELETE FROM sale WHERE id=".$f['sale_info']['sale']['id']);
}
} elseif (!is_null($f['waiting'])) {
// It is standing by
$this->db->query("DELETE FROM hs_wait WHERE id=".$f['waiting']);
} elseif (!is_null($f['moving'])) {
// It's moving?
$this->db->query("DELETE FROM moving_object WHERE id=".$f['moving']);
if (!is_null($f['move']['wait_order'])) {
$this->db->query("DELETE FROM hs_wait WHERE id=".$f['move']['wait_order']);
}
}
// Remove this fleet
$this->db->query("DELETE FROM fleet WHERE id=$fId");
// Update planet status where the fleet was
if (!is_null($f['location'])) {
$this->planets->call('updateMilStatus', $f['location']);
$this->planets->call('updateHappiness', $f['location']);
}
return 0;
}
}
?>

View file

@ -0,0 +1,69 @@
<?php
class beta5_fleet_get {
function beta5_fleet_get($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Returns data regarding a fleet
function run($id, $update = false) {
if ($update) {
$uqs = " FOR UPDATE";
} else {
$uqs = "";
}
// Return the fleet cache's contents if the fleet is in there
if (!is_null($this->lib->mainClass->fleets[$id])) {
return $this->lib->mainClass->fleets[$id];
}
// Get the complete row
$q = $this->db->query("SELECT * FROM fleet WHERE id = $id $uqs");
if (!($q && dbCount($q) == 1)) {
return null;
}
$fdata = dbFetchHash($q);
// Extract movement data
if (!is_null($fdata['moving'])) {
$q = $this->db->query("SELECT * FROM moving_object WHERE id=" . $fdata['moving'] . $uqs);
if ($q && dbCount($q) == 1) {
$fdata['move'] = dbFetchHash($q);
if (!is_null($fdata['move']['wait_order'])) {
$fdata['waiting'] = $fdata['move']['wait_order'];
}
}
}
// Extract HS standby orders
if (!is_null($fdata['waiting'])) {
$q = $this->db->query("SELECT * FROM hs_wait WHERE id=" . $fdata['waiting'] . $uqs);
if ($q && dbCount($q) == 1) {
$fdata['wait'] = dbFetchHash($q);
}
}
// Extract sales data
$q = $this->db->query("SELECT * FROM sale WHERE fleet=" . $fdata['id'] . $uqs);
if (dbCount($q)) {
$a = array('sale' => dbFetchHash($q));
$q = $this->db->query("SELECT * FROM public_offer WHERE offer=" . $a['sale']['id'] . $uqs);
if ($q && dbCount($q) == 1) {
$a['public'] = dbFetchHash($q);
}
$q = $this->db->query("SELECT * FROM private_offer WHERE offer=" . $a['sale']['id'] . $uqs);
if ($q && dbCount($q) == 1) {
$a['private'] = dbFetchHash($q);
}
$fdata['sale_info'] = $a;
}
return ($this->lib->mainClass->fleets[$id] = $fdata);
}
}
?>

View file

@ -0,0 +1,22 @@
<?php
class beta5_fleet_getLocation {
function beta5_fleet_getLocation($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Returns the list of fleets in orbit around a planet
function run($pid, $pl = null) {
$q = $this->db->query("SELECT id,name FROM fleet WHERE location = $pid" . (is_null($pl) ? "" : " AND owner=$pl"));
$a = array();
while ($r = dbFetchArray($q)) {
$a[$r[0]] = $r[1];
}
return $a;
}
}
?>

View file

@ -0,0 +1,22 @@
<?php
class beta5_fleet_getPlayerLocations {
function beta5_fleet_getPlayerLocations($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Returns all of the locations at which a player has stationned fleets
function run($pid) {
$q = $this->db->query("SELECT DISTINCT location FROM fleet WHERE location IS NOT NULL AND owner=$pid");
$a = array();
while ($r = dbFetchArray($q)) {
array_push($a, $r[0]);
}
return $a;
}
}
?>

View file

@ -0,0 +1,28 @@
<?php
class beta5_fleet_getPower {
var $ePower = array();
function beta5_fleet_getPower($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Computes a fleet's power
function run($pl, $g, $f, $c, $b) {
if (!is_array($this->ePower[$pl])) {
$r = $this->rules->call('get', $pl);
$a = array('gaship','fighter','cruiser','bcruiser');
$this->ePower[$pl] = array();
foreach ($a as $st) {
$this->ePower[$pl][$st] = floor($r[$st."_power"] * $r['effective_fleet_power'] / 100);
}
}
$r = $this->ePower[$pl];
return $g * $r['gaship'] + $f * $r['fighter'] + $c * $r['cruiser'] + $b * $r['bcruiser'];
}
}
?>

View file

@ -0,0 +1,85 @@
<?php
class beta5_fleet_getStats {
function beta5_fleet_getStats($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Returns data regarding current fleets
function run($pid) {
// Get count and ship types
$q = $this->db->query(
"SELECT COUNT(*), SUM(gaships), SUM(fighters), SUM(cruisers), SUM(bcruisers)"
. " FROM fleet WHERE owner = $pid GROUP BY owner"
);
$cnt = dbFetchArray($q);
if (!$cnt) {
$cnt = array(0, 0, 0, 0, 0);
}
// Fleets at home
$q = $this->db->query(
"SELECT COUNT(*) FROM fleet f, planet p "
. "WHERE f.owner = $pid AND f.location = p.id AND p.owner = $pid"
);
list($fah) = dbFetchArray($q);
// Fleets at home, in battle
$q = $this->db->query(
"SELECT COUNT(*) FROM fleet f, planet p, fleet f2 "
. "WHERE f.owner = $pid AND f.location = p.id AND p.owner = $pid "
. "AND f2.location = p.id AND f2.attacking"
);
list($fahb) = dbFetchArray($q);
// Fleets on foreign planets
$q = $this->db->query(
"SELECT COUNT(*) FROM fleet f,planet p "
. "WHERE f.owner=$pid AND f.location=p.id"
. " AND (p.owner IS NULL OR p.owner<>$pid)"
);
list($af) = dbFetchArray($q);
// Fleets on foreign planets, in battle
$q = $this->db->query(
"SELECT COUNT(*) FROM fleet f,planet p,fleet f2 "
. "WHERE f.owner=$pid AND f.location=p.id AND (p.owner IS NULL OR p.owner<>$pid) "
. "AND f2.location=p.id AND (f2.attacking AND NOT f.attacking)"
);
list($afb1) = dbFetchArray($q);
$q = $this->db->query(
"SELECT COUNT(*) FROM fleet f, planet p "
. "WHERE f.owner=$pid AND f.location=p.id AND (p.owner IS NULL OR p.owner<>$pid) "
. "AND f.attacking"
);
list($afb2) = dbFetchArray($q);
$afb = $afb1 + $afb2;
// Moving fleets
$q = $this->db->query("SELECT COUNT(*) FROM fleet WHERE owner = $pid AND moving IS NOT NULL");
list($mf) = dbFetchArray($q);
// Waiting fleets
$q = $this->db->query("SELECT COUNT(*) FROM fleet WHERE owner = $pid AND waiting IS NOT NULL");
list($wf) = dbFetchArray($q);
return array(
"fleets" => $cnt[0],
"battle" => $fahb+$afb,
"upkeep" => $this->lib->call('getUpkeep', $pid, $cnt[1], $cnt[2], $cnt[3], $cnt[4]),
"power" => $this->lib->call('getPower', $pid, $cnt[1], $cnt[2], $cnt[3], $cnt[4]),
"at_home" => $fah,
"home_battle" => $fahb,
"foreign" => $af,
"foreign_battle" => $afb,
"moving" => $mf,
"waiting" => $wf,
"gaships" => $cnt[1],
"fighters" => $cnt[2],
"cruisers" => $cnt[3],
"bcruisers" => $cnt[4]
);
}
}
?>

View file

@ -0,0 +1,23 @@
<?php
class beta5_fleet_getUpkeep {
function beta5_fleet_getUpkeep($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
}
// Computes a fleet's upkeep
function run($pl, $g, $f, $c, $b) {
$r = $this->rules->call('get', $pl);
$fu = $g * $r['gaship_upkeep'];
$fu += $f * $r['fighter_upkeep'];
$fu += $c * $r['cruiser_upkeep'];
$fu += $b * $r['bcruiser_upkeep'];
return $fu;
}
}
?>

View file

@ -0,0 +1,163 @@
<?php
class beta5_fleet_merge {
function beta5_fleet_merge($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->moving = $this->lib->game->getLib('beta5/moving');
}
// Merge fleets
function run($fIds, $okOwners, $newName) {
// Did we get fleet IDs?
if (!count($fIds)) {
return array();
}
// Get fleets to merge
$q = $this->db->query(
"SELECT * FROM fleet "
."WHERE id IN (".join(',',$fIds).") AND owner IN (".join(',',$okOwners)
.") AND can_move='Y' AND sale IS NULL "
."ORDER BY location,owner"
);
$q2 = $this->db->query("SELECT id FROM sale WHERE fleet IN (".join(',',$fIds).")");
if (!$q || !$q2 || dbCount($q) != count($fIds) || dbCount($q2)) {
return array();
}
// Generate an array from the fleets read and extract
// movement / stand-by information
$fleets = array(); $mIds = array(); $wIds = array();
while ($r = dbFetchHash($q)) {
$fleets[$r['id']] = $r;
if (!is_null($r['moving'])) {
array_push($mIds, $r['moving']);
} elseif (!is_null($r['waiting'])) {
array_push($wIds, $r['waiting']);
}
}
// Extract movement information
$move = array();
if (count($mIds)) {
$q = $this->db->query("SELECT id,m_to,time_left,wait_order,changed FROM moving_object "
."WHERE id IN (".join(',',$mIds).")");
while ($r = dbFetchHash($q)) {
$move[$r['id']] = $r;
if (!is_null($r['wait_order']))
array_push($wIds, $r['wait_order']);
}
}
// Extract stand-by information
$wait = array();
if (count($wIds)) {
$q = $this->db->query("SELECT id,drop_point,time_left FROM hs_wait "
."WHERE id IN (".join(',',$wIds).")");
while ($r = dbFetchHash($q)) {
$wait[$r['id']] = $r;
}
}
// Group fleets by location / status / owner
$gFleets = array();
foreach ($fIds as $i) {
// Generate identifier and time to wait
$lid = $fleets[$i]['owner'].":";
$am = ($fleets[$i]['attacking'] == 't');
if (!is_null($fleets[$i]['waiting'])) {
$lid .= "W:".$wait[$fleets[$i]['waiting']]['drop_point'];
$tl = $wait[$fleets[$i]['waiting']]['time_left'];
} elseif (!is_null($moid = $fleets[$i]['moving'])) {
$mwo = $move[$moid]['wait_order'];
$lid .= "M:".$move[$moid]['m_to'].':'.$move[$moid]['time_left'].':'
.$move[$moid]['changed'].":".$this->moving->call('getLocation', $moid);
$tl = is_null($mwo) ? 0 : $wait[$mwo]['time_left'];
} else {
$tl = 0;
$lid .= "L:".$fleets[$i]['location'];
}
// Generate / update container
if (!is_array($gFleets[$lid])) {
$gFleets[$lid] = array('t' => $tl, 'a' => $am, 'l' => array());
} else {
if ($tl > $gFleets[$lid]['t']) {
$gFleets[$lid]['t'] = $tl;
}
$gFleets[$lid]['a'] |= $am;
}
// Add fleet
array_push($gFleets[$lid]['l'], $i);
}
// Merge groups into single fleets
$nfl = array();
foreach ($gFleets as $fg) {
// Compute total amount of ships
$sums = array(0,0,0,0);
$minSpent = null;
foreach ($fg['l'] as $i) {
$sums[0] += $fleets[$i]['gaships'];
$sums[1] += $fleets[$i]['fighters'];
$sums[2] += $fleets[$i]['cruisers'];
$sums[3] += $fleets[$i]['bcruisers'];
if (is_null($minSpent) || $minSpent > $fleets[$i]['time_spent']) {
$minSpent = $fleets[$i]['time_spent'];
}
}
// Update merged fleet
$nId = array_shift($fg['l']);
$name = addslashes(($newName == "") ? $fleets[$nId]['name'] : $newName);
$this->db->query("UPDATE fleet SET name='$name',gaships=".$sums[0].",fighters=".$sums[1]
. ",cruisers=".$sums[2].",bcruisers=".$sums[3].",attacking="
. dbBool($fg['a']) . ",time_spent=$minSpent WHERE id=$nId");
// Delete unneeded data
if (count($fg['l'])) {
$dMids = array(); $dWids = array();
foreach ($fg['l'] as $i) {
if (!is_null($fleets[$i]['waiting'])) {
array_push($dWids, $fleets[$i]['waiting']);
} elseif (!is_null($fleets[$i]['moving'])) {
array_push($dMids, $fleets[$i]['moving']);
}
}
foreach ($dMids as $i) {
if (!is_null($move[$i]['wait_order'])) {
array_push($dWids, $move[$i]['wait_order']);
}
}
$this->db->query("DELETE FROM fleet WHERE id IN (".join(',',$fg['l']).")");
if (count($dMids)) {
$this->db->query("DELETE FROM moving_object WHERE id IN (".join(',',$dMids).")");
}
if (count($dWids)) {
$this->db->query("DELETE FROM hs_wait WHERE id IN (".join(',',$dWids).")");
}
}
// Update detection status
$this->db->query("DELETE FROM beacon_detection WHERE fleet = $nId");
// Make sure orders are up-to-date
$mwo = $fleets[$nId]['moving'];
$dest = is_null($mwo) ? null : $move[$mwo]['m_to'];
$wait = $fg['t'] ? $fg['t'] : null;
$this->lib->call('setOrders', $nId, $dest, $wait);
array_push($nfl, $nId);
}
return $nfl;
}
}
?>

View file

@ -0,0 +1,195 @@
<?php
class beta5_fleet_sendMoveMessages {
function beta5_fleet_sendMoveMessages($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->msg = $this->lib->game->getLib('beta5/msg');
}
// Sends messages related to fleet movements
function run() {
$locs = array_unique(array_merge(array_keys($this->lib->mainClass->fleetDepartures), array_keys($this->lib->mainClass->fleetArrivals)));
if (count($locs) == 0) {
return;
}
// Get all fleet or planet owners for the affected locations and their status
$q = $this->db->query(
"SELECT owner AS id,FALSE AS att,id AS loc FROM planet WHERE owner IS NOT NULL AND id IN (".join(',',$locs).") "
. "UNION SELECT owner AS id,attacking AS att,location AS loc FROM fleet WHERE location IN (".join(',',$locs).")"
);
$fMove = array();
$ownArrivals = array();
while ($r = dbFetchArray($q)) {
list($player,$status,$location) = $r;
$oa = $ha = $hd = $fa = $fd = array();
// Generate the list of fleet departures
if (is_array($this->lib->mainClass->fleetDepartures[$location])) {
foreach ($this->lib->mainClass->fleetDepartures[$location][(int)$status] as $fId) {
$f = $this->lib->call('get', $fId);
if ($f['owner'] == $player) {
continue;
}
array_push($fd, $f);
}
foreach ($this->lib->mainClass->fleetDepartures[$location][1-$status] as $fId) {
$f = $this->lib->call('get', $fId);
if ($f['owner'] == $player) {
continue;
}
array_push($hd, $f);
}
}
// Generate the list of fleet arrivals
if (is_array($this->lib->mainClass->fleetArrivals[$location])) {
foreach ($this->lib->mainClass->fleetArrivals[$location][(int)$status] as $fdt) {
list($fId, $from) = $fdt;
$f = $this->lib->call('get', $fId);
$f['from'] = $from;
if ($f['owner'] == $player) {
if (!is_array($ownArrivals[$player])) {
$ownArrivals[$player] = array();
}
if (!is_array($ownArrivals[$player][$location])) {
$ownArrivals[$player][$location] = array();
}
array_push($ownArrivals[$player][$location], $f);
} else {
array_push($fa, $f);
}
}
foreach ($this->lib->mainClass->fleetArrivals[$location][1-$status] as $fdt) {
list($fId, $from) = $fdt;
$f = $this->lib->call('get', $fId);
$f['from'] = $from;
if ($f['owner'] == $player) {
l::warn("beta5/sendFleetMoveMessages(): fleet $fId owned by player $player hostile to its owner");
continue;
}
array_push($ha, $f);
}
}
// Add the data to the list of fleet movements
if (!(count($fa)||count($fd)||count($ha)||count($hd))) {
continue;
}
if (!is_array($fMove[$player])) {
$fMove[$player] = array($location => array($fa, $fd, $ha, $hd));
} else {
$fMove[$player][$location] = array($fa, $fd, $ha, $hd);
}
}
$pnames = array();
$fpowers = array();
// Send messages for own fleets arrivals
$tm = time() - 1;
foreach ($ownArrivals as $player => $locs) {
foreach ($locs as $loc => $flist) {
// Get planet name
if (is_null($pnames[$loc])) {
$q = $this->db->query("SELECT name FROM planet WHERE id=$loc");
list($pnames[$loc]) = dbFetchArray($q);
}
$pname = $pnames[$loc];
// Generate a message
$mid = $this->msg->call('send', $player, 'flmove', array(
'p_id' => $loc,
'p_name' => $pname
));
// Insert fleet data
foreach ($flist as $fleet) {
// Get origin planet name
if (is_null($pnames[$fleet['from']])) {
$q = $this->db->query("SELECT name FROM planet WHERE id={$fleet['from']}");
list($pnames[$fleet['from']]) = dbFetchArray($q);
}
$pname = $pnames[$fleet['from']];
$fpowers[$fleet['id']] = $fPower = $this->lib->call('getPower',
$player, $fleet['gaships'], $fleet['fighters'], $fleet['cruisers'], $fleet['bcruisers']);
$this->db->query("INSERT INTO flmove_data VALUES ($mid,'".addslashes($fleet['name'])."',$player,"
. "{$fleet['gaships']},{$fleet['fighters']},{$fleet['cruisers']},{$fleet['bcruisers']},$fPower,"
. "FALSE,TRUE,{$fleet['from']},'".addslashes($pname)."')");
}
}
}
// Send messages for other fleets
$tm++;
foreach ($fMove as $player => $locs) {
foreach ($locs as $loc => $flists) {
$flist = array();
foreach ($flists[0] as $f) {
$f['hostile'] = 0;
array_push($flist, $f);
}
foreach ($flists[1] as $f) {
$f['hostile'] = 0;
array_push($flist, $f);
}
foreach ($flists[2] as $f) {
$f['hostile'] = 1;
array_push($flist, $f);
}
foreach ($flists[3] as $f) {
$f['hostile'] = 1;
array_push($flist, $f);
}
// Get planet name
if (is_null($pnames[$loc])) {
$q = $this->db->query("SELECT name FROM planet WHERE id=$loc");
list($pnames[$loc]) = dbFetchArray($q);
}
$pname = $pnames[$loc];
// Generate a message
$mid = $this->msg->call('send', $player, 'flmove', array(
'p_id' => $loc,
'p_name' => $pname
));
// Insert fleet data
foreach ($flist as $fleet) {
if (is_null($fleet['from'])) {
$arrived = 0;
} else {
// Get origin planet name
if (is_null($pnames[$fleet['from']])) {
$q = $this->db->query("SELECT name FROM planet WHERE id={$fleet['from']}");
list($pnames[$fleet['from']]) = dbFetchArray($q);
}
$pname = $pnames[$fleet['from']];
$arrived = 1;
}
if (is_null($fpowers[$fleet['id']])) {
$fpowers[$fleet['id']] = $this->lib->call('getPower',
$fleet['owner'], $fleet['gaships'], $fleet['fighters'], $fleet['cruisers'], $fleet['bcruisers']);
}
$fPower = $fpowers[$fleet['id']];
l::trace("beta5/sendFleetMoveMessages: inserting message for player $player, location $loc, fleet {$fleet['id']}");
$this->db->query("INSERT INTO flmove_data VALUES ($mid,'".addslashes($fleet['name'])."',{$fleet['owner']},"
. "{$fleet['gaships']},{$fleet['fighters']},{$fleet['cruisers']},{$fleet['bcruisers']},$fPower,"
. ($fleet['hostile'] ? "TRUE" : "FALSE") . "," . ($arrived ? "TRUE" : "FALSE") . ","
. ($arrived ? ("{$fleet['from']},'".addslashes($pname)."'") : "NULL,NULL") . ")");
}
}
}
$this->lib->mainClass->fleetArrivals = $this->lib->mainClass->fleetDepartures = array();
}
}
?>

View file

@ -0,0 +1,245 @@
<?php
class beta5_fleet_setOrders {
function beta5_fleet_setOrders($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->moving = $this->lib->game->getLib('beta5/moving');
$this->planets = $this->lib->game->getLib('beta5/planet');
$this->players = $this->lib->game->getLib('beta5/player');
$this->rules = $this->lib->game->getLib('beta5/rules');
$this->standby = $this->lib->game->getLib('beta5/standby');
}
// Changes a fleet's orders
function run($fid, $newDest, $newDelay, $attack = null) {
// Get fleet data
$fleet = $this->lib->call('get', $fid);
if (is_null($fleet) || !is_null($fleet['sale_info']) || $fleet['can_move'] != 'Y') {
return false;
}
if (is_null($attack)) {
$attack = ($fleet['attacking'] == 't');
}
// Check for hyperspace capabilities
$r = $this->rules->call('get', $fleet['owner']);
$used = $r['gaship_space'] * $fleet['gaships'] + $r['fighter_space'] * $fleet['fighters'];
$avail = $r['cruiser_haul'] * $fleet['cruisers'] + $r['bcruiser_haul'] * $fleet['bcruisers'];
$hsOk = ($used <= $avail);
// Get cruisers status / Capital ships speed
$cru = ($fleet['cruisers'] > 0);
$csp = $r['capital_ship_speed'];
// Check for an implicit "null" move order
$cLoc = is_null($fleet['move'])
? (is_null($fleet['wait'])
? $fleet['location']
: $fleet['wait']['drop_point'])
: $this->moving->call('getLocation', $fleet['move']['id']);
if ($cLoc == $newDest)
$newDest = null;
// Some checks must be performed if the fleet is going out of system
if (!(is_null($cLoc) || is_null($newDest))) {
$cLocInfo = $this->planets->call('byId', $cLoc);
$nDestInfo = $this->planets->call('byId', $newDest);
if ($cLocInfo['x'] != $nDestInfo['x'] || $cLocInfo['y'] != $nDestInfo['y']) {
// Fleet is not hyperspace-capable
if (!$hsOk) {
return false;
}
// Check protection
if ($this->lib->game->params['victory'] == 0) {
$protected = $this->players->call('getProtectionLevel', $fleet['owner']);
if ($protected) {
$this->players->call('breakProtection', $fleet['owner'], 'ACT');
}
}
}
}
// Identify movement-related actions
$newMove = is_null($fleet['move']) && !is_null($newDest);
$rmMove = !is_null($fleet['move']) && is_null($newDest);
$chgMove = !is_null($fleet['move']) && !is_null($newDest) && ($newDest != $fleet['move']['m_to']);
$mNoAct = !($newMove||$rmMove||$chgMove);
// Identify HS standby-related actions
$newWait = $hsOk && is_null($fleet['wait']) && !is_null($newDelay);
$rmWait = $hsOk && !is_null($fleet['wait']) && is_null($newDelay);
$chgWait = $hsOk && !is_null($fleet['wait']) && !is_null($newDelay) && ($newDelay != $fleet['wait']['time_left']);
$wNoAct = !($newWait||$rmWait||$chgWait);
logText("newMove $newMove; rmMove $rmMove; chgMove $chgMove; mNoAct $mNoAct");
logText("newWait $newWait; rmWait $rmWait; chgWait $chgWait; wNoAct $wNoAct");
// No actions are to be taken, return
if ($mNoAct && $wNoAct) {
return true;
}
// Start moving
$fleetArrived = false;
if ($newMove) {
$departure = false;
// HS orders haven't changed.
if ($wNoAct) {
// Are we already waiting?
if (is_null($fleet['wait'])) {
$wo = null;
$sl = $fleet['location'];
$departure = true;
} else {
$wo = $fleet['wait']['id'];
$sl = $fleet['wait']['drop_point'];
logText("Adding new move orders, initial location: $sl");
$this->db->query("UPDATE hs_wait SET time_left=$newDelay,time_spent=0,origin=NULL WHERE id=$wo");
}
} elseif ($newWait) {
// New HS stand-by order
$wo = $this->standby->call('create', $newDelay, $newDest);
$sl = $fleet['location'];
$departure = true;
} elseif ($rmWait) {
// Delete current HS stand-by order
$wo = null;
$sl = $fleet['wait']['drop_point'];
$this->db->query("DELETE FROM hs_wait WHERE id=".$fleet['wait']['id']);
} elseif ($chgWait) {
// Change HS stand-by order
$wo = $fleet['wait']['id'];
$sl = $fleet['wait']['drop_point'];
$this->db->query("UPDATE hs_wait SET time_left=$newDelay,time_spent=0,origin=NULL,drop_point=$newDest WHERE id=".$fleet['wait']['id']);
}
// Create movement entry
$this->db->query("DELETE FROM beacon_detection WHERE fleet = $fid");
$mo = $this->moving->call('newObject', $sl, $newDest, $csp, $cru, $wo);
if (is_null($mo)) {
logText("beta5/setFleetOrders($fid,$newDest,$newDelay,".($attack?1:0)."): unable to create a new moving_object entry", LOG_ERR);
return false;
}
$this->db->query("UPDATE fleet SET location=NULL,moving=$mo,waiting=NULL WHERE id=$fid");
if ($departure) {
$this->planets->call('updateMilStatus', $sl);
$this->planets->call('updateHappiness', $sl);
$this->addDeparture($sl, $fid, $fleet['attacking'] == 't');
}
} elseif ($rmMove) {
// Fleet stop requested
$mo = $fleet['move']['id'];
$nloc = $this->moving->call('getLocation', $mo);
if ($wNoAct) {
// HS orders haven't changed.
// Do we have stand-by orders?
if (is_null($fleet['wait'])) {
$wo = null;
} else {
$wo = $fleet['wait']['id'];
$this->db->query("UPDATE hs_wait SET drop_point=$nloc WHERE id=$wo");
}
}
elseif ($newWait) {
// New HS stand-by order
$wo = $this->standby->call('create', $newDelay, $nloc);
} elseif ($rmWait) {
// Delete current HS stand-by order
$wo = null;
$this->db->query("DELETE FROM hs_wait WHERE id=".$fleet['wait']['id']);
} elseif ($chgWait) {
// Change HS stand-by order
$wo = $fleet['wait']['id'];
$this->db->query("UPDATE hs_wait SET time_left=$newDelay,time_spent=0,drop_point=$nloc WHERE id=".$fleet['wait']['id']);
}
// Stop movement
$this->moving->call('stop', $mo, $wo);
} elseif ($chgMove) {
// Fleet destination changed
$mo = $fleet['move']['id'];
if ($wNoAct) {
// HS orders haven't changed.
// Do we have stand-by orders?
if (is_null($fleet['wait'])) {
$wo = null;
} else {
$wo = $fleet['wait']['id'];
$this->db->query("UPDATE hs_wait SET drop_point=$newDest WHERE id=$wo");
}
}
elseif ($newWait) {
// New HS stand-by order
$wo = $this->standby->call('create', $newDelay, $newDest);
} elseif ($rmWait) {
// Delete current HS stand-by order
$wo = null;
$this->db->query("DELETE FROM hs_wait WHERE id=".$fleet['wait']['id']);
} elseif ($chgWait) {
// Change HS stand-by order
$wo = $fleet['wait']['id'];
$this->db->query("UPDATE hs_wait SET time_left=$newDelay,time_spent=0,drop_point=$newDest WHERE id=$wo");
}
// Redirect fleet
$this->moving->call('redirect', $mo, $newDest, $csp, $cru, $wo);
} elseif ($newWait) {
// No destination change, but stand-by orders changed
// New HS stand-by order
if (is_null($fleet['move'])) {
$loc = $fleet['location'];
$wo = $this->standby->call('create', $newDelay, $loc, $loc, null);
$this->db->query("UPDATE fleet SET waiting=$wo,location=NULL WHERE id=$fid");
$this->db->query("UPDATE hs_wait SET origin=$loc WHERE id=$wo");
$this->planets->call('updateMilStatus', $loc);
$this->planets->call('updateHappiness', $loc);
$this->addDeparture($loc, $fid, $fleet['attacking'] == 't');
$this->planets->call('detectFleets', $loc);
} else {
$wo = $this->standby->call('create', $newDelay, $fleet['move']['m_to']);
$this->db->query("UPDATE moving_object SET wait_order=$wo WHERE id=".$fleet['move']['id']);
}
} elseif ($rmWait) {
// Delete current HS stand-by order
$this->db->query("DELETE FROM hs_wait WHERE id=".$fleet['wait']['id']);
if (is_null($fleet['move'])) {
$fleetArrived = true;
$this->lib->call('arrival', $fid, $fleet['wait']['drop_point'], $fleet['wait']['origin'], $attack);
$this->planets->call('updateMilStatus', $fleet['wait']['drop_point']);
$this->planets->call('updateHappiness', $fleet['wait']['drop_point']);
$this->db->query("DELETE FROM beacon_detection WHERE fleet = $fid");
}
} elseif ($chgWait) {
// Change HS stand-by order
$this->db->query("UPDATE hs_wait SET time_left=$newDelay WHERE id=".$fleet['wait']['id']);
}
// If the fleet hasn't arrived, set its status
if (!$fleetArrived) {
$this->db->query("UPDATE fleet SET attacking=".dbBool($attack)." WHERE id=$fid");
}
$this->lib->call('invCache', $fid);
return true;
}
// Adds an entry to the list of fleet departures
function addDeparture($location, $fid, $status) {
if (!is_array($this->lib->mainClass->fleetDepartures[$location])) {
$this->lib->mainClass->fleetDepartures[$location] = array(array(), array());
}
array_push($this->lib->mainClass->fleetDepartures[$location][$status?1:0], $fid);
}
}
?>

View file

@ -0,0 +1,82 @@
<?php
class beta5_fleet_split {
function beta5_fleet_split($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->rules = $this->lib->game->getLib('beta5/rules');
$this->standby = $this->lib->game->getLib('beta5/standby');
$this->moving = $this->lib->game->getLib('beta5/moving');
}
// Manually split a fleet in player-specified fleets
function run($fid, $newName, $count, $sg, $sf, $sc, $sb) {
// Get fleet data
$f = $this->lib->call('get', $fid, true);
if (is_null($f) || $f['can_move'] != 'Y' || !is_null($f['sale_info'])) {
return 1;
}
// Check for enough ships in the original fleet
$mg = $count * $sg; $mf = $count * $sf;
$mc = $count * $sc; $mb = $count * $sb;
if ($f['gaships'] < $mg || $f['fighters'] < $mf || $f['cruisers'] < $mc || $f['bcruisers'] < $mb
|| $f['gaships'] + $f['fighters'] + $f['cruisers'] + $f['bcruisers'] - ($mg+$mf+$mc+$mb) == 0) {
return 2;
}
// If we're moving or standing by in Hyperspace, we need to make sure both
// the new and old fleets are HS-capable
if ((!is_null($f['move']) && $f['move']['hyperspace'] == 't') || !is_null($f['wait'])) {
$r = $this->rules->call('get', $f['owner']);
$nu = $r['gaship_space'] * $sg + $r['fighter_space'] * $sf;
$na = $r['cruiser_haul'] * $sc + $r['bcruiser_haul'] * $sb;
$ou = $r['gaship_space'] * ($f['gaships'] - $mg) + $r['fighter_space'] * ($f['fighters'] - $mf);
$oa = $r['cruiser_haul'] * ($f['cruisers'] - $mc) + $r['bcruiser_haul'] * ($f['bcruisers'] - $mb);
if ($nu > $na || $ou > $oa) {
return 3;
}
}
// Generate code that will set the new fleets' orders
if (is_null($f['location'])) {
$location = "NULL";
if (is_null($f['moving'])) {
$moving = "NULL";
$oCode = '$waiting = $this->standby->call("create", '.$f['wait']['time_left'].",".$f['wait']['drop_point']
. ','.$f['wait']['origin'].','.$f['wait']['time_spent'].');';
} else {
$waiting = "NULL";
$oCode = '$moving = $this->moving->call("cloneObject", '.$f['moving'].');';
}
} else {
$location = $f['location'];
$moving = $waiting = 'NULL';
$oCode = null;
}
// Generate new fleets
$nn = addslashes($newName == "" ? preg_replace('/ [0-9]+$/', '', $f['name']) : $newName);
for ($i=0;$i<$count;$i++) {
if ($oCode != "") {
eval($oCode);
}
$nnb = $count > 1 ? (" " . ($i + 1)) : "";
$this->db->query("INSERT INTO fleet(owner,name,location,gaships,fighters,cruisers,bcruisers,attacking,moving,waiting,time_spent) VALUES("
.$f['owner'].",'$nn$nnb',$location,$sg,$sf,$sc,$sb,"
.dbBool($f['attacking'] == 't').",$moving,$waiting,{$f['time_spent']})");
}
// Update original fleet
$this->db->query("UPDATE fleet SET gaships=gaships-$mg,fighters=fighters-$mf,cruisers=cruisers-$mc,bcruisers=bcruisers-$mb "
."WHERE id=$fid");
$this->db->query("DELETE FROM beacon_detection WHERE fleet = $fid");
$this->lib->call('invCache', $fid);
return 0;
}
}
?>

View file

@ -0,0 +1,31 @@
<?php
class beta5_fleet_switchStatus {
function beta5_fleet_switchStatus($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Switches a fleet's status
function run($id) {
$f = $this->lib->call('get', $id);
if ($f['attacking'] == 't') {
$this->db->query("UPDATE fleet SET attacking=".dbBool(0)." WHERE id=$id");
} else {
$this->db->query("UPDATE fleet SET attacking=".dbBool(1)
.(is_null($f['location'])?"":",can_move='B',time_spent=0")." WHERE id=$id");
}
// FIXME: messages
$this->lib->mainClass->fleets[$id]['attacking'] = ($this->lib->mainClass->fleets[$id]['attacking'] == 't') ? 'f' : 't';
if ($this->lib->mainClass->fleets[$id]['attacking'] == 't' && !is_null($f['location'])) {
$this->lib->mainClass->fleets[$id]['can_move'] = 'B';
}
logText("beta5/fleet/switchStatus($id): fleet owner {$f['owner']}, switched to " . ($f['attacking'] == 't' ? "def" : "att"), LOG_DEBUG);
}
}
?>

View file

@ -0,0 +1,65 @@
<?php
class beta5_forums_library {
var $index = array(
'deletePost',
'deleteTopic',
'edit',
'getLatest',
'getPost',
'getPosts',
'getStructure',
'getTopic',
'getTopics',
'moveTopic',
'newTopic',
'reply',
'searchPosts',
'searchTopics',
'updateLast'
);
function beta5_forums_library($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
// Get the amount of read topics in an alliance forum
function getRead($fid, $pid) {
$q = $this->db->query("SELECT COUNT(*) FROM af_read r,af_topic t WHERE t.id=r.topic AND t.forum=$fid AND r.reader=$pid");
list($nr) = dbFetchArray($q);
return $nr;
}
function isRead($topic, $player) {
$q = $this->db->query("SELECT * FROM af_read WHERE topic=$topic AND reader=$player");
return $q && dbCount($q);
}
function markRead($topic, $player) {
if ($this->isRead($topic,$player)) {
return false;
}
$this->db->query("DELETE FROM af_read WHERE topic=$topic AND reader=$player");
$this->db->query("INSERT INTO af_read(topic,reader)VALUES($topic,$player)");
return true;
}
function markUnread($topic, $player) {
$this->db->query("DELETE FROM af_read WHERE topic=$topic AND reader<>$player");
}
function switchSticky($forum, $topic) {
$this->db->query("UPDATE af_topic SET sticky=NOT sticky WHERE id=$topic AND forum=$forum");
}
function markForumRead($fid, $pid) {
$q = $this->db->query("SELECT id FROM af_topic WHERE forum=$fid");
while ($r = dbFetchArray($q)) {
$this->markRead($r[0], $pid);
}
}
}
?>

View file

@ -0,0 +1,31 @@
<?php
class beta5_forums_deletePost {
function beta5_forums_deletePost($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
function run($postId) {
$q = $this->db->query(
"SELECT f.id AS forum, t.id AS topic, reply_to FROM af_post p, af_forum f, af_topic t "
. "WHERE p.id = $postId AND t.id = p.topic AND f.id = p.forum "
. "FOR UPDATE OF p, f, t"
);
if (!($q && dbCount($q))) {
return;
}
list($fid,$tid,$rtid) = dbFetchArray($q);
$this->db->query("UPDATE af_post SET reply_to=$rtid WHERE reply_to=$postId");
$this->db->query("UPDATE af_forum SET posts=posts-1 WHERE id=$fid");
$this->db->query("DELETE FROM af_post WHERE id=$postId");
$q = $this->db->query("SELECT id FROM af_post WHERE topic=$tid ORDER BY moment DESC LIMIT 1");
list($lastid) = dbFetchArray($q);
$this->db->query("UPDATE af_topic SET last_post=$lastid WHERE id=$tid");
$this->lib->call('updateLast', $fid);
}
}
?>

View file

@ -0,0 +1,26 @@
<?php
class beta5_forums_deleteTopic {
function beta5_forums_deleteTopic($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
function run($forum, $topic) {
$q = $this->db->query(
"SELECT t.id, f.id, p.id FROM af_post p, af_topic t, af_forum f "
. "WHERE p.forum = $forum AND p.topic = $topic AND t.id = p.topic AND f.id = p.forum "
. "FOR UPDATE OF p, t, f"
);
if (!($q && dbCount($q))) {
return;
}
$np = dbCount($q);
$this->db->query("DELETE FROM af_post WHERE topic=$topic AND forum=$forum");
$this->db->query("UPDATE af_forum SET posts=posts-$np,topics=topics-1 WHERE id=$forum");
$this->lib->call('updateLast', $forum);
}
}
?>

View file

@ -0,0 +1,23 @@
<?php
class beta5_forums_edit {
function beta5_forums_edit($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
function run($a, $pid, $sub, $txt, $ec, $es) {
$tm = time();
$q = $this->db->query("SELECT topic FROM af_post WHERE id=$pid");
list($tid) = dbFetchArray($q);
$this->lib->call('markUnread', $tid,$a);
$qs = "UPDATE af_post SET edited=$tm,edited_by=$a,title='".addslashes($sub)."',contents='"
.addslashes($txt)."',enable_code=".dbBool($ec).",enable_smileys="
. dbBool($es) . " WHERE id=$pid";
return !is_null($this->db->query($qs));
}
}
?>

View file

@ -0,0 +1,43 @@
<?php
class beta5_forums_getLatest {
function beta5_forums_getLatest($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->mForums = $this->lib->game->getLib('main/forums');
}
function run($aForums, $gForums, $nb, $first) {
if (count($aForums) && count($gForums)) {
$qs = "SELECT 'A',id,moment FROM af_post WHERE forum IN (".join(',',$aForums).")";
$qs .= "UNION SELECT 'G',id,moment FROM f_post WHERE forum IN (".join(',',$gForums).") AND deleted IS NULL ";
} elseif (count($aForums)) {
$qs = "SELECT 'A',id,moment FROM af_post WHERE forum IN (".join(',',$aForums).") ";
} elseif (count($gForums)) {
$qs = "SELECT 'G',id,moment FROM f_post WHERE forum IN (".join(',',$gForums).") AND deleted IS NULL ";
} else {
return array();
}
$qs .= "ORDER BY moment DESC LIMIT $nb OFFSET $first";
$q = $this->db->query($qs);
$posts = array();
while ($r = dbFetchArray($q)) {
if ($r[0] == 'A') {
$p = $this->lib->call('getPost', $r[1]);
$p['contents'] = $p['html'];
} else {
$p = $this->mForums->call('getPost',$r[1]);
$p['contents'] = $p['html'];
}
$p['ctype'] = $r[0];
array_push($posts, $p);
}
return $posts;
}
}
?>

View file

@ -0,0 +1,46 @@
<?php
class beta5_forums_getPost {
function beta5_forums_getPost($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
$this->mForums = $this->lib->game->getLib('main/forums');
}
function run($pid) {
// Get post data
$q = $this->db->query(
"SELECT p.id AS id,p.title AS title,"
. "t.id AS tid,p2.title AS tname,"
. "f.id AS fid,f.title AS fname,"
. "c.id AS cid,c.name AS cname,"
. "p.author AS pid,p.reply_to as reply_to,"
. "p.moment AS moment,p.title AS title,"
. "p.contents AS contents,p.enable_code AS ec,"
. "p.enable_smileys AS es,p.edited AS edited,"
. "p.edited_by AS edit_id "
. "FROM af_topic t,af_post p,af_post p2,af_forum f,alliance c "
. "WHERE p.id=$pid AND t.id=p.topic AND p2.id=t.first_post "
. "AND f.id=p.forum AND c.id=f.alliance"
);
if (!$q || dbCount($q) != 1) {
return null;
}
$rv = dbFetchHash($q);
$rv['html'] = $this->mForums->call('substitute',
$rv['contents'], $rv['ec'], $rv['es']
);
$pinf = $this->players->call('get', $rv['pid'], true);
$rv['html'] .= $this->mForums->call('signature', $pinf['uid']);
$rv['author'] = $pinf['name'];
if (!is_null($rv['edit_id'])) {
$rv['edited_by'] = $this->players->call('getName', $rv['edit_id'], true);
}
return $rv;
}
}
?>

View file

@ -0,0 +1,113 @@
<?php
class beta5_forums_getPosts {
function beta5_forums_getPosts($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
$this->mForums = $this->lib->game->getLib('main/forums');
}
function run($tid, $thr, $o, $cnt, $fst) {
$os = $o?"DESC":"ASC";
$posts = array();
// FIXME: this is the wrong way to access player ID
$myId = $_SESSION[game::sessName()]['player'];
if ($thr) {
// Read list of IDs
$q = $this->db->query(
"SELECT id,reply_to FROM af_post WHERE topic=$tid ORDER BY moment $os"
);
$ids = array();
while ($qr = dbFetchArray($q)) {
array_push($ids, $qr);
}
// Get first post
if ($o) {
$mp = array_pop($ids);
} else {
$mp = array_shift($ids);
}
// Initialize IDs and depths
$sids = array($mp[0]);
$dpth = array(0);
// Create lists
$ist = array($mp[0]);
$cd = 0;
while (count($ids)) {
$od = $cd;
for ($i=0;$i<count($ids)&&$od==$cd;$i++) {
if ($ids[$i][1] != $ist[$cd]) {
continue;
}
array_push($ist, $ids[$i][0]);
array_push($sids, $ids[$i][0]);
array_splice($ids, $i, 1);
array_push($dpth, $cd);
$cd++;
}
if ($cd == $od) {
$cd--;
array_pop($ist);
}
}
$rsids = array_splice($sids, $fst, $cnt);
$q = $this->db->query(
"SELECT id,author AS pid,moment,title,contents,enable_code AS ec,"
. "enable_smileys AS es,edited,edited_by AS edit_id "
. "FROM af_post WHERE id IN (".join(',',$rsids).")"
);
while ($qr = dbFetchHash($q)) {
$pinf = $this->players->call('get', $qr['pid'], true);
$qr['author'] = $pinf['name'];
$qr['mine'] = ($qr['pid'] == $myId);
$qr['contents'] = $this->mForums->call('substitute',
$qr['contents'], $qr['ec'], $qr['es']
);
$qr['contents'] .= $this->mForums->call('signature', $pinf['uid']);
$i = array_search($qr['id'], $rsids);
$qr['depth'] = $dpth[$i+$fst];
if ($qr['depth'] > 9) {
$qr['depth'] = 9;
}
if (!is_null($qr['edit_id'])) {
$qr['edited_by'] = $this->players->call('getName', $qr['edit_id']);
}
$posts[$i] = $qr;
$i++;
}
} else {
$q = $this->db->query(
"SELECT id,author AS pid,moment,title,contents,enable_code AS ec,"
. "enable_smileys AS es,edited,edited_by AS edit_id "
. "FROM af_post WHERE topic=$tid "
. "ORDER BY moment $os LIMIT $cnt OFFSET $fst"
);
while ($qr = dbFetchHash($q)) {
$pinf = $this->players->call('get', $qr['pid'], true);
$qr['mine'] = ($qr['pid'] == $myId);
$qr['author'] = $pinf['name'];
$qr['contents'] = $this->mForums->call('substitute',
$qr['contents'], $qr['ec'], $qr['es']
);
$qr['contents'] .= $this->mForums->call('signature', $pinf['uid']);
$qr['depth'] = 0;
if (!is_null($qr['edit_id'])) {
$qr['edited_by'] = $this->players->call('getName', $qr['edit_id']);
}
array_push($posts, $qr);
}
}
return $posts;
}
}
?>

View file

@ -0,0 +1,98 @@
<?php
class beta5_forums_getStructure {
function beta5_forums_getStructure($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
$this->alliance = $this->lib->game->getLib('beta5/alliance');
$this->account = $this->lib->game->getLib('main/account');
$this->mForums = $this->lib->game->getLib('main/forums');
}
function run($player) {
$rv = array();
$ord = 0;
$pi = $this->players->call('get', $player);
$isAdm = $this->account->call('isAdmin', $pi['uid']);
$gAdm = $this->mForums->call('getAdministrator', $pi['uid']);
$gMod = $this->mForums->call('getModerator', $pi['uid']);
// Get categories for general forums
$gCats = $this->mForums->call('getCategories');
foreach ($gCats as $gc) {
$rv['G#'.$gc['id']] = array(
"id" => $gc['id'],
"type" => "G",
"title" => $gc['title'],
"desc" => $gc['description'],
"order" => $ord ++,
"forums" => array()
);
}
// Get version-specific general category
$vCat = $this->mForums->call('getVersionCategory', 'beta5');
if ($vCat) {
$rv['G#'.$vCat['id']] = array(
"id" => $vCat['id'],
"type" => "V",
"title" => "Legacy Worlds - Beta 5",
"desc" => $vCat['description'],
"order" => $ord ++,
"forums" => array()
);
}
// Get general forums
$gCats = array_keys($rv);
foreach ($gCats as $cid) {
$rcid = substr($cid,2);
$rv[$cid]['forums'] = $this->mForums->call('getForums', $rcid);
$foDiff = 0;
for ($i=0;$i<count($rv[$cid]['forums']);$i++) {
if (!$isAdm && $rv[$cid]['forums'][$i]['admin_only']) {
array_splice($rv[$cid]['forums'], $i, 1);
$i --;
$foDiff ++;
continue;
}
$id = $rv[$cid]['forums'][$i]['id'];
$rv[$cid]['forums'][$i]['unread'] = $rv[$cid]['forums'][$i]['topics'] - $this->mForums->call('getRead', $id, $pi['uid']);
$rv[$cid]['forums'][$i]['mod'] = in_array($rv[$cid]['id'], $gAdm) || in_array($id, $gMod);
$rv[$cid]['forums'][$i]['forder'] -= $foDiff;
}
}
// Get alliance forums
$ap = $this->alliance->call('getPrivileges', $player);
if (count($ap['f_read']) || count($ap['f_mod'])) {
$rv['A#'.$pi['aid']] = array(
"id" => $pi['aid'],
"type" => "A",
"title" => $pi['aname'],
"order" => $ord ++,
"forums" => array()
);
$fl = $this->alliance->call('getForumsComplete', $pi['aid']);
$rcid = 'A#'.$pi['aid'];
foreach ($fl as $f) {
if (!(in_array($f['id'],$ap['f_read']) || in_array($f['id'],$ap['f_mod']))) {
continue;
}
$f['mod'] = in_array($f['id'],$ap['f_mod']);
$f['unread'] = $f['topics'] - $this->lib->call('getRead', $f['id'], $player);
$f['rcid'] = $rcid;
array_push($rv[$rcid]['forums'],$f);
}
}
return $rv;
}
}
?>

View file

@ -0,0 +1,32 @@
<?php
class beta5_forums_getTopic {
function beta5_forums_getTopic($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
}
function run($tid) {
// Get main topic data
$q = $this->db->query(
"SELECT t.id AS id,p.title AS title,"
. "f.id AS fid,f.title AS fname,"
. "p.id AS fpid,t.last_post AS lpid "
. "FROM af_topic t,af_post p,af_forum f "
. "WHERE t.id=$tid AND p.id=t.first_post AND f.id=t.forum"
);
if (!$q || dbCount($q) != 1) {
return null;
}
$rv = dbFetchHash($q);
// Get post count
$q = $this->db->query("SELECT COUNT(*) FROM af_post WHERE topic=$tid");
list($rv["nitems"]) = dbFetchArray($q);
return $rv;
}
}
?>

View file

@ -0,0 +1,37 @@
<?php
class beta5_forums_getTopics {
function beta5_forums_getTopics($lib) {
$this->lib = $lib;
$this->db = $this->lib->game->db;
$this->players = $this->lib->game->getLib('beta5/player');
}
function run($f, $first, $count) {
$q = $this->db->query(
"SELECT t.id AS id,p.title AS title,p.moment AS moment,"
. "p.author AS author_id,p2.moment AS last_moment,"
. "p2.author AS last_author_id,t.sticky AS sticky "
. "FROM af_topic t,af_post p,af_post p2 "
. "WHERE t.forum=$f AND p.id=t.first_post AND p2.id=t.last_post "
. "ORDER BY sticky DESC,last_moment DESC LIMIT $count OFFSET $first"
);
$a = array();
if (!$q) {
return $a;
}
while ($rs = dbFetchHash($q)) {
$q2 = $this->db->query("SELECT COUNT(*)-1 FROM af_post WHERE topic=".$rs["id"]);
list($rs['posts']) = dbFetchArray($q2);
$rs['sticky'] = ($rs['sticky'] == 't');
$rs['author'] = $this->players->call('getName', $rs['author_id']);
$rs['last_author'] = $this->players->call('getName', $rs['last_author_id']);
array_push($a, $rs);
}
return $a;
}
}
?>

Some files were not shown because too many files have changed in this diff Show more