Fixed login

Started building page cleanup
Modified code pools
Backported layout/blocks/templates 3-step view system
Reforged Overview page
Moved graphics, added topnav template, fixed number render bug
Added BCMath optionnal usage
Updated BC Math comparison for capped resources
Fixed planet resource production updates
Various additions

Signed-off-by: Gregory PLANCHAT <g.planchat@gmail.com>
This commit is contained in:
Gregory PLANCHAT 2011-07-25 08:45:57 +02:00
commit f2d4b0f7e2
384 changed files with 2727 additions and 1364 deletions

View file

@ -1,85 +0,0 @@
<?php
class Legacies
{
private static $_listeners = array();
private static $_translators = array();
public static $request = null;
public static $response = null;
protected static $_now = null;
public static function registerListener($event, $listener)
{
if (!isset(self::$_listeners[$event])) {
self::$_listeners[$event] = array();
}
self::$_listeners[$event][] = $listener;
}
public static function clearAllListeners()
{
self::$_listeners = array();
}
public static function clearEventListeners($event)
{
if (isset(self::$_listeners[$event])) {
self::$_listeners[$event] = array();
}
}
public static function dispatchEvent($event, $params)
{
if (!isset(self::$_listeners[$event])) {
return;
}
$eventObject = new Legacies_Core_Event($params);
foreach (self::$_listeners[$event] as $listener) {
call_user_func($listener, $eventObject);
}
}
public static function getSession($namespace)
{
return Legacies_Core_Model_Session::factory($namespace);
}
public static function getTranslator($locale = 'fr_FR')
{
if (!isset($translator[$locale])) {
$path = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'locale';
$translator[$locale] = new Legacies_Core_Model_Translator($path, $locale);
}
return $translator[$locale];
}
public static function translate($locale, $message, Array $args)
{
return vsprintf(self::getTranslator($locale)->translateArgs($message), $args);
}
public static function __($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return self::getTranslator(self::getLocale())->translate($message, $args);
}
public static function getLocale()
{
return 'fr_FR';
}
public static function now()
{
if (self::$_now === null) {
self::$_now = time();
}
return self::$_now;
}
}

View file

@ -1,324 +0,0 @@
<?php
class Legacies_Core_Collection
extends Legacies_Core_Model
implements Iterator, Countable
{
protected $_tableName = null;
protected $_tableAlias = null;
protected $_entityClassName = 'Legacies_Object';
protected $_columns = array();
protected $_where = array();
protected $_join = array();
protected $_order = array();
protected $_union = array();
protected $_limit = null;
protected $_offset = null;
protected $_group = array();
protected $_items = array();
public function __construct($tableName = null, $entityClassName = null)
{
if ($tableName !== null) {
$this->setTableName($tableName);
}
if ($entityClassName != null) {
$this->setEntityClassName($entityClassName);
}
}
protected function _init()
{
return $this;
}
public function setTableName($tableName)
{
if (!is_array($tableName)) {
$this->_tableName = $tableName;
} else {
$this->_tableName = current($tableName);
$this->_tableAlias = key($tableName);
}
return $this;
}
public function getTableName()
{
return $this->_tableName;
}
public function setEntityClassName($entityClassName)
{
$this->_entityClassName = $entityClassName;
return $this;
}
public function getEntityClassName()
{
return $this->_entityClassName;
}
public function quote($data)
{
static $database = null;
if ($database === null) {
$database = Legacies_Database::getSingleton();
}
return $database->quote($data);
}
public function column($column = '*', $alias = null)
{
if (is_array($column)) {
foreach ($column as $alias => $field) {
if (is_int($alias)) {
$this->_columns[] = array($field);
} else {
$this->_columns[] = array($alias => $field);
}
}
} else if ($alias === null || is_int($alias)) {
$this->_columns[] = array($column);
} else {
$this->_columns[] = array($alias => $column);
}
return $this;
}
public function where($condition)
{
$this->_where[] = $condition;
return $this;
}
public function join($table, $condition, $fields = array('*'), $mode = 'INNER')
{
static $database = null;
if ($database === null) {
$database = Legacies_Database::getSingleton();
}
if (is_array($table)) {
$alias = key($table);
$table = current($table);
foreach ($fields as $fieldAlias => $fieldName) {
$this->column("{$alias}.{$field}", $fieldAlias);
}
$this->_join[] = "{$mode} JOIN {$database->getTable($table)} AS {$alias} ON {$condition}";
} else {
foreach ($fields as $field) {
$this->column("{$field}");
}
$this->_join[] = "{$mode} JOIN {$database->getTable($table)} ON {$condition}";
}
return $this;
}
public function order($field, $direction = 'ASC')
{
$this->_order[] = "{$field} {$direction}";
return $this;
}
public function union($collection)
{
$this->_union[] = $collection;
return $this;
}
public function limit($limit, $offset = null)
{
$this->_limit = intval($limit);
$this->_offset = $offset;
return $this;
}
public function group($groupField)
{
$this->_group[] = $groupField;
return $this;
}
protected function _prepareSql()
{
if (empty($this->_union)) {
$database = Legacies_Database::getSingleton();
$fields = array();
foreach ($this->_columns as $field) {
$fieldName = current($field);
$fieldAlias = key($field);
if (is_string($fieldAlias)) {
$fields[] = "{$fieldName} AS {$fieldAlias}";
} else {
$fields[] = $fieldName;
}
}
if (!empty($fields)) {
$fields = implode(", ", $fields);
} else {
$fields = '*';
}
if (!empty($where)) {
$where = 'WHERE ' . implode(" AND ", $this->_where);
} else {
$where = '';
}
$joinedTables = implode("\n ", $this->_join);
$order = '';
if (!empty($this->_order)) {
$order = 'ORDER BY ' . implode(", ", $this->_order);
}
$alias = '';
if ($this->_tableAlias !== null) {
$alias = " AS {$this->_tableAlias}";
}
$limit = '';
if ($this->_limit) {
if ($this->_offset) {
$limit = "LIMIT {$this->_limit}, {$this->_offset}";
} else {
$limit = "LIMIT {$this->_limit}";
}
}
$group = '';
if (!empty($this->_group)) {
$group = 'GROUP BY ' . implode(', ', $this->_group);
}
return <<<SQL_EOF
SELECT {$fields}
FROM {$database->getTable($this->getTableName())}{$alias}
{$joinedTables}
{$where}
{$group}
{$order}
{$limit}
SQL_EOF;
} else {
$statements = array();
foreach ($this->_union as $statement) {
$statements[] = $statement->_prepareSql();
}
$statements = '(' . implode(') UNION (', $statements) . ')';
if (!empty($where)) {
$where = 'WHERE ' . implode(" AND ", $this->_where);
} else {
$where = '';
}
$where = implode(" AND ", $this->_where);
$limit = '';
if ($this->_limit) {
if ($this->_offset) {
$limit = "LIMIT {$this->_limit}, {$this->_offset}";
} else {
$limit = "LIMIT {$this->_limit}";
}
}
return <<<SQL_EOF
$statements
{$where}
{$limit}
SQL_EOF;
}
}
public function __toString()
{
return $this->_prepareSql();
}
protected function _load()
{
$sql = $this->_prepareSql();
$database = Legacies_Database::getSingleton();
$statement = $database->prepare($sql);
$args = func_get_args();
$statement->execute(array_shift($args));
$this->_items = array();
$reflection = new ReflectionClass($this->getEntityClassName());
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$params = array_merge(array($row), $args);
$this->_items[] = $reflection->newInstanceArgs($params);
}
return $this;
}
protected function _save()
{
foreach ($this->_items as $child) {
$child->save();
}
return $this;
}
protected function _delete()
{
foreach ($this->_items as $child) {
$child->delete();
}
return $this;
}
public function count()
{
return count($this->_items);
}
public function current()
{
return current($this->_items);
}
public function next()
{
next($this->_items);
return $this;
}
public function rewind()
{
reset($this->_items);
return $this;
}
public function key()
{
return key($this->_items);
}
public function valid()
{
return current($this->_items) !== false;
}
}

View file

@ -1,153 +0,0 @@
<?php
abstract class Legacies_Core_Entity
extends Legacies_Core_Model
implements Legacies_Core_EntityInterface
{
protected $_idFieldName = null;
protected $_tableName = null;
public function setIdFieldName($fieldName)
{
$this->_idFieldName = $fieldName;
return $this;
}
public function getIdFieldName()
{
return $this->_idFieldName;
}
public function setTableName($tableName)
{
$this->_tableName = $tableName;
return $this;
}
public function getTableName()
{
return $this->_tableName;
}
public function setId($id)
{
$this->setData($this->getIdFieldName(), $id);
return $this;
}
public function getId()
{
return $this->getData($this->getIdFieldName());
}
protected function _load()
{
$id = func_get_arg(0);
$idFieldName = self::getIdFieldName();
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
SELECT * FROM {$database->getTable(self::getTableName())}
WHERE {$idFieldName}=:id
LIMIT 1
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute(array(
'id' => $id
));
$datas = $statement->fetch(PDO::FETCH_ASSOC);
if (!is_array($datas) || empty($datas)) {
throw new Legacies_Core_Model_Exception('Could not load data: this id could not be found.');
}
unset($datas[self::getIdFieldName()]);
$this->_data = $datas;
$this->setId($id);
return $this;
}
protected function _save()
{
if ($this->getId() !== null) {
$fields = array();
$values = array();
foreach ($this->getAllDatas() as $field => $value) {
if ($field == self::getIdFieldName()) {
continue;
}
$fields[] = "{$field}=:{$field}";
$values[$field] = $value;
}
$fieldsImploded = implode(', ', $fields);
$idFieldName = self::getIdFieldName();
$values[$idFieldName] = $this->getId();
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
UPDATE {$database->getTable(self::getTableName())}
SET {$fieldsImploded}
WHERE {$idFieldName}=:{$idFieldName}
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
} else {
$datas = $this->getAllDatas();
$fieldsImploded = implode(', ', array_keys($datas));
$tokens = array();
$values = array();
foreach ($datas as $field => $value) {
if ($field == self::getIdFieldName()) {
continue;
}
$tokens[] = ":{$field}";
$values[$field] = $value;
}
$tokensImploded = implode(', ', $tokens);
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
INSERT INTO {$database->getTable(self::getTableName())} ($fieldsImploded)
VALUES ({$tokensImploded})
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
$this->setId($database->lastInsertId());
}
return $this;
}
protected function _delete()
{
$fields = array();
foreach ($this->getAllDatas() as $field => $value) {
if ($field == self::getIdFieldName()) {
continue;
}
$fields[] = "{$field}=:{$field}";
}
$fieldsImploded = implod(', ', $fields);
$idFieldName = self::getIdFieldName();
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
DELETE {$database->getTable(self::getTableName())}
WHERE {$idFieldName}=:{$idFieldName}
SQL_EOF;
$statement->execute($this->getAllDatas());
return $this;
}
}

View file

@ -1,131 +0,0 @@
<?php
/**
*
* @uses Legacies_Object
* @uses Legacies_Empire
* @uses Legacies_Empire_User
*/
abstract class Legacies_Core_Entity_SubTable
extends Legacies_Core_Model
{
private $_isLoaded = false;
protected $_tableName = null;
protected $_idFieldNames = array();
protected function _save()
{
if ($this->_isLoaded !== false) {
$fields = array();
$values = array();
$idFields = array();
foreach ($this->getAllDatas() as $field => $value) {
if (in_array($field, $this->_idFieldNames)) {
$idFields[] = "{$field}=:{$field}";
} else {
$fields[] = "{$field}=:{$field}";
}
$values[$field] = $value;
}
$idFields = '(' . implode(') AND (', $idFields) . ')';
$fields = implode(', ', $fields);
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
UPDATE {$database->getTable(self::getTableName())}
SET {$fields}
WHERE {$idFields}
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
} else {
$datas = $this->getAllDatas();
$fields = implode(', ', array_keys($datas));
$tokens = array();
foreach ($datas as $field => $value) {
$tokens[] = ":{$field}";
}
$tokens = implode(', ', $tokens);
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
INSERT INTO {$database->getTable(self::getTableName())} ($fields)
VALUES ({$tokens})
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($datas);
}
return $this;
}
protected function _load()
{
$idValues = func_get_arg(0);
$database = Legacies_Database::getSingleton();
$idFields = array();
foreach ($this->_idFieldNames as $field) {
$idFields[] = "{$field}=:{$field}";
}
$idFields = '(' . implode(') AND (', $idFields) . ')';
$sql =<<<SQL_EOF
SELECT * FROM {$database->getTable(self::getTableName())}
WHERE $idFields
LIMIT 1
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($idValues);
$datas = $statement->fetch(PDO::FETCH_ASSOC);
if (!is_array($datas) || empty($datas)) {
throw new Legacies_Core_Model_Exception('Could not load data: this id combination could not be found.');
}
$this->_data = $datas;
$this->_isLoaded = true;
return $this;
}
protected function _delete()
{
$database = Legacies_Database::getSingleton();
$idFields = array();
$idValues = array();
foreach ($this->_idFieldNames as $field) {
$idFields[] = "{$field}=:{$field}";
$idValues[$field] = $this->getData($field);
}
$idFields = '(' . implode(') AND (', $idFields) . ')';
$sql =<<<SQL_EOF
DELETE {$database->getTable(self::getTableName())}
WHERE $idFields
LIMIT 1
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($idValues);
$this->_data = array();
$this->_isLoaded = false;
return $this;
}
public function setTableName($tableName)
{
$this->_tableName = $tableName;
return $this;
}
public function getTableName()
{
return $this->_tableName;
}
}

View file

@ -1,13 +0,0 @@
<?php
interface Legacies_Core_EntityInterface
{
public function getId();
public function setId($id);
public function getIdFieldName();
public function setIdFieldName($fieldName);
public function getTableName();
public function setTableName($tableName);
}

View file

@ -1,163 +0,0 @@
<?php
class Legacies_Core_Error
{
private static $_singleton = null;
protected $_errors = array();
protected $_warnings = array();
protected $_notices = array();
protected $_otherErrors = array();
protected $_exceptions = array();
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self;
}
return self::$_singleton;
}
public function errorManager($errno, $errstr, $errfile = null, $errline = null, Array $errcontext = array())
{
switch ($errno) {
case E_USER_ERROR:
case E_ERROR:
$this->_errors[] = array(
'time' => explode(' ', microtime()),
'code' => $errno,
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
'context' => $errcontext
);
break;
case E_USER_WARNING:
case E_WARNING:
$this->_warnings[] = array(
'time' => explode(' ', microtime()),
'code' => $errno,
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
'context' => $errcontext
);
break;
case E_USER_NOTICE:
case E_NOTICE:
$this->_notices[] = array(
'time' => explode(' ', microtime()),
'code' => $errno,
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
'context' => $errcontext
);
break;
default:
if (!isset($this->_otherErrors[$errno])) {
$this->_otherErrors[$errno] = array();
}
$this->_otherErrors[$errno][] = array(
'time' => explode(' ', microtime()),
'code' => $errno,
'message' => $errstr,
'file' => $errfile,
'line' => $errline,
'context' => $errcontext
);
break;
}
return true;
}
public function exceptionManager($exception)
{
$this->_exceptions[] = $exception;
}
protected function _renderError($error)
{
$types = array(
0x0001 => 'E_ERROR',
0x0002 => 'E_WARNING',
0x0004 => 'E_PARSE',
0x0008 => 'E_NOTICE',
0x0010 => 'E_CORE_ERROR',
0x0020 => 'E_CORE_WARNING',
0x0040 => 'E_COMPILE_ERROR',
0x0080 => 'E_COMPILE_WARNING',
0x0100 => 'E_USER_ERROR',
0x0200 => 'E_USER_WARNING',
0x0400 => 'E_USER_NOTICE',
0x0800 => 'E_STRICT',
0x1000 => 'E_RECOVERABLE_ERROR',
0x2000 => 'E_DEPRECATED',
0x4000 => 'E_USER_DEPRECATED',
);
if (isset($types[$error['code']])) {
$code = $types[$error['code']];
} else {
$code = "Unknown ({$error['code']})";
}
$date = date('Y-m-d H:i:s', (int) $error['time'][1]);
$microsec = (int) ($error['time'][0] * 1000000);
return <<<ERROR_EOF
On: {$date} +{$microsec}µs
Type: {$code}
Message: {$error['message']}
File: {$error['file']}
Line: {$error['line']}
\n
ERROR_EOF;
}
public function shutdownManager()
{
echo '<pre style="background:#FFF;border:1px solid #F00;color:#000;padding:10px;margin:20px;">';
foreach ($this->_errors as $error) {
echo $this->_renderError($error);
}
foreach ($this->_warnings as $error) {
echo $this->_renderError($error);
}
foreach ($this->_notices as $error) {
echo $this->_renderError($error);
}
foreach ($this->_otherErrors as $error) {
echo $this->_renderError($error);
}
foreach ($this->_exceptions as $exception) {
echo $exception->getMessage();
echo $exception->getTraceAsString();
}
echo '</pre>';
}
public static function register()
{
static $registered = false;
set_error_handler(array(self::getSingleton(), 'errorManager'));
set_exception_handler(array(self::getSingleton(), 'exceptionManager'));
if ($registered === false && defined('DEBUG')) {
$registered = true;
register_shutdown_function(array(self::getSingleton(), 'shutdownManager'));
}
}
public static function unregister()
{
restore_error_handler();
restore_exception_handler();
}
}

