Initial commit

This commit is contained in:
Gregory PLANCHAT 2011-06-07 09:23:48 +02:00
commit d7619777af
915 changed files with 59386 additions and 0 deletions

View file

@ -0,0 +1,74 @@
<?php
class Legacies
{
private static $_listeners = array();
private static $_translators = array();
public static $request = null;
public static $response = 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;
}
foreach (self::$_listeners[$event] as $listener) {
call_user_func($listener, $params);
}
}
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';
}
}

View file

@ -0,0 +1,302 @@
<?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;
}
public 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;
}
}
$fields = implode(", ", $fields);
$where = implode(" AND ", $this->_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 $where
{$group}
{$order}
{$limit}
SQL_EOF;
} else {
$statements = array();
foreach ($this->_union as $statement) {
$statements[] = $statement->_prepareSql();
}
$statements = '(' . implode(') UNION (', $statements) . ')';
$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 $where
{$limit}
SQL_EOF;
}
}
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)) {
$args = array($row) + $args;
$this->_items[] = $reflection->newInstanceArgs($args);
}
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()
{
return next($this->_items);
}
public function rewind()
{
return reset($this->_items);
}
public function key()
{
return key($this->_items);
}
public function valid()
{
return (key($this->_items) < (current($this->_items)));
}
}

View file

