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

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/config.php

2
.htaccess Normal file
View file

@ -0,0 +1,2 @@
SetEnv DEBUG On
SetEnv DEPRECATION Off

View file

@ -32,33 +32,32 @@ define('INSIDE' , true);
define('INSTALL' , false); define('INSTALL' , false);
require_once dirname(__FILE__) .'/common.php'; require_once dirname(__FILE__) .'/common.php';
includeLang('buildings'); includeLang('buildings');
// Mise a jour de la liste de construction si necessaire $user = Legacies_Empire_Model_User::getSingleton();
UpdatePlanetBatimentQueueList ( $planetrow, $user ); $planet = $user->getCurrentPlanet();
$IsWorking = HandleTechnologieBuild ( $planetrow, $user );
switch ($_GET['mode']) { switch ($_GET['mode']) {
case 'fleet': case 'fleet':
// -------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------
FleetBuildingPage ( $planetrow, $user ); FleetBuildingPage($planet, $user);
break; break;
case 'research': case 'research':
// -------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------
ResearchBuildingPage ( $planetrow, $user, $IsWorking['OnWork'], $IsWorking['WorkOn'] ); ResearchBuildingPage($planet, $user, $IsWorking['OnWork'], $IsWorking['WorkOn'] );
break; break;
case 'defense': case 'defense':
// -------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------
DefensesBuildingPage ( $planetrow, $user ); DefensesBuildingPage($planet, $user);
break; break;
default: default:
// -------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------
BatimentBuildingPage ( $planetrow, $user ); BatimentBuildingPage($planet, $user);
break; break;
} }
// ----------------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------------
// History version // History version

View file