View file

@ -1,6 +0,0 @@
<?php
class Legacies_Core_Event
extends Legacies_Object
{
}

View file

@ -1,7 +0,0 @@
<?php
class Legacies_Core_Event_Break
extends Exception
implements Legacies_Core_Exception
{
}

View file

@ -1,3 +0,0 @@
<?php
interface Legacies_Core_Exception extends Legacies_Exception {}

View file

@ -1,99 +0,0 @@
<?php
abstract class Legacies_Core_Model
extends Legacies_Object
{
protected $_originalData = array();
public function __construct(Array $data = array())
{
$this->_data = $data;
$this->_setOriginalData($data);
$this->_init();
}
abstract protected function _init();
protected function _setOriginalData(Array $data)
{
$this->_originalData = $data;
}
final public function save()
{
try {
$params = func_get_args();
call_user_func_array(array($this, '_beforeSave'), $params);
call_user_func_array(array($this, '_save'), $params);
call_user_func_array(array($this, '_afterSave'), $params);
$this->_setOriginalData($this->_data);
} catch (PDOException $e) {
throw new Legacies_Core_Model_Exception('Could not save data: ' . $e->getMessage(), 0);
}
return $this;
}
abstract protected function _save();
protected function _beforeSave()
{
return $this;
}
protected function _afterSave()
{
return $this;
}
final public function load()
{
try {
$params = func_get_args();
call_user_func_array(array($this, '_beforeLoad'), $params);
call_user_func_array(array($this, '_load'), $params);
call_user_func_array(array($this, '_afterLoad'), $params);
$this->_setOriginalData($this->_data);
} catch (PDOException $e) {
throw new Legacies_Core_Model_Exception('Could not load data: ' . $e->getMessage(), 0);
}
return $this;
}
abstract protected function _load();
protected function _beforeLoad()
{
return $this;
}
protected function _afterLoad()
{
return $this;
}
final public function delete()
{
try {
$params = func_get_args();
call_user_func_array(array($this, '_beforeDelete'), $params);
call_user_func_array(array($this, '_delete'), $params);
call_user_func_array(array($this, '_afterDelete'), $params);
} catch (PDOException $e) {
throw new Legacies_Core_Model_Exception('Could not delete entity: ' . $e->getMessage(), 0);
}
return $this;
}
abstract protected function _delete();
protected function _beforeDelete()
{
return $this;
}
protected function _afterDelete()
{
return $this;
}
}

View file

@ -1,85 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Core_Model_Config
extends Legacies_Core_Model
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
$this->load();
}
protected function _load()
{
$database = Legacies_Database::getSingleton();
$sql =<<<SQL_EOF
SELECT config_name AS attribute, config_value AS value
FROM {$database->getTable('config')} AS config
SQL_EOF;
$attributeName = null;
$attributeValue = null;
$statement = $database->prepare($sql);
$statement->execute();
$statement->bindColumn('attribute', $attributeName, PDO::PARAM_STR);
$statement->bindColumn('value', $attributeValue, PDO::PARAM_STR);
while ($statement->fetch(PDO::FETCH_BOUND)) {
$this->setData($attributeName, $attributeValue);
}
return $this;
}
protected function _save()
{
$database = Legacies_Database::getSingleton();
$fields = array();
$sql =<<<SQL_EOF
UPDATE {{table}}
SET config_value=:value
WHERE config_name=:name
SQL_EOF;
$statement = $database->prepare($sql);
foreach ($this->getAllDatas() as $attributeName => $attributeValue) {
$statement->execute(array(
'name' => $attributeName,
'value' => $attributeValue
));
}
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
public function isEnabled()
{
return (bool) $this->getData('game_disable');
}
}

View file

@ -1,7 +0,0 @@
<?php
class Legacies_Core_Model_Exception
extends RuntimeException
implements Legacies_Core_Exception
{
}

View file

@ -1,116 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Core_Model_Session
extends Legacies_Object
{
const CRIT = 0x80;
const ERROR = 0x40;
const WARN = 0x20;
const INFO = 0x10;
const DEBUG = 0x01;
protected static $_instances = null;
protected static $_levels = null;
public static function factory($namespace)
{
$namespace = (string) $namespace;
if (!isset(self::$_instances[$namespace])) {
if (self::$_levels === null) {
$reflection = new ReflectionClass(__CLASS__);
self::$_levels = array_flip($reflection->getConstants());
}
if (session_id() == '') {
session_start();
}
self::$_instances[$namespace] = new self($namespace);
}
return self::$_instances[$namespace];
}
public static function destroy()
{
session_destroy();
}
public function __construct($namespace)
{
$this->_data = &$_SESSION[$namespace];
$this->_data['messages'] = array();
}
public function getMessages($clear = true)
{
$messages = $this->_data['messages'];
if ($clear == true) {
$this->_data['messages'] = array();
}
return $messages;
}
public function addMessage($message, $type = self::DEBUG)
{
if (!isset(self::$_levels[$type])) {
$type = self::DEBUG;
}
if (!isset($this->_data['messages'])) {
$this->_data['messages'] = array();
}
if (!isset($this->_data['messages'][self::$_levels[$type]])) {
$this->_data['messages'][self::$_levels[$type]] = array();
}
$this->_data['messages'][self::$_levels[$type]][] = $message;
return $this;
}
public function addCritical($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::CRIT);
}
public function addError($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::ERROR);
}
public function addWarning($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::WARN);
}
public function addInfo($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::INFO);
}
public function addDebug($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::DEBUG);
}
}

View file

@ -1,37 +0,0 @@
<?php
class Legacies_Core_Model_Translator
{
protected $_translations = array();
public function __construct($path, $locale)
{
$fileList = glob($path . DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . '*.csv');
foreach ($fileList as $file) {
$fp = fopen($file, 'r');
while (!feof($fp)) {
$line = fgetcsv($fp);
if (count($line) >= 2) {
$this->_translations[$line[0]] = $line[1];
}
}
}
}
public function translate($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->translateArgs($message, $args);
}
public function translateArgs($message, Array $args = array())
{
if (isset($this->_translations[$message])) {
$message = $this->_translations[$message];
}
return vsprintf($message, $args);
}
}

View file

@ -1,444 +0,0 @@
<?php
class Legacies_Core_Setup_Model_Updater_ScriptQueue
implements Iterator, Countable, ArrayAccess
{
const PCRE_FILE_PATTERN = '%^(?<action>install|upgrade|uninstall|downgrade)-(?<version1>[0-9]+\.[0-9]+\.[0-9]+)(?:\.(?<stage1>[a-z]+)(?<level1>[0-9]+))?(?:-(?<version2>[0-9]+\.[0-9]+\.[0-9]+)(?:\.(?<stage2>[a-z]+)(?<level2>[0-9]+))?)?$%';
const PCRE_VERSION_PATTERN = '%^(?<version>[0-9]+\.[0-9]+\.[0-9]+)(?:-(?<stage>[a-z]+)(?<level>[0-9]+)?)?$%';
const STAGE_ALPHA = 'alpha';
const STAGE_BETA = 'beta';
const STAGE_RC = 'rc';
const STAGE_STABLE = 'stable';
const MODE_INSTALL = 'install';
const MODE_UNINSTALL = 'uninstall';
const MODE_UPGRADE = 'upgrade';
const MODE_DOWNGRADE = 'downgrade';
const VERSION_NULL = '0.0.0';
protected $_installVersions = array();
protected $_upgradeVersions = array();
protected $_uninstallVersions = array();
protected $_downgradeVersions = array();
protected $_finalVersion = null;
protected $_scripts = array();
public function __construct($path, $fromVersion = null, $toVersion = null)
{
try {
$this->_analyzePath($path);
} catch (Exception $e) {
return;
}
if ($fromVersion === null) {
$fromVersion = '0.0.0';
}
if ($toVersion === null) {
$toVersion = '0.0.0';
}
preg_match(self::PCRE_VERSION_PATTERN, $fromVersion, $matches);
$fromVersion = array(
'version' => isset($matches['version']) ? $matches['version'] : self::VERSION_NULL,
'stage' => isset($matches['stage']) && !empty($matches['stage']) ? $matches['stage'] : self::STAGE_STABLE,
'level' => isset($matches['level']) && !empty($matches['level']) ? (int) $matches['level'] : 0,
);
preg_match(self::PCRE_VERSION_PATTERN, $toVersion, $matches);
$toVersion = array(
'version' => isset($matches['version']) ? $matches['version'] : self::VERSION_NULL,
'stage' => isset($matches['stage']) && !empty($matches['stage']) ? $matches['stage'] : self::STAGE_STABLE,
'level' => isset($matches['level']) && !empty($matches['level']) ? (int) $matches['level'] : 0,
);
switch (version_compare($toVersion['version'], $fromVersion['version'])) {
case 1:
$this->_upgradeToVersion($fromVersion, $toVersion);
break;
case -1:
$this->_downgradeToVersion($fromVersion, $toVersion);
break;
case 0:
if ($toVersion['stage'] === self::STAGE_STABLE) {
if ($fromVersion['stage'] !== self::STAGE_STABLE) {
$this->_upgradeToVersion($fromVersion, $toVersion);
} else {
$this->_downgradeToVersion($fromVersion, $toVersion);
}
} else if ($toVersion['stage'] === self::STAGE_RC) {
if ($fromVersion['stage'] === self::STAGE_STABLE) {
$this->_downgradeToVersion($fromVersion, $toVersion);
} else if ($fromVersion['stage'] === self::STAGE_RC) {
if ($fromVersion['level'] < $toVersion['level']) {
$this->_upgradeToVersion($fromVersion, $toVersion);
} else {
// throw new RuntimeException("Version already installed.");
}
} else {
$this->_upgradeToVersion($fromVersion, $toVersion);
}
} else if ($toVersion['stage'] === self::STAGE_BETA) {
if (in_array($fromVersion['stage'], array(self::STAGE_STABLE, self::STAGE_RC))) {
$this->_downgradeToVersion($fromVersion, $toVersion);
} else if ($fromVersion['stage'] === self::STAGE_BETA) {
if ($fromVersion['level'] < $toVersion['level']) {
$this->_upgradeToVersion($fromVersion, $toVersion);
} else {
// throw new RuntimeException("Version already installed.");
}
} else {
$this->_upgradeToVersion($fromVersion, $toVersion);
}
} else if ($toVersion['stage'] === self::STAGE_ALPHA) {
if (in_array($fromVersion['stage'], array(self::STAGE_STABLE, self::STAGE_RC, self::STAGE_BETA))) {
$this->_downgradeToVersion($fromVersion, $toVersion);
} else if ($fromVersion['stage'] === self::STAGE_ALPHA) {
if ($fromVersion['level'] < $toVersion['level']) {
$this->_upgradeToVersion($fromVersion, $toVersion);
} else {
// throw new RuntimeException("Version already installed.");
}
} else {
$this->_upgradeToVersion($fromVersion, $toVersion);
}
} else {
throw new RuntimeException("Invalid version stage.");
}
break;
}
return $this;
}
public function getFinalVersion()
{
return $this->_finalVersion;
}
protected function _installHighestInstaller($currentVersion, $toVersion)
{
$highestVersion = self::VERSION_NULL;
foreach (array_keys($this->_installVersions) as $version) {
if (version_compare($version, $highestVersion, '>') && version_compare($version, $toVersion['version'], '<=')) {
$highestVersion = $version;
}
}
if (isset($this->_installVersions[$highestVersion][self::STAGE_STABLE][0])) {
$version = array(
'version' => $highestVersion,
'stage' => self::STAGE_STABLE,
'level' => 0,
);
$this->enqueue(array($version, $this->_installVersions[$highestVersion][self::STAGE_STABLE][0]));
return $version;
}
if (isset($this->_installVersions[$highestVersion][self::STAGE_RC])) {
$stage = self::STAGE_RC;
} else if (isset($this->_installVersions[$highestVersion][self::STAGE_BETA])) {
$stage = self::STAGE_BETA;
} else if (isset($this->_installVersions[$highestVersion][self::STAGE_ALPHA])) {
$stage = self::STAGE_ALPHA;
} else {
throw new RuntimeException("Invalid version stage.");
}
$levelList = array_keys($this->_installVersions[$highestVersion][$stage]);
$highestLevel = 0;
foreach ($levelList as $level) {
if ($level > $highestLevel) {
$highestLevel = $level;
}
}
$version = array(
'version' => $highestVersion,
'stage' => $stage,
'level' => $highestLevel,
);
$this->enqueue(array($version, $this->_installVersions[$highestVersion][$stage][$highestLevel]));
return $version;
}
protected function _downgradeToVersion($fromVersion, $toVersion)
{
throw new RuntimeException("Downgrade isn't yet implemented.");
}
protected function _upgradeToVersion($fromVersion, $toVersion)
{
$currentVersion = $fromVersion;
if ($fromVersion['version'] === self::VERSION_NULL) {
// run the higher install script
$currentVersion = $this->_installHighestInstaller($currentVersion, $toVersion);
}
$upgradeVersions = $this->_upgradeVersions;
while (true) {
if ($currentVersion['version'] === $toVersion['version'] &&
$currentVersion['stage'] === $toVersion['stage'] &&
$currentVersion['level'] === $toVersion['level']) {
break;
}
$versionPointer = &$upgradeVersions[$currentVersion['version']][$currentVersion['stage']][$currentVersion['level']];
if (empty($versionPointer)) {
break;
}
$highestVersion = $currentVersion['version'];
foreach ($versionPointer as $version => $stages) {
if (version_compare($version, $highestVersion['version'], '>') && version_compare($version, $toVersion['version'], '<=')) {
$highestVersion = $version;
}
}
if (version_compare($highestVersion, $toVersion['version'], '<')) {
$stage = self::STAGE_STABLE;
$level = 0;
} else if (version_compare($highestVersion, $toVersion['version']) === 0) {
if (isset($versionPointer[$highestVersion][self::STAGE_STABLE]) && $toVersion['stage'] === self::STAGE_STABLE) {
$stage = self::STAGE_STABLE;
} else if (isset($versionPointer[$highestVersion][self::STAGE_RC]) &&
in_array($toVersion['stage'], array(self::STAGE_RC, self::STAGE_STABLE))) {
$stage = self::STAGE_RC;
} else if (isset($versionPointer[$highestVersion][self::STAGE_BETA]) &&
in_array($toVersion['stage'], array(self::STAGE_RC, self::STAGE_STABLE, self::STAGE_BETA))) {
$stage = self::STAGE_BETA;
} else if (isset($versionPointer[$highestVersion][self::STAGE_ALPHA]) &&
in_array($toVersion['stage'], array(self::STAGE_RC, self::STAGE_STABLE, self::STAGE_BETA, self::STAGE_ALPHA))) {
$stage = self::STAGE_ALPHA;
} else {
break;
}
$level = max(array_keys($versionPointer[$highestVersion][$stage]));
} else {
throw new RuntimeException("Invalid version value.");
}
$currentVersion = array(
'version' => $highestVersion,
'stage' => $stage,
'level' => $level
);
$this->enqueue(array($currentVersion, $versionPointer[$highestVersion][$stage][$level]));
}
$this->_finalVersion = $currentVersion;
}
protected function _analyzePath($path)
{
$iterator = new DirectoryIterator($path);
foreach ($iterator as $file) {
if ($file->isDir() || $file->isDot()) {
continue;
}
if (!preg_match(self::PCRE_FILE_PATTERN, $file->getBasename('.php'), $matches)) {
continue;
}
switch ($matches['action']) {
case self::MODE_INSTALL:
$this->_addInstallFile(
$file->getPathname(),
$matches['version1'],
(isset($matches['stage1']) && !empty($matches['stage1']) ? $matches['stage1'] : self::STAGE_STABLE),
(isset($matches['level1']) && !empty($matches['level1']) ? (int) $matches['level1'] : 0)
);
break;
case self::MODE_UNINSTALL:
$this->_addUninstallFile(
$file->getPathname(),
$matches['version1'],
(isset($matches['stage1']) && !empty($matches['stage1']) ? $matches['stage1'] : self::STAGE_STABLE),
(isset($matches['level1']) && !empty($matches['level1']) ? (int) $matches['level1'] : 0)
);
break;
case self::MODE_UPGRADE:
$this->_addUpgradeFile(
$file->getPathname(),
$matches['version1'],
$matches['version2'],
(isset($matches['stage1']) && !empty($matches['stage1']) ? $matches['stage1'] : self::STAGE_STABLE),
(isset($matches['stage2']) && !empty($matches['stage2']) ? $matches['stage2'] : self::STAGE_STABLE),
(isset($matches['level1']) && !empty($matches['level1']) ? (int) $matches['level1'] : 0),
(isset($matches['level2']) && !empty($matches['level2']) ? (int) $matches['level2'] : 0)
);
break;
case self::MODE_DOWNGRADE:
$this->_addDowngradeFile(
$file->getPathname(),
$matches['version1'],
$matches['version2'],
(isset($matches['stage1']) && !empty($matches['stage1']) ? $matches['stage1'] : self::STAGE_STABLE),
(isset($matches['stage2']) && !empty($matches['stage2']) ? $matches['stage2'] : self::STAGE_STABLE),
(isset($matches['level1']) && !empty($matches['level1']) ? (int) $matches['level1'] : 0),
(isset($matches['level2']) && !empty($matches['level2']) ? (int) $matches['level2'] : 0)
);
break;
}
}
}
private function _addInstallFile($file, $version, $stage = self::STAGE_STABLE, $level = null)
{
if (!isset($this->_installVersions[$version])) {
$this->_installVersions[$version] = array();
}
if (!isset($this->_installVersions[$version][$stage])) {
$this->_installVersions[$version][$stage] = array();
}
$this->_installVersions[$version][$stage][$level] = $file;
return $this;
}
private function _addUpgradeFile($file, $upperVersion, $lowerVersion, $upperStage = self::STAGE_STABLE, $lowerStage = self::STAGE_STABLE, $upperLevel = null, $lowerLevel = null)
{
if (!isset($this->_upgradeVersions[$upperVersion])) {
$this->_upgradeVersions[$upperVersion] = array();
}
if (!isset($this->_upgradeVersions[$upperVersion][$upperStage])) {
$this->_upgradeVersions[$upperVersion][$upperStage] = array();
}
if (!isset($this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel])) {
$this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel] = array();
}
if (!isset($this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion])) {
$this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion] = array();
}
if (!isset($this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion][$lowerStage])) {
$this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion][$lowerStage] = array();
}
$this->_upgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion][$lowerStage][$lowerLevel] = $file;
return $this;
}
private function _addUninstallFile($file, $version, $stage = self::STAGE_STABLE, $level = null)
{
if (!isset($this->_uninstallVersions[$version])) {
$this->_uninstallVersions[$version] = array();
}
if (!isset($this->_uninstallVersions[$version][$stage])) {
$this->_uninstallVersions[$version][$stage] = array();
}
$this->_uninstallVersions[$version][$stage][$level] = $file;
return $this;
}
private function _addDowngradeFile($file, $upperVersion, $lowerVersion, $upperStage = self::STAGE_STABLE, $lowerStage = self::STAGE_STABLE, $upperLevel = null, $lowerLevel = null)
{
if (!isset($this->_downgradeVersions[$upperVersion])) {
$this->_downgradeVersions[$upperVersion] = array();
}
if (!isset($this->_downgradeVersions[$upperVersion][$upperStage])) {
$this->_downgradeVersions[$upperVersion][$upperStage] = array();
}
if (!isset($this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel])) {
$this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel] = array();
}
if (!isset($this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion])) {
$this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion] = array();
}
if (!isset($this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion][$lowerStage])) {
$this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion][$lowerStage] = array();
}
$this->_downgradeVersions[$upperVersion][$upperStage][$upperLevel][$lowerVersion][$lowerStage][$lowerLevel] = $file;
return $this;
}
public function count()
{
return count($this->_scripts);
}
public function offsetExists($offset)
{
return array_key_exists($offset, $this->_scripts);
}
public function offsetSet($offset, $value)
{
$this->_scripts[(int) $offset] = $value;
}
public function offsetGet($offset)
{
if ($this->offsetExists($offset)) {
return $this->_scripts[(int) $offset];
}
return null;
}
public function offsetUnset($offset)
{
if ($this->offsetExists($offset)) {
unset($this->_scripts[(int) $offset]);
}
}
public function current()
{
return current($this->_scripts);
}
public function key()
{
return key($this->_scripts);
}
public function next()
{
next($this->_scripts);
}
public function rewind()
{
reset($this->_scripts);
}
public function valid()
{
return (bool) (key($this->_scripts) !== null);
}
public function enqueue($data)
{
$this->_scripts[] = array(
'script' => $data[1],
'version' => $data[0]
);
}
}

