Refactored to 2 namespaces: Wootook & Legacies

Signed-off-by: Gregory PLANCHAT <g.planchat@gmail.com>
This commit is contained in:
Gregory PLANCHAT 2011-10-04 19:57:00 +02:00
commit ec7e40e1aa
1004 changed files with 4808 additions and 2971 deletions

View file

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

View file

@ -0,0 +1,10 @@
<?php
class Wootook_Core_Block_Deprecated
extends Wootook_Core_Block_Template
{
public function getScriptPath()
{
return $this->getLayout()->getScriptPath();
}
}

View file

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

View file

@ -0,0 +1,145 @@
<?php
class Wootook_Core_Block_Html_Head
extends Wootook_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($js['type'])) {
$js['type'] = 'text/javascript';
}
$render .=<<<HTML_EOF
<script type="{$js['type']}" src="{$js['path']}"></script>
HTML_EOF;
}
return $render;
}
}

View file

@ -0,0 +1,66 @@
<?php
class Wootook_Core_Block_Html_Navigation
extends Wootook_Core_Block_Template
{
public function addLink($name, $label, $title, $uri, Array $params = array(), Array $classes = array(), $template = null)
{
$explodedPath = explode('/', $name);
$baseName = array_pop($explodedPath);
$parent = $this->_getNode($explodedPath);
$child = $this->getLayout()
->createBlock('core/html.navigation.link', $this->getNameInLayout() . '.' . $baseName, array(
'url' => array(
'uri' => $uri,
'params' => $params
),
'label' => $label,
'title' => $title,
'classes' => $classes
));
$parent->setPartial($baseName, $child);
if ($template !== null) {
$child->setTemplate($template);
}
return $this;
}
public function setNodeTitle($path, $title)
{
return $this->getNode($path)->setTitle($title);
}
public function setNodeTemplate($path, $template)
{
return $this->getNode($path)->setTemplate($template);
}
public function getNode($path)
{
return $this->_getNode(explode('/', $path));
}
protected function _getNode($explodedPath)
{
$name = array_shift($explodedPath);
if ($this->hasPartial($name)) {
$child = $this->getPartial($name)->_getNode($explodedPath);
} else {
$child = $this->getLayout()
->createBlock('core/html.navigation.node', $this->getNameInLayout() . '.' . $name);
}
if ($child instanceof Wootook_Core_Block_Html_Navigation_Link) {
throw new Wootook_Core_Exception_RuntimeException('Node is a link. Could not append a child node to a link node.');
}
if (count($explodedPath) == 0) {
return $child;
}
return $child->_getNode($explodedPath);
}
}

View file

@ -0,0 +1,116 @@
<?php
class Wootook_Core_Block_Html_Navigation_Link
extends Wootook_Core_Block_Template
{
protected $_label = '';
protected $_title = '';
protected $_uri = '';
protected $_params = array();
protected $_classes = array('link');
public function getTemplate()
{
if ($this->_template !== null) {
return $this->_template;
}
return 'page/html/navigation/link.phtml';
}
public function setLabel($label)
{
$this->_label = $label;
return $this;
}
public function getLabel()
{
return $this->_label;
}
public function setTitle($title)
{
$this->_title = $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setUrl($uri, $params = array())
{
$this->_uri = $uri;
$this->_params = $params;
return $this;
}
public function getLinkUrl($moreParams = array())
{
$params = array_merge($this->_params, $moreParams);
return $this->getUrl($this->_uri, $params);
}
public function addClass($class)
{
$this->_classes[] = $class;
return $this;
}
public function clearClasses()
{
$this->_classes = array();
return $this;
}
public function renderClasses($moreClasses)
{
$classes = array_merge($this->_classes, $moreClasses);
return implode(' ', $classes);
}
public function __construct(Array $data = array())
{
if (isset($data['label'])) {
$this->setLabel($data['label']);
unset($data['label']);
}
if (isset($data['title'])) {
$this->setTitle($data['title']);
unset($data['title']);
}
if (isset($data['url'])) {
if (is_array($data['url']) && isset($data['url']['uri'])) {
if (isset($data['url']['params'])) {
$this->setUrl($data['url']['uri'], $data['url']['params']);
} else {
$this->setUrl($data['url']['uri']);
}
} else {
$this->setUrl($data['url']);
}
unset($data['url']);
}
if (isset($data['classes'])) {
$classes = (array) $data['classes'];
unset($data['classes']);
foreach ($classes as $class) {
$this->set($class);
}
}
parent::__construct($data);
return $this;
}
}

View file

@ -0,0 +1,27 @@
<?php
class Wootook_Core_Block_Html_Navigation_Node
extends Wootook_Core_Block_Html_Navigation
{
protected $_title = '';
public function setTitle($title)
{
$this->_title = $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function getTemplate()
{
if ($this->_template !== null) {
return $this->_template;
}
return 'page/html/navigation/node.phtml';
}
}

View file

@ -0,0 +1,19 @@
<?php
class Wootook_Core_Block_Html_Page
extends Wootook_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,36 @@
<?php
class Wootook_Core_Block_Template
extends Wootook_Core_View
{
protected function _getTemplatePath($file)
{
$pattern = "{$this->getScriptPath()}/%s/%s/scripts/{$file}";
if (($layout = $this->getLayout()) !== null) {
$package = $this->getLayout()->getPackage();
$theme = $this->getLayout()->getTheme();
if ($package !== Wootook_Core_Layout::DEFAULT_PACKAGE) {
if ($theme !== Wootook_Core_Layout::DEFAULT_THEME) {
$path = sprintf($pattern, $package, $theme);
if (Wootook::fileExists($path)) {
return $path;
}
}
$path = sprintf($pattern, $package, Wootook_Core_Layout::DEFAULT_THEME);
if (Wootook::fileExists($path)) {
return $path;
}
}
}
$path = sprintf($pattern, Wootook_Core_Layout::DEFAULT_PACKAGE, Wootook_Core_Layout::DEFAULT_THEME);
if (Wootook::fileExists($path)) {
return $path;
}
trigger_error("Template '{$file}' could not be found.", E_USER_ERROR);
return null;
}
}

View file

@ -0,0 +1,28 @@
<?php
class Wootook_Core_Block_Text
extends Wootook_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

@ -0,0 +1,366 @@
<?php
class Wootook_Core_Collection
extends Wootook_Core_Model
implements Iterator, Countable
{
protected $_tableName = null;
protected $_tableAlias = null;
protected $_entityClassName = 'Wootook_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 = Wootook_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 = Wootook_Database::getSingleton();
}
if (is_array($table)) {
$alias = key($table);
$table = current($table);
foreach ($fields as $fieldAlias => $fieldName) {
$this->column("{$alias}.{$field}", $fieldAlias);
}
$this->_join[] = "{$mode} JOIN {$database->getTable($table)} AS {$alias} ON {$condition}";
} else {
foreach ($fields as $field) {
$this->column("{$field}");
}
$this->_join[] = "{$mode} JOIN {$database->getTable($table)} ON {$condition}";
}
return $this;
}
public function order($field, $direction = 'ASC')
{
$this->_order[] = "{$field} {$direction}";
return $this;
}
public function union($collection)
{
$this->_union[] = $collection;
return $this;
}
public function limit($limit, $offset = null)
{
$this->_limit = intval($limit);
$this->_offset = $offset;
return $this;
}
public function group($groupField)
{
$this->_group[] = $groupField;
return $this;
}
protected function _prepareSql()
{
if (empty($this->_union)) {
$database = Wootook_Database::getSingleton();
$fields = array();
foreach ($this->_columns as $field) {
$fieldName = current($field);
$fieldAlias = key($field);
if (is_string($fieldAlias)) {
$fields[] = "{$fieldName} AS {$fieldAlias}";
} else {
$fields[] = $fieldName;
}
}
if (!empty($fields)) {
$fields = implode(", ", $fields);
} else {
$fields = '*';
}
if (!empty($this->_where)) {
$where = 'WHERE (' . implode(") AND (", $this->_where) . ')';
} else {
$where = '';
}
$joinedTables = implode("\n ", $this->_join);
$order = '';
if (!empty($this->_order)) {
$order = 'ORDER BY ' . implode(", ", $this->_order);
}
$alias = '';
if ($this->_tableAlias !== null) {
$alias = " AS {$this->_tableAlias}";
}
$limit = '';
if ($this->_limit) {
if ($this->_offset) {
$limit = "LIMIT {$this->_limit}, {$this->_offset}";
} else {
$limit = "LIMIT {$this->_limit}";
}
}
$group = '';
if (!empty($this->_group)) {
$group = 'GROUP BY ' . implode(', ', $this->_group);
}
return <<<SQL_EOF
SELECT {$fields}
FROM {$database->getTable($this->getTableName())}{$alias}
{$joinedTables}
{$where}
{$group}
{$order}
{$limit}
SQL_EOF;
} else {
$statements = array();
foreach ($this->_union as $statement) {
$statements[] = $statement->_prepareSql();
}
$statements = '(' . implode(') UNION (', $statements) . ')';
if (!empty($where)) {
$where = 'WHERE ' . implode(" AND ", $this->_where);
} else {
$where = '';
}
$where = implode(" AND ", $this->_where);
$limit = '';
if ($this->_limit) {
if ($this->_offset) {
$limit = "LIMIT {$this->_limit}, {$this->_offset}";
} else {
$limit = "LIMIT {$this->_limit}";
}
}
return <<<SQL_EOF
$statements
{$where}
{$limit}
SQL_EOF;
}
}
public function __toString()
{
return $this->_prepareSql();
}
protected function _load()
{
$sql = $this->_prepareSql();
$database = Wootook_Database::getSingleton();
$statement = $database->prepare($sql);
$args = func_get_args();
$statement->execute(array_shift($args));
$this->_items = array();
if (func_num_args() > 1) {
$reflection = new ReflectionClass(array_shift($args));
} else {
$reflection = new ReflectionClass($this->getEntityClassName());
}
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$params = array_merge(array($row), $args);
$this->_items[] = $reflection->newInstanceArgs($params);
}
return $this;
}
protected function _save()
{
foreach ($this->_items as $child) {
$child->save();
}
return $this;
}
protected function _delete()
{
foreach ($this->_items as $child) {
$child->delete();
}
return $this;
}
public function getSize()
{
$clone = clone $this;
$clone->_fields = array();
$clone->column('1');
$sql = $clone->_prepareSql();
$database = Wootook_Database::getSingleton();
$statement = $database->prepare($sql);
$args = func_get_args();
$statement->execute(array_shift($args));
$count = $statement->rowCount();
$statement->closeCursor();
return $count;
}
public function count()
{
return count($this->_items);
}
public function current()
{
return current($this->_items);
}
public function next()
{
next($this->_items);
return $this;
}
public function rewind()
{
reset($this->_items);
return $this;
}
public function key()
{
return key($this->_items);
}
public function valid()
{
return current($this->_items) !== false;
}
public function getFirstItem()
{
if (!$this->_)
if (count($this->_items) > 0) {
return $this->_items[0];
}
return null;
}
public function getLastItem()
{
$size = count($this->_items);
if ($size > 0) {
return $this->_items[$size - 1];
}
return null;
}
}