@ -0,0 +1,162 @@
<?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()
{
static $statement = null;
$id = func_get_arg(0);
if ($statement === null) {
$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()
{
static $statement = null;
if ($statement == null) {
$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

@ -0,0 +1,13 @@
<?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

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

View file

@ -0,0 +1,100 @@
<?php
abstract class Legacies_Core_Model
extends Legacies_Object
{
protected $_originalData = array();
protected $_data = 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

@ -0,0 +1,85 @@
<?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

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

View file

@ -0,0 +1,116 @@
<?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

@ -0,0 +1,37 @@
<?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

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

View file

@ -0,0 +1,70 @@
<?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

@ -0,0 +1,32 @@
<?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);
}
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

@ -0,0 +1,140 @@
<?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_RESEARCH = 'tech';
const TYPE_SHIP = 'fleet';
const TYPE_DEFENSE = 'defense';
const TYPE_SPECIAL = 'special';
const TYPE_OFFICER = 'officier';
const TYPE_PRODUCTION = 'prod';
const RESOURCE_METAL = 'metal';
const RESOURCE_CRISTAL = 'crystal';
const RESOURCE_DEUTERIUM = 'deuterium';
const RESOURCE_ENERGY = 'energy';
const RESOURCE_MULTIPLIER = 'factor';
const RESOURCE_FORMULA = 'formule';
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';
public static function getFieldName($id)
{
global $resource;
if (!isset($resource[$id])) {
return null;
}
return $resource[$id];
}
}

View file

@ -0,0 +1,39 @@
<?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

@ -0,0 +1,49 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Combat
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()
{
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

@ -0,0 +1,49 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_FieldsAlias
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()
{
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

@ -0,0 +1,49 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Prices
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()
{
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

@ -0,0 +1,49 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Production
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()
{
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

@ -0,0 +1,49 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Requirements
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()
{
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

@ -0,0 +1,49 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Resources
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()
{
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

@ -0,0 +1,54 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Game_Types
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()
{
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)
{
return in_array($element, $this->getData($type));
}
}

View file

@ -0,0 +1,425 @@
<?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 $_user = null;
protected $_moon = null;
protected $_now = null;
protected static $_instances = array();
protected static $_productionConfig = array(
Legacies_Empire::RESOURCE_METAL => array(
'field' => Legacies_Empire::RESOURCE_METAL,
'production_field' => 'metal_perhour',
'ratio_field' => 'metal_porcent',
'storage_field' => 'metal_max',
'production' => array(
Legacies_Empire::ID_BUILDING_METAL_MINE => 'metal_mine_porcent'
),
'storage' => Legacies_Empire::ID_BUILDING_METAL_STORAGE
),
Legacies_Empire::RESOURCE_CRISTAL => array(
'field' => Legacies_Empire::RESOURCE_CRISTAL,
'production_field' => 'crystal_perhour',
'ratio_field' => 'crystal_porcent',
'storage_field' => 'crystal_max',
'production' => array(
Legacies_Empire::ID_BUILDING_CRISTAL_MINE => 'crystal_mine_porcent'
),
'storage' => Legacies_Empire::ID_BUILDING_CRISTAL_STORAGE
),
Legacies_Empire::RESOURCE_DEUTERIUM => array(
'field' => Legacies_Empire::RESOURCE_DEUTERIUM,
'production_field' => 'deuterium_perhour',
'ratio_field' => 'deuterium_porcent',
'storage_field' => 'deuterium_max',
'production' => array(
Legacies_Empire::ID_BUILDING_DEUTERIUM_SYNTHETISER => 'deuterium_sintetizer_porcent'
),
'storage' => Legacies_Empire::ID_BUILDING_DEUTERIUM_TANK
),
Legacies_Empire::RESOURCE_ENERGY => array(
'field' => 'energy_used',
'production_field' => 'energy_max',
'storage_field' => null,
'production' => array(
Legacies_Empire::ID_BUILDING_SOLAR_PLANT => 'solar_plant_porcent',
Legacies_Empire::ID_BUILDING_FUSION_REACTOR => 'fusion_plant_porcent',
Legacies_Empire::ID_SHIP_SOLAR_SATELLITE => 'solar_satelit_porcent'
),
'storage' => null
)
);
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->_now = time();
$this->_tableName = 'planets';
$this->_idFieldName = 'id';
}
/**
* @deprecated
*/
protected function _now()
{
return $this->_now;
}
public function updateResources($time = null)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
if ($time === null) {
$time = $this->_now();
}
if ($this->getData('planet_type') != 1) {
return $this;
}
$resourcesProductions = array();
foreach (self::$_productionConfig as $resource => $resourceData) {
if ($resourceData['storage_field'] !== null && $resourceData['storage_field'] !== null) {
$officerEnhancement = Math::add(Math::mul(.5, $this->getUser('rpg_stockeur')), 1);
$storageCapacity = Math::pow(1.5, $this->getData(Legacies_Empire::getFieldName($resourceData['storage'])));
$value = Math::mul(MAX_OVERFLOW, Math::mul($officerEnhancement, Math::add(BASE_STORAGE_SIZE, $storageCapacity)));
$this->setData($resourceData['storage_field'], $value);
}
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::getProducitonElementInstance($productionUnit);
foreach ($element->getRatios($level, $ratio, $this, $this->getUser()) as $resourceId => $resourceProduction) {
if (!isset($resourcesProductions[$resourceId])) {
$resourcesProductions[$resourceId] = $resourceProduction;
} else {
$resourcesProductions[$resourceId] = Math::add($resourcesProductions[$resourceId], $resourceProduction);
}
}
}
}
$timeDiff = ($time - $this->getData('last_update')) / 3600;
foreach ($resourcesProductions as $resourceId => $productionPerHour) {
if (!isset(self::$_productionConfig[$resource])) {
continue;
}
$this->setData(self::$_productionConfig[$resource]['production_field'], $productionPerHour);
$production = Math::add($this->getData(self::$_productionConfig[$resource]['field']), Math::mul($timeDiff, $productionPerHour));
if (Math::diff($production, $this->getData(self::$_productionConfig[$resource]['storage_field'])) > 0) {
$production = $this->getData(self::$_productionConfig[$resource]['storage_field']);
}
$this->setData(self::$_productionConfig[$resource]['field'], $production);
}
return $this;
}
public static function getProducitonElementInstance($buildingId)
{
global $ProdGrid; // FIXME
if (!isset(self::$_productionInstances[$buildingId])) {
if (!isset($ProdGrid[$buildingId])) {
return null;
}
$class = $ProdGrid[$buildingId][Legacies_Empire::RESOURCE_FORMULA];
self::$_productionInstances[$buildingId] = new $class;
}
return self::$_productionInstances[$buildingId];
}
public function getUser()
{
if ($this->_user === null) {
$this->_user = Legacies_Empire_Model_User::factory($this->getData('id_owner'));
}
return $this->_user;
}
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 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'];
$time = null;
if (isset($eventData['time'])) {
$time = $eventData['time'];
}
if ($planet === null || !$planet instanceof Legacies_Empire_Model_Planet || !$planet->getId()) {
return;
}
$user = $planet->getUser();
if (($queue = $this->getData('b_building_id')) != '') {
$explodedQueue = explode(';', $queue);
foreach ($explodedQueue as $item) {
$partialTime = $this->getData('b_building');
if ($partialTime < $time) {
$planet->updateResources($partialTime);
if (CheckPlanetBuildingQueue($planet, $user)) {
SetNextQueueElementOnTop($planet, $user);
}
} else {
$planet->updateResources($time);
break;
}
}
} else {
$planet->updateResources($time);
}
}
}
}

View file

@ -0,0 +1,13 @@
<?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 => 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

@ -0,0 +1,13 @@
<?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

@ -0,0 +1,13 @@
<?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

@ -0,0 +1,13 @@
<?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 => 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

@ -0,0 +1,487 @@
<?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
{
/**
* 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 $_queue = null;
/**
* Current timestamp
*
* @var int
* @deprecated
*/
private $_now = 0;
/**
* 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 false;
}
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->_queue = unserialize($this->_currentPlanet->getData('b_hangar_id'));
if (!is_array($this->_queue)) {
$this->_queue = array();
}
$this->_now = time();
}
/**
* Returns the timestamp at the instance creation.
*
* @deprecated
* @return int
*/
protected function _now()
{
return $this->_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)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
if (Math::comp($qty, 0) <= 0) {
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;
}
$qty = $this->_checkMaximumQuantity($shipId, $qty);
if (MAX_FLEET_OR_DEFS_PER_ROW > 0 && Math::comp($qty, MAX_FLEET_OR_DEFS_PER_ROW) > 0) {
$qty = MAX_FLEET_OR_DEFS_PER_ROW;
}
// Dispatch event
Legacies::dispatchEvent('planet.shipyard.append-queue.before', array(
'ship_id' => $shipId,
'qty' => $qty,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
$resourcesNeeded = $this->_getResourcesNeeded($shipId, $qty);
$buildTime = $this->getBuildTime($shipId, $qty);
$this->_queue[] = new Legacies_Empire_Model_Planet_Building_Shipyard_Item(array(
'ship_id' => $shipId,
'qty' => $qty,
'created_at' => $this->_now(),
'updated_at' => $this->_now()
));
foreach ($this->_resourcesTypes as $resourceType) {
$this->_currentPlanet[$resourceType] = Math::sub($this->_currentPlanet[$resourceType], $resourcesNeeded[$resourceType]);
}
// Dispatch event
Legacies::dispatchEvent('planet.shipyard.append-queue.after', array(
'ship_id' => $shipId,
'qty' => $qty,
'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)
{
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
if ($time === null) {
$time = $this->_now();
}
$elapsedTime = $time - $this->_currentPlanet['b_hangar'];
// Dispatch event
Legacies::dispatchEvent('planet.shipyard.update-queue.before', array(
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
foreach ($this->_queue as $id => &$element) {
$shipId = $element->getData('ship_id');
$qty = $element->getData('qty');
$buildTime = $this->getBuildTime($shipId, $qty);
if ($elapsedTime >= $buildTime) {
$this->_currentPlanet[$fields[$shipId]] = Math::add($this->_currentPlanet[$fields[$shipId]], $qty);
$elapsedTime -= $buildTime;
unset($this->_queue[$id]);
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;
}
unset($element);
// Dispatch event
Legacies::dispatchEvent('planet.shipyard.update-queue.after', array(
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
return $this;
}
/**
* Return the construction queue
* @see Legacies_Empire_Model_Planet_Building_Shipyard_Item
*
* @return array
*/
public function getQueue()
{
return $this->_queue;
}
/**
* 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();
$requirements = Legacies_Empire_Model_Game_Requirements::getSingleton();
if (!isset($requirements[$shipId]) || empty($requirements[$shipId])) {
return true;
}
foreach ($requirements[$shipId] 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;
}
try {
// Dispatch event. Throw an exception to break the avaliability.
Legacies::dispatchEvent('planet.shipyard.check-availability', array(
'ship_id' => $shipId,
'shipyard' => $this,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser
));
} catch (Exception $e) {
return false;
}
return true;
}
/**
* 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)
{
$max = $this->getMaximumBuildableElementsCount($shipId);
if (Math::comp($qty, $max) > 0) {
return $max;
}
return $qty;
}
/**
* 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 = array(
Legacies_Empire::RESOURCE_METAL,
Legacies_Empire::RESOURCE_CRISTAL,
Legacies_Empire::RESOURCE_DEUTERIUM,
Legacies_Empire::RESOURCE_ENERGY
);
$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;
}
protected function _getResourcesNeeded($shipId, $qty)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
$resourcesNeeded = array();
foreach ($this->_resourcesTypes as $resourceId) {
if (isset($prices[$shipId]) && isset($prices[$shipId][$resourceId]) && $prices[$shipId][$resourceId] > 0) {
$resourcesNeeded[$resourceId] = Math::mul($prices[$shipId][$resourceId], $qty);
}
}
return $resourcesNeeded;
}
public function getBuildTime($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();
$scale = 30;
$totalCost = Math::mul(Math::add($prices[$shipId][Legacies_Empire::RESOURCE_METAL], $prices[$shipId][Legacies_Empire::RESOURCE_CRISTAL]), $qty, $scale);
$speedFactor = $gameConfig->getData('game_speed');
$shipyardSpeedup = Math::div(1, Math::add($this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_SHIPYARD]], 1, $scale), $scale);
$naniteSpeedup = Math::pow(.5, $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_NANITE_FACTORY]], $scale);
$structuresSpeedup = Math::mul($shipyardSpeedup, $naniteSpeedup, $scale);
$officerSpeedup = 1;
if (in_array($shipId, $types[Legacies_Empire::TYPE_SHIP])) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_technocrate'] * .05);
} else if (in_array($shipId, $types[Legacies_Empire::TYPE_SPECIAL])) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_technocrate'] * .05);
} else if (in_array($shipId, $types[Legacies_Empire::TYPE_DEFENSE])) {
$officerSpeedup = 1 - ($this->_currentUser['rpg_defenseur'] * .375);
}
$baseTime = ($totalCost / $speedFactor) * $structuresSpeedup;
return $baseTime * $officerSpeedup * 3600;
}
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

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

View file

@ -0,0 +1,12 @@
<?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

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

View file

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

View file

@ -0,0 +1,12 @@
<?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)
);
}
}

View file

@ -0,0 +1,12 @@
<?php
class Legacies_Empire_Model_Planet_Ship_Supernova
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) * -1250
);
}
}

View file

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

View file

@ -0,0 +1,301 @@
<?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;
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::COOKIE_NAME)) !== 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('request_uri', $_SERVER['REQUEST_URI'])
->setData('remote_addr', $_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::COOKIE_NAME);
}
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::COOKIE_NAME, 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 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);
}
public function getPlanetCollection()
{
$planetCollection = new Legacies_Core_Collection(array('planet' => 'planets'), 'Legacies_Empire_Model_Planet');
$planetCollection->where('id_owner=:user');
$order = ($user['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;
}
$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;
}
}

View file

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

View file

@ -0,0 +1,102 @@
<?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, $value);
}
public function __unset($key)
{
return $this->unsetData($key);
}
public function __isset($key)
{
return $this->hasData($key);
}
}

View file

@ -0,0 +1,73 @@
<?php
class Math
{
protected static $_singleton = null;
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);
}
}

View file

@ -0,0 +1,119 @@
<?php
class Math_Bcmath
{
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

@ -0,0 +1,59 @@
<?php
class Math_Native
{
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, ',', '.'));
}
}