View file

@ -1,6 +0,0 @@
<?php
interface Legacies_Core_Singleton
{
public static function getSingleton();
}

View file

@ -1,70 +0,0 @@
<?php
class Legacies_Core_View
extends Legacies_Object
{
protected $_template = null;
public function __construct(Array $data = array())
{
parent::__construct($data);
}
protected function _prepareRender()
{
return $this;
}
public function renderNumber($number)
{
return Math::render($number);
}
protected function escape($unescaped)
{
return htmlspecialchars($unescaped, ENT_QUOTES, 'UTF-8');
}
public function __($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return Legacies::translateArgs($message, $args);
}
public function renderScript($file)
{
$this->_prepareRender();
$path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'design' . DIRECTORY_SEPARATOR . 'scripts';
ob_start();
include $path . DIRECTORY_SEPARATOR . $file;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
public function render()
{
$template = $this->getTemplate();
if (empty($template)) {
return null;
}
return $this->renderScript($this->getTemplate());
}
public function setTemplate($template)
{
$this->_template = $template;
return $this;
}
public function getTemplate()
{
return $this->_template;
}
}

View file

@ -1,792 +0,0 @@
<?php
/**
* This file is part of XNova:Legacies
*
* @license Modified BSD
* @see https://github.com/gplanchat/one.platform
*
* Copyright (c) 2009-2010, Grégory PLANCHAT <g.planchat at gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of Grégory PLANCHAT nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing One.Platform.
*
*/
$this->setSetupConnection('legacies_setup');
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/aks')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL,
`teilnehmer` TEXT NULL,
`flotten` TEXT NULL,
`ankunft` INT UNSIGNED NULL,
`galaxy` TINYINT UNSIGNED NULL,
`system` SMALLINT UNSIGNED NULL,
`planet` TINYINT UNSIGNED NULL,
`eingeladen` INT UNSIGNED NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/aks', 'legacies_read', array('SELECT'))
->grant('legacies/aks', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/aks', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/alliance')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`ally_name` VARCHAR(32) NOT NULL,
`ally_tag` VARCHAR(8) NOT NULL,
`ally_owner` BIGINT UNSIGNED NOT NULL DEFAULT 0,
`ally_register_time` TIMESTAMP NOT NULL,
`ally_description` TEXT NULL,
`ally_web` VARCHAR(255) NULL,
`ally_text` TEXT NULL,
`ally_image` VARCHAR(255) NULL,
`ally_request` TEXT NULL,
`ally_request_waiting` TEXT NULL,
`ally_request_notallow` BOOL NOT NULL DEFAULT FALSE,
`ally_owner_range` VARCHAR(32) NULL,
`ally_ranks` TEXT NULL,
`ally_members` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/alliance', 'legacies_read', array('SELECT'))
->grant('legacies/alliance', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/alliance', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/annonce')} (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user` TEXT NOT NULL,
`galaxie` TINYINT UNSIGNED NOT NULL,
`systeme` SMALLINT UNSIGNED NOT NULL,
`metala` DECIMAL(65,0) NOT NULL,
`cristala` DECIMAL(65,0) NOT NULL,
`deuta` DECIMAL(65,0) NOT NULL,
`metals` DECIMAL(65,0) NOT NULL,
`cristals` DECIMAL(65,0) NOT NULL,
`deuts` DECIMAL(65,0) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/annonce', 'legacies_read', array('SELECT'))
->grant('legacies/annonce', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/annonce', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/banned')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`who` BIGINT UNSIGNED NOT NULL,
`theme` TEXT NOT NULL,
`who2` BIGINT UNSIGNED NOT NULL,
`time` TIMESTAMP NOT NULL,
`longer` INT UNSIGNED NOT NULL DEFAULT 3600,
`author` BIGINT UNSIGNED NOT NULL,
`email` VARCHAR(100) NOT NULL,
KEY `ID` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/banned', 'legacies_read', array('SELECT'))
->grant('legacies/banned', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/banned', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/buddy')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`sender` BIGINT UNSIGNED NOT NULL,
`owner` BIGINT UNSIGNED NOT NULL,
`active` BOOL NOT NULL DEFAULT TRUE,
`text` TEXT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/buddy', 'legacies_read', array('SELECT'))
->grant('legacies/buddy', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/buddy', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/chat')} (
`messageid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user` VARCHAR(255) NOT NULL,
`message` TEXT NOT NULL,
`timestamp` TIMESTAMP NOT NULL,
PRIMARY KEY (`messageid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/chat', 'legacies_read', array('SELECT'))
->grant('legacies/chat', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/chat', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/config')} (
`config_name` VARCHAR(64) NOT NULL,
`config_value` TEXT NOT NULL,
UNIQUE KEY (`config_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/config', 'legacies_read', array('SELECT'))
->grant('legacies/config', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/config', 'legacies_setup')
;
$sql = <<<SQL_EOF
INSERT INTO {$this->getTableName('legacies/config')} (`config_name`, `config_value`) VALUES
('game_speed', '2500'),
('fleet_speed', '2500'),
('resource_multiplier', '1000'),
('Fleet_Cdr', '30'),
('Defs_Cdr', '30'),
('initial_fields', '5000'),
('COOKIE_NAME', 'xnova-legacies'),
('game_name', 'XNova:Legacies'),
('game_disable', '1'),
('close_reason', 'Le jeu est clos pour le moment!'),
('metal_basic_income', '20'),
('crystal_basic_income', '10'),
('deuterium_basic_income', '0'),
('energy_basic_income', '0'),
('BuildLabWhileRun', '0'),
('LastSettedGalaxyPos', '1'),
('LastSettedSystemPos', '1'),
('LastSettedPlanetPos', '1'),
('urlaubs_modus_erz', '1'),
('noobprotection', '1'),
('noobprotectiontime', '5000'),
('noobprotectionmulti', '5'),
('forum_url', 'http://board.xnova-ng.org/'),
('OverviewNewsFrame', '1'),
('OverviewNewsTEXT', 'Bienvenue sur le nouveau serveur XNova Legacies'),
('OverviewExternChat', '0'),
('OverviewExternChatCmd', ''),
('OverviewBanner', '0'),
('OverviewClickBanner', ''),
('ExtCopyFrame', '0'),
('ExtCopyOwner', ''),
('ExtCopyFunct', ''),
('ForumBannerFrame', '0'),
('stat_settings', '1000'),
('link_enable', '0'),
('link_name', ''),
('link_url', ''),
('enable_announces', '1'),
('enable_marchand', '1'),
('enable_notes', '1'),
('bot_name', 'XNoviana Reali'),
('bot_adress', 'xnova@xnova.fr'),
('banner_source_post', '../images/bann.png'),
('ban_duration', '30'),
('enable_bot', '0'),
('enable_bbcode', '1'),
('debug', '0');
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/declared')} (
`declarator` TEXT NOT NULL,
`declared_1` TEXT NOT NULL,
`declared_2` TEXT NOT NULL,
`declared_3` TEXT NOT NULL,
`reason` TEXT NOT NULL,
`declarator_name` TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/declared', 'legacies_read', array('SELECT'))
->grant('legacies/declared', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/declared', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/errors')} (
`error_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`error_sender` VARCHAR(32) NOT NULL,
`error_time` TIMESTAMP NOT NULL,
`error_type` VARCHAR(32) NOT NULL DEFAULT 'unknown',
`error_text` TEXT,
PRIMARY KEY (`error_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/errors', 'legacies_read', array('SELECT'))
->grant('legacies/errors', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/errors', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/fleets')} (
`fleet_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`fleet_owner` BIGINT UNSIGNED NOT NULL,
`fleet_mission` TINYINT UNSIGNED NOT NULL,
`fleet_amount` DECIMAL(65,0) NOT NULL,
`fleet_array` TEXT NULL,
`fleet_start_time` TIMESTAMP NOT NULL,
`fleet_start_galaxy` TINYINT UNSIGNED NOT NULL,
`fleet_start_system` SMALLINT UNSIGNED NOT NULL,
`fleet_start_planet` TINYINT UNSIGNED NOT NULL,
`fleet_start_type` TINYINT UNSIGNED NOT NULL,
`fleet_end_time` TIMESTAMP NOT NULL,
`fleet_end_stay` TIMESTAMP NOT NULL,
`fleet_end_galaxy` TINYINT UNSIGNED NOT NULL,
`fleet_end_system` SMALLINT UNSIGNED NOT NULL,
`fleet_end_planet` TINYINT UNSIGNED NOT NULL,
`fleet_end_type` TINYINT UNSIGNED NOT NULL,
`fleet_taget_owner` BIGINT UNSIGNED NOT NULL,
`fleet_resource_metal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`fleet_resource_crystal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`fleet_resource_deuterium` DECIMAL(65,0) NOT NULL DEFAULT 0,
`fleet_target_owner` BIGINT UNSIGNED NOT NULL,
`fleet_group` BIGINT UNSIGNED NOT NULL,
`fleet_mess` BIGINT UNSIGNED NOT NULL,
`start_time` INT,
PRIMARY KEY (`fleet_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/fleets', 'legacies_read', array('SELECT'))
->grant('legacies/fleets', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/fleets', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/galaxy')} (
`galaxy` TINYINT UNSIGNED NOT NULL,
`system` SMALLINT UNSIGNED NOT NULL,
`planet` TINYINT UNSIGNED NOT NULL,
`id_planet` BIGINT UNSIGNED NOT NULL,
`metal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`crystal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`id_luna` BIGINT UNSIGNED NULL,
`luna` BOOL NOT NULL DEFAULT FALSE,
PRIMARY KEY (`galaxy`, `system`, `planet`),
KEY `galaxy` (`galaxy`),
KEY `system` (`system`),
KEY `planet` (`planet`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/galaxy', 'legacies_read', array('SELECT'))
->grant('legacies/galaxy', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/galaxy', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/iraks')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`zeit` TIMESTAMP NOT NULL,
`galaxy` TINYINT UNSIGNED NOT NULL,
`system` SMALLINT UNSIGNED NOT NULL,
`planet` TINYINT UNSIGNED NOT NULL,
`galaxy_angreifer` TINYINT UNSIGNED NOT NULL,
`system_angreifer` SMALLINT UNSIGNED NOT NULL,
`planet_angreifer` TINYINT UNSIGNED NOT NULL,
`owner` BIGINT UNSIGNED NOT NULL,
`zielid` BIGINT UNSIGNED NOT NULL,
`anzahl` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`primaer` SMALLINT UNSIGNED,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/iraks', 'legacies_read', array('SELECT'))
->grant('legacies/iraks', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/iraks', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/lunas')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`id_luna` BIGINT UNSIGNED NOT NULL,
`name` VARCHAR(100) NOT NULL DEFAULT 'Lune',
`image` VARCHAR(50) NOT NULL DEFAULT 'mond',
`destruyed` BOOL NOT NULL DEFAULT FALSE,
`id_owner` BIGINT UNSIGNED NOT NULL,
`galaxy` TINYINT UNSIGNED NOT NULL,
`system` SMALLINT UNSIGNED NOT NULL,
`lunapos` TINYINT UNSIGNED NOT NULL,
`temp_min` TINYINT NOT NULL DEFAULT 0,
`temp_max` TINYINT NOT NULL DEFAULT 0,
`diameter` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/lunas', 'legacies_read', array('SELECT'))
->grant('legacies/lunas', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/lunas', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/messages')} (
`message_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`message_owner` BIGINT UNSIGNED NOT NULL,
`message_sender` BIGINT UNSIGNED NOT NULL,
`message_time` TIMESTAMP NOT NULL,
`message_type` TINYINT UNSIGNED NOT NULL,
`message_from` VARCHAR(50),
`message_subject` VARCHAR(150),
`message_text` TEXT,
PRIMARY KEY (`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/messages', 'legacies_read', array('SELECT'))
->grant('legacies/messages', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/messages', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/multi')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`player` BIGINT UNSIGNED NOT NULL,
`sharer` BIGINT UNSIGNED NOT NULL,
`reason` TEXT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/multi', 'legacies_read', array('SELECT'))
->grant('legacies/multi', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/multi', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/notes')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`owner` BIGINT UNSIGNED NOT NULL,
`time` TIMESTAMP NOT NULL,
`priority` TINYINT UNSIGNED NOT NULL,
`title` VARCHAR(32) NOT NULL,
`TEXT` TEXT NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/notes', 'legacies_read', array('SELECT'))
->grant('legacies/notes', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/notes', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/planets')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`id_owner` BIGINT UNSIGNED NOT NULL,
`id_level` TINYINT UNSIGNED NOT NULL,
`galaxy` TINYINT UNSIGNED NOT NULL,
`system` SMALLINT UNSIGNED NOT NULL,
`planet` TINYINT UNSIGNED NOT NULL,
`last_update` TIMESTAMP NOT NULL,
`planet_type` TINYINT UNSIGNED NOT NULL,
`destruyed` BOOL NOT NULL DEFAULT FALSE,
`b_building` SMALLINT UNSIGNED NOT NULL,
`b_building_id` TEXT NOT NULL,
`b_tech` SMALLINT UNSIGNED NOT NULL,
`b_tech_id` SMALLINT UNSIGNED NOT NULL,
`b_hangar` SMALLINT UNSIGNED NOT NULL,
`b_hangar_id` TEXT NOT NULL,
`b_hangar_plus` SMALLINT UNSIGNED NOT NULL,
`image` VARCHAR(50) NOT NULL DEFAULT 'normaltempplanet01',
`diameter` INT UNSIGNED NOT NULL DEFAULT 12800,
`points` DECIMAL(65,0) NOT NULL DEFAULT 0,
`ranks` BIGINT UNSIGNED NOT NULL,
`field_current` INT UNSIGNED NOT NULL DEFAULT 163,
`field_max` INT UNSIGNED NOT NULL DEFAULT 163,
`temp_min` INT NOT NULL DEFAULT 0,
`temp_max` INT NOT NULL DEFAULT 0,
`metal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`metal_perhour` DECIMAL(65,0) NOT NULL DEFAULT 0,
`metal_max` DECIMAL(65,0) NOT NULL DEFAULT 0,
`crystal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`crystal_perhour` DECIMAL(65,0) NOT NULL DEFAULT 0,
`crystal_max` DECIMAL(65,0) NOT NULL DEFAULT 0,
`deuterium` DECIMAL(65,0) NOT NULL DEFAULT 0,
`deuterium_perhour` DECIMAL(65,0) NOT NULL DEFAULT 0,
`deuterium_max` DECIMAL(65,0) NOT NULL DEFAULT 0,
`energy_used` DECIMAL(65,0) NOT NULL DEFAULT 0,
`energy_max` DECIMAL(65,0) NOT NULL DEFAULT 0,
`metal_mine` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`crystal_mine` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`deuterium_sintetizer` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`solar_plant` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`fusion_plant` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`robot_factory` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`nano_factory` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`hangar` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`metal_store` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`crystal_store` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`deuterium_store` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`laboratory` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`terraformer` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`ally_deposit` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`silo` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`mondbasis` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`phalanx` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`sprungtor` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`small_ship_cargo` DECIMAL(65,0) NOT NULL DEFAULT 0,
`big_ship_cargo` DECIMAL(65,0) NOT NULL DEFAULT 0,
`light_hunter` DECIMAL(65,0) NOT NULL DEFAULT 0,
`heavy_hunter` DECIMAL(65,0) NOT NULL DEFAULT 0,
`crusher` DECIMAL(65,0) NOT NULL DEFAULT 0,
`battle_ship` DECIMAL(65,0) NOT NULL DEFAULT 0,
`colonizer` DECIMAL(65,0) NOT NULL DEFAULT 0,
`recycler` DECIMAL(65,0) NOT NULL DEFAULT 0,
`spy_sonde` DECIMAL(65,0) NOT NULL DEFAULT 0,
`bomber_ship` DECIMAL(65,0) NOT NULL DEFAULT 0,
`solar_satelit` DECIMAL(65,0) NOT NULL DEFAULT 0,
`destructor` DECIMAL(65,0) NOT NULL DEFAULT 0,
`dearth_star` DECIMAL(65,0) NOT NULL DEFAULT 0,
`battleship` DECIMAL(65,0) NOT NULL DEFAULT 0,
`misil_launcher` DECIMAL(65,0) NOT NULL DEFAULT 0,
`small_laser` DECIMAL(65,0) NOT NULL DEFAULT 0,
`big_laser` DECIMAL(65,0) NOT NULL DEFAULT 0,
`gauss_canyon` DECIMAL(65,0) NOT NULL DEFAULT 0,
`ionic_canyon` DECIMAL(65,0) NOT NULL DEFAULT 0,
`buster_canyon` DECIMAL(65,0) NOT NULL DEFAULT 0,
`small_protection_shield` ENUM('0','1') NOT NULL DEFAULT 0,
`big_protection_shield` ENUM('0','1') NOT NULL DEFAULT 0,
`interceptor_misil` SMALLINT NOT NULL DEFAULT 0,
`interplanetary_misil` SMALLINT NOT NULL DEFAULT 0,
`metal_mine_porcent` TINYINT NOT NULL DEFAULT 10,
`crystal_mine_porcent` TINYINT NOT NULL DEFAULT 10,
`deuterium_sintetizer_porcent` TINYINT NOT NULL DEFAULT 10,
`solar_plant_porcent` TINYINT NOT NULL DEFAULT 10,
`fusion_plant_porcent` TINYINT NOT NULL DEFAULT 10,
`solar_satelit_porcent` TINYINT NOT NULL DEFAULT 10,
`last_jump_time` TIMESTAMP NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/planets', 'legacies_read', array('SELECT'))
->grant('legacies/planets', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/planets', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/rw')} (
`id_owner1` BIGINT UNSIGNED NOT NULL,
`id_owner2` BIGINT UNSIGNED NOT NULL,
`rid` VARCHAR(72) NOT NULL,
`raport` LONGTEXT NOT NULL,
`a_zestrzelona` TINYINT UNSIGNED NOT NULL,
`time` TIMESTAMP NOT NULL,
KEY (`rid`),
UNIQUE KEY `id_owner1` (`id_owner1`,`rid`),
UNIQUE KEY `id_owner2` (`id_owner2`,`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/rw', 'legacies_read', array('SELECT'))
->grant('legacies/rw', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/rw', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/statpoints')} (
`id_owner` BIGINT UNSIGNED NOT NULL,
`id_ally` BIGINT UNSIGNED NOT NULL,
`stat_type` TINYINT UNSIGNED NOT NULL,
`stat_code` TINYINT UNSIGNED NOT NULL,
`tech_rank` BIGINT UNSIGNED NOT NULL,
`tech_old_rank` BIGINT UNSIGNED NOT NULL,
`tech_points` DECIMAL(65,0) NOT NULL,
`tech_count` BIGINT UNSIGNED NOT NULL,
`build_rank` BIGINT UNSIGNED NOT NULL,
`build_old_rank` BIGINT UNSIGNED NOT NULL,
`build_points` DECIMAL(65,0) NOT NULL,
`build_count` BIGINT UNSIGNED NOT NULL,
`defs_rank` BIGINT UNSIGNED NOT NULL,
`defs_old_rank` BIGINT UNSIGNED NOT NULL,
`defs_points` DECIMAL(65,0) NOT NULL,
`defs_count` BIGINT UNSIGNED NOT NULL,
`fleet_rank` BIGINT UNSIGNED NOT NULL,
`fleet_old_rank` BIGINT UNSIGNED NOT NULL,
`fleet_points` DECIMAL(65,0) NOT NULL,
`fleet_count` BIGINT UNSIGNED NOT NULL,
`total_rank` BIGINT UNSIGNED NOT NULL,
`total_old_rank` BIGINT UNSIGNED NOT NULL,
`total_points` DECIMAL(65,0) NOT NULL,
`total_count` BIGINT UNSIGNED NOT NULL,
`stat_date` TIMESTAMP NOT NULL,
KEY (`tech_points`),
KEY (`build_points`),
KEY (`defs_points`),
KEY (`fleet_points`),
KEY (`total_points`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/statpoints', 'legacies_read', array('SELECT'))
->grant('legacies/statpoints', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/statpoints', 'legacies_setup')
;
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('legacies/users')} (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(100) NOT NULL, -- FIXME
`password` VARCHAR(64) NOT NULL, -- FIXME
`email` VARCHAR(200) NOT NULL, -- FIXME
`email_2` VARCHAR(200) NOT NULL, -- FIXME
`lang` VARCHAR(3) NOT NULL DEFAULT 'fr',
`authlevel` TINYINT UNSIGNED NOT NULL DEFAULT 0, -- FIXME
`sex` ENUM('M','F') NULL DEFAULT NULL,
`avatar` VARCHAR(255) NULL DEFAULT NULL,
`sign` TEXT NULL,
`id_planet` BIGINT UNSIGNED NOT NULL, -- FIXME
`galaxy` TINYINT UNSIGNED NOT NULL, -- FIXME
`system` SMALLINT UNSIGNED NOT NULL, -- FIXME
`planet` TINYINT UNSIGNED NOT NULL, -- FIXME
`current_planet` BIGINT UNSIGNED NOT NULL, -- FIXME
`user_lastip` VARCHAR(16) NOT NULL, -- FIXME
`ip_at_reg` VARCHAR(16) NOT NULL, -- FIXME
`user_agent` TEXT NOT NULL, -- FIXME
`current_page` TEXT NOT NULL, -- FIXME
`register_time` TIMESTAMP NOT NULL, -- FIXME
`onlinetime` TIMESTAMP NOT NULL, -- FIXME
`dpath` VARCHAR(255) NOT NULL, -- FIXME
`design` TINYINT NOT NULL DEFAULT 1, -- FIXME
`noipcheck` BOOL NOT NULL DEFAULT TRUE, -- FIXME
`planet_sort` TINYINT NOT NULL DEFAULT 0, -- FIXME
`planet_sort_order` TINYINT NOT NULL DEFAULT 0, -- FIXME
`spio_anz` TINYINT UNSIGNED NOT NULL DEFAULT 1, -- FIXME
`settings_tooltiptime` TINYINT UNSIGNED NOT NULL DEFAULT 5, -- FIXME
`settings_fleetactions` TINYINT UNSIGNED NOT NULL DEFAULT 0, -- FIXME
`settings_allylogo` TINYINT UNSIGNED NOT NULL DEFAULT 0, -- FIXME
`settings_esp` TINYINT UNSIGNED NOT NULL DEFAULT 1, -- FIXME
`settings_wri` TINYINT UNSIGNED NOT NULL DEFAULT 1, -- FIXME
`settings_bud` TINYINT UNSIGNED NOT NULL DEFAULT 1, -- FIXME
`settings_mis` TINYINT UNSIGNED NOT NULL DEFAULT 1, -- FIXME
`settings_rep` TINYINT UNSIGNED NOT NULL DEFAULT 0, -- FIXME
`urlaubs_modus` TINYINT UNSIGNED NOT NULL DEFAULT 0, -- FIXME
`urlaubs_until` TIMESTAMP NOT NULL, -- FIXME
`db_deaktjava` BOOL NOT NULL DEFAULT FALSE, -- FIXME
`new_message` TINYINT UNSIGNED NOT NULL DEFAULT 0, -- FIXME
`fleet_shortcut` TEXT NULL,
`b_tech_planet` INT NOT NULL, -- FIXME
`spy_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`computer_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`military_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`defence_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`shield_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`energy_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`hyperspace_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`combustion_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`impulse_motor_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`hyperspace_motor_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`laser_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`ionic_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`buster_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`intergalactic_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`expedition_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`graviton_tech` TINYINT UNSIGNED NOT NULL, -- FIXME
`ally_id` BIGINT UNSIGNED NOT NULL,
`ally_name` VARCHAR(32) NULL, -- FIXME
`ally_request` BOOL NOT NULL DEFAULT FALSE, -- FIXME
`ally_request_text` TEXT NULL, -- FIXME
`ally_register_time` TIMESTAMP NOT NULL, -- FIXME
`ally_rank_id` BIGINT UNSIGNED NOT NULL, -- FIXME
`current_luna` INT NOT NULL, -- FIXME
`kolorminus` VARCHAR(11) NOT NULL DEFAULT 'red',
`kolorplus` VARCHAR(11) NOT NULL DEFAULT '#00FF00',
`kolorpoziom` VARCHAR(11) NOT NULL DEFAULT 'yellow',
`rpg_geologue` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_amiral` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_ingenieur` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_technocrate` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_espion` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_constructeur` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_scientifique` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_commandant` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_points` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_stockeur` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_defenseur` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_destructeur` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_general` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_bunker` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_raideur` TINYINT UNSIGNED NOT NULL, -- FIXME
`rpg_empereur` TINYINT UNSIGNED NOT NULL, -- FIXME
`lvl_minier` BIGINT UNSIGNED NOT NULL, -- FIXME
`lvl_raid` BIGINT UNSIGNED NOT NULL, -- FIXME
`xpraid` BIGINT UNSIGNED NOT NULL, -- FIXME
`xpminier` BIGINT UNSIGNED NOT NULL, -- FIXME
`raids` BIGINT UNSIGNED NOT NULL, -- FIXME
`p_infligees` DECIMAL(65,0) NOT NULL, -- FIXME
`mnl_alliance` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_joueur` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_attaque` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_spy` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_exploit` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_transport` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_expedition` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_general` TINYINT UNSIGNED NOT NULL, -- FIXME
`mnl_buildlist` TINYINT UNSIGNED NOT NULL, -- FIXME
`bana` BOOL NOT NULL DEFAULT FALSE, -- FIXME
`multi_validated` BOOL NOT NULL DEFAULT FALSE, -- FIXME
`banaday` TIMESTAMP NULL DEFAULT NULL, -- FIXME
`raids1` BIGINT UNSIGNED NOT NULL, -- FIXME
`raidswin` BIGINT UNSIGNED NOT NULL, -- FIXME
`raidsloose` BIGINT UNSIGNED NOT NULL, -- FIXME
PRIMARY KEY (`id`),
UNIQUE KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL_EOF;
$this->query($sql);
$this
->grant('legacies/users', 'legacies_read', array('SELECT'))
->grant('legacies/users', 'legacies_write', array('SELECT', 'CREATE', 'UPDATE', 'DELETE'))
->grant('legacies/users', 'legacies_setup')
;
$sql = <<<SQL_EOF
INSERT INTO {$this->getTableName('legacies/alliance')} (
`id`, `ally_name`, `ally_tag`, `ally_owner`, `ally_register_time`, `ally_description`,
`ally_web`, `ally_text`, `ally_image`, `ally_request`, `ally_request_waiting`,
`ally_request_notallow`, `ally_owner_range`, `ally_ranks`, `ally_members`
)
VALUES
('1', 'Admin', 'Admin', 1, NOW(), 'Administrator alliance', 'http://www.xnova-ng.org/',
'', '', '', '', '', '', '', '')
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
INSERT INTO {$this->getTableName('legacies/users')} (
`id`, `username`, `password`, `email`, `email_2`, `lang`, `authlevel`, `sex`,
`avatar`, `sign`, `id_planet`, `galaxy`, `system`, `planet`, `current_planet`,
`user_lastip`, `ip_at_reg`, `user_agent`, `current_page`, `register_time`,
`onlinetime`, `dpath`, `design`, `noipcheck`, `planet_sort`, `planet_sort_order`,
`spio_anz`, `settings_tooltiptime`, `settings_fleetactions`, `settings_allylogo`,
`settings_esp`, `settings_wri`, `settings_bud`, `settings_mis`, `settings_rep`,
`urlaubs_modus`, `urlaubs_until`, `db_deaktjava`, `new_message`, `fleet_shortcut`,
`b_tech_planet`, `spy_tech`, `computer_tech`, `military_tech`, `defence_tech`,
`shield_tech`, `energy_tech`, `hyperspace_tech`, `combustion_tech`,
`impulse_motor_tech`, `hyperspace_motor_tech`, `laser_tech`, `ionic_tech`,
`buster_tech`, `intergalactic_tech`, `expedition_tech`, `graviton_tech`,
`ally_id`, `ally_name`, `ally_request`, `ally_request_text`, `ally_register_time`,
`ally_rank_id`, `current_luna`, `kolorminus`, `kolorplus`, `kolorpoziom`,
`rpg_geologue`, `rpg_amiral`, `rpg_ingenieur`, `rpg_technocrate`, `rpg_espion`,
`rpg_constructeur`, `rpg_scientifique`, `rpg_commandant`, `rpg_points`, `rpg_stockeur`,
`rpg_defenseur`, `rpg_destructeur`, `rpg_general`, `rpg_bunker`, `rpg_raideur`,
`rpg_empereur`, `lvl_minier`, `lvl_raid`, `xpraid`, `xpminier`, `raids`,
`p_infligees`, `mnl_alliance`, `mnl_joueur`, `mnl_attaque`, `mnl_spy`,
`mnl_exploit`, `mnl_transport`, `mnl_expedition`, `mnl_general`, `mnl_buildlist`,
`bana`, `multi_validated`, `banaday`, `raids1`, `raidswin`, `raidsloose`
)
VALUES
('1', 'Admin', '', '', '', 'fr', '3', NULL, '', '', '1', '1', '1', '1',
'1', '127.0.0.1', '', '', '', '1254743313', '1269391977', '', '1', '1', '0',
'0', '1', '5', '0', '0', '1', '1', '1', '1', '0', '0', '0', '0', '0', '', '0',
'16', '20', '11', '11', '11', '12', '10', '14', '10', '9', '0', '0', '0', '0',
'0', '1', 1, 'Admin', '0', '', NOW(), '0', '0', 'red', '#00FF00', 'yellow', '20',
'20', '10', '10', '0', '3', '3', '0', '27', '2', '2', '0', '0', '0', '0', '0',
'98', '1', '0', '1133583738', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0')
SQL_EOF;
$this->query($sql);

View file

@ -1,163 +0,0 @@
<?php
/**
* This file is part of XNova:Legacies
*
* @license Modified BSD
* @see https://github.com/gplanchat/one.platform
*
* Copyright (c) 2009-2010, Grégory PLANCHAT <g.planchat at gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of Grégory PLANCHAT nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing One.Platform.
*
*/
$this->setSetupConnection('legacies_setup');
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/aks')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/alliance')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/annonce')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/banned')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/buddy')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/chat')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/config')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/declared')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/errors')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/fleets')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/galaxy')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/iraks')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/lunas')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/messages')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/multi')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/notes')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/planets')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/rw')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/statpoints')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('legacies/users')};
SQL_EOF;
$this->query($sql);