View file

@ -0,0 +1,50 @@
<?php
class Wootook_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()->setRedirect($url);
return $this;
}
}

View file

@ -0,0 +1,102 @@
<?php
class Wootook_Core_Controller_Request_Http
extends Wootook_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];
}
public function getServer($key, $default = null)
{
if (!isset($_SERVER[$key])) {
return $default;
}
return $_SERVER[$key];
}
public function isPost()
{
if (strtoupper($this->getServer('REQUEST_METHOD')) == 'POST') {
return true;
}
return false;
}
public function isGet()
{
if (strtoupper($this->getServer('REQUEST_METHOD')) == 'GET') {
return true;
}
return false;
}
}

View file

@ -0,0 +1,158 @@
<?php
class Wootook_Core_Controller_Response_Http
extends Wootook_Object
{
const REDIRECT_MOVED_PERMANENTLY = 301;
const REDIRECT_FOUND = 302;
const REDIRECT_SEE_OTHER = 303;
const REDIRECT_TEMPORARY = 307;
protected static $_redirectCodes = array(
REDIRECT_MOVED_PERMANENTLY => 'Moved Permanently',
REDIRECT_FOUND => 'Found',
REDIRECT_SEE_OTHER => 'See Other',
REDIRECT_TEMPORARY => 'Temporary Redirect'
);
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;
}
public function setRedirect($url, $code = self::REDIRECT_FOUND)
{
if (!in_array($code, self::$_redirectCodes)) {
$code = self::REDIRECT_FOUND;
}
$statusText = self::$_redirectCodes[$code];
$this->setRawHeader("HTTP/1.1 {$code} {$statusText}")
->setHeader('Location', $url)
->setIsRedirect(true);
return $this;
}
}

View file

@ -0,0 +1,32 @@
<?php
class Wootook_Core_Email
{
protected static $_defaultHeadrs = array(
);
protected $_headers = array();
public function send($to, $from, $subject, $body, Array $headers = array())
{
$this->_prepareHeaders($headers);
}
public function setHeader($name, $value)
{
$this->_headers[$name] = $value;
}
protected function _prepareHeaders($headers)
{
foreach ($headers as $name => $value) {
$this->setHeader($name, $value);
}
$this->addHeader('X-Mailer', 'PHP/' . PHP_VERSION . ' Wootook/' . VERSION);
$this->addHeader('Content-Transfer-Encoding', '7bit');
$this->addHeader('Content-Type', 'text/plain; charset=utf-8');
return $this;
}
}

View file