@ -28,8 +28,25 @@
* *
*/ */
if (!defined('DEBUG') && in_array(strtolower(getenv('DEBUG')), array('1', 'on', 'true'))) { define('DEPRECATION', true);
define('DEBUG', true);
if (!defined('DEBUG') && ($env = getenv('DEBUG')) !== false && in_array(strtolower($env), array('1', 'on', 'true'))) {
define('DEBUG', true); define('DEBUG', true);
} else if (!defined('DEBUG') && isset($_SERVER['DEBUG']) && in_array(strtolower($_SERVER['DEBUG']), array('1', 'on', 'true'))) {
define('DEBUG', true);
}
if (!defined('DEPRECATION') && ($env = getenv('DEPRECATION')) !== false && in_array(strtolower($env), array('1', 'on', 'true'))) {
define('DEPRECATION', true);
} else if (!defined('DEPRECATION') && isset($_SERVER['DEPRECATION']) && in_array(strtolower($_SERVER['DEPRECATION']), array('1', 'on', 'true'))) {
define('DEPRECATION', true);
}
if (!defined('BCNUMBERS') && ($env = getenv('BCNUMBERS')) !== false && in_array(strtolower($env), array('1', 'on', 'true'))) {
define('BCNUMBERS', true);
} else if (!defined('BCNUMBERS') && isset($_SERVER['BCNUMBERS']) && in_array(strtolower($_SERVER['BCNUMBERS']), array('1', 'on', 'true'))) {
define('BCNUMBERS', true);
} }
if (!defined('DEBUG')) { if (!defined('DEBUG')) {
@ -47,6 +64,7 @@ defined('PHPEXT') || define('PHPEXT', require 'extension.inc');
defined('VERSION') || define('VERSION', '2011.1'); defined('VERSION') || define('VERSION', '2011.1');
set_include_path(implode(PATH_SEPARATOR, array( set_include_path(implode(PATH_SEPARATOR, array(
APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'libraries',
APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'local', APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'local',
APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'community', APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'community',
APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'core', APPLICATION_PATH . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR . 'core',
@ -57,7 +75,8 @@ function __autoload($class) {
include_once str_replace('_', '/', $class) . '.php'; include_once str_replace('_', '/', $class) . '.php';
} }
Legacies_Core_Error::register(); Legacies_Core_Time::init();
Legacies_Core_ErrorProfiler::register();
if (0 === filesize(ROOT_PATH . 'config.php')) { if (0 === filesize(ROOT_PATH . 'config.php')) {
header('Location: install/'); header('Location: install/');
@ -72,7 +91,6 @@ foreach (include ROOT_PATH . 'includes/data/events.php' as $event => $listenerLi
$lang = array(); $lang = array();
define('DEFAULT_SKINPATH', 'skins/xnova/');
define('TEMPLATE_DIR', realpath(ROOT_PATH . '/templates/')); define('TEMPLATE_DIR', realpath(ROOT_PATH . '/templates/'));
define('TEMPLATE_NAME', 'OpenGame'); define('TEMPLATE_NAME', 'OpenGame');
define('DEFAULT_LANG', 'fr'); define('DEFAULT_LANG', 'fr');
@ -110,30 +128,17 @@ if (!defined('DISABLE_IDENTITY_CHECK')) {
includeLang('system'); includeLang('system');
includeLang('tech'); includeLang('tech');
include(ROOT_PATH . 'rak.php');
$dpath = DEFAULT_SKINPATH;
if (($user !== null && $user->getId())) { if (($user !== null && $user->getId())) {
$dpath = $user->getSkinPath();
if (empty($dpath)) {
$dpath = DEFAULT_SKINPATH;
}
if (defined('IN_ADMIN')) {
$dpath = '../' . $dpath;
}
if (isset($_GET['cp']) && !empty($_GET['cp'])) { if (isset($_GET['cp']) && !empty($_GET['cp'])) {
$user->updateCurrentPlanet((int) $_GET['cp']); $user->updateCurrentPlanet((int) $_GET['cp']);
} }
$planet = $user->getCurrentPlanet();
foreach ($user->getPlanetCollection() as $planet) { foreach ($user->getPlanetCollection() as $planet) {
FlyingFleetHandler($planet); // TODO: implement logic into a refactored model FlyingFleetHandler($planet); // TODO: implement logic into a refactored model
} }
$planet = $user->getCurrentPlanet();
/* /*
* Update planet resources and constructions * Update planet resources and constructions
*/ */

21
config.php.default Normal file
View file

@ -0,0 +1,21 @@
<?php return array(
'global' => array(
'date' => array(
'timezone' => 'Europe/Paris'
),
'database' => array(
'engine' => 'mysql',
'options' => array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_xnova'
),
'table_prefix' => 'game_',
),
'layout' => array(
'page' => 'page.php',
'empire' => 'empire.php'
)
)
);

View file

@ -1,64 +1,16 @@
<?php <html>
/** <head>
* This file is part of XNova:Legacies <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
* <link rel="shortcut icon" href="favicon.ico">
* @license http://www.gnu.org/licenses/gpl-3.0.txt <title>XNova:Legacies</title>
* @see http://www.xnova-ng.org/ </head>
* <frameset framespacing="0" border="0" cols="190,*" frameborder="0">
* Copyright (c) 2009-Present, XNova Support Team <http://www.xnova-ng.org> <frame name="LeftMenu" target="Mainframe" src="leftmenu.php" noresize scrolling="no" marginwidth="0" marginheight="0">
* All rights reserved. <frame name="Hauptframe" src="overview.php">
* <noframes>
* This program is free software: you can redistribute it and/or modify <body>
* it under the terms of the GNU General Public License as published by <p>Votre navigateur ne gère pas les frames.</p>
* the Free Software Foundation, either version 3 of the License, or </body>
* (at your option) any later version. </noframes>
* </frameset>
* This program is distributed in the hope that it will be useful, </html>
* 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.
*
*/
define('INSIDE' , true);
define('INSTALL' , false);
$XNova_Host = $_SERVER['HTTP_HOST'];
$XNova_Script = $_SERVER['SCRIPT_NAME'];
$Uri_Array = explode ('/', $XNova_Script);
// On vire le script
array_pop($Uri_Array);
$XNova_URI = implode ('/', $Uri_Array);
$XNovaRootURL = "http://". $XNova_Host ."/". $XNova_URI ."/";
require_once dirname(__FILE__) .'/common.php';
$page = "<html>";
$page .= "<head>";
$page .= "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=". $langInfos['ENCODING']."\">";
$page .= "<link rel=\"shortcut icon\" href=\"favicon.ico\">";
$page .= "<title>". $gameConfig['game_name'] ."</title>";
$page .= "</head>";
$page .= "<frameset framespacing=\"0\" border=\"0\" cols=\"190,*\" frameborder=\"0\">";
$page .= "<frame name=\"LeftMenu\" target=\"Mainframe\" src=\"leftmenu.php\" noresize scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\">";
$page .= "<frame name=\"Hauptframe\" src=\"overview.php\">";
$page .= "<noframes>";
$page .= "<body>";
$page .= "<p>Votre navigateur ne gère pas les frames.</p>";
$page .= "</noframes>";
$page .= "</frameset>";
$page .= "</body>";
$page .= "</html>";
echo $page;

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,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,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,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

@ -59,7 +59,7 @@ class Legacies
public static function translate($locale, $message, Array $args) public static function translate($locale, $message, Array $args)
{ {
return vsprintf(self::getTranslator($locale)->translateArgs($message), $args); return self::getTranslator($locale)->translateArgs($message, $args);
} }
public static function __($message, $_ = null) public static function __($message, $_ = null)

View file

@ -0,0 +1,14 @@
<?php
class Legacies_Core_Block_Concat
extends Legacies_Core_View
{
public function render()
{
$content = '';
foreach ($this->_partials as $partial) {
$content .= $partial->render();
}
return $content;
}
}

View file

@ -0,0 +1,11 @@
<?php
class Legacies_Core_Block_Html_Form
extends Legacies_Core_Block_Template
{
public function getFormKey()
{
$session = Legacies::getSession('security');
return $session->getFormKey(true);
}
}

View file

@ -0,0 +1,145 @@
<?php
class Legacies_Core_Block_Html_Head
extends Legacies_Core_Block_Template
{
const TYPE_GLOBAL_JS = 'global_js';
const TYPE_SKIN_CSS = 'skin_css';
const TYPE_SKIN_JS = 'skin_js';
const TYPE_INLINE_CSS = 'inline_css';
const TYPE_INLINE_JS = 'inline_js';
protected $_items = array();
public function addItem($type, Array $options = array())
{
if (!isset($this->_items[$type])) {
$this->_items[$type] = array();
}
$this->_items[$type][] = $options;
return $this;
}
public function addJs($script, $type = 'text/javascript', Array $options = array())
{
$options['type'] = $type;
$options['path'] = $script;
$this->addItem(self::TYPE_GLOBAL_JS, $options);
return $this;
}
public function addCss($stylesheet, $type = 'text/css', $condition = null, Array $options = array())
{
$options['type'] = $type;
$options['path'] = $stylesheet;
$options['condition'] = $condition;
$this->addItem(self::TYPE_SKIN_CSS, $options);
return $this;
}
public function addSkinJs($script, $type = 'text/javascript', Array $options = array())
{
$options['type'] = $type;
$options['path'] = $script;
$this->addItem(self::TYPE_SKIN_JS, $options);
return $this;
}
public function addInlineJs($content, $type = 'text/javascript', Array $options = array())
{
$options['type'] = $type;
$options['content'] = $content;
$this->addItem(self::TYPE_INLINE_JS, $options);
return $this;
}
public function addInlineCss($content, $type = 'text/css', Array $options = array())
{
$options['type'] = $type;
$options['path'] = $path;
$options['content'] = $content;
$this->addItem(self::TYPE_INLINE_CSS, $options);
return $this;
}
public function getCss()
{
if (isset($this->_items[self::TYPE_SKIN_CSS])) {
return $this->_items[self::TYPE_SKIN_CSS];
}
return array();
}
public function getInlineCss()
{
if (isset($this->_items[self::TYPE_INLINE_CSS])) {
return $this->_items[self::TYPE_INLINE_CSS];
}
return array();
}
public function getJs()
{
if (isset($this->_items[self::TYPE_GLOBAL_JS])) {
return $this->_items[self::TYPE_GLOBAL_JS];
}
return array();
}
public function getSkinJs()
{
if (isset($this->_items[self::TYPE_SKIN_JS])) {
return $this->_items[self::TYPE_SKIN_JS];
}
return array();
}
public function getInlineJs()
{
if (isset($this->_items[self::TYPE_INLINE_JS])) {
return $this->_items[self::TYPE_INLINE_JS];
}
return array();
}
public function renderCss()
{
$render = '';
foreach ($this->getCss() as $css) {
if (!isset($css['media'])) {
$css['media'] = 'all';
}
$render .=<<<HTML_EOF
<link rel="stylesheet" type="{$css['type']}" src="{$css['path']}" media="{$css['media']}" />
HTML_EOF;
}
return $render;
}
public function renderJs()
{
$render = '';
foreach ($this->getJs() as $js) {
if (!isset($css['media'])) {
$css['media'] = 'all';
}
$render .=<<<HTML_EOF
<script type="{$js['type']}" src="{$js['path']}"></script>
HTML_EOF;
}
return $render;
}
}

View file

@ -0,0 +1,6 @@
<?php
class Legacies_Core_Block_Html_Navigation
extends Legacies_Core_Block_Template
{
}

View file

@ -0,0 +1,19 @@
<?php
class Legacies_Core_Block_Html_Page
extends Legacies_Core_Block_Template
{
protected $_bodyClasses = array();
public function getBodyClasses()
{
return implode(' ', $this->_bodyClasses);
}
public function addBodyClass($class)
{
$this->_bodyClasses[] = $class;
return $this;
}
}

View file

@ -0,0 +1,7 @@
<?php
class Legacies_Core_Block_Template
extends Legacies_Core_View
{
}

View file

@ -0,0 +1,28 @@
<?php
class Legacies_Core_Block_Text
extends Legacies_Core_View
{
protected $_content = null;
public function setContent($content)
{
$this->_content = $content;
return $this;
}
public function getContent()
{
return $this->_content;
}
public function render()
{
$content = $this->getContent();
if (empty($content)) {
return null;
}
return $content;
}
}

View file

@ -177,8 +177,8 @@ class Legacies_Core_Collection
} else { } else {
$fields = '*'; $fields = '*';
} }
if (!empty($where)) { if (!empty($this->_where)) {
$where = 'WHERE ' . implode(" AND ", $this->_where); $where = 'WHERE (' . implode(") AND (", $this->_where) . ')';
} else { } else {
$where = ''; $where = '';
} }
@ -261,7 +261,12 @@ SQL_EOF;
$statement->execute(array_shift($args)); $statement->execute(array_shift($args));
$this->_items = array(); $this->_items = array();
$reflection = new ReflectionClass($this->getEntityClassName()); if (func_num_args() > 1) {
$reflection = new ReflectionClass(array_shift($args));
} else {
$reflection = new ReflectionClass($this->getEntityClassName());
}
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$params = array_merge(array($row), $args); $params = array_merge(array($row), $args);
$this->_items[] = $reflection->newInstanceArgs($params); $this->_items[] = $reflection->newInstanceArgs($params);
@ -288,6 +293,22 @@ SQL_EOF;
return $this; return $this;
} }
public function getSize()
{
$clone = clone $this;
$clone->_fields = array();
$clone->column('COUNT(*)');
$sql = $clone->_prepareSql();
$database = Legacies_Database::getSingleton();
$statement = $database->prepare($sql);
$args = func_get_args();
$statement->execute(array_shift($args));
return $statement->fetch(PDO::FETCH_COLUMN, 0);
}
public function count() public function count()
{ {
return count($this->_items); return count($this->_items);

View file

@ -0,0 +1,54 @@
<?php
class Legacies_Core_Controller_Action
{
private $_request = null;
private $_response = null;
public function init()
{
}
public function preDispatch()
{
}
public function postDispatch()
{
}
public function getRequest()
{
return $this->_request;
}
public function getResponse()
{
return $this->_response;
}
protected function _forward($action, $controller = null, $module = null)
{
$request = $this->getRequest();
$request->setAction($action);
if ($controller !== null) {
$request->setController($controller);
if ($module != null) {
$request->setModule($module);
}
}
$request->setIsDispatched(false);
}
protected function _redirect($url)
{
$this->getResponse()
->setRawHeader('HTTP/1.1 302 Found')
->setHeader('Location', $url)
->setIsRedirect(true)
;
return $this;
}
}

View file

@ -0,0 +1,78 @@
<?php
class Legacies_Core_Controller_Request_Http
extends Legacies_Object
{
public function __construct()
{
parent::__construct(array());
}
public function setParam($key, $value)
{
return $this->setData($key, $value);
}
public function getParam($key, $default = null)
{
if ($this->hasData($key)) {
return $this->getData($key);
}
if (isset($_POST[$key])) {
return $_POST[$key];
}
if (!isset($_GET[$key])) {
return $_GET[$key];
}
if (!isset($_FILES[$key])) {
return $_FILES[$key];
}
if (!isset($_COOKIE[$key])) {
return $_COOKIE[$key];
}
if (!isset($_SERVER[$key])) {
return $_SERVER[$key];
}
return $default;
}
public function getQuery($key, $default = null)
{
if (!isset($_GET[$key])) {
return $default;
}
return $_GET[$key];
}
public function getFile($key, $default = null)
{
if (!isset($_FILES[$key])) {
return $default;
}
return $_FILES[$key];
}
public function getCookie($key, $default = null)
{
if (!isset($_COOKIE[$key])) {
return $default;
}
return unserialize(stripslashes($_COOKIE[$key]));
}
public function getRawCookie($key, $default = null)
{
if (!isset($_COOKIE[$key])) {
return $default;
}
return $_COOKIE[$key];
}
public function getPost($key, $default = null)
{
if (!isset($_POST[$key])) {
return $default;
}
return $_POST[$key];
}
}

View file

@ -0,0 +1,132 @@
<?php
class Legacies_Core_Controller_Response
extends Legacies_Object
{
public function __construct()
{
parent::__construct(array());
}
public function setBody($data)
{
$this->clearBody();
return $this->appendBody($data);
}
public function appendBody($data)
{
if (!isset($this->_data['body']) || !is_array($this->_data['body'])) {
$this->clearBody();
}
$this->_data['body'][] = $data;
return $this;
}
public function clearBody()
{
$this->_data['body'] = array();
return $this;
}
public function sendBody()
{
return implode('', $this->_data['body']);
}
public function clearHeaders()
{
$this->_data['headers'] = array();
return $this;
}
public function clearRawHeaders()
{
$this->_data['raw_headers'] = array();
return $this;
}
public function clearAllHeaders()
{
$this->clearHeaders();
$this->clearRawHeaders();
return $this;
}
public function setHeader($name, $value)
{
if (!isset($this->_data['headers']) || !is_array($this->_data['headers'])) {
$this->clearHeaders();
}
$this->_data['headers'][$name] = $value;
return $this;
}
public function setRawHeader($name, $value)
{
if (!isset($this->_data['raw_headers']) || !is_array($this->_data['raw_headers'])) {
$this->clearRawHeaders();
}
$this->_data['raw_headers'][] = $value;
return $this;
}
public function sendHeaders()
{
if (isset($this->_data['raw_headers'])) {
foreach ($this->_data['raw_headers'] as $header) {
header($header);
}
}
if (isset($this->_data['headers'])) {
foreach ($this->_data['headers'] as $headerName => $headerValue) {
header("{$headerName}: {$headerValue}");
}
}
$this->clearAllHeaders();
return $this;
}
public function setIsRedirect($value = null)
{
if (is_bool($value)) {
$this->_data['is_redirect'] = $value;
}
return $this->_data['is_redirect'];
}
public function setIsDispatched($dispatched = true)
{
return $this->setData('id_dispatched', $dispatched);
}
public function getIsDispatched()
{
return $this->getData('id_dispatched');
}
public function setCookie($name, $value, $lifetime = null, $path = null, $domain = null)
{
return $this->setRawCookie($name, serialize($value), $lifetime, $path, $domain);
}
public function unsetCookie($name, $path = null, $domain = null)
{
return $this->setRawCookie($name, null, 0, $path, $domain);
}
public function setRawCookie($name, $value, $lifetime = null, $path = null, $domain = null)
{
setcookie($name, $value, time() + $lifetime, $path, $domain);
return $this;
}
}

View file

@ -7,6 +7,8 @@ abstract class Legacies_Core_Entity
protected $_idFieldName = null; protected $_idFieldName = null;
protected $_tableName = null; protected $_tableName = null;
protected $_eventPrefix = 'entity';
public function setIdFieldName($fieldName) public function setIdFieldName($fieldName)
{ {
$this->_idFieldName = $fieldName; $this->_idFieldName = $fieldName;

View file

@ -13,6 +13,8 @@ abstract class Legacies_Core_Entity_SubTable
protected $_tableName = null; protected $_tableName = null;
protected $_idFieldNames = array(); protected $_idFieldNames = array();
protected $_eventPrefix = 'entity.sub-table';
protected function _save() protected function _save()
{ {
if ($this->_isLoaded !== false) { if ($this->_isLoaded !== false) {

View file

@ -1,6 +1,6 @@
<?php <?php
class Legacies_Core_Error class Legacies_Core_ErrorProfiler
{ {
private static $_singleton = null; private static $_singleton = null;
@ -10,6 +10,8 @@ class Legacies_Core_Error
protected $_otherErrors = array(); protected $_otherErrors = array();
protected $_exceptions = array(); protected $_exceptions = array();
private static $_isTraceRegistered = false;
public static function getSingleton() public static function getSingleton()
{ {
if (self::$_singleton === null) { if (self::$_singleton === null) {
@ -101,7 +103,7 @@ class Legacies_Core_Error
0x4000 => 'E_USER_DEPRECATED', 0x4000 => 'E_USER_DEPRECATED',
); );
if (isset($types[$error['code']])) { if (isset($error['code']) && isset($types[$error['code']])) {
$code = $types[$error['code']]; $code = $types[$error['code']];
} else { } else {
$code = "Unknown ({$error['code']})"; $code = "Unknown ({$error['code']})";
@ -122,42 +124,56 @@ ERROR_EOF;
public function shutdownManager() public function shutdownManager()
{ {
echo '<pre style="background:#FFF;border:1px solid #F00;color:#000;padding:10px;margin:20px;">'; echo '<div style="background:#FFF;border:1px solid #F00;color:#000;padding:10px;margin:20px;text-align:left;">';
foreach ($this->_errors as $error) { echo '<h1>Debug profiler</h1>';
echo $this->_renderError($error); if (count($this->_errors) <= 0 && count($this->_warnings) <= 0 &&
count($this->_notices) <= 0 && count($this->_otherErrors) <= 0 &&
count($this->_exceptions) <= 0) {
echo '<p>Profiler was empty.</p>';
} else {
echo '<pre>';
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 $errorList) {
foreach ($errorList as $error) {
echo $this->_renderError($error);
}
}
foreach ($this->_exceptions as $exception) {
echo $exception->getMessage() . PHP_EOL;
echo $exception->getTraceAsString();
}
echo '</pre>';
} }
foreach ($this->_warnings as $error) { echo '</div>';
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() public static function register()
{ {
static $registered = false;
set_error_handler(array(self::getSingleton(), 'errorManager')); set_error_handler(array(self::getSingleton(), 'errorManager'));
set_exception_handler(array(self::getSingleton(), 'exceptionManager')); set_exception_handler(array(self::getSingleton(), 'exceptionManager'));
if ($registered === false && defined('DEBUG')) { if (self::$_isTraceRegistered === false && defined('DEBUG')) {
$registered = true; self::$_isTraceRegistered = true;
register_shutdown_function(array(self::getSingleton(), 'shutdownManager')); register_shutdown_function(array(self::getSingleton(), 'shutdownManager'));
} }
} }
public static function unregister() public static function unregister($force = false)
{ {
restore_error_handler(); restore_error_handler();
restore_exception_handler(); restore_exception_handler();
if ((self::$_isTraceRegistered && defined('DEBUG')) || $force) {
self::$_isTraceRegistered = false;
register_shutdown_function(array(self::getSingleton(), 'shutdownManager'));
}
} }
} }

View file

@ -0,0 +1,220 @@
<?php
class Legacies_Core_Layout
extends Legacies_Core_Model
{
protected $_blocks = array();
protected $_view = null;
protected $_eventPrefix = 'layout';
protected $_eventObject = 'layout';
public function _init()
{
$path = APPLICATION_PATH . 'design/layouts/';
$config = include ROOT_PATH . 'config.php';
$fileList = $config['global']['layout'];
foreach ($fileList as $layoutFile) {
foreach (include $path . $layoutFile as $layoutId => $layoutConfig) {
if ($this->hasData($layoutId)) {
$declared = $this->getData($layoutId);
$layoutConfig = array_merge($declared, $layoutConfig);
}
$this->setData($layoutId, $layoutConfig);
}
}
return $this;
}
public function _load()
{
$layoutId = func_get_arg(0);
if (!$this->hasData($layoutId)) {
return $this;
}
$layoutConfigs = array($this->getData($layoutId));
$layoutUpdates = array();
if (isset($layoutConfigs[0]['update'])) {
$parent = $layoutConfigs[0]['update'];
$i = 0;
while (true) {
$layoutConfigs[++$i] = $this->getData($parent);
if (!isset($layoutConfigs[$i]['update'])) {
break;
}
$parent = $layoutConfigs[$i]['update'];
}
}
$layoutConfig = array();
foreach (array_reverse($layoutConfigs) as $config) {
$layoutConfig = array_merge($layoutConfig, $config);
if (isset($layoutConfig['reference'])) {
foreach ($layoutConfig['reference'] as $name => $update) {
if (!isset($layoutUpdates[$name])) {
$layoutUpdates[$name] = array();
}
$layoutUpdates[$name][] = $update;
}
unset($layoutConfig['reference']);
}
}
unset($layoutConfigs, $layoutConfig['update']);
$type = $layoutConfig['type'];
$name = isset($layoutConfig['name']) ? $layoutConfig['name'] : 'root';
$this->_view = $this->createBlock($type, $name, $layoutConfig);
foreach ($layoutUpdates as $block => $updates) {
if (!isset($this->_blocks[$block])) {
continue;
}
$parent = $this->_blocks[$block];
foreach ($updates as $update) {
if (isset($update['children'])) {
foreach ($update['children'] as $childName => $childConfig) {
$type = $childConfig['type'];
$alias = isset($childConfig['alias']) ? $childConfig['alias'] : $childName;
$parent->$alias = $this->createBlock($type, $childName, $childConfig);
}
}
}
}
}
public function _save()
{
}
public function _delete()
{
}
protected function _resolveBlockClassType($type)
{
$offset = strpos($type, '/');
if ($offset === false) {
return null;
}
$module = substr($type, 0, $offset);
$block = substr($type, $offset + 1);
$module = str_replace(' ', '', ucwords(str_replace('-', ' ', $module)));
$module = str_replace(' ', '_', ucwords(str_replace('.', ' ', $module)));
$block = str_replace(' ', '', ucwords(str_replace('-', ' ', $block)));
$block = str_replace(' ', '_', ucwords(str_replace('.', ' ', $block)));
return 'Legacies_' . $module . '_Block_' . $block;
}
public function createBlock($type, $name, $config = array())
{
$className = $this->_resolveBlockClassType($type);
$children = array();
if (isset($config['children'])) {
$children = $config['children'];
unset($config['children']);
}
$actions = array();
if (isset($config['actions'])) {
$actions = $config['actions'];
unset($config['actions']);
}
try {
$reflectionClass = new ReflectionClass($className);
$instance = $reflectionClass->newInstance($config);
$this->_blocks[$name] = $instance;
foreach ($children as $name => $config) {
if (isset($config['alias'])) {
$alias = $config['alias'];
} else {
$alias = $name;
}
if (!isset($config['type'])) {
$instance->$alias = new Legacies_Core_View($config);
} else {
$instance->$alias = $this->createBlock($config['type'], $name, $config);
}
}
} catch (ReflectionException $e) {
return null;
}
$instance->setLayout($this);
foreach ($actions as $action) {
if (!isset($action['method'])) {
continue;
}
$method = $action['method'];
$params = array();
if (isset($action['params'])) {
$params = $action['params'];
}
try {
$reflectionMethod = $reflectionClass->getMethod($method);
$callParamaters = array();
foreach ($reflectionMethod->getParameters() as $parameter) {
$paramterName = $parameter->getName();
$paramterPosition = $parameter->getPosition();
if (isset($params[$paramterName])) {
$callParamaters[$paramterPosition] = $params[$paramterName];
} else if ($parameter->isDefaultValueAvailable()) {
$callParamaters[$paramterPosition] = $parameter->getDefaultValue();
} else if ($parameter->isOptionnal()) {
continue;
} else {
throw RuntimeException();
}
}
$reflectionMethod->invokeArgs($instance, $callParamaters);
} catch (ReflectionException $e) {
continue;
} catch (RuntimeException $e) {
continue;
}
}
$instance->prepareLayout();
return $instance;
}
public function getBlock($code)
{
if (isset($this->_blocks[$code])) {
return $this->_blocks[$code];
}
return null;
}
public function render()
{
foreach ($this->_blocks as $block) {
$block->beforeToHtml();
}
unset($block);
return $this->_view->render();
}
}

View file

@ -5,12 +5,15 @@ abstract class Legacies_Core_Model
{ {
protected $_originalData = array(); protected $_originalData = array();
protected $_eventPrefix = 'model';
protected $_eventObject = 'model';
public function __construct(Array $data = array()) public function __construct(Array $data = array())
{ {
$this->_data = $data; $this->_data = $data;
$this->_setOriginalData($data);
$this->_init(); $this->_init();
$this->_setOriginalData($this->_data);
} }
abstract protected function _init(); abstract protected function _init();
@ -38,11 +41,17 @@ abstract class Legacies_Core_Model
protected function _beforeSave() protected function _beforeSave()
{ {
Legacies::dispatchEvent('model.before-save', array($this->_eventObject => $this));
Legacies::dispatchEvent($this->_eventPrefix . '.before-save', array($this->_eventObject => $this));
return $this; return $this;
} }
protected function _afterSave() protected function _afterSave()
{ {
Legacies::dispatchEvent('model.after-save', array($this->_eventObject => $this));
Legacies::dispatchEvent($this->_eventPrefix . '.after-save', array($this->_eventObject => $this));
return $this; return $this;
} }
@ -64,11 +73,17 @@ abstract class Legacies_Core_Model
protected function _beforeLoad() protected function _beforeLoad()
{ {
Legacies::dispatchEvent('model.before-load', array($this->_eventObject => $this));
Legacies::dispatchEvent($this->_eventPrefix . '.before-load', array($this->_eventObject => $this));
return $this; return $this;
} }
protected function _afterLoad() protected function _afterLoad()
{ {
Legacies::dispatchEvent('model.after-load', array($this->_eventObject => $this));
Legacies::dispatchEvent($this->_eventPrefix . '.after-load', array($this->_eventObject => $this));
return $this; return $this;
} }
@ -89,11 +104,37 @@ abstract class Legacies_Core_Model
protected function _beforeDelete() protected function _beforeDelete()
{ {
Legacies::dispatchEvent('model.before-delete', array($this->_eventObject => $this));
Legacies::dispatchEvent($this->_eventPrefix . '.before-delete', array($this->_eventObject => $this));
return $this; return $this;
} }
protected function _afterDelete() protected function _afterDelete()
{ {
Legacies::dispatchEvent('model.after-delete', array($this->_eventObject => $this));
Legacies::dispatchEvent($this->_eventPrefix . '.after-delete', array($this->_eventObject => $this));
return $this; return $this;
} }
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

@ -13,6 +13,9 @@ class Legacies_Core_Model_Config
{ {
private static $_singleton = null; private static $_singleton = null;
protected $_eventPrefix = 'core.config';
protected $_eventObject = 'config';
public static function getSingleton() public static function getSingleton()
{ {
if (self::$_singleton === null) { if (self::$_singleton === null) {

View file

@ -10,11 +10,12 @@
class Legacies_Core_Model_Session class Legacies_Core_Model_Session
extends Legacies_Object extends Legacies_Object
{ {
const CRIT = 0x80; const CRIT = 0x80;
const ERROR = 0x40; const ERROR = 0x40;
const WARN = 0x20; const WARN = 0x20;
const INFO = 0x10; const INFO = 0x10;
const DEBUG = 0x01; const DEBUG = 0x01;
const SUCCESS = 0;
protected static $_instances = null; protected static $_instances = null;
@ -98,6 +99,14 @@ class Legacies_Core_Model_Session
return $this->addMessage(vsprintf($message, $args), self::WARN); return $this->addMessage(vsprintf($message, $args), self::WARN);
} }
public function addSuccess($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::SUCCESS);
}
public function addInfo($message, $_ = null) public function addInfo($message, $_ = null)
{ {
$args = func_get_args(); $args = func_get_args();
@ -113,4 +122,19 @@ class Legacies_Core_Model_Session
return $this->addMessage(vsprintf($message, $args), self::DEBUG); return $this->addMessage(vsprintf($message, $args), self::DEBUG);
} }
public function getFormKey($reset = false)
{
if (!$this->getData('form_key')) {
$this->setData('form_key', uniqid());
return $this->getData('form_key');
}
$key = $this->getData('form_key');
if ($reset == true) {
$this->setData('form_key', uniqid());
}
return $key;
}
} }

View file

@ -0,0 +1,13 @@
<?php
class Legacies_Core_Time
{
public static function init()
{
$config = include ROOT_PATH . 'config.php';
$timezone = $config['global']['date']['timezone'];
date_default_timezone_set($timezone);
}
}

View file

@ -0,0 +1,186 @@
<?php
class Legacies_Core_View
extends Legacies_Object
{
protected $_template = null;
protected $_partials = array();
protected $_layout = null;
public function __construct(Array $data = array())
{
if (isset($data['template'])) {
$this->_template = $data['template'];
unset($data['template']);
}
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::translate(Legacies::getLocale(), $message, $args);
}
public function translate($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return Legacies::translate(Legacies::getLocale(), $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($template);
}
public function setTemplate($template)
{
$this->_template = $template;
return $this;
}
public function getTemplate()
{
return $this->_template;
}
public function getUrl($uri, Array $params = array())
{
// TODO: base path integration
$serializedParams = array();
foreach ($params as $paramKey => $paramValue) {
if ($paramValue) {
$serializedParams[] = "{$paramKey}={$paramValue}";
}
}
if (count($serializedParams) > 0) {
return $uri . '?' . implode('&', $serializedParams);
}
return $uri;
}
public function getSkinUrl($uri)
{
static $baseUrl = null;
if ($baseUrl === null) {
$user = Legacies_Empire_Model_User::getSingleton();
if ($user !== null && $user->getId() && ($baseUrl = $user->getSkinPath()) == '') {
$baseUrl = DEFAULT_SKINPATH;
}
}
return $baseUrl . $uri;
}
public function setPartial($name, $content)
{
if (!is_string($content) && !$content instanceof self) {
return $this;
}
$this->_partials[$name] = $content;
return $this;
}
public function getPartial($name)
{
return $this->_partials[$name];
}
public function unsetPartial($name)
{
if (isset($this->_partials[$name])) {
unset($this->_partials[$name]);
}
return $this;
}
public function hasPartial($name)
{
return isset($this->_partials[$name]) && (is_string($this->_partials[$name]) || $this->_partials[$name] instanceof self);
}
public function __set($name, $content)
{
return $this->setPartial($name, $content);
}
public function __get($name)
{
$name = str_replace(' ', '', ucwords(str_replace('-', ' ', $name)));
$name[0] = strtolower($name[0]);
return $this->getPartial($name);
}
public function __unset($name)
{
return $this->unsetPartial($name);
}
public function __isset($name)
{
return $this->hasPartial($name);
}
public function setLayout($layout)
{
$this->_layout = $layout;
return $this;
}
public function getLayout()
{
return $this->_layout;
}
public function prepareLayout()
{
}
public function beforeToHtml()
{
}
}

View file

@ -0,0 +1,7 @@
<?php
class Legacies_Empire_Block_Overview
extends Legacies_Core_Block_Template
{
}

View file

@ -0,0 +1,7 @@
<?php
class Legacies_Empire_Block_Overview_DestroyPlanet
extends Legacies_Core_Block_Html_Form
{
}

View file

@ -0,0 +1,7 @@
<?php
class Legacies_Empire_Block_Overview_RenamePlanet
extends Legacies_Core_Block_Html_Form
{
}

View file

@ -0,0 +1,7 @@
<?php
class Legacies_Empire_Block_PlanetList
extends Legacies_Core_Block_Template
{
}

View file

@ -0,0 +1,32 @@
<?php
class Legacies_Empire_Block_Topnav
extends Legacies_Core_Block_Template
{
/**
*
* @return Legacies_Empire_Model_User
*/
public function getCurrentUser()
{
return Legacies_Empire_Model_User::getSingleton();
}
/**
*
* @return Legacies_Empire_Model_Planet
*/
public function getCurrentPlanet()
{
return $this->getCurrentUser()->getCurrentPlanet();
}
/**
*
* @return Legacies_Core_Collection
*/
public function getPlanetCollection()
{
return $this->getCurrentUser()->getPlanetCollection();
}
}

View file

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

View file

@ -67,7 +67,7 @@ abstract class Legacies_Empire_Model_BuilderAbstract
return $this; return $this;
} }
protected function getItem($itemIndex) public function getItem($itemIndex)
{ {
if (isset($this->_queue[$itemIndex])) { if (isset($this->_queue[$itemIndex])) {
return $this->_queue[$itemIndex]; return $this->_queue[$itemIndex];

View file

@ -0,0 +1,79 @@
<?php
/**
*
* Enter description here ...
*
* @uses Legacies_Object
* @uses Legacies_Empire
*/
class Legacies_Empire_Model_Fleet
extends Legacies_Core_Entity
{
protected static $_instances = array();
protected $_eventPrefix = 'fleet';
protected $_eventObject = 'fleet';
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)
{
}
public function isOwnedBy(Legacies_Empire_Model_User $user)
{
if ($this->getData('fleet_owner') == $user->getId()) {
return true;
}
return false;
}
public function isMission($missionType)
{
if ($this->getData('fleet_mission') == $missionType) {
return true;
}
return false;
}
public function getRowClass()
{
if ($this->isMission(Legacies_Empire::ID_MISSION_ATTACK) || $this->isMission(Legacies_Empire::ID_MISSION_GROUP_ATTACK)) {
return 'attack';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_TRANSPORT)) {
return 'transport';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_STATION) || $this->isMission(Legacies_Empire::ID_MISSION_STATION_ALLY)) {
return 'station';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_SETTLE_COLONY)) {
return 'settle';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_RECYCLE)) {
return 'recycle';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_DESTROY)) {
return 'destroy';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_MISSILES)) {
return 'missiles';
} else if ($this->isMission(Legacies_Empire::ID_MISSION_EXPEDITION)) {
return 'expedition';
}
}
}

View file

@ -0,0 +1,11 @@
<?php
class Legacies_Empire_Model_Galaxy_Position
extends Legacies_Core_Entity_SubTable
{
protected function _init()
{
$this->_tableName = 'galaxy';
$this->_idFieldNames = array('id_planet');
}
}

View file

@ -13,14 +13,37 @@ class Legacies_Empire_Model_Planet
const TYPE_DEBRIS = 2; const TYPE_DEBRIS = 2;
const TYPE_MOON = 3; const TYPE_MOON = 3;
protected $_eventPrefix = 'planet.'; protected $_eventPrefix = 'planet';
protected $_eventObject = 'planet';
/**
* @var Legacies_Empire_Model_User
*/
protected $_user = null; protected $_user = null;
/**
* @var Legacies_Empire_Model_Planet
*/
protected $_moon = null; protected $_moon = null;
/**
* @var Legacies_Empire_Model_Planet_Builder
*/
protected $_builder = null; protected $_builder = null;
/**
* @var Legacies_Empire_Model_Planet_Building_Shipyard
*/
protected $_shipyard = null; protected $_shipyard = null;
/**
* @var Legacies_Empire_Model_Planet_Building_Laboratory
*/
protected $_laboratory = null;
/**
* @var array
*/
protected static $_instances = array(); protected static $_instances = array();
protected static $_productionInstances = array(); protected static $_productionInstances = array();
@ -45,15 +68,13 @@ class Legacies_Empire_Model_Planet
{ {
$this->_tableName = 'planets'; $this->_tableName = 'planets';
$this->_idFieldName = 'id'; $this->_idFieldName = 'id';
$this->_builder = new Legacies_Empire_Model_Planet_Builder($this, $this->getUser());
} }
public function _afterLoad() public function _afterLoad()
{ {
parent::_afterLoad(); parent::_afterLoad();
$this->_builder->init(); $this->getBuildingQueue()->init();
return $this; return $this;
} }
@ -68,6 +89,24 @@ class Legacies_Empire_Model_Planet
return $this->setData('last_update', $time); return $this->setData('last_update', $time);
} }
public function getBuildingFields()
{
return $this->getData('field_max');
}
public function getUsedFields()
{
return $this->getData('field_current');
}
public function getGalaxyData()
{
$entity = new Legacies_Empire_Model_Galaxy_Position();
$entity->load(array('id_planet' => $this->getId()));
return $entity;
}
public function updateStorages($time = null) public function updateStorages($time = null)
{ {
Math::setPrecision(50); Math::setPrecision(50);
@ -77,7 +116,8 @@ class Legacies_Empire_Model_Planet
continue; continue;
} }
$officerEnhancement = (.5 * $this->getUser()->getData('rpg_stockeur')) + 1; //$officerEnhancement = (.5 * $this->getUser()->getData('rpg_stockeur')) + 1;
$officerEnhancement = 1;
$storageEnhancementFactor = Math::floor(Math::pow(1.6, $this[Legacies_Empire::getFieldName($resourceData['storage'])])); $storageEnhancementFactor = Math::floor(Math::pow(1.6, $this[Legacies_Empire::getFieldName($resourceData['storage'])]));
$storageEnhancement = Math::mul(BASE_STORAGE_SIZE / 2, $storageEnhancementFactor); $storageEnhancement = Math::mul(BASE_STORAGE_SIZE / 2, $storageEnhancementFactor);
@ -137,7 +177,7 @@ class Legacies_Empire_Model_Planet
$productionRatios = array(); $productionRatios = array();
foreach ($resources->getAllDatas() as $resource => $resourceData) { foreach ($resources->getAllDatas() as $resource => $resourceData) {
foreach ($resourceData['production'] as $productionUnit => $ratioField) { foreach ($resourceData['production'] as $productionUnit => $ratioField) {
if (!in_array($productionUnit, $types['prod'])) { if (!$types->is($productionUnit, Legacies_Empire::TYPE_PRODUCTION)) {
continue; continue;
} }
@ -147,7 +187,6 @@ class Legacies_Empire_Model_Planet
$productionRatios[$productionUnit] = $element->getProductionRatios($level, $ratio, $this, $this->getUser()); $productionRatios[$productionUnit] = $element->getProductionRatios($level, $ratio, $this, $this->getUser());
foreach ($productionRatios[$productionUnit] as $resourceId => $resourceProduction) { foreach ($productionRatios[$productionUnit] as $resourceId => $resourceProduction) {
$comp = Math::comp($resourceProduction, 0); $comp = Math::comp($resourceProduction, 0);
if ($comp < 0) { if ($comp < 0) {
if (!isset($resourcesConsumers[$resourceId])) { if (!isset($resourcesConsumers[$resourceId])) {
@ -189,7 +228,7 @@ class Legacies_Empire_Model_Planet
*/ */
$actualProduction = $resourcesTotals; $actualProduction = $resourcesTotals;
foreach ($resourcesTotals as $resource => $total) { foreach ($resourcesTotals as $resource => $total) {
if (Math::isPositiveOrZero($total, 0)) { if (Math::isPositiveOrZero($total)) {
continue; continue;
} }
@ -212,10 +251,28 @@ class Legacies_Empire_Model_Planet
} }
} }
// Dispatch 'planet.update-production.before' event
Legacies::dispatchEvent($this->_eventPrefix . '.update-production.before', array(
$this->_eventObject => $this,
'user' => $this->getUser(),
'productions' => $actualProduction
));
foreach ($actualProduction as $resource => $production) { foreach ($actualProduction as $resource => $production) {
$this->setData($resources[$resource]['production_field'], $production); if ($resources[$resource]['storage_field']) {
$this->setData($resources[$resource]['production_field'], $production);
} else if (isset($resourcesProductionTotals[$resource])) {
$this->setData($resources[$resource]['field'], $production);
$this->setData($resources[$resource]['production_field'], $resourcesProductionTotals[$resource]);
}
} }
// Dispatch 'planet.update-production.after' event
Legacies::dispatchEvent($this->_eventPrefix . '.update-production.after', array(
$this->_eventObject => $this,
'user' => $this->getUser()
));
return $this; return $this;
} }
@ -229,6 +286,10 @@ class Legacies_Empire_Model_Planet
$timeDiff = ($time - $this->getLastUpdate()) / 3600; $timeDiff = ($time - $this->getLastUpdate()) / 3600;
foreach ($resources->getAllDatas() as $resourceId => $resourceConfig) { foreach ($resources->getAllDatas() as $resourceId => $resourceConfig) {
if (!$resourceConfig['storage_field']) {
continue;
}
$production = Math::mul($this->getData($resourceConfig['production_field']), $timeDiff); $production = Math::mul($this->getData($resourceConfig['production_field']), $timeDiff);
$resourceValue = Math::add($this->getData($resourceConfig['field']), $production); $resourceValue = Math::add($this->getData($resourceConfig['field']), $production);
$this->setData($resourceConfig['field'], Math::min($resourceValue, $this->getData($resourceConfig['storage_field']))); $this->setData($resourceConfig['field'], Math::min($resourceValue, $this->getData($resourceConfig['storage_field'])));
@ -297,10 +358,15 @@ class Legacies_Empire_Model_Planet
return $collection; return $collection;
} }
public function getUserId()
{
return (int) $this->getData('id_owner');
}
public function getUser() public function getUser()
{ {
if ($this->_user === null) { if ($this->_user === null && $this->getUserId()) {
$this->_user = Legacies_Empire_Model_User::factory($this->getData('id_owner')); $this->_user = Legacies_Empire_Model_User::factory($this->getUserId());
} }
return $this->_user; return $this->_user;
} }
@ -327,6 +393,21 @@ class Legacies_Empire_Model_Planet
return $this; return $this;
} }
public function getLaboratory()
{
if ($this->_laboratory === null) {
$this->_laboratory = new Legacies_Empire_Model_Planet_Building_Laboratory($this, $this->getUser());
}
return $this->_laboratory;
}
public function setLaboratory(Legacies_Empire_Model_Planet_Building_Laboratory $laboratory)
{
$this->_laboratory = $laboratory;
return $this;
}
public function isPlanet() public function isPlanet()
{ {
return (bool) ($this->getData('planet_type') == self::TYPE_PLANET); return (bool) ($this->getData('planet_type') == self::TYPE_PLANET);
@ -407,6 +488,33 @@ class Legacies_Empire_Model_Planet
return (int) $this->getData('planet'); return (int) $this->getData('planet');
} }
public function getCoords()
{
return sprintf('%d:%d:%d', $this->getGalaxy(), $this->getSystem(), $this->getPosition());
}
public function getName()
{
return $this->getData('name');
}
public function setName($name)
{
$this->setData('name', $name);
return $this;
}
public function getImage()
{
return 'graphics/planeten/' . $this->getData('image') . '.jpg';
}
public function getSmallImage()
{
return 'graphics/planeten/small/s_' . $this->getData('image') . '.jpg';
}
public function setType($type) public function setType($type)
{ {
$this->setData('planet_type', $type); $this->setData('planet_type', $type);
@ -419,6 +527,50 @@ class Legacies_Empire_Model_Planet
return (int) $this->getData('planet_type'); return (int) $this->getData('planet_type');
} }
public function isDestroyed()
{
return (bool) $this->getData('destruyed');
}
public function destroy()
{
if ($this->isDebris()) {
return $this;
}
if ($this->isDestroyed()) {
throw new Legacies_Empire_Model_Planet_Exception(Legacies::__('Planet is already destroyed.'));
}
if ($this->getFleetCollection()->count() > 0) {
throw new Legacies_Empire_Model_Planet_Exception(Legacies::__("Could not delete planet until fleets aten't retuned."));
}
$user = $this->getUser();
if ($user->getHomePlanet()->getId() == $this->getId()) {
throw new Legacies_Empire_Model_Planet_Exception(Legacies::__("You can't destroy your home planet."));
}
if ($user->getCurrentPlanet()->getId() == $this->getId()) {
$homePlanet = $user->getHomePlanet();
if ($homePlanet !== null) {
$user->updateCurrentPlanet($homePlanet);
}
}
if ($this->isPlanet() && ($moon = $this->getMoon())) {
$moon->destroy();
}
$this
->setData('destruyed', true)
->setData('id_owner', 0)
->save();
return $this;
}
public function getElement($elementId) public function getElement($elementId)
{ {
$fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton(); $fields = Legacies_Empire_Model_Game_FieldsAlias::getSingleton();
@ -458,12 +610,12 @@ class Legacies_Empire_Model_Planet
} }
// Dispatch 'planet.building.append-queue.before' event // Dispatch 'planet.building.append-queue.before' event
Legacies::dispatchEvent($this->_eventPrefix . 'building.append-queue.before', array( Legacies::dispatchEvent($this->_eventPrefix . '.building.append-queue.before', array(
'bulding_id' => $buildingId, 'bulding_id' => $buildingId,
'level' => $this->getElement($buildingId), 'level' => $this->getElement($buildingId),
'planet' => $this, $this->_eventObject => $this,
'user' => $this->getUser(), 'user' => $this->getUser(),
'destroy' => $destroy 'destroy' => $destroy
)); ));
if ($destroy === false) { if ($destroy === false) {
@ -472,15 +624,15 @@ class Legacies_Empire_Model_Planet
$level = max($this->getElement($buildingId) - 1, 0); $level = max($this->getElement($buildingId) - 1, 0);
} }
$this->_builder->appendQueue($buildingId, $level, $time); $this->getBuildingQueue()->appendQueue($buildingId, $level, $time);
// Dispatch 'planet.shipyard.append-queue.after' event // Dispatch 'planet.shipyard.append-queue.after' event
Legacies::dispatchEvent($this->_eventPrefix . 'building.append-queue.after', array( Legacies::dispatchEvent($this->_eventPrefix . '.building.append-queue.after', array(
'bulding_id' => $buildingId, 'bulding_id' => $buildingId,
'level' => $this->getElement($buildingId), 'level' => $this->getElement($buildingId),
'planet' => $this, $this->_eventObject => $this,
'user' => $this->getUser(), 'user' => $this->getUser(),
'destroy' => $destroy 'destroy' => $destroy
)); ));
return $this; return $this;
@ -493,30 +645,52 @@ class Legacies_Empire_Model_Planet
} }
// Dispatch event // Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'update-queue.before', array( Legacies::dispatchEvent($this->_eventPrefix . '.update-queue.before', array(
'time' => &$time, 'time' => &$time,
'planet' => $this->_currentPlanet, $this->_eventObject => $this->_currentPlanet,
'user' => $this->_currentUser 'user' => $this->_currentUser
)); ));
$this->_builder->updateQueue($time); $this->getBuildingQueue()->updateQueue($time);
// Dispatch event // Dispatch event
Legacies::dispatchEvent($this->_eventPrefix . 'update-queue.after', array( Legacies::dispatchEvent($this->_eventPrefix . '.update-queue.after', array(
'time' => $time, 'time' => $time,
'shipyard' => $this, 'shipyard' => $this,
'planet' => $this->_currentPlanet, $this->_eventObject => $this->_currentPlanet,
'user' => $this->_currentUser 'user' => $this->_currentUser
)); ));
return $this; return $this;
} }
/**
*
* @return Legacies_Empire_Model_Planet_Builder
*/
public function getBuildingQueue() public function getBuildingQueue()
{ {
if ($this->_builder === null) {
$this->_builder = new Legacies_Empire_Model_Planet_Builder($this, $this->getUser());
}
return $this->_builder; return $this->_builder;
} }
/**
*
* Enter description here ...
* @return Legacies_Empire_Model_Planet
*/
public function dequeueBuilding()
{
$this->getBuildingQueue()->rewind();
$item = $this->getBuildingQueue()->current();
$this->getBuildingQueue()->dequeueFirstItem(Legacies::now());
return $this;
}
/** /**
* Check if a building is actually buildable on the current planet, * Check if a building is actually buildable on the current planet,
* depending on the technology and buildings requirements. * depending on the technology and buildings requirements.
@ -526,15 +700,15 @@ class Legacies_Empire_Model_Planet
*/ */
public function checkAvailability($buildingId) public function checkAvailability($buildingId)
{ {
$this->_builder->checkAvailability($buildingId); $this->getBuildingQueue()->checkAvailability($buildingId);
try { try {
// Dispatch event. Throw an exception to break the avaliability. // Dispatch event. Throw an exception to break the avaliability.
Legacies::dispatchEvent($this->_eventPrefix . 'check-availability', array( Legacies::dispatchEvent($this->_eventPrefix . '.check-availability', array(
'ship_id' => $buildingId, 'ship_id' => $buildingId,
'shipyard' => $this, 'shipyard' => $this,
'planet' => $this->_currentPlanet, $this->_eventObject => $this->_currentPlanet,
'user' => $this->_currentUser 'user' => $this->_currentUser
)); ));
} catch (Exception $e) { } catch (Exception $e) {
return false; return false;
@ -551,7 +725,7 @@ class Legacies_Empire_Model_Planet
*/ */
public function getResourcesNeeded($buildingId, $level) public function getResourcesNeeded($buildingId, $level)
{ {
return $this->_builder->getResourcesNeeded($buildingId, $level); return $this->getBuildingQueue()->getResourcesNeeded($buildingId, $level);
} }
/** /**
@ -562,7 +736,7 @@ class Legacies_Empire_Model_Planet
*/ */
public function getBuildingTime($buildingId, $level) public function getBuildingTime($buildingId, $level)
{ {
return $this->_builder->getBuildingTime($buildingId, $level); return $this->getBuildingQueue()->getBuildingTime($buildingId, $level);
} }
public static function registrationListener($eventData) public static function registrationListener($eventData)
@ -683,4 +857,38 @@ class Legacies_Empire_Model_Planet
$planet->setLastUpdate($time); $planet->setLastUpdate($time);
} }
} }
public function getResourceAmount($resourceType)
{
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
$resourceConfig = $resources->getData($resourceType);
if ($resourceConfig === null) {
return null;
}
return $this->getData($resourceConfig['field']);
}
public function getResourceCap($resourceType)
{
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
$resourceConfig = $resources->getData($resourceType);
if ($resourceConfig === null) {
return null;
}
if ($resourceConfig['storage_field'] === null) {
return $this->getData($resourceConfig['production_field']);
}
return $this->getData($resourceConfig['storage_field']);
}
public function isResourceCapped($resourceType)
{
if (Math::comp($this->getResourceAmount($resourceType), $this->getResourceCap($resourceType)) >= 0) {
return true;
}
return false;
}
} }

View file

@ -19,7 +19,7 @@ class Legacies_Empire_Model_Planet_Builder
$level = func_get_arg(1); $level = func_get_arg(1);
$time = func_get_arg(2); $time = func_get_arg(2);
return new Legacies_Empire_Model_Planet_Building_Shipyard_Item(array( return new Legacies_Empire_Model_Planet_Builder_Item(array(
'building_id' => $buildingId, 'building_id' => $buildingId,
'level' => $level, 'level' => $level,
'created_at' => $time, 'created_at' => $time,
@ -166,4 +166,27 @@ class Legacies_Empire_Model_Planet_Builder
return $this; 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 dequeueFirstItem($time)
{
$types = Legacies_Empire_Model_Game_Types::getSingleton();
$resources = Legacies_Empire_Model_Game_Resources::getSingleton();
if (!Math::isPositive($level)) {
return $this;
}
// FIXME
$this->_currentPlanet->setData('b_building_id', $this->serialize());
return $this;
}
} }

View file

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

View file

@ -0,0 +1,3 @@
<?php
class Legacies_Empire_Model_Planet_Exception implements Legacies_Core_Exception {}

View file

@ -0,0 +1,19 @@
<?php
class Legacies_Empire_Model_Planet_Ship_LargeTransport
extends Legacies_Empire_Model_Planet_ShipAbstract
{
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE = 4;
public function getBaseSpeed(Legacies_Empire_Model_User $user)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
return $prices[Legacies_Empire::ID_SHIP_LARGE_TRANSPORT][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
}
public function getSpeedMultiplier(Legacies_Empire_Model_User $user)
{
return pow(1.1, $user->getElement(Legacies_Empire::ID_RESEARCH_COMBUSTION_DRIVE));
}
}

View file

@ -1,7 +1,7 @@
<?php <?php
class Legacies_Empire_Model_Planet_Ship_LightTransport class Legacies_Empire_Model_Planet_Ship_LightTransport
implements Legacies_Empire_Model_Planet_ShipInterface extends Legacies_Empire_Model_Planet_ShipAbstract
{ {
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE = 4; const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE = 4;

View file

@ -1,7 +1,8 @@
<?php <?php
class Legacies_Empire_Model_Planet_Ship_SolarSatellite class Legacies_Empire_Model_Planet_Ship_SolarSatellite
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_ShipInterface extends Legacies_Empire_Model_Planet_ShipAbstract
implements Legacies_Empire_Model_Planet_ResourceProductionInterface
{ {
public function getProductionRatios($quantity, $produtionRatio, $planet, $user) public function getProductionRatios($quantity, $produtionRatio, $planet, $user)
{ {
@ -10,12 +11,22 @@ class Legacies_Empire_Model_Planet_Ship_SolarSatellite
); );
} }
public function getMaximumSpeed(Legacies_Empire_Model_User $user) public function getBaseSpeed(Legacies_Empire_Model_User $user)
{ {
return 0; return 0;
} }
public function getActualMaximumSpeed(Legacies_Empire_Model_User $user) public function getSpeedMultiplier(Legacies_Empire_Model_User $user)
{
return 0;
}
public function getActualSpeed(Legacies_Empire_Model_User $user)
{
return 0;
}
public function getBaseConsumption(Legacies_Empire_Model_User $user)
{ {
return 0; return 0;
} }

View file

@ -1,7 +1,8 @@
<?php <?php
class Legacies_Empire_Model_Planet_Ship_Supernova class Legacies_Empire_Model_Planet_Ship_Supernova
implements Legacies_Empire_Model_Planet_ResourceProductionInterface, Legacies_Empire_Model_Planet_ShipInterface extends Legacies_Empire_Model_Planet_ShipAbstract
implements Legacies_Empire_Model_Planet_ResourceProductionInterface
{ {
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE = 20; const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE = 20;
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY = 15; const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY = 15;

View file

@ -0,0 +1,27 @@
<?php
abstract class Legacies_Empire_Model_Planet_ShipAbstract
implements Legacies_Empire_Model_Planet_ShipInterface
{
public function getBaseSpeed(Legacies_Empire_Model_User $user)
{
$prices = Legacies_Empire_Model_Game_Prices::getSingleton();
return $prices[Legacies_Empire::ID_SHIP_SUPERNOVA][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
}
public function getSpeedMultiplier(Legacies_Empire_Model_User $user)
{
return pow(1.1, $user->getElement(Legacies_Empire::ID_RESEARCH_COMBUSTION_DRIVE));
}
public function getActualSpeed(Legacies_Empire_Model_User $user)
{
return $this->getBaseSpeed($user) * $this->getSpeedMultiplier($user);
}
public function getActualConsumption(Legacies_Empire_Model_User $user, $speed)
{
return $this->getBaseConsumption($user) * ($speed / 100) * $this->getSpeedMultiplier($user);
}
}

View file

@ -0,0 +1,11 @@
<?php
interface Legacies_Empire_Model_Planet_ShipInterface
{
public function getBaseSpeed(Legacies_Empire_Model_User $user);
public function getSpeedMultiplier(Legacies_Empire_Model_User $user);
public function getActualSpeed(Legacies_Empire_Model_User $user);
public function getBaseConsumption(Legacies_Empire_Model_User $user);
public function getActualConsumption(Legacies_Empire_Model_User $user, $speed);
}

View file

@ -14,6 +14,11 @@ class Legacies_Empire_Model_User
protected static $_singleton = null; protected static $_singleton = null;
protected $_eventPrefix = 'user';
protected $_eventObject = 'user';
public static $hashCallback = 'md5';
const SESSION_KEY = 'user'; const SESSION_KEY = 'user';
const COOKIE_NAME = 'legacies'; const COOKIE_NAME = 'legacies';
const COOKIE_LIFETIME = 2592000; const COOKIE_LIFETIME = 2592000;
@ -90,6 +95,15 @@ class Legacies_Empire_Model_User
return self::$_singleton; return self::$_singleton;
} }
public static function hash($password, $salt = null)
{
if ($salt === null) {
return call_user_func(self::$hashCallback, ($password));
}
return call_user_func(self::$hashCallback, ($password . $salt));
}
protected function _init() protected function _init()
{ {
$this->setIdFieldName('id'); $this->setIdFieldName('id');
@ -118,23 +132,29 @@ class Legacies_Empire_Model_User
public static function login($username, $password, $remember = false) public static function login($username, $password, $remember = false)
{ {
static $statement = null;
$session = Legacies::getSession(self::SESSION_KEY); $session = Legacies::getSession(self::SESSION_KEY);
$collection = new Legacies_Core_Collection(array('user' => 'users')); try {
$collection $collection = new Legacies_Core_Collection(array('user' => 'users'));
->column('user.id')
->column('user.username') $passwordHash = md5($password);
->column('user.banaday') $collection
->column('(CASE WHEN MD5(:password)=user.password THEN 1 ELSE 0 END) AS login_success') ->column('user.id')
->column('CONCAT((@salt:=MID(MD5(RAND()), 0, 4)), SHA1(CONCAT(user.username, user.password, @salt))) AS login_rememberme') ->column('user.username')
->where('user.username=:username') ->column('user.password')
->load(array( ->column('user.banaday')
'username' => $username, ->column('CONCAT((@salt:=MID(MD5(RAND()), 0, 4)), SHA1(CONCAT(user.username, user.password, @salt))) AS login_rememberme')
'password' => $password ->column('(CASE WHEN user.password="' . $passwordHash . '" THEN 1 ELSE 0 END) AS login_success')
)) ->where('user.username=:username')
; ->load(array(
'username' => $username
))
;
} catch (Legacies_Core_Model_Exception $e) {
Legacies_Core_ErrorProfiler::getSingleton()->exceptionManager($e);
$session->addError('No such user.');
return null;
}
if ($collection->count() <= 0) { if ($collection->count() <= 0) {
$session->addError('No such user.'); $session->addError('No such user.');
@ -197,33 +217,97 @@ class Legacies_Empire_Model_User
return $user; return $user;
} }
public function updateCurrentPlanet($planetId) /**
*
* Enter description here ...
* @param int|Legacies_Empire_Model_Planet $planet
*/
public function updateCurrentPlanet($planet)
{ {
$planetColelction = $this->_preparePlanetCollection()->where('id=:id'); if (!$planetId instanceof Legacies_Empire_Model_Planet) {
$planetColelction = $this->_preparePlanetCollection()->where('id=:id');
$planetCollection->load(array( $planetCollection->load(array(
'id' => $planetId, 'id' => $planet,
'user' => $this->getId() 'user' => $this->getId()
)); ));
if ($planetCollection->count() !== 1) { if ($planetCollection->count() !== 1) {
return false; return $this;
}
$planet = $planetCollection->current();
} }
$planet = $planetCollection->current(); if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
$this->setData('current_planet', $planet->getId()); return $this;
}
return true; $this->setData('current_planet', $planet->getId())->save();
return $this;
} }
/**
*
* Enter description here ...
* @param Legacies_Empire_Model_Planet $planet
*/
public function setCurrentPlanet(Legacies_Empire_Model_Planet $planet)
{
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return $this;
}
$this->setData('current_planet', $planet->getId());
return $this;
}
/**
*
* Enter description here ...
* @return Legacies_Empire_Model_Planet
*/
public function getHomePlanet()
{
$planetId = $this->getData('id_planet');
if (!$planetId) {
return null;
}
$planet = Legacies_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return null;
}
return $planet;
}
/**
*
* Enter description here ...
* @return Legacies_Empire_Model_Planet
*/
public function getCurrentPlanet() public function getCurrentPlanet()
{ {
$planetId = $this->getData('current_planet'); $planetId = $this->getData('current_planet');
if (!$planetId) { if (!$planetId) {
$planetId = $this->getData('id_planet'); $planet = $this->getHomePlanet();
$this->setData('current_planet', $planetId)->save(); $this->setData('current_planet', $planet->getId())->save();
return $planet;
} }
return Legacies_Empire_Model_Planet::factory($planetId);
$planet = Legacies_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return null;
}
return $planet;
} }
protected function _preparePlanetCollection() protected function _preparePlanetCollection()
@ -345,4 +429,59 @@ class Legacies_Empire_Model_User
return $this; return $this;
} }
public function checkPassword($password)
{
if (self::hash($password) == $this->getData('password')) {
return true;
}
return false;
}
public function getFleetCollection($time = null)
{
$firstCollection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$firstCollection
->column('*')
->where('fleet.fleet_owner = :user')
;
$backCollection = new Legacies_Core_Collection(array('fleet' => 'fleets'));
$backCollection
->column('*')
->where('fleet.fleet_target_owner = :user')
;
$options = array(
'user' => $this->getId()
);
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 getNewMessagesCount()
{
$messageCollection = new Legacies_Core_Collection('messages');
$messageCollection->where('message_owner=:user');
$messageCollection->where('message_read_at<=0');
$newMessages = null;
if (($count = $messageCollection->getSize(array('user' => $this->getId()))) > 0) {
return $count;
}
return null;
}
} }

View file

@ -0,0 +1,11 @@
<?php
class Legacies_Empire_Model_User_Message
extends Legacies_Core_Entity_SubTable
{
protected function _init()
{
$this->_tableName = 'messages';
$this->_idFieldNames = array('message_id', 'message_owner');
}
}

View file

@ -79,24 +79,4 @@ class Legacies_Object
{ {
return $this->unsetData($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

@ -0,0 +1,37 @@
<?php
class Legacies_Officers_Model_Observer
{
public static function planetUpdateListener($eventData)
{
if (isset($eventData['planet'])) {
$planet = $eventData['planet'];
$user = $planet->getUser();
$level = floor(sqrt($user->getData('xpminier') / 500));
if ($user->getData('lvl_minier') < $level) {
$difference = $level - $user->getData('lvl_minier');
if ($difference == 1) {
Legacies::getSession(Legacies_Empire_Model_User::SESSION_KEY)
->addInfo('You gained 1 miner level.');
} else {
Legacies::getSession(Legacies_Empire_Model_User::SESSION_KEY)
->addInfo('You gained %1$d miner level.', (int) $difference);
}
}
$level = floor(sqrt($user->getData('xpraid')));
if ($user->getData('lvl_raid') < $level) {
$difference = $level - $user->getData('lvl_raid');
if ($difference == 1) {
Legacies::getSession(Legacies_Empire_Model_User::SESSION_KEY)
->addInfo('You gained 1 raider level.');
} else {
Legacies::getSession(Legacies_Empire_Model_User::SESSION_KEY)
->addInfo('You gained %1$d raider level.', (int) $difference);
}
}
}
}
}

View file

@ -18,7 +18,7 @@ class Math
public static function getSingleton() public static function getSingleton()
{ {
if (self::$_singleton === null) { if (self::$_singleton === null) {
if (extension_loaded('bcmath')) { if (extension_loaded('bcmath') && defined('BCNUMBERS')) {
self::$_singleton = new Math_Bcmath(); self::$_singleton = new Math_Bcmath();
} else { } else {
self::$_singleton = new Math_Native(); self::$_singleton = new Math_Native();

View file

@ -83,9 +83,12 @@ class Math_Bcmath
if (!$a) { if (!$a) {
return '0'; return '0';
} }
$a = strval($a);
$pos = strrpos(strval($a), '.'); $pos = strrpos($a, '.');
$a = substr(strval($a), 0, $pos); if ($pos !== false) {
$a = substr($a, 0, $pos);
}
$length = $pos + ((3 - ($pos % 3)) % 3); $length = $pos + ((3 - ($pos % 3)) % 3);
$a = str_pad($a, $length, ' ', STR_PAD_LEFT); $a = str_pad($a, $length, ' ', STR_PAD_LEFT);

View file

@ -38,7 +38,7 @@ class Math_Native
public function comp($a, $b) public function comp($a, $b)
{ {
return ($a > $b) ? 1 : ($a < $b) ? -1 : 0; return ($a > $b) ? 1 : (($a < $b) ? -1 : 0);
} }
public function ceil($x) public function ceil($x)
@ -56,8 +56,8 @@ class Math_Native
return round($x, $range); return round($x, $range);
} }
public function render($a, $b) public function render($a)
{ {
return strval(number_format($a, 0, ',', '.')); return number_format($a, 0, ',', '.');
} }
} }

View file

@ -0,0 +1,46 @@
<?php return array(
'overview' => array(
'update' => '1column',
'reference' => array(
'content' => array(
'children' => array(
'overview.forms' => array(
'type' => 'core/concat'
),
'overview' => array(
'type' => 'empire/overview',
'template' => 'empire/overview.phtml'
),
)
)
)
),
'overview.rename-planet' => array(
'update' => 'overview',
'reference' => array(
'overview.forms' => array(
'children' => array(
'rename-planet' => array(
'type' => 'empire/overview.rename-planet',
'template' => 'empire/overview/form/rename-planet.phtml'
),
)
)
)
),
'overview.destroy-planet' => array(
'update' => 'overview',
'reference' => array(
'overview.forms' => array(
'children' => array(
'destroy-planet' => array(
'type' => 'empire/overview.destroy-planet',
'template' => 'empire/overview/form/destroy-planet.phtml'
),
)
)
)
)
);

View file

@ -0,0 +1,120 @@
<?php return array(
'1column' => array(
'update' => 'default'
),
'2columns-left' => array(
'update' => 'default',
'template' => 'page/2columns-left.phtml',
'reference' => array(
'root' => array(
'children' => array(
'left' => array(
'type' => 'core/concat'
),
)
)
)
),
'2columns-right' => array(
'update' => 'default',
'template' => 'page/2columns-right.phtml',
'reference' => array(
'root' => array(
'children' => array(
'right' => array(
'type' => 'core/concat'
),
)
)
)
),
'3columns' => array(
'update' => 'default',
'template' => 'page/3columns.phtml',
'reference' => array(
'root' => array(
'children' => array(
'left' => array(
'type' => 'core/concat'
),
'right' => array(
'type' => 'core/concat'
),
)
)
)
),
'default' => array(
'type' => 'core/html.page',
'template' => 'page/1column.phtml',
'children' => array(
'head' => array(
'type' => 'core/html.head',
'template' => 'page/html/head.phtml',
'actions' => array(
array(
'method' => 'addCss',
'params' => array(
'stylesheet' => 'css/default.css'
)
),
array(
'method' => 'addCss',
'params' => array(
'stylesheet' => 'css/formate.css'
)
)
)
),
'header' => array(
'type' => 'core/template',
'template' => 'page/html/header.phtml',
'children' => array(
'menu' => array(
'type' => 'core/html.navigation',
'template' => 'page/html/navigation.phtml',
),
'planet-list' => array(
'type' => 'empire/planet-list',
'template' => 'empire/planet-list.phtml',
)
)
),
'footer' => array(
'type' => 'core/template',
'template' => 'page/html/footer.phtml'
),
'content' => array(
'type' => 'core/concat'
)
)
),
'ajax' => array(
'type' => 'core/html.page',
'template' => 'page/empty.phtml',
'children' => array(
'content' => array(
'type' => 'core/concat'
)
)
),
'empty' => array(
'type' => 'core/html.page',
'template' => 'page/empty.phtml',
'children' => array(
'head' => array(
'type' => 'core/html.head',
'template' => 'page/html/head.phtml'
),
'content' => array(
'type' => 'core/concat'
)
)
),
);

View file

@ -0,0 +1 @@
<?php

View file

@ -0,0 +1 @@
<?php

View file

@ -0,0 +1,10 @@
<form name="destroy-planet" id="overview:destroy-planet" method="post" action="">
<fieldset>
<input type="hidden" name="form_key" value="<?php echo $this->getFormKey()?>" />
<label for="overview:destroy-planet:password"><?php echo $this->__('Password:')?></label>
<input id="overview:destroy-planet:password" type="password" name="password" />
<label for="overview:destroy-planet:confirm"><?php echo $this->__('I want to destroy this planet')?></label>
<input id="overview:destroy-planet:confirm" type="checkbox" name="confirm" />
<input type="submit" />
</fieldset>
</form>

View file

@ -0,0 +1,10 @@
<form name="rename-planet" id="overview:rename-planet" method="post" action="">
<fieldset>
<input type="hidden" name="form_key" value="<?php echo $this->getFormKey()?>" />
<label for="overview:rename-planet:password"><?php echo $this->__('Password:')?></label>
<input id="overview:rename-planet:password" type="password" name="password" />
<label for="overview:rename-planet:name"><?php echo $this->__('New name:')?></label>
<input id="overview:rename-planet:name" type="text" name="name" />
<input type="submit" />
</fieldset>
</form>

View file

@ -0,0 +1,11 @@
<?php if ($this['count'] > 0):?>
<tr>
<th colspan=4>
<?php if ($this['count'] == 1):?>
<a href=messages.php><?php echo $this->__('You have 1 unread message.')?></a>
<?php else:?>
<a href=messages.php><?php echo $this->__('You have %1$d unread messages.', $this['count'])?></a>
<?php endif?>
</th>
</tr>
<?php endif?>

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