View file

@ -1,34 +0,0 @@
<?php
class Legacies_Database
extends PDO
{
protected static $_singleton = null;
protected static $_prefix = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
$config = include ROOT_PATH . 'config.php';
$hostname = $config['global']['database']['options']['hostname'];
$username = $config['global']['database']['options']['username'];
$password = $config['global']['database']['options']['password'];
$database = $config['global']['database']['options']['database'];
self::$_singleton = new self("mysql:dbname={$database};host={$hostname}", $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
return self::$_singleton;
}
public function getTable($name)
{
if (self::$_prefix === null) {
$config = include ROOT_PATH . 'config.php';
self::$_prefix = $config['global']['database']['table_prefix'];
}
return self::$_prefix . $name;
}
}

View file

@ -1,157 +0,0 @@
<?php
/**
* This file is part of XNova:Legacies
*
* @license http://www.gnu.org/licenses/gpl-3.0.txt
* @see http://www.xnova-ng.org/
*
* Copyright (c) 2009-Present, XNova Support Team <http://www.xnova-ng.org>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing XNova.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire
{
const TYPE_BUILDING = 'build';
const TYPE_BUILDING_MOON = 'build_moon';
const TYPE_BUILDING_PLANET = 'build_planet';
const TYPE_RESEARCH = 'tech';
const TYPE_SHIP = 'fleet';
const TYPE_DEFENSE = 'defense';
const TYPE_SPECIAL = 'special';
const TYPE_OFFICER = 'officier';
const TYPE_PRODUCTION = 'prod';
const TYPE_FLEET_MISSION = 'mission';
const RESOURCE_METAL = 'metal';
const RESOURCE_CRISTAL = 'cristal';
const RESOURCE_DEUTERIUM = 'deuterium';
const RESOURCE_ENERGY = 'energy';
const RESOURCE_MULTIPLIER = 'factor';
const RESOURCE_FORMULA = 'formule';
const RESOURCE_CLASS = 'class';
const SHIPS_CONSUMPTION_PRIMARY = 'consumption';
const SHIPS_CELERITY_PRIMARY = 'speed';
const SHIPS_CONSUMPTION_SECONDARY = 'consumption2';
const SHIPS_CELERITY_SECONDARY = 'speed2';
const SHIPS_CAPACITY = 'capacity';
const ID_BUILDING_METAL_MINE = 1;
const ID_BUILDING_CRISTAL_MINE = 2;
const ID_BUILDING_DEUTERIUM_SYNTHETISER = 3;
const ID_BUILDING_SOLAR_PLANT = 4;
const ID_BUILDING_FUSION_REACTOR = 12;
const ID_BUILDING_ROBOTIC_FACTORY = 14;
const ID_BUILDING_NANITE_FACTORY = 15;
const ID_BUILDING_SHIPYARD = 21;
const ID_BUILDING_METAL_STORAGE = 22;
const ID_BUILDING_CRISTAL_STORAGE = 23;
const ID_BUILDING_DEUTERIUM_TANK = 24;
const ID_BUILDING_RESEARCH_LAB = 31;
const ID_BUILDING_TERRAFORMER = 33;
const ID_BUILDING_ALLIANCE_DEPOT = 34;
const ID_BUILDING_LUNAR_BASE = 41;
const ID_BUILDING_SENSOR_PHALANX = 42;
const ID_BUILDING_JUMP_GATE = 43;
const ID_BUILDING_MISSILE_SILO = 44;
const ID_RESEARCH_ESPIONAGE_TECHNOLOGY = 106;
const ID_RESEARCH_COMPUTER_TECHNOLOGY = 108;
const ID_RESEARCH_WEAPON_TECHNOLOGY = 109;
const ID_RESEARCH_SHIELDING_TECHNOLOGY = 110;
const ID_RESEARCH_ARMOUR_TECHNOLOGY = 111;
const ID_RESEARCH_ENERGY_TECHNOLOGY = 113;
const ID_RESEARCH_HYPERSPACE_TECHNOLOGY = 114;
const ID_RESEARCH_COMBUSTION_DRIVE = 115;
const ID_RESEARCH_IMPULSE_DRIVE = 117;
const ID_RESEARCH_HYPERSPACE_DRIVE = 118;
const ID_RESEARCH_LASER_TECHNOLOGY = 120;
const ID_RESEARCH_ION_TECHNOLOGY = 121;
const ID_RESEARCH_PLASMA_TECHNOLOGY = 122;
const ID_RESEARCH_INTERGALACTIC_RESEARCH_NETWORK = 123;
const ID_RESEARCH_EXPEDITION_TECHNOLOGY = 124;
const ID_RESEARCH_ASTROPHYSICS = 124;
const ID_RESEARCH_GRAVITON_TECHNOLOGY = 199;
const ID_SHIP_LIGHT_TRANSPORT = 202;
const ID_SHIP_LARGE_TRANSPORT = 203;
const ID_SHIP_LIGHT_FIGHTER = 204;
const ID_SHIP_HEAVY_FIGHTER = 205;
const ID_SHIP_CRUISER = 206;
const ID_SHIP_BATTLESHIP = 207;
const ID_SHIP_COLONY_SHIP = 208;
const ID_SHIP_RECYCLER = 209;
const ID_SHIP_SPY_DRONE = 210;
const ID_SHIP_BOMBER = 211;
const ID_SHIP_SOLAR_SATELLITE = 212;
const ID_SHIP_DESTRUCTOR = 213;
const ID_SHIP_DEATH_STAR = 214;
const ID_SHIP_BATTLECRUISER = 215;
const ID_SHIP_SUPERNOVA = 216;
const ID_DEFENSE_ROCKET_LAUNCHER = 401;
const ID_DEFENSE_LIGHT_LASER = 402;
const ID_DEFENSE_HEAVY_LASER = 403;
const ID_DEFENSE_ION_CANNON = 404;
const ID_DEFENSE_GAUSS_CANNON = 405;
const ID_DEFENSE_PLASMA_TURRET = 406;
const ID_DEFENSE_SMALL_SHIELD_DOME = 407;
const ID_DEFENSE_LARGE_SHIELD_DOME = 408;
const ID_SPECIAL_ANTIBALLISTIC_MISSILE = 502;
const ID_SPECIAL_INTERPLANETARY_MISSILE = 503;
const ID_COMBAT_SHIELDS = 'shield';
const ID_COMBAT_FIREPOWER = 'attack';
const ID_COMBAT_RAPID_FIRE = 'sd';
const ID_MISSION_ATTACK = 1;
const ID_MISSION_GROUP_ATTACK = 2;
const ID_MISSION_TRANSPORT = 3;
const ID_MISSION_STATION = 4;
const ID_MISSION_STATION_ALLY = 5;
const ID_MISSION_SPY = 6;
const ID_MISSION_SETTLE_COLONY = 7;
const ID_MISSION_RECYCLE = 8;
const ID_MISSION_DESTROY = 9;
const ID_MISSION_MISSILES = 10;
const ID_MISSION_EXPEDITION = 15;
public static function getFieldName($id)
{
$fieldsAlias = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
if (!isset($fieldsAlias[$id])) {
return null;
}
return $fieldsAlias[$id];
}
}

View file

@ -1,7 +0,0 @@
<?php
class Legacies_Empire_Model_Builder_Break
extends Exception
{
}

View file

@ -1,19 +0,0 @@
<?php
class Legacies_Empire_Model_Builder_Item
extends Legacies_Object
{
protected $_index = null;
public function getIndex()
{
return $this->_index;
}
public function setIndex($index)
{
$this->_index = $index;
return $this;
}
}

View file

@ -1,221 +0,0 @@
<?php
abstract class Legacies_Empire_Model_BuilderAbstract
implements Countable, Serializable, Iterator
{
/**
* Planet instance
* @var Legacies_Empire_Model_Planet
*/
protected $_currentPlanet = null;
/**
* User instance
* @var Legacies_Empire_Model_User
*/
protected $_currentUser = null;
/**
* construction queue
* @var array
*/
private $_queue = null;
/**
* construction queue
* @var array
*/
protected $_itemClass = 'Legacies_Empire_Model_Builder_Item';
/**
* construction queue
* @var array
*/
protected $_index = 0;
/**
*
* @param Legacies_Empire_Model_Planet $currentPlanet
* @param Legacies_Empire_Model_User $currentUser
*/
public function __construct(Legacies_Empire_Model_Planet $currentPlanet, Legacies_Empire_Model_User $currentUser)
{
$this->_currentPlanet = $currentPlanet;
$this->_currentUser = $currentUser;
$this->init();
}
abstract public function init();
abstract protected function _initItem();
public function enqueue()
{
$params = func_get_args();
$item = call_user_func_array(array($this, '_initItem'), $params);
$item->setIndex($this->_index);
$this->_queue[$this->_index++] = $item;
return $this;
}
public function dequeue($item)
{
unset($this->_queue[(int) $item->getIndex()]);
return $this;
}
protected function getItem($itemIndex)
{
if (isset($this->_queue[$itemIndex])) {
return $this->_queue[$itemIndex];
}
return null;
}
protected function _serializeQueue()
{
$serialize = array();
foreach ($this->_queue as $item) {
$serialize[] = $item->getAllDatas();
}
return serialize($serialize);
}
protected function _unserializeQueue($serialized)
{
$this->clearQueue();
$unserialized = @unserialize($serialized);
if ($unserialized === false) {
$this->_queue = array();
return $this;
}
foreach ($unserialized as $itemData) {
call_user_func_array(array($this, 'enqueue'), $itemData);
}
return $this;
}
public function __toString()
{
return $this->_serializeQueue();
}
public function getQueue()
{
return $this->_queue;
}
public function clearQueue()
{
$this->_queue = array();
}
abstract public function updateQueue($time);
abstract public function appendQueue($typeId, $qty, $time);
/**
* Check if an item type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int $typeId
* @return bool
*/
public function checkAvailability($typeId)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$requirements = Legacies_Empire_Model_Game_Requirements::getSingleton();
if (!isset($requirements[$typeId]) || empty($requirements[$typeId])) {
return true;
}
foreach ($requirements[$typeId] as $requirement => $level) {
if ($types->is($requirement, Legacies_Empire::TYPE_BUILDING) && $this->_currentPlanet->hasElement($requirement, $level)) {
continue;
} else if ($types->is($requirement, Legacies_Empire::TYPE_RESEARCH) && $this->_currentUser->hasElement($requirement, $level)) {
continue;
} else if ($types->is($requirement, Legacies_Empire::TYPE_DEFENSE) && $this->_currentPlanet->hasElement($requirement, $level)) {
continue;
} else if ($types->is($requirement, Legacies_Empire::TYPE_SHIP) && $this->_currentPlanet->hasElement($requirement, $level)) {
continue;
}
return false;
}
return true;
}
abstract public function getResourcesNeeded($typeId, $level);
abstract public function getBuildingTime($typeId, $level);
public function serialize()
{
return $this->_serializeQueue();
}
public function unserialize($serialized)
{
$this->_unserializeQueue($serialized);
}
public function count()
{
return count($this->_queue);
}
public function current()
{
return current($this->_queue);
}
public function next()
{
return next($this->_queue);
}
public function key()
{
return key($this->_queue);
}
public function valid()
{
return current($this->_queue) !== false;
}
public function rewind()
{
reset($this->_queue);
}
public function getCurrentPlanet()
{
return $this->_currentPlanet;
}
public function getCurrentUser()
{
return $this->_currentUser;
}
public function setCurrentPlanet(Legacies_Empire_Model_Planet $planet)
{
$this->_currentPlanet = $planet;
return $this;
}
public function setCurrentUser(Legacies_Empire_Model_User $user)
{
$this->_currentUser = $user;
return $this;
}
}