@ -0,0 +1,153 @@
<?php
abstract class Wootook_Core_Entity
extends Wootook_Core_Model
implements Wootook_Core_EntityInterface
{
protected $_idFieldName = null;
protected $_tableName = null;
public function setIdFieldName($fieldName)
{
$this->_idFieldName = $fieldName;
return $this;
}
public function getIdFieldName()
{
return $this->_idFieldName;
}
public function setTableName($tableName)
{
$this->_tableName = $tableName;
return $this;
}
public function getTableName()
{
return $this->_tableName;
}
public function setId($id)
{
$this->setData($this->getIdFieldName(), $id);
return $this;
}
public function getId()
{
return $this->getData($this->getIdFieldName());
}
protected function _load()
{
$id = func_get_arg(0);
$idFieldName = self::getIdFieldName();
$database = Wootook_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 Wootook_Core_Exception_DataAccessException('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 = Wootook_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 = Wootook_Database::getSingleton();
$sql =<<<SQL_EOF
INSERT INTO {$database->getTable(self::getTableName())} ($fieldsImploded)
VALUES ({$tokensImploded})
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
$this->setId($database->lastInsertId());
}
return $this;
}
protected function _delete()
{
$fields = array();
foreach ($this->getAllDatas() as $field => $value) {
if ($field == self::getIdFieldName()) {
continue;
}
$fields[] = "{$field}=:{$field}";
}
$fieldsImploded = implod(', ', $fields);
$idFieldName = self::getIdFieldName();
$database = Wootook_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,133 @@
<?php
/**
*
* @uses Wootook_Object
* @uses Legacies_Empire
* @uses Wootook_Empire_Model_User
*/
abstract class Wootook_Core_Entity_SubTable
extends Wootook_Core_Model
{
private $_isLoaded = false;
protected $_tableName = null;
protected $_idFieldNames = array();
protected $_eventPrefix = 'entity.sub-table';
protected function _save()
{
if ($this->_isLoaded !== false) {
$fields = array();
$values = array();
$idFields = array();
foreach ($this->getAllDatas() as $field => $value) {
if (in_array($field, $this->_idFieldNames)) {
$idFields[] = "{$field}=:{$field}";
} else {
$fields[] = "{$field}=:{$field}";
}
$values[$field] = $value;
}
$idFields = '(' . implode(') AND (', $idFields) . ')';
$fields = implode(', ', $fields);
$database = Wootook_Database::getSingleton();
$sql =<<<SQL_EOF
UPDATE {$database->getTable(self::getTableName())}
SET {$fields}
WHERE {$idFields}
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
} else {
$datas = $this->getAllDatas();
$fields = implode(', ', array_keys($datas));
$tokens = array();
foreach ($datas as $field => $value) {
$tokens[] = ":{$field}";
}
$tokens = implode(', ', $tokens);
$database = Wootook_Database::getSingleton();
$sql =<<<SQL_EOF
INSERT INTO {$database->getTable(self::getTableName())} ($fields)
VALUES ({$tokens})
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($datas);
}
return $this;
}
protected function _load()
{
$idValues = func_get_arg(0);
$database = Wootook_Database::getSingleton();
$idFields = array();
foreach ($this->_idFieldNames as $field) {
$idFields[] = "{$field}=:{$field}";
}
$idFields = '(' . implode(') AND (', $idFields) . ')';
$sql =<<<SQL_EOF
SELECT * FROM {$database->getTable(self::getTableName())}
WHERE $idFields
LIMIT 1
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($idValues);
$datas = $statement->fetch(PDO::FETCH_ASSOC);
if (!is_array($datas) || empty($datas)) {
throw new Wootook_Core_Exception_DataAccessException('Could not load data: this id combination could not be found.');
}
$this->_data = $datas;
$this->_isLoaded = true;
return $this;
}
protected function _delete()
{
$database = Wootook_Database::getSingleton();
$idFields = array();
$idValues = array();
foreach ($this->_idFieldNames as $field) {
$idFields[] = "{$field}=:{$field}";
$idValues[$field] = $this->getData($field);
}
$idFields = '(' . implode(') AND (', $idFields) . ')';
$sql =<<<SQL_EOF
DELETE {$database->getTable(self::getTableName())}
WHERE $idFields
LIMIT 1
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($idValues);
$this->_data = array();
$this->_isLoaded = false;
return $this;
}
public function setTableName($tableName)
{
$this->_tableName = $tableName;
return $this;
}
public function getTableName()
{
return $this->_tableName;
}
}

View file

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

View file

@ -0,0 +1,6 @@
<?php
class Wootook_Core_Event
extends Wootook_Object
{
}

View file

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

View file

@ -0,0 +1,3 @@
<?php
interface Wootook_Core_Exception extends Wootook_Exception {}

View file

@ -0,0 +1,6 @@
<?php
class Wootook_Core_Exception_DataAccessException
extends Wootook_Core_Exception_RuntimeException
{
}

View file

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

View file

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

View file

@ -0,0 +1,399 @@
<?php
class Wootook_Core_Layout
extends Wootook_Core_Model
{
const DEFAULT_PACKAGE = 'base';
const DEFAULT_THEME = 'default';
protected $_blocks = array();
protected $_view = null;
protected $_eventPrefix = 'layout';
protected $_eventObject = 'layout';
protected $_package = self::DEFAULT_PACKAGE;
protected $_theme = self::DEFAULT_THEME;
protected $_namespaces = array(
'core' => array(
'Wootook_Core_Block_' => 'Wootook/core/Block'
)
);
public function _init()
{
$modules = Wootook_Core_Model_Config_Modules::getSingleton();
foreach ($modules['block'] as $module => $moduleNamespaces) {
foreach ($moduleNamespaces as $namespace => $path) {
$this->registerBlockNamespace($module, $namespace, $path);
}
}
$config = include ROOT_PATH . 'config.php';
$fileList = array();
if (isset($config['global'])) {
if (isset($config['global']['layout'])) {
$fileList = $config['global']['layout'];
}
if (isset($config['global']['package'])) {
$this->setPackage($config['global']['package']);
}
if (isset($config['global']['theme'])) {
$this->setTheme($config['global']['theme']);
}
}
foreach ($fileList as $layoutFile) {
foreach (include $this->_getLayoutPath($layoutFile) as $layoutId => $layoutConfig) {
if ($this->hasData($layoutId)) {
$declared = $this->getData($layoutId);
$layoutConfig = array_merge($declared, $layoutConfig);
}
$this->setData($layoutId, $layoutConfig);
}
}
return $this;
}
protected function _load()
{
$layoutId = func_get_arg(0);
if (!$this->hasData($layoutId)) {
return $this;
}
$layoutConfigs = array($this->getData($layoutId));
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'];
}
}
$layoutUpdates = array();
$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']);
if (isset($layoutConfig['type'])) {
$type = $layoutConfig['type'];
$name = isset($layoutConfig['name']) ? $layoutConfig['name'] : 'root';
$this->_view = $this->_createBlock($type, $name, $layoutConfig);
} else if (!isset($this->_view)) {
return $this;
}
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);
}
}
}
}
foreach ($layoutUpdates as $block => $updates) {
if (!isset($this->_blocks[$block])) {
continue;
}
foreach ($updates as $update) {
if (isset($update['actions'])) {
$this->_callActions($this->_blocks[$block], $update['actions']);
}
}
}
foreach ($this->_blocks as $block) {
$block->prepareLayout();
}
}
protected function _save()
{
}
protected 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)));
if (isset($this->_namespaces[$module])) {
foreach ($this->_namespaces[$module] as $namespace => $path) {
$className = $namespace . $block;
$fileName = $path . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $block) . '.php';
Wootook_Core_ErrorProfiler::sleep();
if (!($fp = @fopen($fileName, 'r', true))) {
Wootook_Core_ErrorProfiler::wakeup();
continue;
}
Wootook_Core_ErrorProfiler::wakeup();
fclose($fp);
if (!class_exists($className, true)) {
continue;
}
return $className;
}
}
trigger_error(Wootook::__('Class type "%s" could not be resolved.', $type), E_USER_INFO);
return null;
}
public function registerBlockNamespace($module, $namespace, $path = null)
{
if ($path === null) {
$path = str_replace('_', DIRECTORY_SEPARATOR, $namespace);
}
if (!isset($this->_namespaces[$module])) {
$this->_namespaces[$module] = array();
}
$this->_namespaces[$module][$namespace] = $path;
return $this;
}
public function unregisterBlockNamespace($module, $namespace)
{
if (isset($this->_namespaces[$module]) && isset($this->_namespaces[$module][$namespace])) {
unset($this->_namespaces[$module][$namespace]);
}
return $this;
}
public function createBlock($type, $name, $config = array())
{
$instance = $this->_createBlock($type, $name, $config);
$instance->prepareLayout();
return $instance;
}
protected function _createBlock($type, $name, $config = array())
{
$className = $this->_resolveBlockClassType($type);
if ($className === null) {
return null;
}
$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;
$instance->setNameInLayout($name);
$instance->setLayout($this);
foreach ($children as $name => $config) {
if (isset($config['alias'])) {
$alias = $config['alias'];
} else {
$alias = $name;
}
if (!isset($config['type'])) {
$instance->$alias = new Wootook_Core_View($config);
} else {
$instance->$alias = $this->_createBlock($config['type'], $name, $config);
}
}
} catch (ReflectionException $e) {
trigger_error($e->getMessage(), E_USER_INFO);
return null;
}
$this->_callActions($instance, $actions);
return $instance;
}
protected function _callActions($block, $actions)
{
$reflectionClass = new ReflectionClass($block);
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);
$requiredParameterCount = $reflectionMethod->getNumberOfRequiredParameters();
$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()) {
} else if ($paramterPosition <= $requiredParameterCount) {
throw new Wootook_Core_Exception_RuntimeException();
}
}
$reflectionMethod->invokeArgs($block, $callParamaters);
} catch (ReflectionException $e) {
trigger_error($e->getMessage(), E_USER_INFO);
continue;
} catch (RuntimeException $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
continue;
}
}
}
public function getPackage()
{
return $this->_package;
}
public function setPackage($package)
{
$this->_package = $package;
return $this;
}
public function getTheme()
{
return $this->_theme;
}
public function setTheme($theme)
{
$this->_theme = $theme;
return $this;
}
public function getScriptPath()
{
return APPLICATION_PATH . DIRECTORY_SEPARATOR . 'design';
}
public function getBlock($code)
{
if (isset($this->_blocks[$code])) {
return $this->_blocks[$code];
}
return null;
}
public function render()
{
$scriptPath = $this->getScriptPath();
foreach ($this->_blocks as $block) {
if ($block instanceof Wootook_Core_Block_Template) {
$block->setScriptPath($scriptPath);
}
$block->beforeToHtml();
}
unset($block);
return $this->_view->render();
}
protected function _getLayoutPath($file)
{
$package = $this->getPackage();
$theme = $this->getTheme();
$pattern = "{$this->getScriptPath()}/%s/%s/layouts/{$file}";
$path = sprintf($pattern, $package, $theme);
if (Wootook::fileExists($path)) {
return $path;
}
$path = sprintf($pattern, $package, self::DEFAULT_THEME);
if (Wootook::fileExists($path)) {
return $path;
}
$path = sprintf($pattern, self::DEFAULT_PACKAGE, self::DEFAULT_THEME);
if (Wootook::fileExists($path)) {
return $path;
}
trigger_error(Legacies::__("Layout file '%s' does not exist.", $file), E_USER_INFO);
return null;
}
}

View file