View file

@ -1,39 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Fleet
extends Legacies_Core_Entity
{
protected static $_instances = array();
public static function factory($id)
{
if ($id === null) {
return new self();
}
$id = intval($id);
if (!isset(self::$_instances[$id])) {
$instance = new self();
$params = func_get_args();
call_user_func_array(array($instance, 'load'), $params);
self::$_instances[$id] = $instance;
}
return self::$_instances[$id];
}
protected function _init()
{
$this->setIdFieldName('fleet_id');
$this->setTableName('fleets');
}
public static function planetListener($eventData)
{
}
}

View file

@ -1,36 +0,0 @@
<?php
abstract class Legacies_Empire_Model_Game_Abstract
extends Legacies_Core_Model
implements Iterator, Countable
{
public function count()
{
return count($this->_data);
}
public function current()
{
return current($this->_data);
}
public function next()
{
return next($this->_data);
}
public function key()
{
return key($this->_data);
}
public function valid()
{
return $this->current() !== false;
}
public function rewind()
{
reset($this->_data);
}
}

View file

@ -1,49 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Combat
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/combat.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
}

View file

@ -1,49 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_FieldsAlias
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/fields-alias.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
}

View file

@ -1,49 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Prices
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/prices.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
}

View file

@ -1,49 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Production
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/production.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
}

View file

@ -1,49 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Requirements
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/requirements.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
}

View file

@ -1,49 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Resources
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/resources.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
}

View file

@ -1,57 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Types
extends Legacies_Empire_Model_Game_Abstract
implements Legacies_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
foreach (include ROOT_PATH . 'includes/data/types.php' as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
public function is($element, $type)
{
if (!is_array($this->getData($type))) {
return false;
}
return in_array($element, $this->getData($type));
}
}

View file

@ -1,686 +0,0 @@
<?php
/**
*
* @uses Legacies_Object
* @uses Legacies_Empire
* @uses Legacies_Empire_User
*/
class Legacies_Empire_Model_Planet
extends Legacies_Core_Entity
{
const TYPE_PLANET = 1;
const TYPE_DEBRIS = 2;
const TYPE_MOON = 3;
protected $_eventPrefix = 'planet.';
protected $_user = null;
protected $_moon = null;
protected $_builder = null;
protected $_shipyard = null;
protected static $_instances = array();
protected static $_productionInstances = array();
public static function factory($id)
{
if ($id === null) {
return new self();
}
$id = intval($id);
if (!isset(self::$_instances[$id])) {
$instance = new self();
$params = func_get_args();
call_user_func_array(array($instance, 'load'), $params);
self::$_instances[$id] = $instance;
}
return self::$_instances[$id];
}
public function _init()
{
$this->_tableName = 'planets';
$this->_idFieldName = 'id';
$this->_builder = new Legacies_Empire_Model_Planet_Builder($this, $this->getUser());
}
public function _afterLoad()
{
parent::_afterLoad();
$this->_builder->init();
return $this;
}
public function getLastUpdate()
{
return $this->getData('last_update');
}
public function setLastUpdate($time)
{
return $this->setData('last_update', $time);
}
public function updateStorages($time = null)
{
Math::setPrecision(50);
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
foreach ($resources->getAllDatas() as $resource => $resourceData) {
if (!isset($resourceData['storage_field']) || $resourceData['storage_field'] === null) {
continue;
}
$officerEnhancement = (.5 * $this->getUser()->getData('rpg_stockeur')) + 1;
$storageEnhancementFactor = Math::floor(Math::pow(1.6, $this[Legacies_Empire::getFieldName($resourceData['storage'])]));
$storageEnhancement = Math::mul(BASE_STORAGE_SIZE / 2, $storageEnhancementFactor);
$value = Math::mul(MAX_OVERFLOW, Math::mul($officerEnhancement, Math::add(BASE_STORAGE_SIZE, $storageEnhancement)));
$this->setData($resourceData['storage_field'], Math::floor($value));
}
Math::setPrecision();
return $this;
}
public function updateBuildingFields()
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
if ($this->isPlanet()) {
$filter = Legacies_Empire::TYPE_BUILDING_PLANET;
} else if ($this->isMoon()) {
$filter = Legacies_Empire::TYPE_BUILDING_MOON;
} else {
return $this;
}
$usedFields = 0;
foreach ($types[$filter] as $buildingId) {
$usedFields += $this->getElement($buildingId);
}
$this->setData('field_current', $usedFields);
return $this;
}
public function updateResourceProduction($time = null)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
$production = Legacies_Empire_Model_Game_Production::getSingleton();
if ($time === null) {
$time = Legacies::now();
}
if (!$this->isPlanet()) {
return $this;
}
/*
* Compute resources consumers and resources producers
*/
$resourcesTotals = array();
$resourcesProductionTotals = array();
$resourcesConsumptionTotals = array();
$resourcesProducers = array();
$resourcesConsumers = array();
$productionRatios = array();
foreach ($resources->getAllDatas() as $resource => $resourceData) {
foreach ($resourceData['production'] as $productionUnit => $ratioField) {
if (!in_array($productionUnit, $types['prod'])) {
continue;
}
$level = $this->getData(Legacies_Empire::getFieldName($productionUnit));
$ratio = $this->getData($ratioField);
$element = self::getProductionElementInstance($productionUnit);
$productionRatios[$productionUnit] = $element->getProductionRatios($level, $ratio, $this, $this->getUser());
foreach ($productionRatios[$productionUnit] as $resourceId => $resourceProduction) {
$comp = Math::comp($resourceProduction, 0);
if ($comp < 0) {
if (!isset($resourcesConsumers[$resourceId])) {
$resourcesConsumers[$resourceId] = array();
}
$resourcesConsumers[$resourceId][] = $productionUnit;
if (!isset($resourcesConsumptionTotals[$resourceId])) {
$resourcesConsumptionTotals[$resourceId] = 0;
}
$resourcesConsumptionTotals[$resourceId] = Math::add($resourcesConsumptionTotals[$resourceId], $resourceProduction);
if (!isset($resourcesTotals[$resourceId])) {
$resourcesTotals[$resourceId] = 0;
}
$resourcesTotals[$resourceId] = Math::add($resourcesTotals[$resourceId], $resourceProduction);
} else if ($comp > 0) {
if (!isset($resourcesProducers[$resourceId])) {
$resourcesProducers[$resourceId] = array();
}
$resourcesProducers[$resourceId][] = $productionUnit;
if (!isset($resourcesProductionTotals[$resourceId])) {
$resourcesProductionTotals[$resourceId] = 0;
}
$resourcesProductionTotals[$resourceId] = Math::add($resourcesProductionTotals[$resourceId], $resourceProduction);
if (!isset($resourcesTotals[$resourceId])) {
$resourcesTotals[$resourceId] = 0;
}
$resourcesTotals[$resourceId] = Math::add($resourcesTotals[$resourceId], $resourceProduction);
}
}
}
}
/*
* Compute resource consumption
*/
$actualProduction = $resourcesTotals;
foreach ($resourcesTotals as $resource => $total) {
if (Math::isPositiveOrZero($total, 0)) {
continue;
}
$productionRatio = 0;
if (isset($resourcesProductionTotals[$resource]) && Math::isPositive($resourcesProductionTotals[$resource])) {
$consumptions = Math::mul(-1, $resourcesConsumptionTotals[$resource]);
Math::setPrecision(50);
$productionRatio = Math::div($resourcesProductionTotals[$resource], $consumptions);
Math::setPrecision();
}
foreach ($resourcesConsumers[$resource] as $consumer) {
foreach ($productionRatios[$consumer] as $resourceId => $ratio) {
Math::setPrecision(50);
$productionOverhead = Math::mul(Math::sub(1, $productionRatio), $ratio);
Math::setPrecision();
$actualProduction[$resourceId] = Math::sub($actualProduction[$resourceId], $productionOverhead);
}
}
}
foreach ($actualProduction as $resource => $production) {
$this->setData($resources[$resource]['production_field'], $production);
}
return $this;
}
public function updateResources($time = null)
{
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
if ($time === null) {
$time = Legacies::now();
}
$timeDiff = ($time - $this->getLastUpdate()) / 3600;
foreach ($resources->getAllDatas() as $resourceId => $resourceConfig) {
$production = Math::mul($this->getData($resourceConfig['production_field']), $timeDiff);
$resourceValue = Math::add($this->getData($resourceConfig['field']), $production);
$this->setData($resourceConfig['field'], Math::min($resourceValue, $this->getData($resourceConfig['storage_field'])));
}
$this->setLastUpdate($time);
return $this;
}
public static function getProductionElementInstance($buildingId)
{
$production = Legacies_Empire_Model_Game_Production::getSingleton();
if (!isset(self::$_productionInstances[$buildingId])) {
if (!isset($production[$buildingId])) {
return null;
}
$class = $production[$buildingId][Legacies_Empire::RESOURCE_CLASS];
$reflection = new ReflectionClass($class);
self::$_productionInstances[$buildingId] = $reflection->newInstance();
}
return self::$_productionInstances[$buildingId];
}
public function getFleetCollection($time = null)
{
$firstCollection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$firstCollection
->column('*')
->where('fleet.fleet_start_galaxy = :galaxy')
->where('fleet.fleet_start_system = :system')
->where('fleet.fleet_start_planet = :position')
->where('fleet.fleet_start_type = :planet_type')
;
$backCollection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$backCollection
->column('*')
->where('fleet.fleet_end_galaxy = :galaxy')
->where('fleet.fleet_end_system = :system')
->where('fleet.fleet_end_planet = :position')
->where('fleet.fleet_end_type = :planet_type')
;
$options = array(
'galaxy' => $this->getSystem(),
'system' => $this->getSystem(),
'position' => $this->getPosition(),
'planet_type' => $this->getType()
);
if ($time !== null) {
$options['now'] = $time;
$firstCollection->where('fleet_start_time <= :now');
$backCollection->where('fleet_end_time <= :now');
}
$collection = new Legacies_Core_Collection();
$collection
->setEntityClassName('Legacies_Empire_Model_Fleet')
->union($firstCollection)
->union($backCollection)
->load($options)
;
return $collection;
}
public function getUser()
{
if ($this->_user === null) {
$this->_user = Legacies_Empire_Model_User::factory($this->getData('id_owner'));
}
return $this->_user;
}
public function setUser(Legacies_Empire_Model_User $user)
{
$this->_user = $user;
return $this;
}
public function getShipyard()
{
if ($this->_shipyard === null) {
$this->_shipyard = new Legacies_Empire_Model_Planet_Building_Shipyard($this, $this->getUser());
}
return $this->_shipyard;
}
public function setShipyard(Legacies_Empire_Model_Planet_Building_Shipyard $shipyard)
{
$this->_shipyard = $shipyard;
return $this;
}
public function isPlanet()
{
return (bool) ($this->getData('planet_type') == self::TYPE_PLANET);
}
public function isDebris()
{
return (bool) ($this->getData('planet_type') == self::TYPE_DEBRIS);
}
public function isMoon()
{
return (bool) ($this->getData('planet_type') == self::TYPE_MOON);
}
public function getMoon()
{
static $statement = null;
if ($this->isMoon()) {
return null;
}
if ($this->_moon === null) {
if ($statement === null) {
$statement = new Legacies_Core_Collection(array('planet' => 'planets'), get_class($this));
$statement
->where('galaxy=:galaxy')
->where('system=:system')
->where('planet=:position')
->where('planet_type=' . strval(self::TYPE_MOON))
;
}
$statement->load(array(
'galaxy' => $this->getGalaxy(),
'system' => $this->getSystem(),
'position' => $this->getPosition()
));
$this->_moon = $statement->current();
}
return $this->_moon;
}
public function setGalaxy($galaxy)
{
$this->setData('galaxy', $galaxy);
return $this;
}
public function getGalaxy()
{
return (int) $this->getData('galaxy');
}
public function setSystem($system)
{
$this->setData('system', $system);
return $this;
}
public function getSystem()
{
return (int) $this->getData('system');
}
public function setPosition($position)
{
$this->setData('planet', $position);
return $this;
}
public function getPosition()
{
return (int) $this->getData('planet');
}
public function setType($type)
{
$this->setData('planet_type', $type);
return $this;
}
public function getType()
{
return (int) $this->getData('planet_type');
}
public function getElement($elementId)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->getData($fields[$elementId]);
}
public function setElement($elementId, $level)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->setData($fields[$elementId], $level);
}
public function hasElement($elementId, $levelRequired = 0)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->hasData($fields[$elementId]) && Math::comp($this->getElement($elementId), $levelRequired) > 0;
}
public function appendBuildingQueue($buildingId, $destroy = false, $time = null)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
if ($time === null) {
$time = Legacies::now();
}
if (!$types->is($buildingId, Legacies_Empire::TYPE_BUILDING)) {
return $this;
}
if ($destroy === false && !$this->checkAvailability($buildingId)) {
return $this;
}
// Dispatch 'planet.building.append-queue.before' event
Legacies::dispatchEvent($this->_eventPrefix . 'building.append-queue.before', array(
'bulding_id' => $buildingId,
'level' => $this->getElement($buildingId),
'planet' => $this,
'user' => $this->getUser(),
'destroy' => $destroy
));
if ($destroy === false) {
$level = $this->getElement($buildingId) + 1;
} else {
$level = max($this->getElement($buildingId) - 1, 0);
}
$this->_builder->appendQueue($buildingId, $level, $time);
// Dispatch 'planet.shipyard.append-queue.after' event
Legacies::dispatchEvent($this->_eventPrefix . 'building.append-queue.after', array(
'bulding_id' => $buildingId,
'level' => $this->getElement($buildingId),
'planet' => $this,
'user' => $this->getUser(),
'destroy' => $destroy
));
return $this;
}
public function updateBuildingQueue($time = null)
{
if ($time === null) {
$time = Legacies::now();
}
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'update-queue.before', array(
'time' => &$time,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
$this->_builder->updateQueue($time);
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'update-queue.after', array(
'time' => $time,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
return $this;
}
public function getBuildingQueue()
{
return $this->_builder;
}
/**
* Check if a building is actually buildable on the current planet,
* depending on the technology and buildings requirements.
*
* @param int $buildingId
* @return bool
*/
public function checkAvailability($buildingId)
{
$this->_builder->checkAvailability($buildingId);
try {
// Dispatch event. Throw an exception to break the avaliability.
Legacies::dispatchEvent($this->_eventPrefix . 'check-availability', array(
'ship_id' => $buildingId,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
} catch (Exception $e) {
return false;
}
return true;
}
/**
* Get the resources needed to build a specific building
*
* @param int $buildingId
* @return bool
*/
public function getResourcesNeeded($buildingId, $level)
{
return $this->_builder->getResourcesNeeded($buildingId, $level);
}
/**
* Get the time needed to build a specific building
*
* @param int $buildingId
* @return bool
*/
public function getBuildingTime($buildingId, $level)
{
return $this->_builder->getBuildingTime($buildingId, $level);
}
public static function registrationListener($eventData)
{
if (isset($eventData['user'])) {
$user = $eventData['user'];
$request = $eventData['request'];
if ($user === null || !$user instanceof Legacies_Empire_Model_User || $user->getId()) {
return;
}
if ($request === null || !$request instanceof Legacies_Core_Controller_Request) {
return;
}
$collection = new Legacies_Core_Collection('planets');
$collection
->column(array(
'galaxy' => 'planet.galaxy',
'system' => 'planet.system',
'count' => 'COUNT(planet.id)'
))
->group('planet.galaxy')
->group('planet.system')
->where('planet.planet_type=1')
->order('COUNT(planet.id)', 'ASC')
->order('RAND()', 'ASC')
->limit(1)
;
$params = array();
$galaxy = $request->getParam('system');
if ($galaxy !== null) {
$collection->where('planet.galaxy=:galaxy');
$params['galaxy'] = $galaxy;
$systems = explode(',', $request->getParam('system'));
if (is_array($systems) && count($systems) == 2 && is_int($systems[0]) && is_int($systems[1])) {
$collection->where('planet.system IN(' . implode(', ', range($systems[0], $systems[1])) . ')');
}
}
$collection->load($params);
if ($collection->count() == 0) {
throw new Exception('No planet to colonize there!'); // FIXME
}
$systemInfo = $collection->current();
if ($systemInfo->getData('count') >= MAX_PLANET_IN_SYSTEM) {
throw new Exception('No planet to colonize there!'); // FIXME
}
$system = $systemInfo->getData('system');
$galaxy = $systemInfo->getData('galaxy');
$collection = new Legacies_Core_Collection('planets');
$collection
->column(array('position' => 'planet.position'))
->where('planet.planet_type=1')
->where('planet.planet_type=:system')
->load()
;
$positions = range(1, MAX_PLANET_IN_SYSTEM);
foreach ($collection as $planet) {
$key = array_search($planet->getData('position'), $positions);
if ($key !== false) {
unset($positions[$key]);
}
}
$key = array_rand($positions, 1);
$finalPosition = $positions[$key];
$planet = new self();
$planet
->setData('id_owner', $user->getId())
->setData('name', $request->getParam('planet'))
->setData('galaxy', $galaxy)
->setData('system', $system)
->setData('position', $finalPosition)
->setData('planet_type', 1)
;
Legacies::dispatchEvent('planet.init', array(
'planet' => $planet,
'user' => $user
));
$planet
->setData('field_max', 163)
->setData('field_current', 0)
->save()
;
$user
->setData('id_planet', $planet->getId())
->setData('current_planet', $planet->getId())
;
}
}
public static function planetUpdateListener($eventData)
{
if (isset($eventData['planet'])) {
$planet = $eventData['planet'];
if (isset($eventData['time'])) {
$time = $eventData['time'];
} else {
$time = time();
}
if ($planet === null || !$planet instanceof Legacies_Empire_Model_Planet) {
return;
}
$planet->updateBuildingQueue($time);
$planet->updateResources($time);
$planet->getShipyard()->updateQueue($time);
$planet->setLastUpdate($time);
}
}
}

View file

@ -1,169 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Builder
extends Legacies_Empire_Model_BuilderAbstract
{
public function init()
{
$this->_unserializeQueue($this->_currentPlanet->getData('b_building_id'));
}
/**
* @param int $buildingId
* @param int $level
* @param int $time
*/
public function _initItem()
{
$buildingId = func_get_arg(0);
$level = func_get_arg(1);
$time = func_get_arg(2);
return new Legacies_Empire_Model_Planet_Building_Shipyard_Item(array(
'building_id' => $buildingId,
'level' => $level,
'created_at' => $time,
'updated_at' => $time
));
}
/**
* Check if a building is actually buildable on the current planet,
* depending on the technology and buildings requirements.
*
* @param int $buildingId
* @return bool
*/
public function checkAvailability($buildingId)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
if ($types->is($buildingId, Legacies_Empire::TYPE_BUILDING)) {
return true;
}
return $this->checkAvailability($buildingId);
}
public function getResourcesNeeded($buildingId, $level)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
if (!isset($prices[$buildingId])) {
return array();
}
$resourcesNeeded = array();
foreach ($resources as $resourceId => $resourceConfig) {
if (!isset($prices[$buildingId][$resourceId])) {
continue;
}
if (Math::isPositive($prices[$buildingId][$resourceId])) {
$firstLevelCost = $prices[$buildingId][$resourceId];
$partialLevelCost = Math::mul($firstLevelCost, Math::pow($prices[$buildingId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
$resourcesNeeded[$resourceId] = Math::sub($partialLevelCost, $firstLevelCost);
}
}
return $resourcesNeeded;
}
public function getBuildingTime($buildingId, $level)
{
return 0;
}
/**
* Update the contruction queue.
*
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function updateQueue($time)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
$elapsedTime = $time - $this->_currentPlanet->getData('b_building');
foreach ($this->getQueue() as $element) {
$buildingId = $element->getData('building_id');
$level = $element->getData('level');
$buildTime = $this->getBuildingTime($buildingId, $level); // FIXME: consider total time, not only the construction time
if ($elapsedTime >= $buildTime) {
$this->_currentPlanet->updateResources($time - $elapsedTime);
$this->_currentPlanet->setElement($buildingId, $level);
$this->_currentPlanet->updateResourceProduction($time - $elapsedTime);
$this->_currentPlanet->updateStorages($time - $elapsedTime);
$this->_currentPlanet->updateBuildingFields();
$this->dequeue($element);
Legacies::dispatchEvent('planet.building.level-update', array(
'time' => $time - $elapsedTime,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser,
'building_id' => $buildingId,
'level' => $level
));
$elapsedTime -= $buildTime;
continue;
}
$element->setData('updated_at', $time);
break;
}
$this->_currentPlanet->setData('b_building_id', $this->serialize());
$this->_currentPlanet->setData('b_building', $time);
return $this;
}
/**
* Append items to build to the construction list
*
* @param int $buildingId
* @param int|string $level
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function appendQueue($buildingId, $level, $time)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
if (!Math::isPositive($level)) {
return $this;
}
if (!$types->is($buildingId, Legacies_Empire::TYPE_BUILDING)) {
return $this;
}
if (!$this->checkAvailability($buildingId)) {
return $this;
}
$resourcesNeeded = $this->getResourcesNeeded($buildingId, $level);
$amounts = array();
foreach ($resourcesNeeded as $resourceId => $resourceCost) {
$amount[$resourceId] = Math::sub($this->_currentPlanet[$resourceId], $resourceCost);
if (Math::isNegative($amount[$resourceId])) {
return $this;
}
}
$this->enqueue($buildingId, $level, $time);
foreach ($resourcesNeeded as $resourceId => $resourceCost) {
if (!isset($resources[$resourceId]) || !Math::isPositive($resourceCost)) {
continue;
}
$this->_currentPlanet->setData($resourceId, $resourceId[$resourceId]);
}
$this->_currentPlanet->setData('b_building_id', $this->serialize());
return $this;
}
}

View file

@ -1,13 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_CristalMine
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_CRISTAL => 10 + 20 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => -10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -1,13 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_DeuteriumSynthetiser
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_DEUTERIUM => 10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => -30 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -1,13 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_FusionReactor
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_DEUTERIUM => -10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => 50 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -1,13 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_MetalMine
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_METAL => 20 + 30 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => -10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -1,285 +0,0 @@
<?php
/**
* This file is part of XNova:Legacies
*
* @license http://www.gnu.org/licenses/gpl-3.0.txt
* @see http://www.xnova-ng.org/
*
* Copyright (c) 2009-Present, XNova Support Team <http://www.xnova-ng.org>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing XNova.
*
*/
/**
* Shipyard building, manages ship and defenses building queue on each planet
*
* @access public
* @category Empire
* @category Planet
* @package Legacies
* @subpackage Legacies_Empire
*/
class Legacies_Empire_Model_Planet_Building_Shipyard
implements Legacies_Empire_Model_Planet_BuildingInterface
{
private $_eventPrefix = 'planet.shipyard.';
/**
* Planet instance
* @var Legacies_Empire_Model_Planet
*/
protected $_currentPlanet = null;
/**
* User instance
* @var Legacies_Empire_Model_User
*/
protected $_currentUser = null;
/**
* construction queue
* @var array
*/
protected $_builder = null;
/**
* Resource list
*
* @var array
*/
protected $_resourcesTypes = array(
Legacies_Empire::RESOURCE_METAL,
Legacies_Empire::RESOURCE_CRISTAL,
Legacies_Empire::RESOURCE_DEUTERIUM,
Legacies_Empire::RESOURCE_ENERGY
);
/**
* Multiton instances
* @var array
*/
protected static $_instances = array();
/**
* Multiton factory. Retruns the planet's shipyard instance or created it if
* it doesn't yet exist.
*
* @param Legacies_Empire_Model_Planet $currentPlanet
* @param Legacies_Empire_Model_User $currentUser
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public static function factory($currentPlanet, $currentUser)
{
if ($currentPlanet->getId()) {
return null;
}
if (!isset(self::$_instances[$currentPlanet->getId()])) {
self::$_instances[$currentPlanet->getId()] = new self($currentPlanet, $currentUser);
}
return self::$_instances[$currentPlanet->getId()];
}
/**
* Constructor. Used for specific usage, use the factory for standard usage.
*
* @see Legacies_Empire_Model_Planet_Building_Shipyard::factory()
*
* @param Legacies_Empire_Model_Planet $currentPlanet
* @param Legacies_Empire_Model_User $currentUser
*/
public function __construct($currentPlanet, $currentUser)
{
$this->_currentPlanet = $currentPlanet;
$this->_currentUser = $currentUser;
$this->_builder = new Legacies_Empire_Model_Planet_Building_Shipyard_Builder($currentPlanet, $currentUser);
}
/**
* Returns the timestamp at the instance creation.
*
* @deprecated
* @return int
*/
protected function _now()
{
return Legacies::now();
}
/**
* @deprecated
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function save()
{
$this->_currentPlanet->save();
return $this;
}
/**
* Append items to build to the construction list
*
* @param int $shipId
* @param int|string $qty
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function appendQueue($shipId, $qty, $time = null)
{
if ($time === null) {
$time = Legacies::now();
}
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'append-queue.before', array(
'ship_id' => $shipId,
'qty' => &$qty,
'time' => &$time,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
$this->_builder->appendQueue($shipId, $qty, $time);
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'append-queue.before', array(
'ship_id' => $shipId,
'qty' => $qty,
'time' => $time,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
return $this;
}
/**
* Update the contruction queue.
*
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function updateQueue($time = null)
{
if ($time === null) {
$time = Legacies::now();
}
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'update-queue.before', array(
'time' => &$time,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
$this->_builder->updateQueue($time);
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'update-queue.after', array(
'time' => $time,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
return $this;
}
/**
* Return the construction queue
* @see Legacies_Empire_Model_Planet_Building_Shipyard_Builder
*
* @return array
*/
public function getBuilder()
{
return $this->_builder;
}
/**
* Check if a ship or defense type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int $shipId
* @return bool
*/
public function checkAvailability($shipId)
{
try {
// Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'check-availability', array(
'ship_id' => $shipId,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
} catch (Legacies_Core_Event_Break $e) {
return false;
}
return $this->_builder->checkAvailability($shipId);
}
/**
* Returns the maximum quantity of elements that are possible to build on
* the current planet.
*
* @param int $shipId
* @return int|string
*/
public function getMaximumBuildableElementsCount($shipId)
{
return $this->_builder->getMaximumBuildableElementsCount($shipId);
}
public function getResourcesNeeded($shipId, $qty)
{
return $this->_builder->getResourcesNeeded($shipId, $qty);
}
public function getBuildingTime($shipId, $qty)
{
$this->_builder->getBuildingTime($shipId, $qty);
}
public static function planetUpdateListener($eventData)
{
if (isset($eventData['planet'])) {
$planet = $eventData['planet'];
if ($planet === null || !$planet instanceof Legacies_Empire_Model_Planet || !$planet->getId()) {
return;
}
$time = null;
if (isset($eventData['time'])) {
$time = $eventData['time'];
}
$shipyard = self::factory($planet, $planet->getUser());
if ($shipyard !== null) {
$shipyard->updateQueue();
}
}
}
}

View file

@ -1,294 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_Shipyard_Builder
extends Legacies_Empire_Model_BuilderAbstract
{
public function init()
{
$this->_unserializeQueue($this->_currentPlanet->getData('b_hangar_id'));
}
/**
* @param int $buildingId
* @param int $qty
* @param int $time
*/
public function _initItem()
{
$shipId = func_get_arg(0);
$qty = func_get_arg(1);
$time = func_get_arg(2);
return new Legacies_Empire_Model_Planet_Building_Shipyard_Item(array(
'ship_id' => $shipId,
'qty' => $qty,
'created_at' => $time,
'updated_at' => $time
));
}
/**
* Check if a ship or defense type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int $shipId
* @return bool
*/
public function checkAvailability($shipId)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
if (!$types->is($shipId, Legacies_Empire::TYPE_SHIP) && !$types->is($shipId, Legacies_Empire::TYPE_DEFENSE)) {
return false;
}
parent::checkAvailability($shipId);
return true;
}
/**
* Returns the maximum quantity of elements that are possible to build on
* the current planet.
*
* @param int $shipId
* @return int|string
*/
public function getMaximumBuildableElementsCount($shipId)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
$qty = 0;
foreach ($resources as $resourceId => $_) {
if (isset($prices[$shipId]) && isset($prices[$shipId][$resourceId]) && Math::comp($prices[$shipId][$resourceId], 0) > 0) {
$maxQty = Math::floor(Math::div($this->_currentPlanet->getData($resourceId), $prices[$shipId][$resourceId]));
if ($maxQty == 0) {
return 0;
}
if ($qty == 0 || Math::comp($maxQty, $qty) < 0) {
$qty = $maxQty;
}
}
}
if ($qty == 0) {
return 0;
}
$limitedElementsQty = array(
Legacies_Empire::ID_DEFENSE_SMALL_SHIELD_DOME => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_SMALL_SHIELD_DOME]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_SMALL_SHIELD_DOME]],
'limit' => 1
),
Legacies_Empire::ID_DEFENSE_LARGE_SHIELD_DOME => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_LARGE_SHIELD_DOME]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_LARGE_SHIELD_DOME]],
'limit' => 1
),
Legacies_Empire::ID_SPECIAL_ANTIBALLISTIC_MISSILE => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_ANTIBALLISTIC_MISSILE]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_ANTIBALLISTIC_MISSILE]],
'limit' => $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_MISSILE_SILO]] * 10
),
Legacies_Empire::ID_SPECIAL_INTERPLANETARY_MISSILE => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_INTERPLANETARY_MISSILE]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_INTERPLANETARY_MISSILE]],
'limit' => $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_MISSILE_SILO]] * 5
)
);
if (in_array($shipId, array_keys($limitedElementsQty))) {
foreach ($this->_queue as $element) {
if ($element['ship_id'] != $shipId) {
continue;
}
$limitedElementsQty[$shipId]['requested'] = Math::add($limitedElementsQty[$shipId]['requested'], $element['qty']);
if (Math::comp($limitedElementsQty[$shipId]['requested'], $limitedElementsQty[$shipId]['limit']) >= 0) {
return 0;
}
}
if (Math::comp($limitedElementsQty[$shipId]['current'], $limitedElementsQty[$shipId]['limit']) >= 0) {
return 0;
}
if (Math::comp($qty, $limitedElementsQty[$shipId]['limit']) >= 0) {
return $limitedElementsQty[$shipId]['limit'];
}
}
return $qty;
}
/**
* Returns the time needed to build $qty of $shipId
*
* @param int $shipId
* @param int $qty
*/
public function getBuildingTime($shipId, $qty)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$gameConfig = Legacies_Core_Model_Config::getSingleton();
Math::setPrecision(50);
// FIXME: Resource dependency
$totalCost = Math::mul(Math::add($prices[$shipId][Legacies_Empire::RESOURCE_METAL], $prices[$shipId][Legacies_Empire::RESOURCE_CRISTAL]), $qty);
$speedFactor = $gameConfig->getData('game_speed');
// FIXME: Building dependency
$shipyardSpeedup = Math::div(1, Math::add($this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_SHIPYARD]], 1));
$naniteSpeedup = Math::pow(.5, $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_NANITE_FACTORY]]);
$structuresSpeedup = Math::mul($shipyardSpeedup, $naniteSpeedup);
// FIXME: officers
$officerSpeedup = 1;
if ($types->is($shipId, Legacies_Empire::TYPE_SHIP)) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_technocrate'] * .05);
} else if ($types->is($shipId, Legacies_Empire::TYPE_SPECIAL)) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_technocrate'] * .05);
} else if ($types->is($shipId, Legacies_Empire::TYPE_DEFENSE)) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_defenseur'] * .375);
}
Math::setPrecision();
$baseTime = ($totalCost / $speedFactor) * $structuresSpeedup;
return (int) Math::floor($baseTime * $officerSpeedup * 3600);
}
/**
* (non-PHPdoc)
* @see Legacies_Empire_Model_BuilderAbstract::getResourcesNeeded()
*/
public function getResourcesNeeded($shipId, $qty)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
if (!isset($prices[$shipId])) {
return array();
}
$resourcesNeeded = array();
foreach ($resources as $resourceId => $resourceConfig) {
if (!isset($prices[$shipId][$resourceId])) {
continue;
}
if (Math::isPositive($prices[$shipId][$resourceId])) {
$resourcesNeeded[$resourceId] = Math::mul($prices[$shipId][$resourceId], $qty);
}
}
return $resourcesNeeded;
}
/**
* Returns the quantity set in parameter or the maximum buildable elements
* if the quantity requested exeeds this number.
*
* @param int $shipId
* @param int|string $qty
* @return int|stirng
*/
protected function _checkMaximumQuantity($shipId, $qty)
{
return Math::min($qty, $this->getMaximumBuildableElementsCount($shipId));
}
/**
* Update the contruction queue.
*
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function updateQueue($time)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
$elapsedTime = $time - $this->_currentPlanet->getData('b_hangar');
foreach ($this->getQueue() as $element) {
$shipId = $element->getData('ship_id');
$qty = $element->getData('qty');
$buildTime = $this->getBuildingTime($shipId, $qty);
if ($elapsedTime >= $buildTime) {
$this->_currentPlanet[$fields[$shipId]] = Math::add($this->_currentPlanet[$fields[$shipId]], $qty);
$elapsedTime -= $buildTime;
$this->dequeue($element);
continue;
}
$timeRatio = $elapsedTime / $buildTime;
$itemsBuilt = Math::mul($timeRatio, $qty);
$element->setData('updated_at', $time);
$element->setData('qty', Math::sub($qty, $itemsBuilt));
$this->_currentPlanet->setData($fields[$shipId], Math::add($this->_currentPlanet->getData($fields[$shipId]), $itemsBuilt));
break;
}
$this->_currentPlanet->setData('b_hangar_id', $this->serialize());
$this->_currentPlanet->setData('b_hangar', $time);
return $this;
}
/**
* Append items to build to the construction list
*
* @param int $shipId
* @param int|string $qty
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function appendQueue($shipId, $qty, $time)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
if (!Math::isPositive($qty)) {
return $this;
}
if (!$types->is($shipId, Legacies_Empire::TYPE_SHIP) && !$types->is($shipId, Legacies_Empire::TYPE_DEFENSE)) {
return $this;
}
if (!$this->checkAvailability($shipId)) {
return $this;
}
if (MAX_FLEET_OR_DEFS_PER_ROW > 0) {
$qty = Math::min($this->_checkMaximumQuantity($shipId, $qty), MAX_FLEET_OR_DEFS_PER_ROW);
} else {
$qty = $this->_checkMaximumQuantity($shipId, $qty);
}
if (!Math::isPositive($qty)) {
return $this;
}
$resourcesNeeded = $this->getResourcesNeeded($shipId, $qty);
$buildTime = $this->getBuildingTime($shipId, $qty);
$this->enqueue($shipId, $qty, $time);
foreach ($resources as $resourceId => $resourceConfig) {
if (!isset($resourcesNeeded[$resourceId])) {
continue;
}
$this->_currentPlanet[$resourceId] = Math::sub($this->_currentPlanet[$resourceId], $resourcesNeeded[$resourceId]);
}
$this->_currentPlanet->setData('b_hangar_id', $this->serialize());
return $this;
}
};

View file

@ -1,6 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_Shipyard_Item
extends Legacies_Empire_Model_Builder_Item
{
}

View file

@ -1,12 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Building_SolarPlant
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_ENERGY => 20 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -1,5 +0,0 @@
<?php
interface Legacies_Empire_Model_Planet_BuildingInterface
{
}

View file

@ -1,20 +0,0 @@
<?php
/**
*
* @uses Legacies_Object
* @uses Legacies_Empire
* @uses Legacies_Empire_User
*/
class Legacies_Empire_Model_Planet_Production
extends Legacies_Core_Entity_SubTable
{
public function _init()
{
$this->_tableName = 'planet_production';
$this->_idFieldNames = array(
'production_code',
'planet_id'
);
}
}