@ -0,0 +1,158 @@
<?php
abstract class Wootook_Core_Model
extends Wootook_Object
{
protected $_originalData = array();
protected $_eventPrefix = null;
protected $_eventObject = null;
public function __construct(Array $data = array())
{
$this->_data = $data;
$this->_init();
$this->_setOriginalData($this->_data);
}
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 Wootook_Core_Exception_DataAccessException('Could not save data: ' . $e->getMessage(), 0);
}
return $this;
}
abstract protected function _save();
protected function _beforeSave()
{
Wootook::dispatchEvent('model.before-save', array('model' => $this));
if ($this->_eventPrefix !== null && $this->_eventObject !== null) {
Wootook::dispatchEvent($this->_eventPrefix . '.before-save', array($this->_eventObject => $this));
}
return $this;
}
protected function _afterSave()
{
Wootook::dispatchEvent('model.after-save', array('model' => $this));
if ($this->_eventPrefix !== null && $this->_eventObject !== null) {
Wootook::dispatchEvent($this->_eventPrefix . '.after-save', array($this->_eventObject => $this));
}
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 Wootook_Core_Exception_DataAccessException('Could not load data: ' . $e->getMessage(), 0);
}
return $this;
}
abstract protected function _load();
protected function _beforeLoad()
{
Wootook::dispatchEvent('model.before-load', array('model' => $this));
if ($this->_eventPrefix !== null && $this->_eventObject !== null) {
Wootook::dispatchEvent($this->_eventPrefix . '.before-load', array($this->_eventObject => $this));
}
return $this;
}
protected function _afterLoad()
{
Wootook::dispatchEvent('model.after-load', array('model' => $this));
if ($this->_eventPrefix !== null && $this->_eventObject !== null) {
Wootook::dispatchEvent($this->_eventPrefix . '.after-load', array($this->_eventObject => $this));
}
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 Wootook_Core_Exception_DataAccessException('Could not delete entity: ' . $e->getMessage(), 0);
}
return $this;
}
abstract protected function _delete();
protected function _beforeDelete()
{
Wootook::dispatchEvent('model.before-delete', array('model' => $this));
if ($this->_eventPrefix !== null && $this->_eventObject !== null) {
Wootook::dispatchEvent($this->_eventPrefix . '.before-delete', array($this->_eventObject => $this));
}
return $this;
}
protected function _afterDelete()
{
Wootook::dispatchEvent('model.after-delete', array('model' => $this));
if ($this->_eventPrefix !== null && $this->_eventObject !== null) {
Wootook::dispatchEvent($this->_eventPrefix . '.after-delete', array($this->_eventObject => $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

@ -0,0 +1,88 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Core_Model_Config
extends Wootook_Core_Model
implements Wootook_Core_Singleton
{
private static $_singleton = null;
protected $_eventPrefix = 'core.config';
protected $_eventObject = 'config';
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
protected function _init()
{
$this->load();
}
protected function _load()
{
$database = Wootook_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 = Wootook_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,52 @@
<?php
abstract class Wootook_Core_Model_Config_Abstract
extends Wootook_Core_Model
implements Iterator, Countable
{
protected function _initData($filename)
{
$config = include ROOT_PATH . 'config.php';
$universe = $config['global']['storyline']['universe'];
$episode = $config['global']['storyline']['episode'];
$path = 'gamedata' . DIRECTORY_SEPARATOR . $universe . DIRECTORY_SEPARATOR
. $episode . DIRECTORY_SEPARATOR . $filename . '.php';
foreach (include APPLICATION_PATH . $path as $elementId => $fieldName) {
$this->setData($elementId, $fieldName);
}
return $this;
}
public function count()
{
return count($this->_data);
}
public function current()
{
return current($this->_data);
}
public function next()
{
return next($this->_data);
}
public function key()
{
return key($this->_data);
}
public function valid()
{
return $this->current() !== false;
}
public function rewind()
{
reset($this->_data);
}
}

View file

@ -0,0 +1,56 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Core_Model_Config_Events
extends Wootook_Core_Model_Config_Abstract
implements Wootook_Core_Singleton
{
private static $_singleton = null;
public static function getSingleton()
{
if (self::$_singleton === null) {
self::$_singleton = new self();
}
return self::$_singleton;
}
public static function registerEvents()
{
foreach (self::getSingleton() as $event => $listenerList) {
foreach ($listenerList as $listener) {
Wootook::registerListener($event, $listener);
}
}
}
protected function _init()
{
$this->_initData('events');
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,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Core_Model_Config_Modules
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('modules');
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,145 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Core_Model_Session
extends Wootook_Object
{
const CRIT = 0x80;
const ERROR = 0x40;
const WARN = 0x20;
const INFO = 0x10;
const DEBUG = 0x01;
const SUCCESS = 0;
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());
}
self::$_instances[$namespace] = new self($namespace);
}
return self::$_instances[$namespace];
}
public static function destroy()
{
session_destroy();
}
public function __construct($namespace)
{
if (session_id() == '') {
session_start();
}
if (!isset($_SESSION[$namespace])) {
$_SESSION[$namespace] = array();
}
$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 addSuccess($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return $this->addMessage(vsprintf($message, $args), self::SUCCESS);
}
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);
}
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,37 @@
<?php
class Wootook_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,76 @@
<?php
abstract class Wootook_Core_Plugin_LoaderAbstract
{
protected $_pluginInstances = array();
protected $_namespaces = array();
public function load($pluginName, $useSingleton = false)
{
if (isset($this->_pluginInstances[$pluginName])) {
return $this->_pluginInstances[$pluginName];
}
foreach ($this->_namespaces as $namespace => $path) {
$className = $namespace . ucfirst($pluginName);
$fileName = $path . DIRECTORY_SEPARATOR . ucfirst($pluginName) . '.php';
if (!file_exists($fileName)) {
continue;
}
if (!class_exists($className, true)) {
continue;
}
return $this->_load($className, $useSingleton);
}
return $this;
}
public function registerNamespace($namespace, $path = null)
{
if ($path === null) {
$path = str_replace('_', DIRECTORY_SEPARATOR, $namespace);
}
$this->_namespaces[$namespace] = $path;
return $this;
}
public function unregisterNamespace($namespace)
{
if (isset($this->_namespaces[$namespace])) {
unset($this->_namespaces[$namespace]);
}
return $this;
}
abstract protected function _load($className);
public function getPlugin($pluginName)
{
return $this->load($pluginName);
}
public function setPlugin($pluginName, $pluginInstance)
{
$this->_pluginInstances[$pluginName] = $pluginInstance;
return $this;
}
public function hasPlugin($pluginName)
{
return isset($this->_pluginInstances[$pluginName]);
}
public function unsetPlugin($pluginName)
{
unset($this->_pluginInstances[$pluginName]);
return $this;
}
}

View file

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

View file

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

View file

@ -0,0 +1,13 @@
<?php
class Wootook_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,252 @@
<?php
class Wootook_Core_View
extends Wootook_Object
{
protected $_template = null;
protected $_partials = array();
protected $_layout = null;
protected $_nameInLayout = null;
protected $_scriptPath = 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);
}
public function renderTime($time, $unique = false)
{
if ($time >= 10) {
$seconds = $time % 60;
$minutes = (int) (($time - $seconds) / 60) % 60;
$hours = (int) ((($time - $seconds) / 60) - $minutes) / 60;
if ($hours > 24) {
$dayHours = (int) $hours % 24;
$days = (int) ($hours - $dayHours) / 24;
return $this->__('%1$d day(s) and %2$d hour(s)', $days, $dayHours);
} else if ($hours > 0) {
return $this->__('%1$d hour(s), %2$d minute(s) and %3$d second(s)', $hours, $minutes, $seconds);
} else if ($minutes > 0) {
return $this->__('%1$d minute(s) and %2$d second(s)', $minutes, $seconds);
} else {
return $this->__('%1$d second(s)', $seconds);
}
} else if (!$unique && $time > 0) {
return $this->__('%1$d per minute', 60 / $time);
} else {
return $this->__('instantaneous');
}
}
protected function escape($unescaped)
{
return htmlspecialchars($unescaped, ENT_QUOTES, 'UTF-8');
}
public function __($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return Wootook::translate(Wootook::getDefaultLocale(), $message, $args);
}
public function translate($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return Wootook::translate(Wootook::getLocale(), $message, $args);
}
public function renderScript($file)
{
$this->_prepareRender();
$templatePath = $this->_getTemplatePath($file);
if ($templatePath !== null) {
ob_start();
include $this->_getTemplatePath($file);
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return '';
}
protected function _getTemplatePath($file)
{
return $this->getScriptPath() . DIRECTORY_SEPARATOR . $file;
}
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())
{
return Wootook::getUrl($uri, $params);
}
public function getSkinUrl($uri, Array $params = array())
{
$package = $this->getLayout()->getPackage();
if (empty($package)) {
$package = Wootook_Core_Layout::DEFAULT_PACKAGE;
}
$user = Wootook_Empire_Model_User::getSingleton();
if ($user !== null && $user->getId()) {
$theme = $user->getSkinPath();
}
if (empty($theme)) {
$theme = $this->getLayout()->getTheme();
}
if (empty($theme)) {
$theme = Wootook_Core_Layout::DEFAULT_THEME;
}
return Wootook::getSkinUrl($package, $theme, $uri, $params);
}
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 getAllPartials()
{
return $this->_partials;
}
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;
}
/**
*
* @return Wootook_Core_Layout
*/
public function getLayout()
{
return $this->_layout;
}
public function prepareLayout()
{
}
public function beforeToHtml()
{
}
public function setNameInLayout($name)
{
$this->_nameInLayout = $name;
return $this;
}
public function getNameInLayout()
{
return $this->_nameInLayout;
}
public function setScriptPath($scriptPath)
{
$this->_scriptPath = $scriptPath;
return $this;
}
public function getScriptPath()
{
return $this->_scriptPath;
}
}

View file

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

View file

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

View file

@ -0,0 +1,51 @@
<?php
class Wootook_Database
extends PDO
{
protected static $_singleton = null;
protected static $_prefix = null;
public static $options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
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'];
$port = 3306;
if (isset($config['global']['database']['options']['port'])) {
$port = $config['global']['database']['options']['port'];
}
$event = Wootook::dispatchEvent('database.prepare-options', array(
'options' => self::$options
));
self::$options = $event->getData('options');
self::$_singleton = new self("mysql:dbname={$database};host={$hostname};port={$port}", $username, $password, self::$options);
Wootook::dispatchEvent('database.init', array(
'handler' => self::$_singleton
));
}
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,7 @@
<?php
class Wootook_Empire_Block_Overview
extends Wootook_Core_Block_Template
{
}

View file

@ -0,0 +1,7 @@
<?php
class Wootook_Empire_Block_Overview_DestroyPlanet
extends Wootook_Core_Block_Html_Form
{
}

View file

@ -0,0 +1,7 @@
<?php
class Wootook_Empire_Block_Overview_RenamePlanet
extends Wootook_Core_Block_Html_Form
{
}

View file

@ -0,0 +1,118 @@
<?php
abstract class Wootook_Empire_Block_Planet_Builder_ItemAbstract
extends Wootook_Core_Block_Template
{
protected $_user = null;
protected $_planet = null;
protected $_itemId = null;
public function setUser(Wootook_Empire_Model_User $user)
{
$this->_user = $user;
return $this;
}
public function getUser()
{
if ($this->_user === null) {
$this->_user = Wootook_Empire_Model_User::getSingleton();
}
return $this->_user;
}
public function setPlanet(Wootook_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = $this->getUser()->getCurrentPlanet();
}
return $this->_planet;
}
public function setItemId($itemId)
{
$this->_itemId = $itemId;
return $this;
}
public function getItemId()
{
return $this->_itemId;
}
public function getItemInfoUrl()
{
return $this->getUrl('infos.php', array('gid' => $this->getItemId()));
}
public function getItemImageUrl()
{
// TODO : Upgrade theme
return $this->getSkinUrl('graphics/gebaeude/' . $this->getItemId() . '.gif');
}
public function getName()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['tech']) && isset($lang['tech'][$this->getItemId()])) {
return $this->__($lang['tech'][$this->getItemId()]);
}
return '';
}
public function getDescription()
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('tech');
}
if (isset($lang['res']) && isset($lang['res']['descriptions']) && isset($lang['res']['descriptions'][$this->getItemId()])) {
return $this->__($lang['res']['descriptions'][$this->getItemId()]);
}
return '';
}
public function getResourceName($resourceId)
{
static $lang = null;
if ($lang === null) {
// FIXME: implement a cleaner way to get names
$lang = includeLang('imperium');
}
if ($resourceId == 'cristal') {
$resourceId = 'crystal';
}
if (isset($lang[$resourceId])) {
return $this->__($lang[$resourceId]);
}
return '';
}
public function getNextLevel()
{
return $this->getQueuedLevel() + 1;
}
abstract public function getResourcesNeeded($level);
abstract public function getBuildingTime($level);
}