View file

@ -1,20 +0,0 @@
<?php
/**
*
* @uses Legacies_Object
* @uses Legacies_Empire
* @uses Legacies_Empire_User
*/
class Legacies_Empire_Model_Planet_Resource
extends Legacies_Core_Entity_SubTable
{
public function _init()
{
$this->_tableName = 'planet_resource';
$this->_idFieldNames = array(
'resource_code',
'planet_id'
);
}
}

View file

@ -1,6 +0,0 @@
<?php
interface Legacies_Empire_Model_Planet_ResourceProductionInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $user);
}

View file

@ -1,27 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Ship_LightTransport
implements Legacies_Empire_Model_Planet_ShipInterface
{
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE = 4;
public function getBaseSpeed(Legacies_Empire_Model_User $user)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
if ($user->getElement(Legacies_Empire::ID_RESEARCH_IMPULSE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE) {
return $prices[Legacies_Empire::ID_SHIP_LIGHT_TRANSPORT][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
} else {
return $prices[Legacies_Empire::ID_SHIP_LIGHT_TRANSPORT][Legacies_Empire::SHIPS_CELERITY_SECONDARY];
}
}
public function getSpeedMultiplier(Legacies_Empire_Model_User $user)
{
if ($user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE) {
return pow(1.1, $user->getElement(Legacies_Empire::ID_RESEARCH_COMBUSTION_DRIVE));
} else {
return pow(1.2, $user->getElement(Legacies_Empire::ID_RESEARCH_IMPULSE_DRIVE));
}
}
}

View file

@ -1,22 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Ship_SolarSatellite
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_ShipInterface
{
public function getProductionRatios($quantity, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_ENERGY => ((floatval($planet->getData('temp_max')) / 4) + 20) * (0.1 * $produtionRatio) * floatval($quantity)
);
}
public function getMaximumSpeed(Legacies_Empire_Model_User $user)
{
return 0;
}
public function getActualMaximumSpeed(Legacies_Empire_Model_User $user)
{
return 0;
}
}

View file

@ -1,38 +0,0 @@
<?php
class Legacies_Empire_Model_Planet_Ship_Supernova
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_ShipInterface
{
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE = 20;
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY = 15;
public function getProductionRatios($quantity, $produtionRatio, $planet, $user)
{
return array(
Legacies_Empire::RESOURCE_ENERGY => ((floatval($planet->getData('temp_max')) / 4) + 20) * (0.1 * $produtionRatio) * floatval($quantity) * -1250
);
}
public function getBaseSpeed(Legacies_Empire_Model_User $user)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
if ($user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE &&
$user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_TECHNOLOGY) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY) {
return $prices[Legacies_Empire::ID_SHIP_SUPERNOVA][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
} else {
return $prices[Legacies_Empire::ID_SHIP_SUPERNOVA][Legacies_Empire::SHIPS_CELERITY_SECONDARY];
}
}
public function getSpeedMultiplier(Legacies_Empire_Model_User $user)
{
if ($user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE &&
$user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_TECHNOLOGY) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY) {
return pow(1.2, $user->getElement(Legacies_Empire::ID_RESEARCH_IMPULSE_DRIVE));
} else {
return pow(1.3, $user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE)) *
pow(1.1, $user->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_TECHNOLOGY));
}
}
}

View file

@ -1,7 +0,0 @@
<?php
interface Legacies_Empire_Model_Planet_ShipInterface
{
public function getBaseSpeed(Legacies_Empire_Model_User $user);
public function getSpeedMultiplier(Legacies_Empire_Model_User $user);
}

View file

@ -1,348 +0,0 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_User
extends Legacies_Core_Entity
{
protected static $_instances = array();
protected static $_singleton = null;
const SESSION_KEY = 'user';
const COOKIE_NAME = 'legacies';
const COOKIE_LIFETIME = 2592000;
const PLANET_SORT_DATE = 0;
const PLANET_SORT_POSITION = 1;
const PLANET_SORT_NAME = 2;
protected static $_cookieName = self::COOKIE_NAME;
public static function setCookieName($name)
{
self::$_cookieName = $name;
}
public static function factory($id)
{
if ($id === null) {
return new self();
}
$id = intval($id);
if (!isset(self::$_instances[$id])) {
$instance = new self();
$params = func_get_args();
call_user_func_array(array($instance, 'load'), $params);
self::$_instances[$id] = $instance;
}
return self::$_instances[$id];
}
public static function getSingleton()
{
if (self::$_singleton === null) {
$session = Legacies::getSession(self::SESSION_KEY);
if ($session->hasData('user_id')) {
$id = intval($session->getData('user_id'));
} else if (Legacies::$request !== null && ($cookie = Legacies::$request->getCookie(self::$_cookieName)) !== null) {
$cookieData = unserialize(stripslashes($cookie));
if (is_array($cookieData)) {
$collection = new Legacies_Core_Collection(array('user' => 'users'));
$cookieData = array(
'id' => (isset($cookieData['id']) ? intval($cookieData['id']) : 0),
'key' => (isset($cookieData['key']) ? $collection->quote($cookieData['key']) : null)
);
$collection
->column('id')
->where('user.id=:id')
->where(':key=CONCAT((@salt:=MID(:key, 0, 4)), SHA1(CONCAT(user.username, user.password, @salt)))')
->load($cookieData)
;
if ($collection->count() > 0) {
$session->setData(self::SESSION_KEY, $cookieData['id']);
} else {
$session->addError('Your session has expired, please login.');
return null;
}
}
} else {
$session->addError('Your session has expired, please login.');
return null;
}
try {
self::$_singleton = self::factory($id);
} catch (Legacies_Core_Model_Exception $e) {
$session->addError('Session error.');
return null;
}
self::$_singleton->_updateActivity();
}
return self::$_singleton;
}
protected function _init()
{
$this->setIdFieldName('id');
$this->setTableName('users');
}
protected function _updateActivity()
{
$this
->setData('current_page', $_SERVER['REQUEST_URI'])
->setData('user_lastip', $_SERVER['REMOTE_ADDR'])
->setData('user_agent', $_SERVER['HTTP_USER_AGENT'])
->setData('onlinetime', time())
->save()
;
return $this;
}
public function logout()
{
if (Legacies::$response !== null) {
Legacies::$response->unsetCookie(self::$_cookieName);
}
Legacies_Core_Model_Session::destroy();
}
public static function login($username, $password, $remember = false)
{
static $statement = null;
$session = Legacies::getSession(self::SESSION_KEY);
$collection = new Legacies_Core_Collection(array('user' => 'users'));
$collection
->column('user.id')
->column('user.username')
->column('user.banaday')
->column('(CASE WHEN MD5(:password)=user.password THEN 1 ELSE 0 END) AS login_success')
->column('CONCAT((@salt:=MID(MD5(RAND()), 0, 4)), SHA1(CONCAT(user.username, user.password, @salt))) AS login_rememberme')
->where('user.username=:username')
->load(array(
'username' => $username,
'password' => $password
))
;
if ($collection->count() <= 0) {
$session->addError('No such user.');
return null;
}
$login = $collection->current();
if (intval($login['login_success']) == 1) {
if ($login['banaday'] != 0) {
if($login['banaday'] <= time() && $login['banaday'] != '0') {
$user->setData('banaday', 0)
->setData('bana', 0)
->setData('urlaubs_modus', 0)
->save()
;
} else {
$session->addError('You were banned, please contact admin for more information.');
return null;
}
}
if (isset($_POST["rememberme"]) && Legacies::$request !== null) {
Legacies::$response->setCookie(self::$_cookieName, array('id' => $login['id'], 'key' => $login['login_rememberme']), self::COOKIE_LIFETIME);
}
self::$_singleton = self::factory($login['id']);
self::$_singleton->_updateActivity();
$session->setData('user_id', intval($login['id']));
return self::$_singleton;
}
$session->addError('Your username or credential is invalid, please check your input.');
return null;
}
public static function register($username, $email, $password)
{
try {
$user = new self(array(
'username' => $username,
'password' => md5($password),
'email' => $email,
'email_2' => $email
));
$user->save();
Legacies::dispatchEvent('user.init', array(
'user' => $user
));
$user->save();
} catch (Legacies_Core_Model_Exception $e) {
$session->addError($e->getMessage());
return null;
}
return $user;
}
public function updateCurrentPlanet($planetId)
{
$planetColelction = $this->_preparePlanetCollection()->where('id=:id');
$planetCollection->load(array(
'id' => $planetId,
'user' => $this->getId()
));
if ($planetCollection->count() !== 1) {
return false;
}
$planet = $planetCollection->current();
$this->setData('current_planet', $planet->getId());
return true;
}
public function getCurrentPlanet()
{
$planetId = $this->getData('current_planet');
if (!$planetId) {
$planetId = $this->getData('id_planet');
$this->setData('current_planet', $planetId)->save();
}
return Legacies_Empire_Model_Planet::factory($planetId);
}
protected function _preparePlanetCollection()
{
$planetCollection = new Legacies_Core_Collection(array('planet' => 'planets'), 'Legacies_Empire_Model_Planet');
$planetCollection->where('id_owner=:user');
$order = ($this->getData('planet_sort_order') == 1) ? 'DESC' : 'ASC';
switch ($this->getData('planet_sort')) {
case self::PLANET_SORT_POSITION:
$planetCollection
->order('planet.galaxy', $order)
->order('planet.system', $order)
->order('planet.planet', $order)
->order('planet.planet_type', $order)
;
break;
case self::PLANET_SORT_NAME:
$planetCollection->order('planet.name', $order);
break;
case self::PLANET_SORT_DATE:
default:
$planetCollection->order('planet.id', $order);
break;
}
return $planetCollection;
}
public function getPlanetCollection()
{
$planetCollection = $this->_preparePlanetCollection();
$planetCollection->load(array(
'user' => $this->getId()
));
return $planetCollection;
}
public function getFleets()
{
$collection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$collection
->setEntityClassName('Legacies_Empire_Model_Fleet')
->where('fleet_owner <= :user_id')
->load(array('user_id' => $this->getId()))
;
return $collection;
}
public function getVisibleFleets()
{
$user = Legacies_Empire_Model_User::getSingleton();
$firstCollection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$firstCollection
// ->column('*')
->column('fleet.fleet_start_galaxy', 'galaxy')
->column('fleet.fleet_start_system', 'system')
->column('fleet.fleet_start_planet', 'planet')
->column('fleet.fleet_start_type', 'planet_type')
->where('fleet_end_time <= :now')
;
$backCollection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$backCollection
// ->column('*')
->column('fleet.fleet_end_galaxy', 'galaxy')
->column('fleet.fleet_end_system', 'system')
->column('fleet.fleet_end_planet', 'planet')
->column('fleet.fleet_end_type', 'planet_type')
->where('fleet_end_time <= :now')
;
$collection = new Legacies_Core_Collection();
$collection
->setEntityClassName('Legacies_Empire_Model_Fleet')
->union($firstCollection)
->union($backCollection)
->load(array('now' => time()));
return $collection;
}
public function getElement($elementId)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->getData($fields[$elementId]);
}
public function setElement($elementId, $level)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->setData($fields[$elementId], $level);
}
public function hasElement($elementId, $levelRequired = 0)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->hasData($fields[$elementId]) && Math::comp($this->getElement($elementId), $levelRequired) > 0;
}
public function getSkinPath($default = null)
{
if ($path = $this->getData('dpath')) {
return $path;
}
return $default;
}
public function setSkinPath($path)
{
$this->setData('dpath', $path);
return $this;
}
}

View file

@ -1,3 +0,0 @@
<?php
interface Legacies_Exception {}

View file

@ -1,102 +0,0 @@
<?php
class Legacies_Object
implements ArrayAccess
{
protected $_data = array();
public function __construct(Array $data = array())
{
$this->_data = $data;
}
public function getData($key)
{
if ($this->hasData($key)) {
return $this->_data[$key];
}
return null;
}
public function getAllDatas()
{
return $this->_data;
}
public function hasData($key)
{
return (bool) isset($this->_data[$key]);
}
public function setData($key, $value)
{
$this->_data[$key] = $value;
return $this;
}
public function addData(Array $data)
{
foreach ($data as $key => $value) {
$this->setData($key, $value);
}
return $this;
}
public function unsetData($key)
{
if ($this->hasData($key)) {
unset($this->_data[$key]);
}
return $this;
}
public function clearData()
{
$this->_data = array();
return $this;
}
public function offsetExists($offset)
{
return $this->hasData($offset);
}
public function offsetGet($offset)
{
return $this->getData($offset);
}
public function offsetSet($offset, $data)
{
return $this->setData($offset, $data);
}
public function offsetUnset($offset)
{
return $this->unsetData($offset);
}
public function __set($key, $value)
{
return $this->setData($key, $value);
}
public function __get($key)
{
return $this->getData($key);
}
public function __unset($key)
{
return $this->unsetData($key);
}
public function __isset($key)
{
return $this->hasData($key);
}
}

View file

@ -1,130 +0,0 @@
<?php
class Math
{
const DEFAULT_PRECISTION = 0;
protected static $_singleton = null;
public static function setPrecision($precision = null)
{
if ($precision === null) {
$precision = self::DEFAULT_PRECISTION;
}
self::getSingleton()->setPrecision($precision);
}
public static function getSingleton()
{
if (self::$_singleton === null) {
if (extension_loaded('bcmath')) {
self::$_singleton = new Math_Bcmath();
} else {
self::$_singleton = new Math_Native();
}
}
return self::$_singleton;
}
public static function add($a, $b)
{
return self::getSingleton()->add($a, $b);
}
public static function sub($a, $b)
{
return self::getSingleton()->sub($a, $b);
}
public static function mul($a, $b)
{
return self::getSingleton()->mul($a, $b);
}
public static function div($a, $b)
{
return self::getSingleton()->div($a, $b);
}
public static function comp($a, $b)
{
return self::getSingleton()->comp($a, $b);
}
public static function pow($a, $b)
{
return self::getSingleton()->pow($a, $b);
}
public static function mod($a, $b)
{
return self::getSingleton()->mod($a, $b);
}
public static function ceil($a)
{
return self::getSingleton()->ceil($a);
}
public static function floor($a)
{
return self::getSingleton()->floor($a);
}
public static function round($a, $range = 0)
{
return self::getSingleton()->round($a, $range);
}
public static function render($a)
{
return self::getSingleton()->render($a);
}
public static function isNegative($a)
{
return (bool) (self::getSingleton()->comp($a, 0) < 0);
}
public static function isPositive($a)
{
return (bool) (self::getSingleton()->comp($a, 0) > 0);
}
public static function isNegativeOrZero($a)
{
return (bool) (self::getSingleton()->comp($a, 0) <= 0);
}
public static function isPositiveOrZero($a)
{
return (bool) (self::getSingleton()->comp($a, 0) >= 0);
}
public static function isZero($a)
{
return (bool) (self::getSingleton()->comp($a, 0) == 0);
}
public static function isNotZero($a)
{
return (bool) (self::getSingleton()->comp($a, 0) != 0);
}
public static function min($a, $b)
{
if (self::getSingleton()->comp($a, $b) > 0) {
return $b;
}
return $a;
}
public static function max($a, $b)
{
if (self::getSingleton()->comp($a, $b) < 0) {
return $b;
}
return $a;
}
}

View file

@ -1,124 +0,0 @@
<?php
class Math_Bcmath
{
public function setPrecision($precision)
{
bcscale($precision);
}
public function add($a, $b)
{
return bcadd($a, $b);
}
public function mul($a, $b)
{
return bcmul($a, $b);
}
public function sub($a, $b)
{
return bcsub($a, $b);
}
public function div($a, $b)
{
return bcdiv($a, $b);
}
public function mod($a, $b)
{
return bcmod($a, $b);
}
public function pow($a, $b)
{
return bcpow($a, $b);
}
public function comp($a, $b)
{
return bccomp($a, $b);
}
public function ceil($x)
{
$integer = bcmul($x, 1, 0);
$decimals = bcsub($x, $integer);
if (bccomp($decimals, 0) > 0) {
return bcadd($integer, 1);
} else {
return $integer;
}
}
public function floor($x)
{
$integer = bcmul($x, 1, 0);
$decimals = bcsub($x, $integer);
if (bccomp($decimals, 0) < 0) {
return bcsub($integer, 1);
} else {
return $integer;
}
}
public function round($x, $range = 0)
{
$integer = bcmul($x, 1, 0);
$decimals = bcsub($x, $integer, $range);
if (bccomp($decimals, 0) > 0) {
return bcadd($integer, '0.' . str_pad('5', $range, STR_PAD_LEFT), $range);
} else {
return bcsub($integer, '0.' . str_pad('5', $range, STR_PAD_LEFT), $range);
}
}
public function render($a)
{
if (!$a) {
return '0';
}
$pos = strrpos(strval($a), '.');
$a = substr(strval($a), 0, $pos);
$length = $pos + ((3 - ($pos % 3)) % 3);
$a = str_pad($a, $length, ' ', STR_PAD_LEFT);
$parts = str_split($a, 3);
switch ((int) (count($parts) / 3)) {
case 0:
case 1:
return implode('.', $parts);
break;
case 2:
return implode('.', array_slice($parts, 0, 2)) . 'M';
break;
case 3:
return implode('.', array_slice($parts, 0, 2)) . 'G';
break;
case 4:
return implode('.', array_slice($parts, 0, 2)) . 'T';
break;
case 5:
return implode('.', array_slice($parts, 0, 2)) . 'P';
break;
case 6:
return implode('.', array_slice($parts, 0, 2)) . 'Y';
break;
default:
return implode('.', array_slice($parts, 0, sizeof($parts) - 18)) . 'Z';
break;
}
}
}

View file

@ -1,63 +0,0 @@
<?php
class Math_Native
{
public function setPrecision($precision)
{
}
public function add($a, $b)
{
return $a + $b;
}
public function mul($a, $b)
{
return $a * $b;
}
public function sub($a, $b)
{
return $a - $b;
}
public function div($a, $b)
{
return $a / $b;
}
public function mod($a, $b)
{
return $a % $b;
}
public function pow($a, $b)
{
return pow($a, $b);
}
public function comp($a, $b)
{
return ($a > $b) ? 1 : ($a < $b) ? -1 : 0;
}
public function ceil($x)
{
return ceil($x);
}
public function floor($x)
{
return floor($x);
}
public function round($range = 0)
{
return round($x, $range);
}
public function render($a, $b)
{
return strval(number_format($a, 0, ',', '.'));
}
}