View file

@ -0,0 +1,22 @@
<?php
abstract class Wootook_Empire_Block_Planet_Builder_Queue_ItemAbstract
extends Wootook_Empire_Block_Planet_Builder_ItemAbstract
{
protected $_item = null;
protected $_itemIdField = null;
public function setItem(Wootook_Empire_Model_Builder_Item $item)
{
$this->_item = $item;
$this->setItemId($item->getData($this->_itemIdField));
return $this;
}
public function getItem()
{
return $this->_item;
}
}

View file

@ -0,0 +1,95 @@
<?php
abstract class Wootook_Empire_Block_Planet_Builder_QueueAbstract
extends Wootook_Core_Block_Template
{
protected $_user = null;
protected $_planet = null;
protected $_itemTemplate = null;
protected $_itemBlock = null;
public function setUser(Wootook_Empire_Model_User $user)
{
$this->_user = $user;
return $this;
}
public function getUser()
{
if ($this->_user === null) {
$this->_user = Wootook_Empire_Model_User::getSingleton();
}
return $this->_user;
}
public function setPlanet(Wootook_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = $this->getUser()->getCurrentPlanet();
}
return $this->_planet;
}
public function setItemTemplate($template)
{
$this->_itemTemplate = $template;
return $this;
}
public function getItemTemplate()
{
return $this->_itemTemplate;
}
public function setItemBlockType($blockType)
{
$this->_itemBlockType = $blockType;
return $this;
}
public function getItemBlockType()
{
return $this->_itemBlockType;
}
public function getItemBlock(Wootook_Empire_Model_Builder_Item $item)
{
$index = $item->getIndex();
$blockName = "item({$index})";
return $this->getLayout()
->createBlock($this->getItemBlockType(), $blockName)
->setTemplate($this->getItemTemplate())
->setPlanet($this->getPlanet())
->setItem($item);
}
public function prepareLayout()
{
$parentBlock = $this->getLayout()
->createBlock('core/concat', $this->getNameInLayout() . '.item-list')
;
$this->setPartial('item-list', $parentBlock);
foreach ($this->getQueue() as $item) {
$block = $this->getItemBlock($item);
$parentBlock->setPartial($block->getNameInLayout(), $block);
}
return $this;
}
abstract public function getQueue();
}

View file

@ -0,0 +1,54 @@
<?php
abstract class Wootook_Empire_Block_Planet_BuilderAbstract
extends Wootook_Core_Block_Template
{
protected $_itemTemplate = null;
protected $_itemBlock = null;
public function setItemTemplate($template)
{
$this->_itemTemplate = $template;
return $this;
}
public function getItemTemplate()
{
return $this->_itemTemplate;
}
public function setItemBlockType($blockType)
{
$this->_itemBlockType = $blockType;
return $this;
}
public function getItemBlockType()
{
return $this->_itemBlockType;
}
public function getItemBlock($itemId)
{
$blockName = "item({$itemId})";
return $this->getLayout()
->createBlock($this->getItemBlockType(), $blockName)
->setTemplate($this->getItemTemplate())
->setPlanet($this->getPlanet())
->setItemId($itemId);
}
public function prepareLayout()
{
parent::prepareLayout();
$this->_initChildBlocks();
return $this;
}
abstract protected function _initChildBlocks();
}

View file

@ -0,0 +1,46 @@
<?php
class Wootook_Empire_Block_Planet_Buildings
extends Wootook_Empire_Block_Planet_BuilderAbstract
{
protected $_planet = null;
public function setPlanet(Wootook_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = Wootook_Empire_Model_User::getSingleton()
->getCurrentPlanet()
;
}
return $this->_planet;
}
public function _initChildBlocks()
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
$type = Legacies_Empire::TYPE_BUILDING_PLANET;
if ($this->getPlanet()->isMoon()) {
$type = Legacies_Empire::TYPE_BUILDING_MOON;
}
/** @var Wootook_Core_Block_Concat $parentBlock */
$parentBlock = $this->getLayout()->getBlock('item-list.items');
foreach ($types->getData($type) as $itemId) {
if (!$this->getPlanet()->checkAvailability($itemId)) {
continue;
}
$block = $this->getItemBlock($itemId);
$parentBlock->setPartial($block->getName(), $block);
}
return $this;
}
}

View file

@ -0,0 +1,56 @@
<?php
class Wootook_Empire_Block_Planet_Buildings_Item
extends Wootook_Empire_Block_Planet_Builder_ItemAbstract
{
public function getLevel()
{
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResourcesNeeded($this->getItemId(), $level);
}
public function getQueuedLevel()
{
return $this->getPlanet()->getBuildingLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getBuildingTime($this->getItemId(), $level);
}
public function getResourcesConfigForLevel($level)
{
$resources = $this->getResourcesNeeded($level);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Wootook_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
public function getResourcesConfigForNextLevel()
{
return $this->getResourcesConfigForLevel($this->getNextLevel());
}
public function getBuildingTimeForNextLevel()
{
return $this->getBuildingTime($this->getNextLevel());
}
}

View file

@ -0,0 +1,15 @@
<?php
class Wootook_Empire_Block_Planet_Buildings_Queue
extends Wootook_Empire_Block_Planet_Builder_QueueAbstract
{
public function getQueue()
{
return $this->getPlanet()->getBuildingQueue();
}
public function isEmpty()
{
return $this->getQueue()->count() == 0;
}
}

View file

@ -0,0 +1,63 @@
<?php
class Wootook_Empire_Block_Planet_Buildings_Queue_Item
extends Wootook_Empire_Block_Planet_Builder_Queue_ItemAbstract
{
protected $_itemIdField = 'building_id';
public function getLevel()
{
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResourcesNeeded($this->getItemId(), $this->getQueuedLevel() + 1);
}
public function getItemQueuedLevel()
{
return $this->getItem()->getData('level');
}
public function getQueuedLevel()
{
return $this->getPlanet()->getBuildingLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getBuildingTime($this->getItemId(), $level);
}
public function getResourcesConfigForLevel($level)
{
$resources = $this->getResourcesNeeded($level);
$resourceConfig = array();
foreach ($resources as $resourceId => $resourceValue) {
$resourceConfig[$resourceId] = new Wootook_Object(array(
'resource_id' => $resourceId,
'value' => $resourceValue
));
$amount = $this->getPlanet()->getResourceAmount($resourceId);
if (Math::comp($amount, $resourceValue) < 0) {
$resourceConfig[$resourceId]->setData('requirement', Math::sub($amount, $resourceValue));
} else {
$resourceConfig[$resourceId]->setData('overflow', Math::sub($amount, $resourceValue));
}
}
return $resourceConfig;
}
public function getResourcesConfigForNextLevel()
{
return $this->getResourcesConfigForLevel($this->getNextLevel());
}
public function getBuildingTimeForNextLevel()
{
return $this->getBuildingTime($this->getNextLevel());
}
}

View file

@ -0,0 +1,7 @@
<?php
class Wootook_Empire_Block_PlanetList
extends Wootook_Core_Block_Template
{
}

View file

@ -0,0 +1,32 @@
<?php
class Wootook_Empire_Block_Topnav
extends Wootook_Core_Block_Template
{
/**
*
* @return Wootook_Empire_Model_User
*/
public function getCurrentUser()
{
return Wootook_Empire_Model_User::getSingleton();
}
/**
*
* @return Wootook_Empire_Model_Planet
*/
public function getCurrentPlanet()
{
return $this->getCurrentUser()->getCurrentPlanet();
}
/**
*
* @return Wootook_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

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,247 @@
<?php
abstract class Wootook_Empire_Model_BuilderAbstract
implements Countable, Serializable, Iterator
{
/**
* Planet instance
* @var Wootook_Empire_Model_Planet
*/
protected $_currentPlanet = null;
/**
* User instance
* @var Wootook_Empire_Model_User
*/
protected $_currentUser = null;
/**
* construction queue
* @var array
*/
protected $_queue = null;
/**
* construction queue
* @var array
*/
protected $_itemClass = 'Wootook_Empire_Model_Builder_Item';
/**
*
* @param Wootook_Empire_Model_Planet $currentPlanet
* @param Wootook_Empire_Model_User $currentUser
*/
public function __construct(Wootook_Empire_Model_Planet $currentPlanet, Wootook_Empire_Model_User $currentUser)
{
$this->_currentPlanet = $currentPlanet;
$this->_currentUser = $currentUser;
$this->init();
}
abstract public function init();
abstract protected function _initItem(Array $params);
public function enqueue($params, $index = null)
{
$item = $this->_initItem($params);
if ($item === null) {
return $this;
}
if ($index === null) {
$index = $this->_generateIndex();
}
$item->setIndex($index);
$this->_queue[$index] = $item;
return $this;
}
public function dequeue($item)
{
unset($this->_queue[$item->getIndex()]);
return $this;
}
protected function _generateIndex()
{
return uniqid();
}
public function getItem($itemIndex)
{
if (isset($this->_queue[$itemIndex])) {
return $this->_queue[$itemIndex];
}
return null;
}
protected function _serializeQueue()
{
$serialize = array();
foreach ($this->_queue as $itemIndex => $itemInstance) {
$serialize[$itemIndex] = $itemInstance->getAllDatas();
}
return serialize($serialize);
}
protected function _unserializeQueue($serialized)
{
$this->clearQueue();
$unserialized = @unserialize($serialized);
if ($unserialized === false) {
$this->_queue = array();
return $this;
}
foreach ($unserialized as $itemIndex => $itemData) {
$this->enqueue($itemData, $itemIndex);
}
return $this;
}
public function __toString()
{
return $this->_serializeQueue();
}
public function getQueue()
{
return $this->_queue;
}
public function clearQueue()
{
$this->_queue = array();
}
abstract public function updateQueue($time);
abstract public function appendQueue($typeId, $qty, $time);
/**
* Check if an item type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int $typeId
* @return bool
*/
public function checkAvailability($typeId)
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
$requirements = Wootook_Empire_Model_Game_Requirements::getSingleton();
if (!isset($requirements[$typeId]) || empty($requirements[$typeId])) {
return true;
}
foreach ($requirements[$typeId] as $requirement => $level) {
if ($types->is($requirement, Legacies_Empire::TYPE_BUILDING) && $this->_currentPlanet->hasElement($requirement, $level)) {
continue;
} else if ($types->is($requirement, Legacies_Empire::TYPE_RESEARCH) && $this->_currentUser->hasElement($requirement, $level)) {
continue;
} else if ($types->is($requirement, Legacies_Empire::TYPE_DEFENSE) && $this->_currentPlanet->hasElement($requirement, $level)) {
continue;
} else if ($types->is($requirement, Legacies_Empire::TYPE_SHIP) && $this->_currentPlanet->hasElement($requirement, $level)) {
continue;
}
return false;
}
return true;
}
abstract public function getResourcesNeeded($typeId, $level);
abstract public function getBuildingTime($typeId, $level);
public function serialize()
{
return $this->_serializeQueue();
}
public function unserialize($serialized)
{
$this->_unserializeQueue($serialized);
}
public function count()
{
return count($this->_queue);
}
public function current()
{
return current($this->_queue);
}
public function next()
{
return next($this->_queue);
}
public function key()
{
return key($this->_queue);
}
public function valid()
{
return current($this->_queue) !== false;
}
public function rewind()
{
reset($this->_queue);
}
public function getCurrentPlanet()
{
return $this->_currentPlanet;
}
public function getCurrentUser()
{
return $this->_currentUser;
}
public function setCurrentPlanet(Wootook_Empire_Model_Planet $planet)
{
$this->_currentPlanet = $planet;
return $this;
}
public function setCurrentUser(Wootook_Empire_Model_User $user)
{
$this->_currentUser = $user;
return $this;
}
protected function _calculateResourceRemainingAmounts($resourceNeeded)
{
$resourceAmounts = array();
foreach ($resourceNeeded as $resourceId => $resourceAmount) {
$resourceAmounts[$resourceId] = Math::sub($this->_currentPlanet[$resourceId], $resourceAmount);
if (Math::isNegative($resourceAmounts[$resourceId])) {
return false;
}
}
return $resourceAmounts;
}
protected function _calculateResourceReclaimedAmounts($resourceNeeded)
{
$resourceAmounts = array();
foreach ($resourceNeeded as $resourceId => $resourceAmount) {
$resourceAmounts[$resourceId] = Math::add($this->_currentPlanet[$resourceId], $resourceAmount);
}
return $resourceAmounts;
}
}

View file

@ -0,0 +1,155 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Fleet
extends Wootook_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(Wootook_Empire_Model_User $user)
{
if ($this->getData('fleet_owner') == $user->getId()) {
return true;
}
return false;
}
public function getOwner()
{
if ($id = $this->getData('fleet_owner')) {
return Wootook_Empire_Model_User::factory($id);
}
return null;
}
public function isMission($missionType)
{
if ($this->getData('fleet_mission') == $missionType) {
return true;
}
return false;
}
public function getRowClass(Wootook_Empire_Model_User $user = null)
{
if ($this->isMission(Legacies_Empire::ID_MISSION_ATTACK) || $this->isMission(Legacies_Empire::ID_MISSION_GROUP_ATTACK)) {
if ($user !== null && $this->isOwnedBy($user)) {
return 'attack';
} else {
return 'ownattack';
}
} 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';
}
}
public function getMissionLabel()
{
if ($this->isMission(Legacies_Empire::ID_MISSION_ATTACK) || $this->isMission(Legacies_Empire::ID_MISSION_GROUP_ATTACK)) {
return Wootook::__('Attack');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_TRANSPORT)) {
return Wootook::__('Transport');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_STATION) || $this->isMission(Legacies_Empire::ID_MISSION_STATION_ALLY)) {
return Wootook::__('Station');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_SETTLE_COLONY)) {
return Wootook::__('Settle');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_RECYCLE)) {
return Wootook::__('Recycle');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_DESTROY)) {
return Wootook::__('Destroy');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_MISSILES)) {
return Wootook::__('Missiles Launch');
} else if ($this->isMission(Legacies_Empire::ID_MISSION_EXPEDITION)) {
return Wootook::__('Expedition');
}
return Legacies::__('Unknown');
}
public function getStartTime()
{
return $this->getData('fleet_start_time');
}
public function getActionTime()
{
return $this->getData('fleet_end_stay');
}
public function getArrivalTime()
{
if ($this->isMission(Legacies_Empire::ID_MISSION_STATION) || $this->isMission(Legacies_Empire::ID_MISSION_STATION_ALLY)) {
return $this->getActionTime();
}
return $this->getData('fleet_end_time');
}
public function getOriginPlanet()
{
$coords = array(
'galaxy' => $this->getData('fleet_start_galaxy'),
'system' => $this->getData('fleet_start_system'),
'position' => $this->getData('fleet_start_planet')
);
$type = $this->getData('fleet_start_type');
return Wootook_Empire_Model_Planet::factoryFromCoords($coords, $type);
}
public function getDestinationPlanet()
{
$coords = array(
'galaxy' => $this->getData('fleet_end_galaxy'),
'system' => $this->getData('fleet_end_system'),
'position' => $this->getData('fleet_end_planet')
);
$type = $this->getData('fleet_end_type');
return Wootook_Empire_Model_Planet::factoryFromCoords($coords, $type);
}
}

View file

@ -0,0 +1,32 @@
<?php
class Wootook_Empire_Model_Galaxy_Position
extends Wootook_Core_Entity_SubTable
{
protected function _init()
{
$this->_tableName = 'galaxy';
$this->_idFieldNames = array('id_planet');
}
static function initPlanetListerner($eventData)
{
if (!isset($eventData['planet'])) {
return;
}
$planet = $eventData['planet'];
if (!$planet->isPlanet()) {
return;
}
$galaxy = new self();
$galaxy
->setData('galaxy', $planet->getGalaxy())
->setData('system', $planet->getSystem())
->setData('planet', $planet->getPosition())
->setData('id_planet', $planet->getId())
->save()
;
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_Combat
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('combat');
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,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_FieldsAlias
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('fields-alias');
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,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_Prices
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('prices');
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,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_Production
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('production');
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,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_Requirements
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('requirements');
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,47 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_Resources
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('resources');
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,55 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_Game_Types
extends Wootook_Core_Model_Config_Abstract
implements Wootook_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->_initData('types');
return $this;
}
protected function _load()
{
// NOP
return $this;
}
protected function _save()
{
// NOP
return $this;
}
protected function _delete()
{
// NOP
return $this;
}
public function is($element, $type)
{
if (!is_array($this->getData($type))) {
return false;
}
return in_array($element, $this->getData($type));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,272 @@
<?php
class Wootook_Empire_Model_Planet_Builder
extends Wootook_Empire_Model_BuilderAbstract
{
public function init()
{
$this->_unserializeQueue($this->_currentPlanet->getData('b_building_id'));
}
/**
* @param array $params
*/
protected function _initItem(Array $params)
{
if (!isset($params['building_id']) || !isset($params['level'])) {
return null;
}
$buildingId = $params['building_id'];
$level = $params['level'];
if (!isset($params['created_at'])) {
$createdAt = time();
} else {
$createdAt = $params['created_at'];
}
if (!isset($params['started_at'])) {
$startedAt = null;
} else {
$startedAt = $params['started_at'];
}
if (!isset($params['updated_at'])) {
$updatedAt = $createdAt;
} else {
$updatedAt = $params['updated_at'];
}
return new Wootook_Empire_Model_Planet_Builder_Item(array(
'building_id' => $buildingId,
'level' => $level,
'created_at' => $createdAt,
'started_at' => $startedAt,
'updated_at' => $updatedAt
));
}
/**
* Check if a building is actually buildable on the current planet,
* depending on the technology and buildings requirements.
*
* @param int $buildingId
* @return bool
*/
public function checkAvailability($buildingId)
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
if ($types->is($buildingId, Legacies_Empire::TYPE_BUILDING)) {
return true;
}
return false;
}
public function getBuildingTime($buildingId, $level)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
$gameConfig = Wootook_Core_Model_Config::getSingleton();
Math::setPrecision(50);
$firstLevelTime = $prices[$buildingId][Legacies_Empire::BASE_BUILDING_TIME];
$partialLevelTime = Math::mul($firstLevelTime, Math::pow($prices[$buildingId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
$levelTime = Math::sub($partialLevelTime, $firstLevelTime);
$speedFactor = $gameConfig->getData('game_speed');
$baseTime = $levelTime / $speedFactor * 3600;
Math::setPrecision();
$event = Wootook::dispatchEvent('planet.building.building-time', array(
'time' => $baseTime,
'base_time' => $baseTime,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser,
'building_id' => $buildingId,
'level' => $level
));
return $event->getData('time');
}
public function getResourcesNeeded($buildingId, $level)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
$resources = Wootook_Empire_Model_Game_Resources::getSingleton();
if (!isset($prices[$buildingId])) {
return array();
}
$resourcesNeeded = array();
foreach ($resources as $resourceId => $resourceConfig) {
if (!isset($prices[$buildingId][$resourceId])) {
continue;
}
if (Math::isPositive($prices[$buildingId][$resourceId])) {
$firstLevelCost = $prices[$buildingId][$resourceId];
$resourcesNeeded[$resourceId] = Math::mul($firstLevelCost, Math::pow($prices[$buildingId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
}
}
return $resourcesNeeded;
}
/**
* Update the contruction queue.
*
* @return Wootook_Empire_Model_Planet_Building_Shipyard
*/
public function updateQueue($time)
{
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
$startingTime = $this->_currentPlanet->getData('b_building');
foreach ($this->getQueue() as $element) {
$elementTime = $element->getData('started_at');
if ($elementTime === null) {
$element->setData('started_at', $startingTime);
$elementTime = $startingTime;
}
$level = $element->getData('level');
$buildingId = $element->getData('building_id');
$buildTime = $this->getBuildingTime($buildingId, $level);
$elapsedTime = $time - $elementTime;
if ($elapsedTime >= $buildTime) {
$this->_currentPlanet->updateResources($time - $elapsedTime);
$this->_currentPlanet->setElement($buildingId, $level);
$this->_currentPlanet->updateResourceProduction($time - $elapsedTime);
$this->_currentPlanet->updateStorages($time - $elapsedTime);
$this->_currentPlanet->updateBuildingFields();
$this->dequeue($element);
Wootook::dispatchEvent('planet.building.level-update', array(
'time' => $time - $elapsedTime,
'planet' => $this->_currentPlanet,
'user' => $this->_currentUser,
'building_id' => $buildingId,
'level' => $level
));
$startingTime = $elementTime + $buildTime;
continue;
}
$element->setData('updated_at', $time);
break;
}
$this->_currentPlanet->setData('b_building_id', $this->serialize());
$this->_currentPlanet->setData('b_building', $startingTime);
return $this;
}
/**
* Append items to build to the construction list
*
* @param int $buildingId
* @param int|string $level
* @return Wootook_Empire_Model_Planet_Building_Shipyard
*/
public function appendQueue($buildingId, $level, $time)
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
$resources = Wootook_Empire_Model_Game_Resources::getSingleton();
if (!Math::isPositive($level)) {
return $this;
}
if (!$types->is($buildingId, Legacies_Empire::TYPE_BUILDING)) {
return $this;
}
if (!$this->checkAvailability($buildingId)) {
return $this;
}
$resourcesNeeded = $this->getResourcesNeeded($buildingId, $level);
$remainingAmounts = $this->_calculateResourceRemainingAmounts($resourcesNeeded);
if ($remainingAmounts === false) {
return $this;
}
if ($this->count() == 0) {
$this->_currentPlanet->setData('b_building', $time);
}
$this->enqueue(array(
'building_id' => $buildingId,
'level' => $level,
'created_at' => $time
));
$this->_currentPlanet->setData('b_building_id', $this->serialize());
foreach ($remainingAmounts as $resourceId => $resourceAmount) {
$this->_currentPlanet[$resourceId] = $resourceAmount;
}
return $this;
}
/**
* Dequeues the first item to build to the construction list and removes all
* its successors of the same type.
*
* @return Wootook_Empire_Model_Planet_Builder
*/
public function dequeueFirstItem()
{
$this->rewind();
$item = $this->current();
return $this->dequeueItem($item->getIndex());
}
/**
* Dequeues an item to build to the construction list and removes all its
* successors of the same type.
*
* @param string $itemId
* @return Wootook_Empire_Model_Planet_Builder
*/
public function dequeueItem($itemId)
{
$item = $this->getItem($itemId);
if (!$item) {
return $this;
}
$buildingId = $item->getData('building_id');
$keys = array_keys($this->_queue);
$size = count($keys);
$start = array_search($item->getIndex(), $keys);
for ($i = $start; $i < $size; $i++) {
$index = $keys[$i];
if ($this->_queue[$index]->getData('building_id') != $buildingId) {
continue;
}
$resourcesNeeded = $this->getResourcesNeeded($buildingId, $this->_queue[$index]->getData('level'));
$reclaimedAmounts = $this->_calculateResourceReclaimedAmounts($resourcesNeeded);
$this->dequeue($this->_queue[$index]);
foreach ($reclaimedAmounts as $resourceId => $resourceAmount) {
$this->_currentPlanet[$resourceId] = $resourceAmount;
}
}
$this->_currentPlanet->setData('b_building_id', $this->serialize());
return $this;
}
}

View file

@ -0,0 +1,6 @@
<?php
class Wootook_Empire_Model_Planet_Builder_Item
extends Wootook_Empire_Model_Builder_Item
{
}

View file

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

View file

@ -0,0 +1,3 @@
<?php
class Wootook_Empire_Model_Planet_Exception implements Wootook_Empire_Exception {}

View file

@ -0,0 +1,29 @@
<?php
class Wootook_Empire_Model_Planet_PluginLoader
extends Wootook_Core_Plugin_LoaderAbstract
{
protected $_currentUser = null;
protected $_currentPlanet = null;
public function __construct($currentPlanet, $currentUser)
{
$this->_currentUser = $currentUser;
$this->_currentPlanet = $currentPlanet;
}
protected function _load($className, $useSingleton)
{
$reflection = new ClassReflection($className);
if ($useSingleton && $reflection->implementsInterface('Wootook_Core_Singleton')) {
$method = $reflection->getMethod('getSingleton');
$method->invoke();
}
try {
return $reflection->invoke($this->_currentPlanet, $this->_currentUser);
} catch (ReflectionException $e) {
return null;
}
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,538 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Empire_Model_User
extends Wootook_Core_Entity
{
protected static $_instances = array();
protected static $_singleton = null;
protected $_eventPrefix = 'user';
protected $_eventObject = 'user';
public static $hashCallback = 'md5';
protected $_homePlanet = null;
protected $_currentPlanet = null;
const SESSION_KEY = 'user';
const COOKIE_NAME = 'Wootook';
const COOKIE_LIFETIME = 2592000;
const PLANET_SORT_DATE = 0;
const PLANET_SORT_POSITION = 1;
const PLANET_SORT_NAME = 2;
protected static $_cookieName = self::COOKIE_NAME;
public static function setCookieName($name)
{
self::$_cookieName = $name;
}
public static function factory($id)
{
if ($id === null) {
return new self();
}
$id = intval($id);
if (!isset(self::$_instances[$id])) {
$instance = new self();
$params = func_get_args();
call_user_func_array(array($instance, 'load'), $params);
self::$_instances[$id] = $instance;
}
return self::$_instances[$id];
}
public function getUsername()
{
return $this->getData('username');
}
public static function getSingleton()
{
if (self::$_singleton === null) {
$session = Wootook::getSession(self::SESSION_KEY);
if ($session->hasData('user_id')) {
$id = intval($session->getData('user_id'));
} else if (Wootook::getRequest() !== null && ($cookie = Wootook::getRequest()->getCookie(self::$_cookieName)) !== null) {
$cookieData = unserialize(stripslashes($cookie));
if (is_array($cookieData)) {
$collection = new Wootook_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 (Wootook_Core_Exception_DataAccessException $e) {
$session->addError('Session error.');
return null;
}
self::$_singleton->_updateActivity();
}
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()
{
$this->setIdFieldName('id');
$this->setTableName('users');
}
protected function _updateActivity()
{
$this
->setData('current_page', $_SERVER['REQUEST_URI'])
->setData('user_lastip', $_SERVER['REMOTE_ADDR'])
->setData('user_agent', $_SERVER['HTTP_USER_AGENT'])
->setData('onlinetime', time())
->save()
;
return $this;
}
public function logout()
{
Wootook::getResponse()->unsetCookie(self::$_cookieName);
Wootook_Core_Model_Session::destroy();
}
public static function login($username, $password, $remember = false)
{
$session = Wootook::getSession(self::SESSION_KEY);
try {
$collection = new Wootook_Core_Collection(array('user' => 'users'));
$passwordHash = md5($password);
$collection
->column('user.id')
->column('user.username')
->column('user.password')
->column('user.banaday')
->column('CONCAT((@salt:=MID(MD5(RAND()), 0, 4)), SHA1(CONCAT(user.username, user.password, @salt))) AS login_rememberme')
->column('(CASE WHEN user.password="' . $passwordHash . '" THEN 1 ELSE 0 END) AS login_success')
->where('user.username=:username')
->load(array(
'username' => $username
))
;
} catch (Wootook_Core_Exception_DataAccessException $e) {
Wootook_Core_ErrorProfiler::getSingleton()->exceptionManager($e);
$session->addError('No such user.');
return null;
}
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()) {
$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"]) && Wootook::getRequest() !== null) {
Wootook::$response->setCookie(self::$_cookieName, array('id' => $login['id'], 'key' => $login['login_rememberme']), self::COOKIE_LIFETIME);
}
self::$_singleton = self::factory($login['id']);
self::$_singleton->_updateActivity();
$session->setData('user_id', intval($login['id']));
return self::$_singleton;
}
$session->addError('Your username or credential is invalid, please check your input.');
return null;
}
public static function register($username, $email, $password)
{
try {
$request = Wootook::getRequest();
$user = new self(array(
'username' => $username,
'password' => md5($password),
'email' => $email,
'email_2' => $email,
'register_time' => Wootook::now(),
'onlinetime' => Wootook::now(),
'ip_at_reg' => $request->getServer('REMOTE_ADDR'),
'user_lastip' => $request->getServer('REMOTE_ADDR'),
'user_agent' => $request->getServer('HTTP_USER_AGENT')
));
$user->save();
Wootook::dispatchEvent('user.init', array(
'user' => $user
));
$user->save();
} catch (Wootook_Core_Exception_DataAccessException $e) {
echo $e->getTraceAsString();
$session->addError($e->getMessage());
return null;
}
return $user;
}
/**
*
* Enter description here ...
* @param int|Wootook_Empire_Model_Planet $planet
*/
public function updateCurrentPlanet($planet)
{
if (!$planet instanceof Wootook_Empire_Model_Planet) {
$planetCollection = $this->_preparePlanetCollection()->where('id=:id');
$planetCollection->load(array(
'id' => $planet,
'user' => $this->getId()
));
if ($planetCollection->count() !== 1) {
return $this;
}
$planet = $planetCollection->current();
}
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return $this;
}
$this->setData('current_planet', $planet->getId())->save();
return $this;
}
/**
*
* Enter description here ...
* @param Wootook_Empire_Model_Planet $planet
*/
public function setHomePlanet(Wootook_Empire_Model_Planet $planet)
{
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return $this;
}
$this->setData('id_planet', $planet->getId());
$this->_homePlanet = $planet;
return $this;
}
/**
*
* Enter description here ...
* @param Wootook_Empire_Model_Planet $planet
*/
public function setCurrentPlanet(Wootook_Empire_Model_Planet $planet)
{
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return $this;
}
$this->setData('current_planet', $planet->getId());
$this->_currentPlanet = $planet;
return $this;
}
/**
*
* Enter description here ...
* @return Wootook_Empire_Model_Planet
*/
public function getHomePlanet()
{
if ($this->_homePlanet === null) {
$planetId = $this->getData('id_planet');
if (!$planetId) {
return null;
}
$planet = Wootook_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
return null;
}
$this->_homePlanet = $planet;
}
return $planet;
}
/**
*
* Enter description here ...
* @return Wootook_Empire_Model_Planet
*/
public function getCurrentPlanet()
{
if ($this->_currentPlanet === null) {
$planetId = $this->getData('current_planet');
if (!$planetId) {
$this->_currentPlanet = $this->getHomePlanet();
$this->setData('current_planet', $this->_currentPlanet->getId())->save();
return $this->_currentPlanet;
}
$planet = Wootook_Empire_Model_Planet::factory($planetId);
if ($planet->getUserId() != $this->getId() || $planet->isDestroyed()) {
$this->_currentPlanet = $this->getHomePlanet();
$this->setData('current_planet', $this->_currentPlanet->getId())->save();
return $this->_currentPlanet;
}
$this->_currentPlanet = $planet;
}
return $this->_currentPlanet;
}
protected function _preparePlanetCollection()
{
$planetCollection = new Wootook_Core_Collection(array('planet' => 'planets'), 'Wootook_Empire_Model_Planet');
$planetCollection->where('id_owner=:user');
$order = ($this->getData('planet_sort_order') == 1) ? 'DESC' : 'ASC';
switch ($this->getData('planet_sort')) {
case self::PLANET_SORT_POSITION:
$planetCollection
->order('planet.galaxy', $order)
->order('planet.system', $order)
->order('planet.planet', $order)
->order('planet.planet_type', $order)
;
break;
case self::PLANET_SORT_NAME:
$planetCollection->order('planet.name', $order);
break;
case self::PLANET_SORT_DATE:
default:
$planetCollection->order('planet.id', $order);
break;
}
return $planetCollection;
}
public function getPlanetCollection()
{
$planetCollection = $this->_preparePlanetCollection();
$planetCollection->load(array(
'user' => $this->getId()
));
return $planetCollection;
}
protected function _prepareFleetCollection()
{
$collection = new Wootook_Core_Collection(array('fleet' => 'fleets'));
$collection
->setEntityClassName('Wootook_Empire_Model_Fleet')
->where('fleet_owner <= :user_id')
;
return $collection;
}
public function getFleets()
{
return $this->_prepareFleetCollection()->load(array('user_id' => $this->getId()));
}
public function getFleetCount()
{
return $this->_prepareFleetCollection()->getSize(array('user_id' => $this->getId()));
}
public function getVisibleFleets()
{
$user = Wootook_Empire_Model_User::getSingleton();
$firstCollection = new Wootook_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 Wootook_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 Wootook_Core_Collection();
$collection
->setEntityClassName('Wootook_Empire_Model_Fleet')
->union($firstCollection)
->union($backCollection)
->load(array('now' => time()));
return $collection;
}
public function getElement($elementId)
{
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->getData($fields[$elementId]);
}
public function setElement($elementId, $level)
{
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->setData($fields[$elementId], $level);
}
public function hasElement($elementId, $levelRequired = 0)
{
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
return $this->hasData($fields[$elementId]) && Math::comp($this->getElement($elementId), $levelRequired) > 0;
}
public function getSkinPath($default = null)
{
if ($path = $this->getData('dpath')) {
return $path;
}
return $default;
}
public function setSkinPath($path)
{
$this->setData('dpath', $path);
return $this;
}
public function checkPassword($password)
{
if (self::hash($password) == $this->getData('password')) {
return true;
}
return false;
}
public function getFleetCollection($time = null)
{
$firstCollection = new Wootook_Core_Collection(array('fleet' => 'fleets'));
$firstCollection
->column('*')
->where('fleet.fleet_owner = :user')
;
$backCollection = new Wootook_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 Wootook_Core_Collection();
$collection
->setEntityClassName('Wootook_Empire_Model_Fleet')
->union($firstCollection)
->union($backCollection)
->load($options)
;
return $collection;
}
public function getNewMessagesCount()
{
$messageCollection = new Wootook_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,14 @@
<?php
class Wootook_Empire_Model_User_Message
extends Wootook_Core_Entity_SubTable
{
protected $_eventObject = 'message';
protected $_eventPrefix = 'user.message';
protected function _init()
{
$this->_tableName = 'messages';
$this->_idFieldNames = array('message_id', 'message_owner');
}
}

View file

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

View file

@ -0,0 +1,82 @@
<?php
class Wootook_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);
}
}