Updated data access layer

Renamed classes, methods & variables from "User" to "Player"
Fixed dependencies requirements in the research lab queue
Updated overview
Added MVC's controller
Added build files
Updated directory structure

Signed-off-by: Gregory PLANCHAT <g.planchat@gmail.com>
This commit is contained in:
Gregory PLANCHAT 2012-02-28 22:43:37 +01:00
commit 690a7f60f3
1435 changed files with 5772 additions and 5764 deletions

View file

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

View file

@ -0,0 +1,76 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_ResearchLab
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_Player_Model_Session::getSingleton()->getPlayer()
->getCurrentPlanet()
;
}
return $this->_planet;
}
public function _initChildBlocks()
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
/** @var Wootook_Core_Block_Concat $parentBlock */
$parentBlock = $this->getLayout()->getBlock('item-list.items');
foreach ($types->getData(Legacies_Empire::TYPE_RESEARCH) as $itemId) {
if (!$this->getPlanet()->getResearchLab()->checkAvailability($itemId)) {
continue;
}
$block = $this->getItemBlock($itemId);
$parentBlock->setPartial($block->getName(), $block);
}
return $this;
}
}

View file

@ -0,0 +1,90 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_ResearchLab_Item
extends Wootook_Empire_Block_Planet_Builder_ItemAbstract
{
public function getLevel()
{
return $this->getPlayer()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResearchLab()->getResourcesNeeded($this->getItemId(), $level);
}
public function getQueuedLevel()
{
return $this->getPlanet()->getResearchLab()->getResearchLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getResearchLab()->getResearchTime($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,48 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_ResearchLab_Queue
extends Wootook_Empire_Block_Planet_Builder_QueueAbstract
{
public function getQueue()
{
return $this->getPlanet()->getResearchLab()->getBuilder();
}
public function isEmpty()
{
return $this->getQueue()->count() == 0;
}
}

View file

@ -0,0 +1,106 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_ResearchLab_Queue_Item
extends Wootook_Empire_Block_Planet_Builder_Queue_ItemAbstract
{
protected $_itemIdField = 'research_id';
public function getLevel()
{
return $this->getPlayer()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getResearchLab()->getResourcesNeeded($this->getItemId(), $this->getQueuedLevel() + 1);
}
public function getItemQueuedLevel()
{
return $this->getItem()->getData('level');
}
public function getQueuedLevel()
{
return $this->getPlanet()->getResearchLab()->getResearchLevelQueued($this->getItemId());
}
public function getBuildingTime($level)
{
return $this->getPlanet()->getResearchLab()->getBuildingTime($this->getItemId(), $level);
}
public function getBuildingRemainingTime()
{
$totalTime = $this->getPlanet()->getResearchLab()
->getResearchTime($this->getItemId(), $this->getItemQueuedLevel());
$item = $this->getItem();
return $item->getData('created_at') - $item->getData('updated_at') + $totalTime;
}
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,115 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_Shipyard
extends Wootook_Empire_Block_Planet_BuilderAbstract
{
protected $_planet = null;
protected $_type = Legacies_Empire::TYPE_SHIP;
protected $_allowedTypes = array(
Legacies_Empire::TYPE_SHIP,
Legacies_Empire::TYPE_DEFENSE
);
public function setPlanet(Wootook_Empire_Model_Planet $planet)
{
$this->_planet = $planet;
return $this;
}
public function getPlanet()
{
if ($this->_planet === null) {
$this->_planet = Wootook_Player_Model_Session::getSingleton()->getPlayer()
->getCurrentPlanet()
;
}
return $this->_planet;
}
public function setAllowedTypes($types)
{
if (is_array($types)) {
$this->_allowedTypes = $types;
}
return $this;
}
public function addAllowedType($type)
{
if (!in_array($type, $this->_allowedTypes)) {
$this->_allowedTypes[] = $type;
}
return $this;
}
public function getAllowedTypes()
{
return $this->_allowedTypes;
}
public function setType($type)
{
if (in_array($type, $this->_allowedTypes)) {
$this->_type = $type;
}
return $this;
}
public function getType()
{
return $this->_type;
}
public function _initChildBlocks()
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
/** @var Wootook_Core_Block_Concat $parentBlock */
$parentBlock = $this->getLayout()->getBlock('item-list.items');
foreach ($types->getData($this->getType()) as $itemId) {
if (!$this->getPlanet()->getShipyard()->checkAvailability($itemId)) {
continue;
}
$block = $this->getItemBlock($itemId);
$parentBlock->setPartial($block->getName(), $block);
}
return $this;
}
}

View file

@ -0,0 +1,80 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_Shipyard_Item
extends Wootook_Empire_Block_Planet_Builder_ItemAbstract
{
public function getQty()
{
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded($qty)
{
return $this->getPlanet()->getShipyard()->getResourcesNeeded($this->getItemId(), $qty);
}
public function getBuildingTime($qty)
{
return $this->getPlanet()->getShipyard()->getBuildingTime($this->getItemId(), $qty);
}
public function getMaximumBuildableElementsCount()
{
return $this->getPlanet()->getShipyard()->getMaximumBuildableElementsCount($this->getItemId());
}
public function getResourcesConfigForQty($qty)
{
$resources = $this->getResourcesNeeded($qty);
$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;
}
}

View file

@ -0,0 +1,49 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_Shipyard_Queue
extends Wootook_Empire_Block_Planet_Builder_QueueAbstract
{
public function getQueue()
{
return $this->getPlanet()->getShipyard()->getBuilder();
}
public function isEmpty()
{
return $this->getQueue()->count() == 0;
}
}

View file

@ -0,0 +1,87 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Block_Planet_Shipyard_Queue_Item
extends Wootook_Empire_Block_Planet_Builder_Queue_ItemAbstract
{
protected $_itemIdField = 'research_id';
public function getLevel()
{
return $this->getPlanet()->getElement($this->getItemId());
}
public function getResourcesNeeded($level)
{
return $this->getPlanet()->getShipyard()->getResourcesNeeded($this->getItemId(), 1);
}
public function getBuildingTime($qty)
{
return $this->getPlanet()->getShipyard()->getBuildingTime($this->getItemId(), $qty);
}
public function getResourcesConfigForLevel($qty)
{
$resources = $this->getResourcesNeeded($qty);
$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,37 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
interface Legacies_Empire_Exception {}

View file

@ -0,0 +1,46 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_CristalMine
implements Wootook_Empire_Model_Planet_ResourceProductionInterface, Wootook_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_CRISTAL => 10 + 20 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => -10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_DeuteriumSynthetiser
implements Wootook_Empire_Model_Planet_ResourceProductionInterface, Wootook_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_DEUTERIUM => 10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => -30 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_FusionReactor
implements Wootook_Empire_Model_Planet_ResourceProductionInterface, Wootook_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_DEUTERIUM => -10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => 50 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_MetalMine
implements Wootook_Empire_Model_Planet_ResourceProductionInterface, Wootook_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_METAL => 20 + 30 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio),
Legacies_Empire::RESOURCE_ENERGY => -10 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -0,0 +1,52 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_NaniteFactory
implements Wootook_Empire_Model_Planet_BuildingInterface
{
public static function buildingTimeListener($event)
{
$planet = $event->getData('planet');
if (!$planet->getId() || ($level = $planet->getElement(Legacies_Empire::ID_BUILDING_NANITE_FACTORY)) <= 0) {
return;
}
$time = $event->getData('time');
$speedFactor = pow(2, $level);
$event->setData('time', $time / $speedFactor);
}
}

View file

@ -0,0 +1,272 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
* Research lab building, manages researches queue on each planet
*
* @access public
* @category Empire
* @category Planet
* @package Legacies
* @subpackage Legacies_Empire
*/
class Legacies_Empire_Model_Planet_Building_ResearchLab
implements Wootook_Empire_Model_Planet_BuildingInterface,
Wootook_Empire_Model_Planet_QueueInterface
{
private $_eventPrefix = 'planet.laboratory.';
/**
* Planet instance
* @var Legacies_Empire_Model_Planet
*/
protected $_currentPlanet = null;
/**
* Player instance
* @var Woootook_Player_Model_Entity
*/
protected $_currentPlayer = null;
/**
* construction queue
* @var Legacies_Empire_Model_Planet_Building_ResearchLab_Builder
*/
protected $_builder = null;
/**
* Multiton instances
* @var array
*/
protected static $_instances = array();
/**
* Multiton factory. Retruns the planet's research lab instance or created it if
* it doesn't yet exist.
*
* @param Legacies_Empire_Model_Planet $currentPlanet
* @param Woootook_Player_Model_Entity $currentPlayer
* @return Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public static function factory($currentPlanet, $currentPlayer)
{
if ($currentPlanet->getId()) {
return null;
}
if (!isset(self::$_instances[$currentPlanet->getId()])) {
self::$_instances[$currentPlanet->getId()] = new self($currentPlanet, $currentPlayer);
}
return self::$_instances[$currentPlanet->getId()];
}
/**
* Constructor. Used for specific usage, use the factory for standard usage.
*
* @see Legacies_Empire_Model_Planet_Building_ResearchLab::factory()
*
* @param Legacies_Empire_Model_Planet $currentPlanet
* @param Woootook_Player_Model_Entity $currentPlayer
*/
public function __construct($currentPlanet, $currentPlayer)
{
$this->_currentPlanet = $currentPlanet;
$this->_currentPlayer = $currentPlayer;
$this->_builder = new Legacies_Empire_Model_Planet_Building_ResearchLab_Builder($currentPlanet, $currentPlayer);
}
/**
* @deprecated
* @return Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public function save()
{
$this->_currentPlanet->save();
return $this;
}
/**
* Append items to build to the construction list
*
* @param int $researchId
* @param int|string $level
* @return Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public function appendQueue($researchId, $level = null, Wootook_Core_DateTime $time = null)
{
if ($time === null) {
$time = new Wootook_Core_DateTime();
}
if ($level === null) {
$level = $this->_currentPlayer->getElement($researchId) + 1;
}
// Dispatch event
Wootook::dispatchEvent($this->_eventPrefix . 'append-queue.before', array(
'research_id' => $researchId,
'level' => &$level,
'time' => &$time,
'laboratory' => $this,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer
));
$this->_builder->appendQueue($researchId, $level, $time);
// Dispatch event
Wootook::dispatchEvent($this->_eventPrefix . 'append-queue.after', array(
'research_id' => $researchId,
'level' => $level,
'time' => $time,
'laboratory' => $this,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer
));
return $this;
}
/**
* Update the contruction queue.
*
* @return Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public function updateQueue(Wootook_Core_DateTime $time = null)
{
if ($time === null) {
$time = new Wootook_Core_DateTime();
}
// Dispatch event
Wootook::dispatchEvent($this->_eventPrefix . 'update-queue.before', array(
'time' => &$time,
'laboratory' => $this,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer
));
$this->_builder->updateQueue($time);
// Dispatch event
Wootook::dispatchEvent($this->_eventPrefix . 'update-queue.after', array(
'time' => $time,
'laboratory' => $this,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer
));
return $this;
}
/**
* Return the construction queue
* @see Legacies_Empire_Model_Planet_Building_ResearchLab_Builder
*
* @return array
*/
public function getBuilder()
{
return $this->_builder;
}
/**
* Check if a ship or defense type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int $resourceId
* @return bool
*/
public function checkAvailability($researchId)
{
try {
if (!$this->_builder->checkAvailability($researchId)) {
return false;
}
// Dispatch event
Wootook::dispatchEvent($this->_eventPrefix . 'check-availability', array(
'research_id' => $researchId,
'laboratory' => $this,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer
));
} catch (Legacies_Core_Event_Break $e) {
return false;
}
return true;
}
public function getResourcesNeeded($researchId, $level)
{
return $this->_builder->getResourcesNeeded($researchId, $level);
}
public function getResearchTime($researchId, $level)
{
return $this->_builder->getBuildingTime($researchId, $level);
}
public function getResearchLevelQueued($researchId)
{
$level = $this->_currentPlayer->getElement($researchId);
foreach ($this->_builder as $item) {
if ($item->getData('research_id') != $researchId) {
continue;
}
$level = $item->getData('level');
}
return $level;
}
public static function planetUpdateListener($eventData)
{
if (isset($eventData['planet'])) {
$planet = $eventData['planet'];
if ($planet === null || !$planet instanceof Legacies_Empire_Model_Planet || !$planet->getId()) {
return;
}
$time = null;
if (isset($eventData['time'])) {
$time = $eventData['time'];
}
$researchLab = $planet->getResearchLab();
if ($researchLab !== null) {
$researchLab->updateQueue();
}
}
}
}

View file

@ -0,0 +1,337 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_ResearchLab_Builder
extends Wootook_Empire_Model_BuilderAbstract
{
const FIELD_SERIALIZED = 'b_tech_id';
const FIELD_DATETIME = 'b_tech';
/**
* @var int
*/
protected $_maxLength = 0;
public function init()
{
$this->_unserializeQueue($this->_currentPlanet->getData(self::FIELD_SERIALIZED));
$this->_maxLength = Wootook::getGameConfig('engine/core/lab_queue_size');
}
/**
* @param array $params
*/
protected function _initItem(Array $params)
{
if (!isset($params['technology_id']) || !isset($params['level'])) {
return null;
}
$technologyId = $params['technology_id'];
$level = $params['level'];
if (!isset($params['created_at'])) {
$createdAt = new Wootook_Core_DateTime();
} 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 Legacies_Empire_Model_Planet_Building_ResearchLab_Item(array(
'technology_id' => $technologyId,
'level' => $level,
'created_at' => $createdAt,
'started_at' => $startedAt,
'updated_at' => $updatedAt
));
}
/**
* Check if a technology type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int|string $technologyId
* @return bool
*/
public function checkAvailability($technologyId)
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
if (!$types->is($technologyId, Legacies_Empire::TYPE_RESEARCH)) {
return false;
}
return parent::checkAvailability($technologyId);
}
/**
* Returns the time needed to build $level of $technologyId
*
* @param int|string $technologyId
* @param int $level
*/
public function getBuildingTime($technologyId, $level)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
Math::setPrecision(50);
$firstLevelTime = $prices[$technologyId][Legacies_Empire::BASE_BUILDING_TIME];
$partialLevelTime = Math::mul($firstLevelTime, Math::pow($prices[$technologyId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
$levelTime = Math::sub($partialLevelTime, $firstLevelTime);
$speedFactor = Wootook::getGameConfig('game/speed/general');
if ($speedFactor == null) {
$speedFactor = 1;
}
$baseTime = $levelTime / ($speedFactor * 3600);
Math::setPrecision();
$event = Wootook::dispatchEvent('planet.research-lab.technology.building-time', array(
'time' => $baseTime,
'base_time' => $baseTime,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer,
'technology_id' => $technologyId,
'level' => $level
));
return $event->getData('time');
}
/**
* (non-PHPdoc)
* @see Legacies_Empire_Model_BuilderAbstract::getResourcesNeeded()
*/
public function getResourcesNeeded($technologyId, $level)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
$resources = Wootook_Empire_Model_Game_Resources::getSingleton();
if (!isset($prices[$technologyId])) {
return array();
}
$resourcesNeeded = array();
foreach ($resources as $resourceId => $resourceConfig) {
if (!isset($prices[$technologyId][$resourceId])) {
continue;
}
if (Math::isPositive($prices[$technologyId][$resourceId])) {
$firstLevelCost = $prices[$technologyId][$resourceId];
$partialLevelCost = Math::mul($firstLevelCost, Math::pow($prices[$technologyId][Legacies_Empire::RESOURCE_MULTIPLIER], $level));
$resourcesNeeded[$resourceId] = Math::sub($partialLevelCost, $firstLevelCost);
}
}
return $resourcesNeeded;
}
/**
* Update the contruction queue.
*
* @return Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public function updateQueue(Wootook_Core_DateTime $time)
{
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
$startingTime = clone $this->_currentPlanet->getData(self::FIELD_DATETIME);
$elapsedTime = $time->getTimestamp() - $this->_currentPlanet->getData(self::FIELD_DATETIME)->getTimestamp();
foreach ($this->getQueue() as $element) {
$elementTime = $element->getData('started_at');
if ($elementTime === null) {
$element->setData('started_at', $startingTime->getTimestamp());
$elementTime = $startingTime->getTimestamp();
}
$level = $element->getData('level');
$technologyId = $element->getData('technology_id');
$buildTime = $this->getBuildingTime($technologyId, $level);
$elapsedTime = $time->getTimestamp() - $elementTime;
if ($elapsedTime >= $buildTime) {
$this->dequeue($element);
$currentTime = clone $startingTime;
$currentTime->add($elapsedTime);
$this->_currentPlayer->setElement($technologyId, $level);
$this->_currentPlanet->updateStorages($currentTime);
$this->_currentPlanet->updateResourceProduction($currentTime);
$this->_currentPlanet->updateBuildingFields();
Wootook::dispatchEvent('planet.research-lab.technology.level-update', array(
'time' => $currentTime,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer,
'technology_id' => $technologyId,
'level' => $level
));
$startingTime->set($elementTime + $buildTime);
continue;
}
break;
}
$this->_currentPlanet->setData(self::FIELD_SERIALIZED, $this->serialize());
$this->_currentPlanet->setData(self::FIELD_DATETIME, $startingTime->now());
return $this;
}
/**
* Append items to build to the construction list
*
* @param int|string $technologyId
* @param int $level
* @return Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public function appendQueue($technologyId, $level, Wootook_Core_DateTime $time)
{
if ($this->_maxLength > 0 && $this->count() >= $this->_maxLength) {
return $this;
}
$types = Wootook_Empire_Model_Game_Types::getSingleton();
if (!Math::isPositive($level)) {
return $this;
}
if (!$types->is($technologyId, Legacies_Empire::TYPE_RESEARCH)) {
return $this;
}
if (!$this->checkAvailability($technologyId)) {
return $this;
}
$resourcesNeeded = $this->getResourcesNeeded($technologyId, $level);
$remainingAmounts = $this->_calculateResourceRemainingAmounts($resourcesNeeded);
if ($remainingAmounts === false) {
return $this;
}
if ($this->count() == 0) {
$this->_currentPlanet->setData(self::FIELD_DATETIME, $time);
}
$this->enqueue(array(
'technology_id' => $technologyId,
'level' => $level,
'created_at' => $time->getTimestamp()
));
$this->_currentPlanet->setData(self::FIELD_SERIALIZED, $this->serialize());
$this->_currentPlayer->setdata('b_tech_planet', $this->_currentPlanet->getId());
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 Legacies_Empire_Model_Planet_Building_ResearchLab
*/
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 Legacies_Empire_Model_Planet_Building_ResearchLab
*/
public function dequeueItem($itemId)
{
$item = $this->getItem($itemId);
if (!$item) {
return $this;
}
$technologyId = $item->getData('technology_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('technology_id') != $technologyId) {
continue;
}
$resourcesNeeded = $this->getResourcesNeeded($technologyId, $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(self::FIELD_SERIALIZED, $this->serialize());
return $this;
}
}

View file

@ -0,0 +1,39 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_ResearchLab_Item
extends Wootook_Empire_Model_Builder_Item
{
}

View file

@ -0,0 +1,52 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_RoboticFactory
implements Wootook_Empire_Model_Planet_BuildingInterface
{
public static function buildingTimeListener($event)
{
$planet = $event->getData('planet');
if (!$planet->getId() || ($level = $planet->getElement(Legacies_Empire::ID_BUILDING_ROBOTIC_FACTORY)) <= 0) {
return;
}
$time = $event->getData('time');
$speedFactor = 1 + $level;
$event->setData('time', $time / $speedFactor);
}
}

View file

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

View file

@ -0,0 +1,339 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_Shipyard_Builder
extends Wootook_Empire_Model_BuilderAbstract
{
/**
* @var int
*/
protected $_maxLength = 0;
public function init()
{
$this->_unserializeQueue($this->_currentPlanet->getData('b_hangar_id'));
}
/**
* @param int $buildingId
* @param int $qty
* @param int $time
*/
protected function _initItem(Array $params)
{
if (!isset($params['ship_id']) || !isset($params['qty'])) {
return null;
}
$shipId = $params['ship_id'];
$qty = $params['qty'];
if (!isset($params['created_at'])) {
$createdAt = new Wootook_Core_DateTime();
} else {
$createdAt = $params['created_at'];
}
if (!isset($params['updated_at'])) {
$updatedAt = $createdAt;
} else {
$updatedAt = $params['updated_at'];
}
return new Legacies_Empire_Model_Planet_Building_Shipyard_Item(array(
'ship_id' => $shipId,
'qty' => $qty,
'created_at' => $createdAt,
'updated_at' => $updatedAt
));
}
/**
* Check if a ship or defense type is actually buildable on the current
* planet, depending on the technology and buildings requirements.
*
* @param int $shipId
* @return bool
*/
public function checkAvailability($shipId)
{
$types = Wootook_Empire_Model_Game_Types::getSingleton();
if (!$types->is($shipId, Legacies_Empire::TYPE_SHIP) && !$types->is($shipId, Legacies_Empire::TYPE_DEFENSE)) {
return false;
}
return parent::checkAvailability($shipId);
}
/**
* Returns the maximum quantity of elements that are possible to build on
* the current planet.
*
* @param int $shipId
* @return int|string
*/
public function getMaximumBuildableElementsCount($shipId)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
$resources = Wootook_Empire_Model_Game_Resources::getSingleton();
$qty = 0;
foreach ($resources as $resourceId => $_) {
if (isset($prices[$shipId]) && isset($prices[$shipId][$resourceId]) && Math::comp($prices[$shipId][$resourceId], 0) > 0) {
$maxQty = Math::floor(Math::div($this->_currentPlanet->getData($resourceId), $prices[$shipId][$resourceId]));
if ($maxQty == 0) {
return 0;
}
if ($qty == 0 || Math::comp($maxQty, $qty) < 0) {
$qty = $maxQty;
}
}
}
if ($qty == 0) {
return 0;
}
$limitedElementsQty = array(
Legacies_Empire::ID_DEFENSE_SMALL_SHIELD_DOME => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_SMALL_SHIELD_DOME]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_SMALL_SHIELD_DOME]],
'limit' => 1
),
Legacies_Empire::ID_DEFENSE_LARGE_SHIELD_DOME => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_LARGE_SHIELD_DOME]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_DEFENSE_LARGE_SHIELD_DOME]],
'limit' => 1
),
Legacies_Empire::ID_SPECIAL_ANTIBALLISTIC_MISSILE => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_ANTIBALLISTIC_MISSILE]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_ANTIBALLISTIC_MISSILE]],
'limit' => $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_MISSILE_SILO]] * 10
),
Legacies_Empire::ID_SPECIAL_INTERPLANETARY_MISSILE => array(
'current' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_INTERPLANETARY_MISSILE]],
'requested' => $this->_currentPlanet[$fields[Legacies_Empire::ID_SPECIAL_INTERPLANETARY_MISSILE]],
'limit' => $this->_currentPlanet[$fields[Legacies_Empire::ID_BUILDING_MISSILE_SILO]] * 5
)
);
if (in_array($shipId, array_keys($limitedElementsQty))) {
foreach ($this->getQueue() as $element) {
if ($element['ship_id'] != $shipId) {
continue;
}
$limitedElementsQty[$shipId]['requested'] = Math::add($limitedElementsQty[$shipId]['requested'], $element['qty']);
if (Math::comp($limitedElementsQty[$shipId]['requested'], $limitedElementsQty[$shipId]['limit']) >= 0) {
return 0;
}
}
if (Math::comp($limitedElementsQty[$shipId]['current'], $limitedElementsQty[$shipId]['limit']) >= 0) {
return 0;
}
if (Math::comp($qty, $limitedElementsQty[$shipId]['limit']) >= 0) {
return $limitedElementsQty[$shipId]['limit'];
}
}
return $qty;
}
/**
* Returns the time needed to build $qty of $shipId
*
* @param int $shipId
* @param int $qty
*/
public function getBuildingTime($shipId, $qty)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
Math::setPrecision(50);
$buildingTime = Math::mul($prices[$shipId][Legacies_Empire::BASE_BUILDING_TIME], $qty);
$speedFactor = Wootook::getGameConfig('game/speed/general');
$baseTime = Math::div($buildingTime, $speedFactor);
Math::setPrecision();
$event = Wootook::dispatchEvent('planet.shipyard.building-time', array(
'time' => $baseTime,
'base_time' => $baseTime,
'planet' => $this->_currentPlanet,
'player' => $this->_currentPlayer,
'ship_id' => $shipId,
'qty' => $qty
));
return $event->getData('time');
}
/**
* (non-PHPdoc)
* @see Legacies_Empire_Model_BuilderAbstract::getResourcesNeeded()
*/
public function getResourcesNeeded($shipId, $qty)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
$resources = Wootook_Empire_Model_Game_Resources::getSingleton();
if (!isset($prices[$shipId])) {
return array();
}
$resourcesNeeded = array();
foreach ($resources as $resourceId => $resourceConfig) {
if (!isset($prices[$shipId][$resourceId])) {
continue;
}
if (Math::isPositive($prices[$shipId][$resourceId])) {
$resourcesNeeded[$resourceId] = Math::mul($prices[$shipId][$resourceId], $qty);
}
}
return $resourcesNeeded;
}
/**
* Returns the quantity set in parameter or the maximum buildable elements
* if the quantity requested exeeds this number.
*
* @param int $shipId
* @param int|string $qty
* @return int|stirng
*/
protected function _checkMaximumQuantity($shipId, $qty)
{
return Math::min($qty, $this->getMaximumBuildableElementsCount($shipId));
}
/**
* Update the contruction queue.
*
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function updateQueue(Wootook_Core_DateTime $time)
{
$fields = Wootook_Empire_Model_Game_FieldsAlias::getSingleton();
$elapsedTime = $time->getTimestamp() - $this->_currentPlanet->getData('b_hangar')->getTimestamp();
foreach ($this->getQueue() as $element) {
$shipId = $element->getData('ship_id');
$qty = $element->getData('qty');
$buildTime = $this->getBuildingTime($shipId, $qty);
if ($elapsedTime >= $buildTime) {
$this->_currentPlanet[$fields[$shipId]] = Math::add($this->_currentPlanet[$fields[$shipId]], $qty);
$elapsedTime -= $buildTime;
$this->dequeue($element);
continue;
}
$timeRatio = $elapsedTime / $buildTime;
$itemsBuilt = Math::mul($timeRatio, $qty);
$element->setData('updated_at', $time->getTimestamp());
$element->setData('qty', Math::sub($qty, $itemsBuilt));
$this->_currentPlanet->setData($fields[$shipId], Math::add($this->_currentPlanet->getData($fields[$shipId]), $itemsBuilt));
break;
}
$this->_currentPlanet->setData('b_hangar_id', $this->serialize());
$this->_currentPlanet->setData('b_hangar', $time);
return $this;
}
/**
* Append items to build to the construction list
*
* @param int $shipId
* @param int|string $qty
* @return Legacies_Empire_Model_Planet_Building_Shipyard
*/
public function appendQueue($shipId, $qty, Wootook_Core_DateTime $time)
{
if ($this->_maxLength > 0 && $this->count() >= $this->_maxLength) {
return $this;
}
if (!Math::isPositive($qty)) {
return $this;
}
$types = Wootook_Empire_Model_Game_Types::getSingleton();
if (!$types->is($shipId, Legacies_Empire::TYPE_SHIP) && !$types->is($shipId, Legacies_Empire::TYPE_DEFENSE)) {
return $this;
}
if (!$this->checkAvailability($shipId)) {
return $this;
}
if (MAX_FLEET_OR_DEFS_PER_ROW > 0) {
$qty = Math::min($this->_checkMaximumQuantity($shipId, $qty), MAX_FLEET_OR_DEFS_PER_ROW);
} else {
$qty = $this->_checkMaximumQuantity($shipId, $qty);
}
if (!Math::isPositive($qty)) {
return $this;
}
$resourcesNeeded = $this->getResourcesNeeded($shipId, $qty);
$remainingAmounts = $this->_calculateResourceRemainingAmounts($resourcesNeeded);
if ($remainingAmounts === false) {
return $this;
}
$this->enqueue(array(
'ship_id' => $shipId,
'qty' => $qty,
'created_at' => $time->getTimestamp(),
'updated_at' => $time->getTimestamp()
));
$this->_currentPlanet->setData('b_hangar_id', $this->serialize());
foreach ($remainingAmounts as $resourceId => $resourceAmount) {
$this->_currentPlanet[$resourceId] = $resourceAmount;
}
return $this;
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Building_Shipyard_Item
extends Wootook_Empire_Model_Builder_Item
{
}

View file

@ -0,0 +1,40 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
class Legacies_Empire_Model_Planet_Building_SolarPlant
implements Wootook_Empire_Model_Planet_ResourceProductionInterface, Wootook_Empire_Model_Planet_BuildingInterface
{
public function getProductionRatios($level, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_ENERGY => 20 * floatval($level) * pow(1.1, floatval($level)) * (0.1 * $produtionRatio)
);
}
}

View file

@ -0,0 +1,53 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Ship_LargeTransport
extends Wootook_Empire_Model_Planet_ShipAbstract
{
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE = 4;
public function getBaseSpeed(Wootook_Player_Model_Entity $player)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
return $prices[Legacies_Empire::ID_SHIP_LARGE_TRANSPORT][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
}
public function getSpeedMultiplier(Wootook_Player_Model_Entity $player)
{
return pow(1.1, $player->getElement(Legacies_Empire::ID_RESEARCH_COMBUSTION_DRIVE));
}
}

View file

@ -0,0 +1,61 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Ship_LightTransport
extends Wootook_Empire_Model_Planet_ShipAbstract
{
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE = 4;
public function getBaseSpeed(Wootook_Player_Model_Entity $player)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
if ($player->getElement(Legacies_Empire::ID_RESEARCH_IMPULSE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE) {
return $prices[Legacies_Empire::ID_SHIP_LIGHT_TRANSPORT][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
} else {
return $prices[Legacies_Empire::ID_SHIP_LIGHT_TRANSPORT][Legacies_Empire::SHIPS_CELERITY_SECONDARY];
}
}
public function getSpeedMultiplier(Wootook_Player_Model_Entity $player)
{
if ($player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_IMPULSE_DRIVE) {
return pow(1.1, $player->getElement(Legacies_Empire::ID_RESEARCH_COMBUSTION_DRIVE));
} else {
return pow(1.2, $player->getElement(Legacies_Empire::ID_RESEARCH_IMPULSE_DRIVE));
}
}
}

View file

@ -0,0 +1,66 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Ship_SolarSatellite
extends Wootook_Empire_Model_Planet_ShipAbstract
implements Wootook_Empire_Model_Planet_ResourceProductionInterface
{
public function getProductionRatios($quantity, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_ENERGY => ((floatval($planet->getData('temp_max')) / 4) + 20) * (0.1 * $produtionRatio) * floatval($quantity)
);
}
public function getBaseSpeed(Wootook_Player_Model_Entity $player)
{
return 0;
}
public function getSpeedMultiplier(Wootook_Player_Model_Entity $player)
{
return 0;
}
public function getActualSpeed(Wootook_Player_Model_Entity $player)
{
return 0;
}
public function getBaseConsumption(Wootook_Player_Model_Entity $player)
{
return 0;
}
}

View file

@ -0,0 +1,77 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Legacies_Empire_Model_Planet_Ship_Supernova
extends Wootook_Empire_Model_Planet_ShipAbstract
implements Wootook_Empire_Model_Planet_ResourceProductionInterface
{
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE = 20;
const REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY = 15;
public function getProductionRatios($quantity, $produtionRatio, $planet, $player)
{
return array(
Legacies_Empire::RESOURCE_ENERGY => ((floatval($planet->getData('temp_max')) / 4) + 20) * (0.1 * $produtionRatio) * floatval($quantity) * -1250
);
}
public function getBaseSpeed(Wootook_Player_Model_Entity $player)
{
$prices = Wootook_Empire_Model_Game_Prices::getSingleton();
if ($player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE &&
$player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_TECHNOLOGY) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY) {
return $prices[Legacies_Empire::ID_SHIP_SUPERNOVA][Legacies_Empire::SHIPS_CELERITY_PRIMARY];
} else {
return $prices[Legacies_Empire::ID_SHIP_SUPERNOVA][Legacies_Empire::SHIPS_CELERITY_SECONDARY];
}
}
public function getSpeedMultiplier(Wootook_Player_Model_Entity $player)
{
if ($player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_DRIVE &&
$player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_TECHNOLOGY) < self::REQUIREMENT_TO_UPGRADE_CELERITY__RESEARCH_HYPERSPACE_TECHNOLOGY) {
return pow(1.2, $player->getElement(Legacies_Empire::ID_RESEARCH_IMPULSE_DRIVE));
} else {
return pow(1.3, $player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_DRIVE)) *
pow(1.1, $player->getElement(Legacies_Empire::ID_RESEARCH_HYPERSPACE_TECHNOLOGY));
}
}
public function getBaseConsumption(Wootook_Player_Model_Entity $player)
{
return 0;
}
}

View file

@ -0,0 +1,853 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
$this->setSetupConnection('core_setup');
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('galaxy')} (
`galaxy` SMALLINT 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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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` DATETIME NOT NULL,
`planet_type` TINYINT UNSIGNED NOT NULL,
`destruyed` BOOL NOT NULL DEFAULT FALSE,
`b_building` INT UNSIGNED NOT NULL,
`b_building_id` TEXT NOT NULL,
`b_tech` INT UNSIGNED NOT NULL,
`b_tech_id` SMALLINT UNSIGNED NOT NULL,
`b_hangar` INT 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,
`cristal` DECIMAL(65,0) NOT NULL DEFAULT 0,
`cristal_perhour` DECIMAL(65,0) NOT NULL DEFAULT 0,
`cristal_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,
`cristal_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,
`cristal_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,
`cristal_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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
$sql = <<<SQL_EOF
CREATE TABLE IF NOT EXISTS {$this->getTableName('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);
/*
* Galaxy positions generation
*/
$galaxyCount = Wootook::getConfig('engine/universe/galaxies');
$systemCount = Wootook::getConfig('engine/universe/systems');
$sql = <<<SQL_EOF
INSERT INTO {$this->getTableName('galaxy')}
(`galaxy`, `system`, `planet`, `id_planet`, `metal`, `crystal`, `id_luna`, `luna`)
SELECT
_increment.galaxy AS `galaxy`,
_increment.system AS `system`,
0 AS `planet`,
0 AS `id_planet`,
0 AS `metal`,
0 AS `crystal`,
0 AS `id_luna`,
0 AS `luna`
FROM (
SELECT
(1 + _galaxy_10e0.galaxy + _galaxy_10e1.galaxy + _galaxy_10e2.galaxy + _galaxy_10e3.galaxy + _galaxy_10e4.galaxy) AS galaxy,
(1 + _system_10e0.system + _system_10e1.system + _system_10e2.system + _system_10e3.system + _system_10e4.system) AS system
FROM (
SELECT 0 AS system
UNION ALL
SELECT 1 AS system
UNION ALL
SELECT 2 AS system
UNION ALL
SELECT 3 AS system
UNION ALL
SELECT 4 AS system
UNION ALL
SELECT 5 AS system
UNION ALL
SELECT 6 AS system
UNION ALL
SELECT 7 AS system
UNION ALL
SELECT 8 AS system
UNION ALL
SELECT 9 AS system
) AS _system_10e0
SQL_EOF;
if ($systemCount > 10) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS system
UNION ALL
SELECT 10 AS system
UNION ALL
SELECT 20 AS system
UNION ALL
SELECT 30 AS system
UNION ALL
SELECT 40 AS system
UNION ALL
SELECT 50 AS system
UNION ALL
SELECT 60 AS system
UNION ALL
SELECT 70 AS system
UNION ALL
SELECT 80 AS system
UNION ALL
SELECT 90 AS system
) AS _system_10e1
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS system) AS _system_10e1
SQL_EOF;
}
if ($systemCount > 100) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS system
UNION ALL
SELECT 100 AS system
UNION ALL
SELECT 200 AS system
UNION ALL
SELECT 300 AS system
UNION ALL
SELECT 400 AS system
UNION ALL
SELECT 500 AS system
UNION ALL
SELECT 600 AS system
UNION ALL
SELECT 700 AS system
UNION ALL
SELECT 800 AS system
UNION ALL
SELECT 900 AS system
) AS _system_10e2
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS system) AS _system_10e2
SQL_EOF;
}
if ($systemCount > 1000) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS system
UNION ALL
SELECT 1000 AS system
UNION ALL
SELECT 2000 AS system
UNION ALL
SELECT 3000 AS system
UNION ALL
SELECT 4000 AS system
UNION ALL
SELECT 5000 AS system
UNION ALL
SELECT 6000 AS system
UNION ALL
SELECT 7000 AS system
UNION ALL
SELECT 8000 AS system
UNION ALL
SELECT 9000 AS system
) AS _system_10e3
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS system) AS _system_10e3
SQL_EOF;
}
if ($systemCount > 10000) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS system
UNION ALL
SELECT 10000 AS system
UNION ALL
SELECT 20000 AS system
UNION ALL
SELECT 30000 AS system
UNION ALL
SELECT 40000 AS system
UNION ALL
SELECT 50000 AS system
UNION ALL
SELECT 60000 AS system
UNION ALL
SELECT 70000 AS system
UNION ALL
SELECT 80000 AS system
UNION ALL
SELECT 90000 AS system
) AS _system_10e4
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS system) AS _system_10e4
SQL_EOF;
}
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS galaxy
UNION ALL
SELECT 1 AS galaxy
UNION ALL
SELECT 2 AS galaxy
UNION ALL
SELECT 3 AS galaxy
UNION ALL
SELECT 4 AS galaxy
UNION ALL
SELECT 5 AS galaxy
UNION ALL
SELECT 6 AS galaxy
UNION ALL
SELECT 7 AS galaxy
UNION ALL
SELECT 8 AS galaxy
UNION ALL
SELECT 9 AS galaxy
) AS _galaxy_10e0
SQL_EOF;
if ($systemCount > 10) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS galaxy
UNION ALL
SELECT 10 AS galaxy
UNION ALL
SELECT 20 AS galaxy
UNION ALL
SELECT 30 AS galaxy
UNION ALL
SELECT 40 AS galaxy
UNION ALL
SELECT 50 AS galaxy
UNION ALL
SELECT 60 AS galaxy
UNION ALL
SELECT 70 AS galaxy
UNION ALL
SELECT 80 AS galaxy
UNION ALL
SELECT 90 AS galaxy
) AS _galaxy_10e1
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS galaxy) AS _galaxy_10e1
SQL_EOF;
}
if ($systemCount > 100) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS galaxy
UNION ALL
SELECT 100 AS galaxy
UNION ALL
SELECT 200 AS galaxy
UNION ALL
SELECT 300 AS galaxy
UNION ALL
SELECT 400 AS galaxy
UNION ALL
SELECT 500 AS galaxy
UNION ALL
SELECT 600 AS galaxy
UNION ALL
SELECT 700 AS galaxy
UNION ALL
SELECT 800 AS galaxy
UNION ALL
SELECT 900 AS galaxy
) AS _galaxy_10e2
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS galaxy) AS _galaxy_10e2
SQL_EOF;
}
if ($systemCount > 1000) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS galaxy
UNION ALL
SELECT 1000 AS galaxy
UNION ALL
SELECT 2000 AS galaxy
UNION ALL
SELECT 3000 AS galaxy
UNION ALL
SELECT 4000 AS galaxy
UNION ALL
SELECT 5000 AS galaxy
UNION ALL
SELECT 6000 AS galaxy
UNION ALL
SELECT 7000 AS galaxy
UNION ALL
SELECT 8000 AS galaxy
UNION ALL
SELECT 9000 AS galaxy
) AS _galaxy_10e3
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS galaxy) AS _galaxy_10e3
SQL_EOF;
}
if ($systemCount > 10000) {
$sql .= <<<SQL_EOF
CROSS JOIN (
SELECT 0 AS galaxy
UNION ALL
SELECT 10000 AS galaxy
UNION ALL
SELECT 20000 AS galaxy
UNION ALL
SELECT 30000 AS galaxy
UNION ALL
SELECT 40000 AS galaxy
UNION ALL
SELECT 50000 AS galaxy
UNION ALL
SELECT 60000 AS galaxy
UNION ALL
SELECT 70000 AS galaxy
UNION ALL
SELECT 80000 AS galaxy
UNION ALL
SELECT 90000 AS galaxy
) AS _galaxy_10e4
SQL_EOF;
} else {
$sql .= <<<SQL_EOF
CROSS JOIN (SELECT 0 AS galaxy) AS _galaxy_10e4
SQL_EOF;
}
$sql .= <<<SQL_EOF
) _increment
WHERE _increment.galaxy<={$galaxyCount}
AND _increment.system<={$systemCount}
SQL_EOF;
$this->query($sql);

View file

@ -0,0 +1,151 @@
<?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('core_setup');
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('aks')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('alliance')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('annonce')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('banned')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('buddy')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('chat')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('declared')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('fleets')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('galaxy')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('iraks')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('lunas')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('messages')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('multi')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('notes')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('planets')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('rw')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('statpoints')};
SQL_EOF;
$this->query($sql);
$sql = <<<SQL_EOF
DROP TABLE {$this->getTableName('users')};
SQL_EOF;
$this->query($sql);

View file

@ -0,0 +1,37 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
interface Legacies_Exception {}

View file

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

View file

@ -0,0 +1,786 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
* Bootstrap class, used to access main and global functionalities
*
* @package Wootook
* @category core
*/
class Wootook
{
/**
* Static list of application event listeners
*
* @var array
*/
private static $_listeners = array();
/**
* Static list of all locale translators
*
* @var array
*/
private static $_translators = array();
/**
* HTTP request management object
*
* @var Legacies_Core_Controller_Request_Http
*/
private static $_request = null;
/**
* HTTP response management object
*
* @var Legacies_Core_Controller_Response
*/
private static $_response = null;
/**
* The current timestamp
*
* @var int
*/
private static $_now = null;
/**
* Default locale identifier
*
* @var string
*/
private static $_defaultLocale = 'fr_FR';
/**
*
* Enter description here ...
* @var Wootook_Core_Config_Adapter_Abstract
*/
private static $_config = null;
/**
*
* Enter description here ...
* @var Wootook_Core_Config_Adapter_Abstract
*/
private static $_globalConfig = null;
/**
*
* Enter description here ...
* @var array
*/
private static $_websiteConfigs = array();
/**
*
* Enter description here ...
* @var array
*/
private static $_gameConfigs = array();
/**
*
* Enter description here ...
* @var array
*/
private static $_ignoreDatabaseConfig = false;
private static $_defaultWebsite = null;
private static $_defaultGame = null;
private static $_websitesById = array();
private static $_websitesByCode = array();
private static $_gamesById = array();
private static $_gamesByCode = array();
public static $isInstalled = true;
/**
* Registers an event listener to be called later in the application.
*
* @param string $event The event identifier
* @param callback $listener The event callback to be called
*/
public static function registerListener($event, $listener)
{
if (!isset(self::$_listeners[$event])) {
self::$_listeners[$event] = array();
}
self::$_listeners[$event][] = $listener;
}
/**
* Clear all event listeners
*/
public static function clearAllListeners()
{
self::$_listeners = array();
}
/**
* Clear a specific event's listeners
*
* @param unknown_type $event
*/
public static function clearEventListeners($event)
{
if (isset(self::$_listeners[$event])) {
self::$_listeners[$event] = array();
}
}
/**
* Dispatches an event, calls all callbacks that were previously registered
*
* @param string $event The event identifier
* @param array $params The event params
*/
public static function dispatchEvent($event, $params)
{
$eventObject = new Wootook_Core_Event($params);
if (!isset(self::$_listeners[$event])) {
return $eventObject;
}
foreach (self::$_listeners[$event] as $listener) {
call_user_func($listener, $eventObject);
}
return $eventObject;
}
/**
*
* Enter description here ...
* @param unknown_type $namespace
* @return Legacies_Core_Model_Session
*/
public static function getSession($namespace)
{
return Wootook_Core_Model_Session::factory($namespace);
}
public static function getTranslator($locale = null)
{
if ($locale === null) {
$locale = self::getLocale();
}
if (!isset($translator[$locale])) {
$path = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'locale';
$translator[$locale] = new Wootook_Core_Model_Translator($path, $locale);
}
return $translator[$locale];
}
public static function translate($locale, $message, Array $args)
{
return self::getTranslator($locale)->translateArgs($message, $args);
}
public static function __($message, $_ = null)
{
$args = func_get_args();
array_shift($args);
return self::getTranslator(self::getLocale())->translateArgs($message, $args);
}
public static function getLocale()
{
$availableLocales = self::getWebsiteConfig('locales');
if ($availableLocales !== null) {
return self::getPreferredLocale($availableLocales->toArray());
}
return self::getPreferredLocale();
}
public static function setDefaultLocale($locale)
{
$oldLocale = self::$_defaultLocale;
self::$_defaultLocale = $locale;
return $oldLocale;
}
public static function getDefaultLocale()
{
return self::$_defaultLocale;
}
public static function getPreferredLocale($availableLocales = array())
{
if (empty($availableLocales)) {
return self::getDefaultLocale();
}
$userLocale = Wootook_Player_Model_Session::getSingleton()->getData('locale');
if ($userLocale !== null) {
return $userLocale;
}
$locales = array();
if (($accept = self::getRequest()->getServer('HTTP_ACCEPT_LANGUAGE')) !== null) {
// break up string into pieces (languages and q factors)
preg_match_all('/([a-z]{1,8}(?:-([a-z]{1,8}))?)\s*(?:;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $accept, $matches);
$length = count($matches[1]);
for ($i = 0; $i < $length; $i++) {
$locale = $matches[1][$i];
if (!empty($matches[2][$i])) {
$locale .= '_' . strtoupper($matches[2][$i]);
}
$locales[$locale] = !empty($matches[3][$i]) ? min(max(floatval($matches[3][$i]), 0), 1) : 1;
}
arsort($locales, SORT_NUMERIC);
}
if (empty($locales)) {
return self::getDefaultLocale();
}
$preferredLocale = key($locales);
$preferredPriority = current($locales);
foreach ($locales as $locale => $piority) {
if (!in_array($locale, $availableLocales)) {
continue;
}
if ($preferredPriority < $piority) {
$preferredPriority = $piority;
$preferredLocale = $locale;
}
}
Wootook_Player_Model_Session::getSingleton()->setData('locale', $preferredLocale);
return $preferredLocale;
}
public static function now()
{
if (self::$_now === null) {
self::$_now = time();
}
return new Wootook_Core_DateTime(self::$_now);
}
/**
* @return Wootook_Core_Controller_Request_Http
*/
public static function getRequest()
{
if (self::$_request === null) {
self::$_request = new Wootook_Core_Controller_Request_Http();
}
return self::$_request;
}
public static function setRequest($request)
{
self::$_request = $request;
}
/**
* @return Wootook_Core_Controller_Response_Http
*/
public static function getResponse()
{
if (self::$_response === null) {
self::$_response = new Wootook_Core_Controller_Response_Http();
}
return self::$_response;
}
public static function setResponse($response)
{
self::$_response = $response;
}
public static function loadConfig($filename = null)
{
self::$_websiteConfigs = array();
self::$_gameConfigs = array();
self::$_config = new Wootook_Core_Config_Adapter_Array();
try {
self::$_config->load(APPLICATION_PATH . 'configs' . DIRECTORY_SEPARATOR . 'system.php');
if ($filename === null) {
$filename = APPLICATION_PATH . 'configs' . DIRECTORY_SEPARATOR . 'local.php';
}
if (is_string($filename)) {
if (!self::$isInstalled) {
throw new Wootook_Core_Exception_DataAccessException();
}
$localConfig = new Wootook_Core_Config_Adapter_Array($filename);
self::$_config->merge($localConfig);
} else if (is_array($filename)) {
$localConfig = new Wootook_Core_Config_Node($filename);
self::$_config->merge($localConfig);
} else if ($filename instanceof Wootook_Core_Config_Node) {
self::$_config->merge($filename);
} else {
throw new Wootook_Core_Exception_DataAccessException();
}
} catch (Wootook_Core_Exception_DataAccessException $e) {
self::$_globalConfig = new Wootook_Core_Config_Node(array(), self::$_config);
self::$_ignoreDatabaseConfig = true;
return self::$_config;
}
self::$_globalConfig = clone self::$_config['default'];
if (isset(self::$_config['global'])) {
self::$_globalConfig->merge(self::$_config['global']);
}
self::_appendDatabaseConfig(self::$_globalConfig);
return self::$_config;
}
private static function _appendDatabaseConfig(Wootook_Core_Config_Node $config, $type = 'global', $model = null)
{
if (self::$_ignoreDatabaseConfig) {
return $config;
}
$adapter = Wootook_Core_Database::getConnection('core_read');
$select = $adapter->select('core_config');
switch ($type) {
case 'website':
$select->where('website_id = :website_id');
$statement = $adapter->prepare($select);
$statement->execute(array('website_id' => $model->getId()));
break;
case 'game':
$select->where('game_id = :game_id');
$statement = $adapter->prepare($select);
$statement->execute(array('game_id' => $model->getId()));
break;
default:
$select->where('website_id = 0');
$select->where('game_id = 0');
$statement = $adapter->prepare($select);
$statement->execute();
break;
}
foreach ($statement->fetch() as $row) {
$config->setConfig($row['config_path'], $row['config_value']);
}
return $config;
}
public static function getWebsite($websiteId)
{
if (is_numeric($websiteId)) {
if (isset(self::$_websitesById[$websiteId])) {
return self::$_websitesById[$websiteId];
}
$website = new Wootook_Core_Model_Website();
try {
$website->load($websiteId);
$websiteCode = $website->getData('code');
self::$_websitesById[$websiteId] = $website;
self::$_websitesByCode[$websiteCode] = $website;
} catch (Wootook_Core_Exception_DataAccessException $e) {
throw new Wootook_Core_Exception_WebsiteError('Could not load website entity.', null, $e);
}
return $website;
} else {
if (isset(self::$_websitesByCode[$websiteId])) {
return self::$_websitesByCode[$websiteId];
}
$website = new Wootook_Core_Model_Website();
try {
$website->load($websiteId, 'code');
$websiteId = $website->getId();
$websiteCode = $website->getData('code');
self::$_websitesById[$websiteId] = $website;
self::$_websitesByCode[$websiteCode] = $website;
} catch (Wootook_Core_Exception_DataAccessException $e) {
throw new Wootook_Core_Exception_WebsiteError('Could not load website entity.', null, $e);
}
return $website;
}
}
public static function getGame($gameId)
{
if (is_numeric($gameId)) {
if (isset(self::$_gamesById[$gameId])) {
return self::$_gamesById[$gameId];
}
$game = new Wootook_Core_Model_Game();
try {
$game->load($gameId);
$gameCode = $game->getData('code');
self::$_gamesById[$gameId] = $game;
self::$_gamesByCode[$gameCode] = $game;
} catch (Wootook_Core_Exception_DataAccessException $e) {
throw new Wootook_Core_Exception_GameError('Could not load game entity.', null, $e);
}
return $game;
} else {
if (isset(self::$_gamesByCode[$gameId])) {
return self::$_gamesByCode[$gameId];
}
$game = new Wootook_Core_Model_Game();
try {
$game->load($gameId, 'code');
$gameId = $game->getId();
$gameCode = $game->getData('code');
self::$_gamesById[$gameId] = $game;
self::$_gamesByCode[$gameCode] = $game;
} catch (Wootook_Core_Exception_DataAccessException $e) {
throw new Wootook_Core_Exception_GameError('Could not load game entity.', null, $e);
}
return $game;
}
}
public static function addWebsite(Wootook_Core_Model_Website $website)
{
$websiteId = $website->getId();
$websiteKey = $website->getData('code');
self::$_websitesById[$websiteId] = $website;
self::$_websitesByCode[$websiteKey] = $website;
}
public static function addGame(Wootook_Core_Model_Game $game)
{
$gameId = $game->getId();
$gameKey = $game->getData('code');
self::$_gamesById[$gameId] = $game;
self::$_gamesByCode[$gameKey] = $game;
}
public static function setDefaultWebsite(Wootook_Core_Model_Website $website)
{
self::$_defaultWebsite = $website;
}
public static function getDefaultWebsite()
{
if (self::$_defaultWebsite === null) {
self::$_defaultWebsite = new Wootook_Core_Model_Website();
self::$_defaultWebsite->setId(1)->setData('code', Wootook_Core_Model_Website::DEFAULT_CODE);
}
return self::$_defaultWebsite;
}
public static function getDefaultGame()
{
if (self::$_defaultGame === null) {
self::$_defaultGame = new Wootook_Core_Model_Game();
self::$_defaultGame->setId(1)->setData('code', Wootook_Core_Model_Game::DEFAULT_CODE);
}
return self::$_defaultGame;
}
public static function setDefaultGame(Wootook_Core_Model_Game $game)
{
self::$_defaultGame = $game;
}
private static function _initWebsiteConfig($websiteId)
{
if (self::$_config === null) {
self::loadConfig();
}
if (!self::$isInstalled) {
if (isset(self::$_config['default'])) {
self::$_websiteConfigs[Wootook_Core_Model_Website::DEFAULT_CODE] = clone self::$_config['default'];
} else {
self::$_websiteConfigs[Wootook_Core_Model_Website::DEFAULT_CODE] = new Wootook_Core_Config_Node(array(), self::$_config);
}
if (isset(self::$_config['install'])) {
self::$_websiteConfigs[Wootook_Core_Model_Website::DEFAULT_CODE]->merge(self::$_config['install']);
}
return self::$_websiteConfigs[Wootook_Core_Model_Website::DEFAULT_CODE];
}
try {
$website = self::getWebsite($websiteId);
} catch (Wootook_Core_Exception_RuntimeException $e) {
Wootook_Core_ErrorProfiler::getSingleton()->exceptionManager($e);
return null;
}
$websiteKey = $website->getData('code');
$websiteId = $website->getId();
if (!isset(self::$_websiteConfigs[$websiteKey])) {
self::$_websiteConfigs[$websiteKey] = clone self::$_config['default'];
if ($websiteId != 0 && isset(self::$_config['frontend'])) {
self::$_websiteConfigs[$websiteKey]->merge(self::$_config['frontend']);
} else if ($websiteId == 0 && isset(self::$_config['backend'])) {
self::$_websiteConfigs[$websiteKey]->merge(self::$_config['backend']);
}
$websiteConfig = self::$_config->getConfig("website/{$websiteKey}");
if ($websiteConfig !== null) {
self::$_websiteConfigs[$websiteKey]->merge($websiteConfig);
}
self::_appendDatabaseConfig(self::$_websiteConfigs[$websiteKey], 'website', $website);
}
return self::$_websiteConfigs[$websiteKey];
}
private static function _initGameConfig($gameId)
{
if (self::$_config === null) {
self::loadConfig();
}
if (!self::$isInstalled) {
if (isset(self::$_config['default'])) {
self::$_gameConfigs[Wootook_Core_Model_Game::DEFAULT_CODE] = clone self::$_config['default'];
} else {
self::$_gameConfigs[Wootook_Core_Model_Game::DEFAULT_CODE] = new Wootook_Core_Config_Node(array(), self::$_config);
}
if (isset(self::$_config['install'])) {
self::$_gameConfigs[Wootook_Core_Model_Game::DEFAULT_CODE]->merge(self::$_config['install']);
}
return self::$_gameConfigs[Wootook_Core_Model_Game::DEFAULT_CODE];
}
try {
$game = self::getGame($gameId);
} catch (Wootook_Core_Exception_RuntimeException $e) {
Wootook_Core_ErrorProfiler::getSingleton()->exceptionManager($e);
return null;
}
$gameKey = $game->getData('code');
$gameId = $game->getId();
$websiteId = $game->getData('website_id');
if (!isset(self::$_gameConfigs[$gameKey])) {
$websiteConfig = self::_initWebsiteConfig($websiteId);
if ($websiteConfig === null) {
return null;
}
self::$_gameConfigs[$gameKey] = clone $websiteConfig;
$gameConfig = self::$_config->getConfig("game/{$gameKey}");
if ($gameConfig !== null) {
self::$_gameConfigs[$gameKey]->merge($gameConfig);
}
self::_appendDatabaseConfig(self::$_gameConfigs[$gameKey], 'game', $game);
}
return self::$_gameConfigs[$gameKey];
}
public static function getConfig($path = null)
{
if (self::$_config === null) {
self::loadConfig();
}
if ($path !== null) {
return self::$_globalConfig->getConfig($path);
}
return self::$_globalConfig;
}
public static function getWebsiteConfig($path = null, $websiteKey = null)
{
if (self::$_config === null) {
self::loadConfig();
}
if ($websiteKey === null) {
//$websiteKey = Wootook_Core_Model_Website::DEFAULT_CODE;
$websiteKey = self::getDefaultWebsite()->getData('code');
}
$config = self::_initWebsiteConfig($websiteKey);
if ($config === null) {
return null;
}
if ($path !== null) {
return $config->getConfig($path);
}
return $config;
}
public static function getGameConfig($path = null, $gameKey = null)
{
if (self::$_config === null) {
self::loadConfig();
}
if ($gameKey === null) {
//$gameKey = Wootook_Core_Model_Game::DEFAULT_CODE;
$gameKey = self::getDefaultGame()->getData('code');
}
$config = self::_initGameConfig($gameKey);
if ($config === null) {
return null;
}
if ($path !== null) {
return $config->getConfig($path);
}
return $config;
}
public static function setConfig($path, $value, $websiteId = null, $gameId = null)
{
if (self::$_config === null) {
self::loadConfig();
}
if (!self::$_ignoreDatabaseConfig) {
$updater = new Wootook_Core_Model_Config();
$updater->setPath($path)->setValue($value);
if ($websiteId !== null) {
$updater->setWebsiteId($websiteId);
if ($gameId !== null) {
$updater->setGameId($gameId);
self::$_gameConfigs[$gameId]->setConfig($path, $value);
} else {
self::$_websiteConfigs[$websiteId]->setConfig($path, $value);
}
} else {
self::$_globalConfig->setConfig($path, $value);
}
$updater->save();
} else if ($websiteId !== null) {
if ($gameId !== null) {
self::$_gameConfigs[$gameId]->setConfig($path, $value);
} else {
self::$_websiteConfigs[$websiteId]->setConfig($path, $value);
}
} else {
self::$_globalConfig->setConfig($path, $value);
}
return true;
}
public static function getBaseUrl($domain = 'base')
{
$urlConfig = self::getGameConfig('web/url');
if (!$urlConfig instanceof Wootook_Core_Config_Node) {
return null;
}
if (!is_string($domain) || !isset($urlConfig->$domain)) {
return $urlConfig->base;
}
return $urlConfig->$domain;
}
public static function getBasePath($domain = 'base')
{
$pathConfig = self::getGameConfig('system/path');
if (!$pathConfig instanceof Wootook_Core_Config_Node) {
return null;
}
if (!is_string($domain) || !isset($pathConfig->$domain)) {
return $pathConfig->base;
}
return $pathConfig->$domain;
}
public static function getUrl($uri, Array $params = array())
{
$baseUrl = self::getBaseUrl();
$serializedParams = array();
foreach ($params as $paramKey => $paramValue) {
if ($paramValue) {
$serializedParams[] = "{$paramKey}={$paramValue}";
}
}
if (count($serializedParams) > 0) {
return $baseUrl . $uri . '?' . implode('&', $serializedParams);
}
return $baseUrl . $uri;
}
public static function getStaticUrl($uri, Array $params = array())
{
$baseUrl = self::getBaseUrl('static');
$serializedParams = array();
foreach ($params as $paramKey => $paramValue) {
if ($paramValue) {
$serializedParams[] = "{$paramKey}={$paramValue}";
}
}
if (count($serializedParams) > 0) {
return $baseUrl . $uri . '?' . implode('&', $serializedParams);
}
return $baseUrl . $uri;
}
public static function fileExists($path)
{
if ($path === null || empty($path)) {
return false;
}
Wootook_Core_ErrorProfiler::getSingleton()->sleep();
if (($fp = @fopen($path, 'r', true)) === false) {
Wootook_Core_ErrorProfiler::getSingleton()->wakeup();
return false;
}
fclose($fp);
Wootook_Core_ErrorProfiler::getSingleton()->wakeup();
return true;
}
}

View file

@ -0,0 +1,155 @@
<?php
class Wootook_Core_App
{
/**
*
* Enter description here ...
* @var Wootook_Core_Config_Adapter_Abstract
*/
private $_globalConfig = null;
public function __construct($websiteCode, $gameCode)
{
$this->_globalConfig = Wootook::getConfig();
}
protected function _resolveClassType(&$namespaces, $module, $class)
{
$class = str_replace(' ', '', ucwords(str_replace('-', ' ', $class)));
$class = str_replace(' ', '_', ucwords(str_replace('.', ' ', $class)));
if (isset($namespaces[$module])) {
foreach ($namespaces[$module] as $namespace => $path) {
$className = $namespace . $class;
$fileName = $path . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
Wootook_Core_ErrorProfiler::getSingleton()->sleep();
if (!($fp = @fopen($fileName, 'r', true))) {
Wootook_Core_ErrorProfiler::getSingleton()->wakeup();
continue;
}
Wootook_Core_ErrorProfiler::getSingleton()->wakeup();
fclose($fp);
if (!class_exists($className, true)) {
continue;
}
return $className;
}
}
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_LayoutException(sprintf('Class type "%s" could not be resolved.', $type)));
return null;
}
protected function _newInstance($className, Array $constructorParams)
{
if ($className === null) {
return null;
}
if (empty($constructorParams)) {
return new $className;
} else {
$reflection = new ReflectionClass($className);
return $reflection->newInstanceArgs($constructorParams);
}
}
protected function _parseIdentifier($identifier, &$module, &$class)
{
$offset = strpos($identifier, '/');
if ($offset === false) {
$module = $identifier;
$class = null;
return;
}
$module = substr($type, 0, $offset);
$class = substr($type, $offset + 1);
}
public function block($identifier)
{
$this->_parseIdentifier($identifier, $module, $class);
return $this->getBlock($module, $class);
}
public function model($identifier)
{
$this->_parseIdentifier($identifier, $module, $class);
return $this->getModel($module, $class);
}
public function resource($identifier)
{
$this->_parseIdentifier($identifier, $module, $class);
return $this->getResource($module, $class);
}
public function helper($identifier)
{
$this->_parseIdentifier($identifier, $module, $class);
if ($class === null) {
$class = 'data';
}
return $this->getResource($module, $class);
}
public function getBlock($module, $class, Array $constructorParams = array())
{
$className = $this->_resolveClassType($this->_globalConfig->blocks, $module, $class);
return $this->_newInstance($className, $constructorParams);
}
public function getModel($module, $class)
{
$className = $this->_resolveClassType($this->_globalConfig->models, $module, $class);
return $this->_newInstance($className, $constructorParams);
}
public function getResource($module, $class)
{
$className = $this->_resolveClassType($this->_globalConfig->resources, $module, $class);
return $this->_newInstance($className, $constructorParams);
}
public function getHelper($module, $class)
{
$className = $this->_resolveClassType($this->_globalConfig->helpers, $module, $class);
return $this->_newInstance($className, $constructorParams);
}
public function getBlockSingleton($module, $class)
{
}
public function getModelSingleton($module, $class)
{
}
public function getResourceSingleton($module, $class)
{
}
public function getHelperSingleton($module, $class)
{
}
}

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,287 @@
<?php
class Wootook_Core_Block_Html_Head
extends Wootook_Core_Block_Template
{
const TYPE_GLOBAL_CSS = 'global_css';
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';
const TITLE_CONCAT_BEFORE = 'BEFORE';
const TITLE_CONCAT_AFTER = 'AFTER';
const TITLE_OVERWRITE = 'OVERWRITE';
protected $_items = array();
protected $_title = null;
protected $_titleDefaultConcat = self::TITLE_CONCAT_AFTER;
protected $_titleSeparator = ' ¤ ';
protected $_titleConcatTypes = array(
self::TITLE_CONCAT_AFTER,
self::TITLE_CONCAT_BEFORE,
self::TITLE_OVERWRITE
);
public function setTitleSeparator($separator)
{
$this->_titleSeparator = $separator;
return $this;
}
public function getTitleSeparator()
{
return $this->_titleSeparator;
}
public function setTitleDefaultConcat($defaultConcat)
{
if (in_array($concatType, $this->_titleConcatTypes)) {
$this->_titleDefaultConcat = $defaultConcat;
}
return $this;
}
public function getTitleDefaultConcat()
{
return $this->_titleDefaultConcat;
}
public function setTitle($title, $concatType = self::TITLE_CONCAT_AFTER)
{
if (!in_array($concatType, $this->_titleConcatTypes)) {
$concatType = $this->getTitleDefaultConcat();
}
if ($concatType == self::TITLE_OVERWRITE || $this->_title === null) {
$this->_title = $title;
} else if ($concatType == self::TITLE_CONCAT_BEFORE) {
$this->_title = $title . $this->getTitleSeparator() . $this->_title;
} else if ($concatType == self::TITLE_CONCAT_AFTER) {
$this->_title .= $this->getTitleSeparator() . $title;
}
return $this;
}
public function getTitle()
{
return $this->_title;
}
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(), $theme = null, $package = null)
{
$options['type'] = $type;
$options['path'] = $script;
$options['theme'] = $theme;
$options['package'] = $package;
$this->addItem(self::TYPE_GLOBAL_JS, $options);
return $this;
}
public function addCss($stylesheet, $type = 'text/css', $condition = null, Array $options = array(), $theme = null, $package = null)
{
$options['type'] = $type;
$options['path'] = $stylesheet;
$options['condition'] = $condition;
$options['theme'] = $theme;
$options['package'] = $package;
$this->addItem(self::TYPE_GLOBAL_CSS, $options);
return $this;
}
public function addSkinJs($script, $type = 'text/javascript', Array $options = array(), $theme = null, $package = null)
{
$options['type'] = $type;
$options['path'] = $script;
$options['theme'] = $theme;
$options['package'] = $package;
$this->addItem(self::TYPE_SKIN_JS, $options);
return $this;
}
public function addSkinCss($stylesheet, $type = 'text/css', $condition = null, Array $options = array(), $theme = null, $package = null)
{
$options['type'] = $type;
$options['path'] = $stylesheet;
$options['condition'] = $condition;
$options['theme'] = $theme;
$options['package'] = $package;
$this->addItem(self::TYPE_SKIN_CSS, $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['content'] = $content;
$this->addItem(self::TYPE_INLINE_CSS, $options);
return $this;
}
public function getCss()
{
if (isset($this->_items[self::TYPE_GLOBAL_CSS])) {
return $this->_items[self::TYPE_GLOBAL_CSS];
}
return array();
}
public function getSkinCss()
{
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';
}
$url = $this->getStaticUrl($css['path'], array());
$render .=<<<HTML_EOF
<link rel="stylesheet" type="{$css['type']}" src="{$url}" media="{$css['media']}" />
HTML_EOF;
}
}
public function renderSkinCss()
{
$render = '';
foreach ($this->getSkinCss() as $css) {
if (!isset($css['media'])) {
$css['media'] = 'all';
}
$url = $this->getSkinUrl($css['path'], array(), $css['theme'], $css['package']);
$render .=<<<HTML_EOF
<link rel="stylesheet" type="{$css['type']}" src="{$url}" media="{$css['media']}" />
HTML_EOF;
}
}
public function renderInlineCss()
{
foreach ($this->getInlineCss() as $css) {
if (!isset($css['media'])) {
$css['media'] = 'all';
}
$render .=<<<HTML_EOF
<style type="{$css['type']}">/*<![CDATA[*/{$css['content']}/*]]>*/</style>
HTML_EOF;
}
return $render;
}
public function renderJs()
{
$render = '';
foreach ($this->getJs() as $js) {
if (!isset($js['type'])) {
$js['type'] = 'text/javascript';
}
$url = $this->getStaticUrl($js['path']);
$render .=<<<HTML_EOF
<script type="{$js['type']}" src="{$url}"></script>
HTML_EOF;
}
return $render;
}
public function renderSkinJs()
{
$render = '';
foreach ($this->getJs() as $js) {
if (!isset($js['type'])) {
$js['type'] = 'text/javascript';
}
$url = $this->getSkinUrl($js['path'], array(), $js['theme'], $js['package']);
$render .=<<<HTML_EOF
<script type="{$js['type']}" src="{$url}"></script>
HTML_EOF;
}
return $render;
}
public function renderInlineJs()
{
foreach ($this->getInlineJs() as $js) {
$render .=<<<HTML_EOF
<script type="{$js['type']}">/*<![CDATA[*/{$js['content']}/*]]>*/</script>
HTML_EOF;
}
return $render;
}
}

View file

@ -0,0 +1,101 @@
<?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, Array $attributes = array())
{
$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,
'attributes' => $attributes
));
$parent->setPartial($baseName, $child);
if ($template !== null) {
$child->setTemplate($template);
}
return $this;
}
public function addExternalLink($name, $label, $title, $url, Array $classes = array(), $template = null, Array $attributes = array())
{
$explodedPath = explode('/', $name);
$baseName = array_pop($explodedPath);
$parent = $this->_getNode($explodedPath);
$child = $this->getLayout()
->createBlock('core/html.navigation.link', $this->getNameInLayout() . '.' . $baseName, array(
'url' => $url,
'label' => $label,
'title' => $title,
'classes' => $classes,
'attributes' => $attributes
));
$parent->setPartial($baseName, $child);
if ($template !== null) {
$child->setTemplate($template);
}
return $this;
}
public function addPopupLink($name, $label, $title, $uri, Array $params = array(), Array $classes = array(), $template = null, Array $attributes = array())
{
$uri = $this->getStaticUrl($uri, $params);
$attributes['onclick'] = "f('{$params}', '{$label}');return false;";
return $this->addLink($name, $label, $title, null, array(), $classes, $template, $attributes);
}
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);
} else {
$child = $this->getLayout()
->createBlock('core/html.navigation.node', $this->getNameInLayout() . '.' . $name);
$this->setPartial($name, $child);
}
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,180 @@
<?php
class Wootook_Core_Block_Html_Navigation_Link
extends Wootook_Core_Block_Template
{
protected $_label = '';
protected $_title = '';
protected $_uri = null;
protected $_url = null;
protected $_params = array();
protected $_classes = array('link');
protected $_attributes = array();
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())
{
if ($uri === null) {
return $this;
}
$this->_uri = $uri;
$this->_params = $params;
$this->_url = $this->getStaticUrl($uri, $params);
return $this;
}
public function setExternalUrl($url)
{
$this->_url = $url;
$this->_uri = null;
$this->_params = array();
return $this;
}
public function getLinkUrl($moreParams = array())
{
if (empty($moreParams) || $this->_uri === null) {
return $this->_url;
}
$params = array_merge($this->_params, $moreParams);
return $this->getStaticUrl($this->_uri, $params);
}
public function setAttribute($attributeName, $attributeValue)
{
$this->_attributes[$attributeName] = $attributeValue;
return $this;
}
public function getAttribute($attributeName)
{
if ($this->hasAttribute($attributeName)) {
return $this->_attributes[$attributeName];
}
return null;
}
public function hasAttribute($attributeName)
{
if (isset($this->_attributes[$attributeName])) {
return true;
}
return false;
}
public function unsetAttribute($attributeName)
{
if ($this->hasAttribute($attributeName)) {
unset($this->_attributes[$attributeName]);
}
return $this;
}
public function getAttributes()
{
return $this->_attributes;
}
public function addClass($class)
{
$this->_classes[] = $class;
return $this;
}
public function clearClasses()
{
$this->_classes = array();
return $this;
}
public function renderClasses(Array $moreClasses = array())
{
$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->setExternalUrl($data['url']);
}
unset($data['url']);
}
if (isset($data['classes'])) {
$classes = (array) $data['classes'];
unset($data['classes']);
foreach ($classes as $class) {
$this->addClass(trim($class));
}
}
if (isset($data['attributes'])) {
$attributes = (array) $data['attributes'];
unset($data['attributes']);
foreach ($attributes as $attributeName => $attributeValue) {
$this->setAttribute($attributeName, $attributeValue);
}
}
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,43 @@
<?php
class Wootook_Core_Block_Messages
extends Wootook_Core_Block_Template
{
protected $_storages = array();
public function prepareMessages($namespace)
{
$this->_storages[] = $namespace;
}
public function renderGroupedHtml()
{
$messages = array();
foreach ($this->_storages as $namespace) {
$session = Wootook::getSession($namespace);
foreach ($session->getMessages() as $messageLevel => $messageList) {
if (!isset($messages[$messageLevel])) {
$messages[$messageLevel] = $messageList;
} else {
$messages[$messageLevel] += $messageList;
}
}
}
rsort($messages, SORT_NUMERIC);
$output = '<div class="messages">';
foreach ($messages as $messageLevel => $messageList) {
$output .= "<ul class=\"{$messageLevel}\">";
foreach ($messageList as $message) {
$output .= "<li>{$message}</li>";
}
$output .= '</ul>';
}
$output .= '</div>';
return $output;
}
}

View file

@ -0,0 +1,46 @@
<?php
class Wootook_Core_Block_Template
extends Wootook_Core_View
{
protected function _getTemplatePath($file)
{
if ($this->getScriptPath() == '') {
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_RuntimeException("No script path defined in block {$this->getNameInLayout()}."));
return null;
}
$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;
}
}
} else {
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_RuntimeException("No layout defined."));
}
$path = sprintf($pattern, Wootook_Core_Layout::DEFAULT_PACKAGE, Wootook_Core_Layout::DEFAULT_THEME);
if (Wootook::fileExists($path)) {
return $path;
}
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_RuntimeException("Template '{$file}' could not be found."));
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,6 @@
<?php
abstract class Wootook_Core_Config_Adapter_Abstract
extends Wootook_Core_Config_Node
{
}

View file

@ -0,0 +1,35 @@
<?php
class Wootook_Core_Config_Adapter_Array
extends Wootook_Core_Config_Adapter_Abstract
{
public function __construct($filename = null)
{
if ($filename !== null) {
$this->load($filename);
}
}
public function load($filename)
{
if (!file_exists($filename)) {
throw new Wootook_Core_Exception_DataAccessException(sprintf('Could not load config file "%s"', $filename));
}
$data = include $filename;
if (!is_array($data)) {
throw new Wootook_Core_Exception_DataAccessException('Configuration file could not be loaded.');
}
$this->_init($data);
return $this;
}
public function save($filename)
{
file_put_contents($filename, '<' . '?p' . 'hp return ' . var_export($this->toArray(), true) . ';');
return $this;
}
}

View file

@ -0,0 +1,217 @@
<?php
class Wootook_Core_Config_Node
implements ArrayAccess
{
protected $_children = array();
protected $_parent = null;
protected static $_attributeNameCache = array();
public function __construct(Array $data = array(), $parent = null)
{
$this->_init($data, $parent);
}
public function setData(Array $data = array())
{
$this->_init($data);
return $this;
}
protected function _init(Array $data, $parent = null)
{
if ($parent !== null) {
$this->_parent = $parent;
}
$this->_children = array();
foreach ($data as $key => $value) {
if (is_array($value)) {
$this->offsetSet($key, new self($value, $this));
} else {
$this->offsetSet($key, $value);
}
}
return $this;
}
public function getParent()
{
return $this->_parent;
}
public function setConfig($path, $value)
{
$explodedPath = explode('/', $path);
$length = count($explodedPath);
$currentNode = $this;
for ($i = 0; $i < $length; $i++) {
if ($i < ($length - 1)) {
if (!$currentNode->offsetExists($explodedPath[$i])) {
$newNode = new Wootook_Core_Config_Node(array(), $currentNode);
$currentNode->offsetSet($explodedPath[$i], $newNode);
}
} else if (is_array($value)) {
$currentNode->offsetSet($explodedPath[$i], new self($value, $this));
break;
} else {
$currentNode->offsetSet($explodedPath[$i], $value);
break;
}
$currentNode = $currentNode->offsetGet($explodedPath[$i]);
if (!$currentNode instanceof Wootook_Core_Config_Node) {
throw new Wootook_Core_Exception_RuntimeException();
}
}
return $this;
}
public function getConfig($path)
{
$explodedPath = explode('/', $path);
$length = count($explodedPath);
$currentNode = $this;
for ($i = 0; $i < $length; $i++) {
if (!$currentNode instanceof Wootook_Core_Config_Node) {
throw new Wootook_Core_Exception_RuntimeException();
}
if (!$currentNode->offsetExists($explodedPath[$i])) {
return null;
}
$currentNode = $currentNode->offsetGet($explodedPath[$i]);
}
return $currentNode;
}
public function toArray()
{
$result = array();
foreach ($this->_children as $key => $child) {
if ($child instanceof self) {
$result[$key] = $child->toArray();
} else if ($child instanceof Wootook_Core_Config_Leaf) {
$result[$key] = $child->getValue();
} else {
$result[$key] = $child;
}
}
return $result;
}
public function reset()
{
$this->_children = array();
$this->_parent = null;
return $this;
}
public function merge(self $node)
{
foreach ($node->_children as $offset => $value) {
if ($value instanceof self) {
if (!$this->offsetExists($offset)) {
$this->offsetSet($offset, new self(array(), $this));
}
$this->offsetGet($offset)->merge($value);
} else {
$this->offsetSet($offset, $value);
}
}
return $this;
}
private function _resolveAttributeName($key)
{
if (is_numeric($key)) {
return $key;
}
if (!isset(self::$_attributeNameCache[$key])) {
self::$_attributeNameCache[$key] = strtolower(preg_replace('#([A-Z])#', '-\\1', $key));
}
return self::$_attributeNameCache[$key];
}
public function __get($offset)
{
return $this->offsetGet($this->_resolveAttributeName($offset));
}
public function __set($offset, $value)
{
return $this->offsetSet($this->_resolveAttributeName($offset), $value);
}
public function __isset($offset)
{
return $this->offsetExists($this->_resolveAttributeName($offset));
}
public function __unset($offset)
{
return $this->offsetUnset($this->_resolveAttributeName($offset));
}
public function __clone()
{
$clone = new self();
foreach ($this->_children as $childName => $childNode) {
if ($childNode instanceof self) {
$childNode = clone $childNode;
$childNode->_parent = $clone;
}
$clone->offsetSet($childName, $childNode);
}
return $clone;
}
public function offsetGet($offset)
{
if ($this->offsetExists($offset)) {
return $this->_children[$offset];
}
return null;
}
public function offsetSet($offset, $value)
{
if ($offset === null) {
$this->_children[] = $value;
} else {
$this->_children[$offset] = $value;
}
return $value;
}
public function offsetExists($offset)
{
if (isset($this->_children[$offset])) {
return true;
}
return false;
}
public function offsetUnset($offset)
{
if ($this->offsetExists($offset)) {
unset($this->_children[$offset]);
}
}
}

View file

@ -0,0 +1,143 @@
<?php
abstract class Wootook_Core_Controller_Action
{
private $_request = null;
private $_response = null;
private $_layout = null;
public function __construct(Wootook_Core_Controller_Request_Http $request, Wootook_Core_Controller_Response_Http $response)
{
$this->setRequest($request);
$this->setResponse($response);
}
public function init()
{
}
public function preDispatch()
{
}
public function postDispatch()
{
}
public function setRequest(Wootook_Core_Controller_Request_Http $request)
{
$this->_request = $request;
return $this;
}
public function setResponse(Wootook_Core_Controller_Response_Http $response)
{
$this->_response = $response;
return $this;
}
/**
*
* @return Wootook_Core_Controller_Request_Http
*/
public function getRequest()
{
return $this->_request;
}
/**
*
* @return Wootook_Core_Controller_Response_Http
*/
public function getResponse()
{
return $this->_response;
}
protected function _forward($action, $controller = null, $module = null)
{
$request = $this->getRequest();
$request->setActionName($action);
if ($controller !== null) {
$request->setControllerName($controller);
if ($module != null) {
$request->setModuleName($module);
}
}
$this->getResponse()->setIsDispatched(false);
}
protected function _redirect($uri, Array $params = array(), $code = Wootook_Core_Controller_Response_Http::REDIRECT_FOUND)
{
$this->getResponse()
->setIsDispatched(false)
->setRedirect(Wootook::getUrl($uri, $params), $code);
Wootook_Core_ErrorProfiler::unregister(true);
return $this;
}
protected function _redirectUrl($url, $code = Wootook_Core_Controller_Response_Http::REDIRECT_FOUND)
{
$this->getResponse()->setRedirect($url, $code);
return $this;
}
protected function _buildLayoutHandle()
{
$request = $this->getRequest();
$module = $request->getModuleName();
$controller = $request->getControllerName();
$action = $request->getActionName();
return "{$module}.{$controller}.{$action}";
}
public function loadLayout($handle = null)
{
if ($this->_layout === null) {
$this->_layout = $this->_initLayout();
}
if ($handle === null) {
$handle = $this->_buildLayoutHandle();
}
$this->_layout->load($handle);
return $this;
}
protected function _initLayout()
{
return new Wootook_Core_Layout(Wootook_Core_Layout::DOMAIN_FRONTEND);
}
/**
*
* @return Wootook_Core_Layout
*/
public function getLayout()
{
return $this->_layout;
}
public function renderLayout()
{
try {
$content = $this->getLayout()->render();
} catch (Wootook_Core_Exception_LayoutException $e) {
Wootook_Core_ErrorProfiler::getSingleton()->addException($e);
return $this;
}
$this->getResponse()->setBody($content);
return $this;
}
}

View file

@ -0,0 +1,190 @@
<?php
class Wootook_Core_Controller_Front
{
const ROUTE_DEFAULT = 'default';
const ROUTE_ERROR = 'error';
protected $_routes = array(
self::ROUTE_ERROR => array(
'modules' => array(
'core' => array(
'class' => 'Wootook_Core_',
'path' => 'Wootook/Core'
)
),
'defaults' => array(
'module' => 'core',
'controller' => 'error',
'action' => 'no-route'
)
),
self::ROUTE_DEFAULT => array(
'modules' => array(
'core' => array(
'class' => 'Wootook_Core_',
'path' => 'Wootook/Core'
),
'admin' => array(
'class' => 'Wootook_Admin_',
'path' => 'Wootook/Admin'
),
'player' => array(
'class' => 'Wootook_Player_',
'path' => 'Wootook/Player'
),
'empire' => array(
'class' => 'Wootook_Empire_',
'path' => 'Wootook/Empire'
)
),
'defaults' => array(
'module' => 'core',
'controller' => 'index',
'action' => 'index'
)
)
);
protected $_request = null;
protected $_response = null;
public function __construct(Wootook_Core_Controller_Request_Abstract $request,
Wootook_Core_Controller_Response_Abstract $response)
{
$this->_request = $request;
$this->_response = $response;
}
protected function _setNoRouteAction(&$route, &$moduleKey, &$controllerKey, &$actionKey)
{
$route = self::ROUTE_ERROR;
$moduleKey = $this->_routes[self::ROUTE_ERROR]['defaults']['module'];
$controllerKey = $this->_routes[self::ROUTE_ERROR]['defaults']['controller'];
$actionKey = $this->_routes[self::ROUTE_ERROR]['defaults']['action'];
return $this;
}
protected function _setDefaultRouteAction(&$route, &$moduleKey, &$controllerKey, &$actionKey)
{
$route = self::ROUTE_DEFAULT;
$moduleKey = $this->_routes[self::ROUTE_DEFAULT]['defaults']['module'];
$controllerKey = $this->_routes[self::ROUTE_DEFAULT]['defaults']['controller'];
$actionKey = $this->_routes[self::ROUTE_DEFAULT]['defaults']['action'];
return $this;
}
protected function _camelizeClass($string)
{
return str_replace(' ', '_', ucwords(str_replace('-', ' ', $string)));
}
protected function _camelizeMethod($string)
{
return lcfirst(str_replace(' ', '', ucwords(str_replace('-', ' ', $string))));
}
protected function _getControllerClass($modulePrefix, $controllerKey)
{
return $modulePrefix . $this->_camelizeClass($controllerKey) . 'Controller';
}
protected function _getControllerPath($modulePath, $controllerKey)
{
return $modulePath . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR
. $this->_camelizeClass($controllerKey) . 'Controller.php';
}
protected function _getActionMethod($actionKey)
{
return $this->_camelizeMethod($actionKey) . 'Action';
}
public function dispatch($route = null)
{
if ($route == null) {
$route = self::ROUTE_DEFAULT;
}
if (!isset($this->_routes[$route])) {
$route = self::ROUTE_DEFAULT;
}
$loop = 0;
while ($loop++ < 100) {
$moduleKey = $this->_request->getModuleName();
$controllerKey = $this->_request->getControllerName();
$actionKey = $this->_request->getActionName();
if (empty($moduleKey)) {
$this->_setDefaultRouteAction($route, $moduleKey, $controllerKey, $actionKey);
}
if (!isset($this->_routes[$route]['modules'][$moduleKey])) {
$this->_setNoRouteAction($route, $moduleKey, $controllerKey, $actionKey);
}
if (empty($controllerKey)) {
$controllerKey = $this->_routes[$route]['defaults']['controller'];
}
$controllerClass = $this->_getControllerClass($this->_routes[$route]['modules'][$moduleKey]['class'], $controllerKey);
$controllerPath = $this->_getControllerPath($this->_routes[$route]['modules'][$moduleKey]['path'], $controllerKey);
if (!class_exists($controllerClass, false) && Wootook::fileExists($controllerPath)) {
include_once $controllerPath;
}
if (!class_exists($controllerClass, false)) {
$this->_setNoRouteAction($route, $moduleKey, $controllerKey, $actionKey);
$controllerClass = $this->_getControllerClass($this->_routes[$route]['modules'][$moduleKey]['class'], $controllerKey);
$controllerPath = $this->_getControllerPath($this->_routes[$route]['modules'][$moduleKey]['path'], $controllerKey);
include_once $controllerPath;
}
if (empty($actionKey)) {
$actionKey = $this->_routes[$route]['defaults']['action'];
}
$actionMethod = $this->_getActionMethod($actionKey);
if (!method_exists($controllerClass, $actionMethod)) {
$this->_setNoRouteAction($route, $moduleKey, $controllerKey, $actionKey);
$controllerClass = $this->_getControllerClass($this->_routes[$route]['modules'][$moduleKey]['class'], $controllerKey);
$controllerPath = $this->_getControllerPath($this->_routes[$route]['modules'][$moduleKey]['path'], $controllerKey);
include_once $controllerPath;
$actionMethod = $this->_getActionMethod($actionKey);
}
$controller = new $controllerClass($this->_request, $this->_response);
$controller->init();
$this->_response->setIsDispatched();
$controller->preDispatch();
if (!$this->_response->isDispatched()) {
continue;
}
$controller->$actionMethod();
$controller->postDispatch();
if ($this->_response->isDispatched()) {
break;
}
}
return $this;
}
public function send()
{
$this->_response->render();
}
}

View file

@ -0,0 +1,26 @@
<?php
abstract class Wootook_Core_Controller_Request_Abstract
extends Wootook_Object
{
public function setParam($key, $value)
{
return $this->setData($key, $value);
}
public function getParam($key, $default = null)
{
if ($this->hasData($key)) {
return $this->getData($key);
}
return $default;
}
abstract public function getModuleName();
abstract public function getControllerName();
abstract public function getActionName();
abstract public function setModuleName($name);
abstract public function setControllerName($name);
abstract public function setActionName($name);
}

View file

@ -0,0 +1,280 @@
<?php
class Wootook_Core_Controller_Request_Http
extends Wootook_Core_Controller_Request_Abstract
{
protected $_baseUrl = null;
protected $_actionKey = 'action';
protected $_controllerKey = 'controller';
protected $_moduleKey = 'module';
public function __construct(Array $options = array())
{
parent::__construct($options);
$this->_baseUrl = Wootook::getBaseUrl();
$baseUri = substr($this->_baseUrl, strpos($this->_baseUrl, '/', 8)); // Get the path from the DocumentRoot
$params = '';
if (($offset = strpos($this->getServer('REQUEST_URI'), $baseUri)) !== false) {
$path = substr($this->getServer('REQUEST_URI'), $offset + strlen($baseUri));
$moduleOffset = strpos($path, '/');
if ($moduleOffset !== false) {
$this->setModuleName(substr($path, 0, $moduleOffset));
$controllerOffset = strpos($path, '/', $moduleOffset + 1);
if ($controllerOffset !== false) {
$this->setControllerName(substr($path, $moduleOffset + 1, $controllerOffset - $moduleOffset - 1));
$actionOffset = strpos($path, '/', $controllerOffset + 1);
if ($actionOffset !== false) {
$this->setActionName(substr($path, $controllerOffset + 1, $actionOffset - $controllerOffset - 1));
$params = substr($path, $actionOffset);
} else if ($controllerOffset !== false) {
$this->setActionName(substr($path, $controllerOffset + 1));
}
} else if ($moduleOffset !== false) {
$this->setControllerName(substr($path, $moduleOffset + 1));
}
} else {
$this->setModuleName($path);
}
}
if (!empty($params)) {
$paramOffset = 0;
$valueOffset = 0;
while (true) {
$paramOffset = strpos($params, '/', $valueOffset + 1);
if ($paramOffset === false) {
break;
}
$paramKey = substr($params, $valueOffset + 1, $paramOffset - $valueOffset - 1);
$valueOffset = strpos($params, '/', $paramOffset + 1);
if ($valueOffset === false) {
$this->setParam($paramKey, substr($params, $paramOffset + 1));
break;
}
$this->setParam($paramKey, substr($params, $paramOffset + 1, $valueOffset - $paramOffset - 1));
}
}
}
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 getAllQueryData()
{
return $_GET;
}
public function getAllFilesData()
{
return $_FILES;
}
public function getAllCookieData()
{
$data = array();
foreach ($_COOKIE as $key => $value) {
$data[$key] = unserialize(stripslashes($value));
}
return $data;
}
public function getAllRawCookieData()
{
return $_COOKIE;
}
public function getAllPostData()
{
return $_POST;
}
public function getAllServerData()
{
return $_SERVER;
}
public function isPost()
{
if (strtoupper($this->getServer('REQUEST_METHOD')) == 'POST') {
return true;
}
return false;
}
public function isPut()
{
if (strtoupper($this->getServer('REQUEST_METHOD')) == 'PUT') {
return true;
}
return false;
}
public function isHead()
{
if (strtoupper($this->getServer('REQUEST_METHOD')) == 'HEAD') {
return true;
}
return false;
}
public function isGet()
{
if (strtoupper($this->getServer('REQUEST_METHOD')) == 'GET') {
return true;
}
return false;
}
public function getModuleKey()
{
return $this->_moduleKey;
}
public function setModuleKey($key)
{
$this->_moduleKey = $key;
return $this;
}
public function getModuleName()
{
return $this->getParam($this->getModuleKey());
}
public function setModuleName($name)
{
if ($name === null || is_string($name)) {
return $this->setParam($this->getModuleKey(), $name);
}
}
public function getControllerKey()
{
return $this->_controllerKey;
}
public function setControllerKey($key)
{
$this->_controllerKey = $key;
return $this;
}
public function getControllerName()
{
return $this->getParam($this->getControllerKey());
}
public function setControllerName($name)
{
if ($name === null || is_string($name)) {
return $this->setParam($this->getControllerKey(), $name);
}
}
public function getActionKey()
{
return $this->_actionKey;
}
public function setActionKey($key)
{
$this->_actionKey = $key;
return $this;
}
public function getActionName()
{
return $this->getParam($this->getActionKey());
}
public function setActionName($name)
{
if ($name === null || is_string($name)) {
return $this->setParam($this->getActionKey(), $name);
}
}
}

View file

@ -0,0 +1,21 @@
<?php
abstract class Wootook_Core_Controller_Response_Abstract
extends Wootook_Object
{
protected $_isDispatched = false;
public function setIsDispatched($dispatched = true)
{
$this->_isDispatched = $dispatched;
return $this;
}
public function isDispatched()
{
return $this->_isDispatched;
}
abstract public function render($send = true);
}

View file

@ -0,0 +1,159 @@
<?php
class Wootook_Core_Controller_Response_Http
extends Wootook_Core_Controller_Response_Abstract
{
const REDIRECT_MOVED_PERMANENTLY = 301;
const REDIRECT_FOUND = 302;
const REDIRECT_SEE_OTHER = 303;
const REDIRECT_TEMPORARY = 307;
protected static $_redirectCodes = array(
self::REDIRECT_MOVED_PERMANENTLY => 'Moved Permanently',
self::REDIRECT_FOUND => 'Found',
self::REDIRECT_SEE_OTHER => 'See Other',
self::REDIRECT_TEMPORARY => 'Temporary Redirect'
);
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()
{
if (!isset($this->_data['body']) || empty($this->_data['body'])) {
return '';
}
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($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 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)
{
$date = new Wootook_Core_DateTime();
$date->add($lifetime);
setcookie($name, $value, $date->getTimestamp(), $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;
}
public function render($send = true)
{
if ($send) {
$this->sendHeaders();
echo $this->sendBody();
} else {
return $this->sendBody();
}
}
}

View file

@ -0,0 +1,138 @@
<?php
class Wootook_Core_Database
extends PDO
{
const DEFAULT_CONNECTION_NAME = 'default';
protected static $_connections = array();
protected static $_connectionAliases = array();
protected $_tablePrefix = null;
protected $_dsn = null;
protected $_username = null;
protected $_password = null;
public static $options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
/**
*
* @deprecated
*/
public static function getSingleton()
{
return self::getConnection(self::DEFAULT_CONNECTION_NAME);
}
public function quoteIdentifier($identifier)
{
return "`$identifier`";
}
public static function getConnection($connectionName)
{
if (empty($connectionName) || $connectionName === null) {
return null;
}
if (!isset(self::$_connections[$connectionName])) {
if (isset(self::$_connectionAliases[$connectionName])) {
return self::$_connectionAliases[$connectionName];
}
$connectionConfig = Wootook::getConfig("resource/database/{$connectionName}");
if ($connectionConfig === null) {
return null;
}
if ($alias = $connectionConfig->use) {
self::$_connectionAliases[$connectionName] = self::getConnection($alias);
return self::$_connectionAliases[$connectionName];
}
self::$_connections[$connectionName] = self::_initConnection($connectionName,
$connectionConfig->engine, $connectionConfig->params, $connectionConfig->options);
}
return self::$_connections[$connectionName];
}
private static function _initConnection($connectionName, $engine, $params, $options = array())
{
if (is_array($params)) {
$params = new Wootook_Core_Config_Node($params);
} else if (!$params instanceof Wootook_Core_Config_Node) {
$params = new Wootook_Core_Config_Node(array());
}
if ($options instanceof Wootook_Core_Config_Node) {
$options = $options->toArray();
} else if (!is_array($options)) {
$options = array();
}
$hostname = $params->hostname;
$username = $params->username;
$password = $params->password;
$database = $params->database;
if (empty($params->hostname) || empty($params->username) || empty($params->database)) {
return null;
}
$dsn = "mysql:dbname={$params->database};host={$params->hostname}";
if (is_numeric($params->port)) {
$dsn .= ";port={$params->port}";
}
$event = Wootook::dispatchEvent('database.prepare-options', array(
'name' => $connectionName,
'options' => array_merge(self::$options, $options)
));
$options = $event->getData('options');
$connection = new self($dsn, $params->username, $params->password, $options);
$connection->_dsn = $dsn;
$connection->_username = $username;
if (defined('DEBUG')) {
$connection->_password = $password;
}
if (($prefix = Wootook::getConfig("resource/database/{$connectionName}/table_prefix")) !== null) {
$connection->setTablePrefix($prefix);
}
Wootook::dispatchEvent('database.init', array(
'name' => $connectionName,
'handler' => $connection
));
return $connection;
}
public function setTablePrefix($prefix)
{
$this->_tablePrefix = $prefix;
return $this;
}
public function getTablePrefix()
{
return $this->_tablePrefix;
}
public function getTable($name)
{
return $this->getTablePrefix() . $name;
}
public function select($tableName = null)
{
return new Wootook_Core_Database_Sql_Mysql_Select($this, $tableName);
}
}

View file

@ -0,0 +1,115 @@
<?php
class Wootook_Core_Database_Orm_DataMapper
extends Wootook_Core_PluginLoader_Abstract
{
protected $_rules = array();
protected $_alias = array();
public function __construct($config = array())
{
$this->registerNamespace('Wootook_Core_Database_Orm_DataMapper_');
if (!is_array($config) || !$config instanceof Wootook_Core_Config_Node) {
return;
}
foreach ($config as $field => $typeConfig) {
if (is_string($typeConfig)) {
$this->addRule($field, $typeConfig);
} else if (is_array($typeConfig) && isset($typeConfig['type'])) {
if (isset($typeConfig['alias'])) {
$this->addRule($field, $typeConfig['type'], $typeConfig['alias']);
} else {
$this->addRule($field, $typeConfig['type']);
}
}
}
}
public function addRule($field, $type, $alias = null)
{
if (($instance = $this->load($type)) !== null) {
$this->_rules[$field] = $instance;
}
if ($alias === null) {
$alias = $field;
}
$this->_alias[$field] = $alias;
return $this;
}
public function removeRule($field)
{
unset($this->_rules[$field]);
unset($this->_alias[$field]);
return $this;
}
protected function _load($className, $useSingleton)
{
$reflection = new ReflectionClass($className);
if ($useSingleton && $reflection->implementsInterface('Wootook_Core_Singleton')) {
$method = $reflection->getMethod('getSingleton');
return $method->invoke(null);
}
try {
return $reflection->newInstance();
} catch (ReflectionException $e) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException($e);
return null;
}
}
/**
*
* @param Wootook_Core_Database_Resource $entity
* @param Array $datas
* @return Array
*/
public function encode(Wootook_Core_Database_Resource $entity, Array $datas = array())
{
$aliasTable = array_flip($this->_alias);
foreach ($entity->getAllDatas() as $aliasedField => $decodedValue) {
if (!isset($aliasTable[$aliasedField])) {
$field = $aliasedField;
} else {
$field = $aliasTable[$aliasedField];
}
if (isset($this->_rules[$field])) {
$datas[$field] = $this->_rules[$field]->encode($decodedValue);
} else {
$datas[$field] = $decodedValue;
}
}
return $datas;
}
/**
*
* @param Wootook_Core_Database_Resource $entity
* @param Array $datas
* @return Wootook_Core_Database_Resource
*/
public function decode(Wootook_Core_Database_Resource $entity, Array $datas = array())
{
foreach ($datas as $field => $encodedValue) {
if (isset($this->_rules[$field])) {
$entity->setData($this->_alias[$field], $this->_rules[$field]->decode($encodedValue));
} else {
$entity->setData($field, $encodedValue);
}
}
return $entity;
}
}

View file

@ -0,0 +1,15 @@
<?php
class Wootook_Core_Database_Orm_DataMapper_Array
extends Wootook_Core_Database_Orm_DataMapper_FieldAbstract
{
public function encode($value)
{
return serialize($value);
}
public function decode($value)
{
return unserialize($value);
}
}

View file

@ -0,0 +1,15 @@
<?php
class Wootook_Core_Database_Orm_DataMapper_Config
extends Wootook_Core_Database_Orm_DataMapper_Array
{
public function encode($value)
{
return parent::encode($value->toArray());
}
public function decode($value)
{
return new Wootook_Core_Config_Node(parent::decode($value));
}
}

View file

@ -0,0 +1,38 @@
<?php
class Wootook_Core_Database_Orm_DataMapper_DateTime
extends Wootook_Core_Database_Orm_DataMapper_FieldAbstract
{
const DATE_FORMAT_MYSQL = 'Y-m-d G:i:s';
protected $_format = self::DATE_FORMAT_MYSQL;
public function setFormat($format = null)
{
if ($format === null) {
$this->_format = self::DATE_FORMAT_MYSQL;
} else {
$this->_format = $format;
}
return $this;
}
public function getFormat()
{
return $this->_format;
}
public function encode($value)
{
if (!$value instanceof Wootook_Core_DateTime) {
$value = new Wootook_Core_DateTime($value);
}
return $value->toString($this->getFormat());
}
public function decode($value)
{
return new Wootook_Core_DateTime($value, $this->getFormat());
}
}

View file

@ -0,0 +1,8 @@
<?php
abstract class Wootook_Core_Database_Orm_DataMapper_FieldAbstract
{
abstract public function encode($value);
abstract public function decode($value);
}

View file

@ -0,0 +1,43 @@
<?php
class Wootook_Core_Database_Orm_DataMapper_Object
extends Wootook_Core_Database_Orm_DataMapper_Array
{
protected $_entityClass = null;
protected $_reflectionClass = null;
public function setEntityClass($class)
{
$this->_entityClass = $class;
return $this;
}
public function getEntityClass()
{
return $this->_entityClass;
}
protected function _newInstance(Array $args = array())
{
if ($this->_reflectionClass === null && $this->_entityClass !== null) {
$this->_reflectionClass = new ReflectionClass($this->_entityClass);
}
return $this->newInstanceArgs($args);
}
public function encode($value)
{
return parent::encode($value->getAllDatas());
}
public function decode($value)
{
$object = $this->_newInstance();
$object->addData(parent::decode($value));
return $object;
}
}

View file

@ -0,0 +1,81 @@
<?php
abstract class Wootook_Core_Database_Resource
extends Wootook_Core_Model
{
protected $_readConnection = null;
protected $_writeConnection = null;
protected $_tableName = null;
protected $_dataMapper = null;
/**
*
* @return Wootook_Core_Database_Orm_DataMapper
*/
public function getDataMapper()
{
if ($this->_dataMapper === null) {
$this->_dataMapper = new Wootook_Core_Database_Orm_DataMapper();
}
return $this->_dataMapper;
}
public function setTableName($tableName)
{
$this->_tableName = $tableName;
return $this;
}
public function getTableName()
{
return $this->_tableName;
}
public function getReadConnection()
{
if ($this->_readConnection === null) {
$this->_readConnection = Wootook_Core_Database::getConnection('core_read');
}
return $this->_readConnection;
}
public function setReadConnection($connection)
{
if ($connection instanceof Wootook_Core_Database) {
$this->_readConnection = $connection;
} else if (is_string($connection)) {
$this->_readConnection = Wootook_Core_Database::getConnection($connection);
} else {
throw new Wootook_Core_Exception_RuntimeException(
'First parameter should be either a database connection object or a string identifier.');
}
return $this;
}
public function getWriteConnection()
{
if ($this->_writeConnection === null) {
$this->_writeConnection = Wootook_Core_Database::getConnection('core_write');
}
return $this->_writeConnection;
}
public function setWriteConnection($connection)
{
if ($connection instanceof Wootook_Core_Database) {
$this->_readConnection = $connection;
} else if (is_string($connection)) {
$this->_readConnection = Wootook_Core_Database::getConnection($connection);
} else {
throw new Wootook_Core_Exception_RuntimeException(
'First parameter should be either a database connection object or a string identifier.');
}
return $this;
}
}

View file

@ -0,0 +1,105 @@
<?php
class Wootook_Core_Database_Sql_Mysql_Select
extends Wootook_Core_Database_Sql_Select
{
protected function _prepareSql()
{
if (empty($this->_parts[self::UNION])) {
$fields = array();
foreach ($this->_parts[self::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->_parts[self::WHERE])) {
$where = 'WHERE (' . implode(") AND (", $this->_parts[self::WHERE]) . ')';
} else {
$where = '';
}
$joinedTables = implode("\n ", $this->_parts[self::JOIN]);
$order = '';
if (!empty($this->_parts[self::ORDER])) {
$order = 'ORDER BY ' . implode(", ", $this->_parts[self::ORDER]);
}
$limit = '';
if ($this->_parts[self::LIMIT]) {
if ($this->_parts[self::OFFSET]) {
$limit = "LIMIT {$this->_parts[self::LIMIT]}, {$this->_parts[self::OFFSET]}";
} else {
$limit = "LIMIT {$this->_parts[self::LIMIT]}";
}
}
$group = '';
if (!empty($this->_parts[self::GROUP])) {
foreach ($this->_parts[self::GROUP] as &$groupedField) {
$groupedField = $this->_connection->quoteIdentifier($groupedField);
}
unset($groupedField);
$group = 'GROUP BY ' . implode(', ', $this->_parts[self::GROUP]);
}
$tableList = array();
foreach ($this->_parts[self::FROM] as $table) {
if ($table['schema'] !== null) {
$tableString = "{$this->_connection->quoteIdentifier($table['schema'])}.{$this->_connection->quoteIdentifier($this->_connection->getTable($table['table']))}";
} else {
$tableString = $this->_connection->quoteIdentifier($this->_connection->getTable($table['table']));
}
if ($table['alias'] !== null) {
$tableString .= " AS {$this->_connection->quoteIdentifier($table['alias'])}";
}
$tableList[] = $tableString;
}
$tableList = implode(', ', $tableList);
return <<<SQL_EOF
SELECT {$fields}
FROM {$tableList}
{$joinedTables}
{$where}
{$group}
{$order}
{$limit}
SQL_EOF;
} else {
$statements = array();
foreach ($this->_parts[self::UNION] as $statement) {
$statements[] = $statement->_prepareSql();
}
$statements = '(' . implode(') UNION (', $statements) . ')';
if (!empty($where)) {
$where = 'WHERE (' . implode(") AND (", $this->_parts[self::WHERE]) . ')';
} else {
$where = '';
}
$limit = '';
if ($this->_parts[self::LIMIT]) {
if ($this->_parts[self::OFFSET]) {
$limit = "LIMIT {$this->_parts[self::LIMIT]}, {$this->_parts[self::OFFSET]}";
} else {
$limit = "LIMIT {$this->_parts[self::LIMIT]}";
}
}
return <<<SQL_EOF
$statements
{$where}
{$limit}
SQL_EOF;
}
}
}

View file

@ -0,0 +1,207 @@
<?php
abstract class Wootook_Core_Database_Sql_Select
{
const COLUMNS = 'COLUMNS';
const FROM = 'FROM';
const JOIN = 'JOIN';
const WHERE = 'WHERE';
const ORDER = 'ORDER';
const UNION = 'UNION';
const LIMIT = 'LIMIT';
const OFFSET = 'OFFSET';
const GROUP = 'GROUP';
const JOIN_INNER = 'INNER';
const JOIN_OUTER = 'OUTER';
const JOIN_LEFT = 'LEFT';
const JOIN_RIGHT = 'RIGHT';
protected $_parts = array(
self::COLUMNS => array(),
self::FROM => array(),
self::JOIN => array(),
self::WHERE => array(),
self::ORDER => array(),
self::UNION => array(),
self::LIMIT => array(),
self::OFFSET => array(),
self::GROUP => array(),
);
protected $_connection = null;
public function __construct(Wootook_Core_Database $connection, $tableName = null)
{
$this->_connection = $connection;
if ($tableName !== null) {
$this->from($tableName);
}
}
public function getConnection()
{
return $this->_connection;
}
public function setConnection(Wootook_Core_Database $connection)
{
$this->_connection = $connection;
return $this;
}
protected function _init()
{
return $this;
}
public function setTableName($tableName)
{
$this->from($tableName);
return $this;
}
public function getTableName()
{
$table = $this->_parts[self::FROM];
return $table['table'];
}
public function quote($data)
{
return $this->getConnection()->quote($data);
}
public function column($column = '*', $alias = null)
{
if (is_array($column)) {
foreach ($column as $alias => $field) {
if (is_int($alias)) {
$this->_parts[self::COLUMNS][] = array($field);
} else {
$this->_parts[self::COLUMNS][] = array($alias => $field);
}
}
} else if ($alias === null || is_int($alias)) {
$this->_parts[self::COLUMNS][] = array($column);
} else {
$this->_parts[self::COLUMNS][] = array($alias => $column);
}
return $this;
}
public function from($table, $schema = null)
{
if (is_array($table)) {
$alias = key($table);
$table = current($table);
} else {
$alias = null;
}
$this->_parts[self::FROM][] = array(
'table' => $table,
'alias' => $alias,
'schema' => $schema
);
return $this;
}
public function where($condition)
{
$this->_parts[self::WHERE][] = $condition;
return $this;
}
public function join($table, $condition, $fields = array('*'), $mode = self::JOIN_INNER)
{
$database = $this->getConnection();
if (is_array($table)) {
$alias = key($table);
$table = current($table);
foreach ($fields as $fieldAlias => $fieldName) {
$this->column("{$alias}.{$field}", $fieldAlias);
}
$this->_parts[self::JOIN][] = "{$mode} JOIN {$database->getTable($table)} AS {$alias} ON {$condition}";
} else {
foreach ($fields as $field) {
$this->column("{$field}");
}
$this->_parts[self::JOIN][] = "{$mode} JOIN {$database->getTable($table)} ON {$condition}";
}
return $this;
}
public function joinLeft($table, $condition, $fields = array('*'))
{
return $this->join($table, $condition, $fields, self::JOIN_LEFT);
}
public function joinRight($table, $condition, $fields = array('*'))
{
return $this->join($table, $condition, $fields, self::JOIN_RIGHT);
}
public function joinInner($table, $condition, $fields = array('*'))
{
return $this->join($table, $condition, $fields, self::JOIN_INNER);
}
public function joinOuter($table, $condition, $fields = array('*'))
{
return $this->join($table, $condition, $fields, self::JOIN_OUTER);
}
public function order($field, $direction = 'ASC')
{
$this->_parts[self::ORDER][] = "{$field} {$direction}";
return $this;
}
public function union($collection)
{
$this->_parts[self::UNION][] = $collection;
return $this;
}
public function limit($limit, $offset = null)
{
$this->_parts[self::LIMIT] = intval($limit);
$this->_parts[self::OFFSET] = $offset;
return $this;
}
public function group($groupField)
{
$this->_parts[self::GROUP][] = $groupField;
return $this;
}
abstract protected function _prepareSql();
public function __toString()
{
return $this->_prepareSql();
}
public function toString()
{
return $this->_prepareSql();
}
}

View file

@ -0,0 +1,296 @@
<?php
class Wootook_Core_DateTime
{
const ISO_8601 = 'c';
const YEAR = 'year';
const YEAR_ISO = 'year_iso';
const MONTH = 'mon';
const DAY = 'mday';
const WEEK = 'week';
const WEEKDAY = 'wday';
const HOUR = 'hours';
const MINUTE = 'minutes';
const SECOND = 'seconds';
const MICROSECOND = 'microsecond';
const DAYLIGHT = 'daylight';
const MERIDIEM = 'meridiem';
const MERIDIEM_AM = 'am';
const MERIDIEM_PM = 'pm';
const TIMESTAMP = 'timestamp';
const PARSER = 'cb';
const OPERATOR_ADD = '+';
const OPERATOR_SUB = '-';
const OPERATOR_SET = '=';
protected static $_rules = array(
'd' => array(self::DAY => '#(0[1-9]|[12][0-9]|3[01])#'),
'j' => array(self::DAY => '#([1-9]|[12][0-9]|3[01])#'),
'D' => array(self::WEEKDAY => '#(Mon|Tue|Wed|Thu|Fri|Sat|Sun)#i', self::PARSER => '_parseShortWeekday'),
'N' => array(self::WEEKDAY => '#([1-7])#', self::PARSER => '_parseWeekday'),
'w' => array(self::WEEKDAY => '#([0-6])#'),
'm' => array(self::MONTH => '#(0[1-9]|1[0-2])#'),
'M' => array(self::MONTH => '#(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)#i', self::PARSER => '_parseShortMonth'),
'n' => array(self::MONTH => '#([1-9]|1[0-2])#'),
'o' => array(self::YEAR_ISO => '#([0-9]{4})#'),
'Y' => array(self::YEAR => '#([0-9]{4})#'),
'y' => array(self::YEAR => '#([0-9]{2})#', self::PARSER => '_parseShortYear'),
'a' => array(self::MERIDIEM => '#(am|pm)#', self::PARSER => '_parseMeridiem'),
'A' => array(self::MERIDIEM => '#(AM|PM)#', self::PARSER => '_parseMeridiem'),
'g' => array(self::HOUR => '#([0-9]{1,2})#'),
'G' => array(self::HOUR => '#([0-9]{1,2})#'),
'h' => array(self::HOUR => '#([0-9]{2})#'),
'H' => array(self::HOUR => '#([0-9]{2})#'),
'i' => array(self::MINUTE => '#([0-9]{2})#'),
's' => array(self::SECOND => '#([0-9]{2})#'),
'u' => array(self::MICROSECOND => '#([0-9]{6})#'),
'I' => array(self::DAYLIGHT => '#(0|1)#'),
// Unimplemented and ignored modifiers
'l' => array(null => '#.#'),
'S' => array(null => '#.#'),
'z' => array(null => '#.#'),
'W' => array(null => '#.#'),
'f' => array(null => '#.#'),
't' => array(null => '#.#'),
'L' => array(null => '#.#'),
'O' => array(null => '#.#'),
'P' => array(null => '#.#'),
'T' => array(null => '#.#'),
'Z' => array(null => '#.#'),
'c' => array(null => '#.#'),
'r' => array(null => '#.#'),
'U' => array(null => '#.#')
);
protected $_datetime = null;
public static function init($timezone = null, $force = false)
{
static $init = false;
if ($init === false || $force === true) {
if ($timezone === null) {
//$timezone = Wootook::getConfig('system/date/timezone');
}
if ($timezone === null) {
$timezone = 'GMT';
}
date_default_timezone_set($timezone);
$init = true;
}
}
public function __construct($timestamp = null, $format = null)
{
self::init();
if ($timestamp === null) {
$this->_datetime = time();
} else if ($format === null) {
$this->_datetime = intval($timestamp);
} else {
$this->_datetime = $this->_parse($timestamp, $format);
}
}
public function getIso($useTimezone = false)
{
return $this->toString(self::ISO_8601, $useTimezone);
}
public function getTimestamp()
{
return $this->_datetime;
}
public function now()
{
return $this->calc(time(), self::TIMESTAMP, self::OPERATOR_SET);
}
public function set($value, $part = self::TIMESTAMP)
{
return $this->calc($value, $part, self::OPERATOR_SET);
}
public function add($value, $part = self::TIMESTAMP)
{
return $this->calc($value, $part, self::OPERATOR_ADD);
}
public function sub($value, $part = self::TIMESTAMP)
{
return $this->calc($value, $part, self::OPERATOR_SUB);
}
public function calc($value, $part = self::TIMESTAMP, $type = self::OPERATOR_ADD)
{
switch ($part) {
case self::YEAR:
case self::MONTH:
case self::WEEK:
case self::DAY:
case self::HOUR:
case self::MINUTE:
case self::SECOND:
$current = getdate($this->_datetime);
if ($type === self::OPERATOR_ADD) {
$parts = $current[$part] += $value;
} else if ($type === self::OPERATOR_SUB) {
$parts = $current[$part] -= $value;
} else if ($type === self::OPERATOR_SET) {
$parts = $current[$part] = $value;
}
$this->_datetime = $this->_mktime($parts);
break;
case self::TIMESTAMP:
if ($type === self::OPERATOR_ADD) {
$this->_datetime += intval($value);
} else if ($type === self::OPERATOR_SUB) {
$this->_datetime -= intval($value);
} else if ($type === self::OPERATOR_SET) {
$this->_datetime = intval($value);
}
break;
// default: break; // omitted
}
return $this;
}
public function diff(self $date)
{
return $this->_datetime - $date->_datetime;
}
protected function _mktime(Array $parts)
{
return mktime($parts[self::HOUR], $parts[self::MINUTE], $parts[self::SECOND],
$parts[self::MONTH], $parts[self::DAY], $parts[self::YEAR]);
}
public function toString($format, $useTimezone = true)
{
if ($useTimezone) {
return date($format, $this->_datetime);
} else {
return gmdate($format, $this->_datetime);
}
}
public function __toString()
{
return $this->toString(self::ISO_8601, false);
}
protected function _parseShortYear($match)
{
$year = intval($match);
if ($year < 70) {
$year += 2000;
} else if ($year < 100) {
$year += 1900;
}
return $year;
}
protected function _parseShortMonth($match)
{
if ($key = array_search(strtolower($match), array('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'))) {
return $key + 1;
}
return false;
}
protected function _parseShortWeekday($match)
{
if ($key = array_search(strtolower($match), array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'))) {
return $key;
}
return false;
}
protected function _parseWeekday($match)
{
return intval($match) % 7;
}
protected function _parseMeridiem($match)
{
if (in_array(strtolower($match), array(self::MERIDIEM_AM, self::MERIDIEM_PM))) {
return strtolower($match);
}
return false;
}
protected function _parse($datetime, $format)
{
$parts = array(
self::YEAR => false,
self::YEAR_ISO => false,
self::MONTH => false,
self::DAY => false,
self::WEEKDAY => false,
self::HOUR => false,
self::MINUTE => false,
self::SECOND => false,
self::MICROSECOND => false,
self::DAYLIGHT => false,
self::MERIDIEM => false,
);
$offset = 0;
$length = strlen($format);
for ($i = 0; $i < $length; $i++) {
$modifier = $format[$i];
if (!isset(self::$_rules[$modifier])) {
$offset = (strpos($datetime, $format[$i], $offset)) + 1;
continue;
}
$rule = self::$_rules[$modifier];
$callback = null;
if (isset($rule[self::PARSER])) {
$callback = $rule[self::PARSER];
unset($rule[self::PARSER]);
}
foreach ($rule as $part => $regex) {
if (!preg_match($regex, $datetime, $matches, null, $offset)) {
var_dump($datetime);
continue;
}
if ($callback === null) {
$parts[$part] = intval($matches[1]);
} else if (is_callable($callback)) {
$parts[$part] = call_user_func($callback, $matches[1]);
} else {
$parts[$part] = $this->$callback($matches[1]);
}
$offset += strlen($matches[1]);
}
}
if ($parts[self::MERIDIEM] !== false && $parts[self::MERIDIEM] === self::MERIDIEM_PM) {
$parts[self::HOUR] = ($parts[self::HOUR] + 12) % 24;
}
if ($parts[self::YEAR] !== false || $parts[self::YEAR_ISO] === false) {
return $this->_mktime($parts);
} else {
return $this->_mktime($parts);
}
}
}

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,166 @@
<?php
abstract class Wootook_Core_Entity
extends Wootook_Core_Database_Resource
implements Wootook_Core_EntityInterface
{
protected $_idFieldName = null;
public function setIdFieldName($fieldName)
{
$this->_idFieldName = $fieldName;
return $this;
}
public function getIdFieldName()
{
return $this->_idFieldName;
}
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);
if (func_num_args() >= 2) {
$idFieldName = func_get_arg(1);
} else {
$idFieldName = $this->getIdFieldName();
}
$database = $this->getReadConnection();
if ($database === null) {
throw new Wootook_Core_Exception_DataAccessException('Could not load data: no read connection configured.');
}
$sql =<<<SQL_EOF
SELECT * FROM {$database->getTable($this->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[$this->getIdFieldName()]);
$this->_data = array();
$this->getDataMapper()->decode($this, $datas);
$this->setId($id);
return $this;
}
protected function _save()
{
$database = $this->getWriteConnection();
if ($this->getId() !== null) {
$fields = array();
$values = array();
$datas = $this->getDataMapper()->encode($this, $this->getAllDatas());
foreach ($datas as $field => $value) {
if ($field == $this->getIdFieldName()) {
continue;
}
$fields[] = "{$database->quoteIdentifier($field)}=:{$field}";
$values[$field] = $value;
}
$fieldsImploded = implode(', ', $fields);
$idFieldName = $this->getIdFieldName();
$values[$idFieldName] = $this->getId();
if ($database === null) {
throw new Wootook_Core_Exception_DataAccessException('Could not load data: no write connection configured.');
}
$sql =<<<SQL_EOF
UPDATE {$database->getTable($this->getTableName())}
SET {$fieldsImploded}
WHERE {$idFieldName}=:{$idFieldName}
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
} else {
$datas = $this->getAllDatas();
$fields = array();
$tokens = array();
$values = array();
foreach ($datas as $field => $value) {
if ($field == $this->getIdFieldName()) {
continue;
}
$tokens[] = ":{$field}";
$fields[] = $database->quoteIdentifier($field);
$values[$field] = strval($value);
}
$tokensImploded = implode(', ', $tokens);
$fieldsImploded = implode(', ', $fields);
if ($database === null) {
throw new Wootook_Core_Exception_DataAccessException('Could not load data: no write connection configured.');
}
$table = $database->getTable($this->getTableName());
$sql =<<<SQL_EOF
INSERT INTO {$database->quoteIdentifier($table)} ({$database->quoteIdentifier($this->getIdFieldName())}, $fieldsImploded)
VALUES (NULL, {$tokensImploded})
SQL_EOF;
$statement = $database->prepare($sql);
$statement->execute($values);
$id = $database->lastInsertId($table);
$this->setId($id);
}
return $this;
}
protected function _delete()
{
$fields = array();
foreach ($this->getAllDatas() as $field => $value) {
if ($field == $this->getIdFieldName()) {
continue;
}
$fields[] = "{$field}=:{$field}";
}
$fieldsImploded = implod(', ', $fields);
$idFieldName = $this->getIdFieldName();
$database = $this->getWriteConnection();
if ($database === null) {
throw new Wootook_Core_Exception_DataAccessException('Could not load data: no write connection configured.');
}
$sql =<<<SQL_EOF
DELETE {$database->getTable($this->getTableName())}
WHERE {$idFieldName}=:{$idFieldName}
SQL_EOF;
$statement->execute($this->getAllDatas());
return $this;
}
}

View file

@ -0,0 +1,120 @@
<?php
/**
*
* @uses Wootook_Object
* @uses Legacies_Empire
* @uses Wootook_Player_Model_Entity
*/
abstract class Wootook_Core_Entity_SubTable
extends Wootook_Core_Database_Resource
{
private $_isLoaded = false;
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 = $this->getWriteConnection();
$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 = $this->getWriteConnection();
$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 = $this->getReadConnection();
$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 = $this->getWriteConnection();
$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;
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
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,285 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
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 $_listen = true;
private $_mute = false;
/**
*
* @return Wootook_Core_ErrorProfiler
*/
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 (!$this->_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 addException($exception)
{
$this->_exceptions[] = $exception;
}
public function exceptionManager($exception)
{
if (!$this->_listen) {
return;
}
$this->_exceptions[] = new Wootook_Core_Exception_Exception('Uncaught Exception: ' . $exception->getMessage(), null, $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
On: {$date} +{$microsec}µs
Type: {$code}
Message: {$error['message']}
File: {$error['file']}
Line: {$error['line']}
\n
ERROR_EOF;
}
public function shutdownManager()
{
if ($this->_mute === true) {
return;
}
$index = 0;
echo '<div style="background:#FFF;border:5px solid #933;border-top-width:15px;border-radius:5px;color:#000;padding:0;margin:20px;text-align:left;margin:50px auto;width:800px;">';
echo '<h1 style="margin:0;padding:0 10px;text-decoration:none;border-bottom:3px solid #933;">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 style="color:#666;font-style:italic;margin:20px 10px 10px;">Error profiler was empty.</p>';
} else {
echo '<div style="margin:0;overflow:auto;">';
foreach ($this->_errors as $error) {
++$index;
echo '<h2 style="font-size:1.2em;text-decoration:none;margin:0 5px;">Message #' . $index . '</h2>';
echo '<pre style="margin:0 5px;">';
echo $this->_renderError($index, $error);
echo '</pre>';
}
foreach ($this->_warnings as $error) {
++$index;
echo '<h2 style="font-size:1.2em;text-decoration:none;margin:10px 5px 0;">Message #' . $index . '</h2>';
echo '<pre style="margin:0 5px;">';
echo $this->_renderError($index, $error);
echo '</pre>';
}
foreach ($this->_notices as $error) {
++$index;
echo '<h2 style="font-size:1.2em;text-decoration:none;margin:10px 5px 0;">Message #' . $index . '</h2>';
echo '<pre style="margin:0 5px;">';
echo $this->_renderError($index, $error);
echo '</pre>';
}
foreach ($this->_otherErrors as $errorList) {
foreach ($errorList as $error) {
++$index;
echo '<h2 style="font-size:1.2em;text-decoration:none;margin:10px 5px 0;">Message #' . $index . '</h2>';
echo '<pre style="margin:0 5px;">';
echo $this->_renderError($index, $error);
echo '</pre>';
}
}
foreach ($this->_exceptions as $exception) {
++$index;
echo '<h2 style="font-size:1.2em;text-decoration:none;margin:10px 5px 0;">Message #' . $index . '</h2>';
echo '<pre style="margin:0 5px;">';
echo $exception->getMessage() . PHP_EOL;
echo $exception->getTraceAsString() . PHP_EOL;
echo '</pre>';
$child = 0;
$current = $exception;
while (($current = $current->getPrevious()) !== null) {
$child++;
echo '<h3 style="font-size:1em;text-decoration:none;margin:10px 30px 0;">Message #' . $index . ', child level #' . $child . '</h3>';
echo '<pre style="margin:0 30px;">';
echo $current->getMessage() . PHP_EOL;
echo $current->getTraceAsString() . PHP_EOL;
echo PHP_EOL;
echo '</pre>';
}
echo PHP_EOL;
}
echo '</div>';
}
echo '</div>';
}
public static function register()
{
set_error_handler(array(self::getSingleton(), 'errorManager'));
set_exception_handler(array(self::getSingleton(), 'exceptionManager'));
self::getSingleton()->_mute = false;
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();
self::getSingleton()->_mute = true;
if ((self::$_isTraceRegistered === false && defined('DEBUG')) || $force) {
self::$_isTraceRegistered = true;
register_shutdown_function(array(self::getSingleton(), 'shutdownManager'));
}
}
public function sleep()
{
$this->_listen = false;
}
public function wakeup()
{
$this->_listen = true;
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
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,37 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
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_Deprecated
extends Wootook_Core_Exception_RuntimeException
{
}

View file

@ -0,0 +1,25 @@
<?php
class Wootook_Core_Exception_Exception
extends Exception
implements Wootook_Core_Exception
{
protected $_previous = null;
public function __construct($message = null, $code = null, $previous = null)
{
if (PHP_VERSION_ID >= 50300) {
parent::__construct($message, $code, $previous);
} else {
parent::__construct($message, $code);
$this->_previous = $previous;
}
}
public function __call($method, $params)
{
if (strtolower($method) == 'getprevious') {
return $this->_previous;
}
}
}

View file

@ -0,0 +1,7 @@
<?php
class Wootook_Core_Exception_GameError
extends Wootook_Core_Exception_RuntimeException
{
}

View file

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

View file

@ -0,0 +1,32 @@
<?php
class Wootook_Core_Exception_RuntimeException
extends RuntimeException
implements Wootook_Core_Exception
{
protected $_previous = null;
public function __construct($message = null, $code = null, $previous = null)
{
if (PHP_VERSION_ID >= 50300) {
parent::__construct($message, $code, $previous);
} else {
parent::__construct($message, $code);
$this->_previous = $previous;
}
}
public function __call($method, $params)
{
if (strtolower($method) == 'getprevious') {
return $this->_previous;
}
}
public function __toString()
{
return <<<STRING_EOF
STRING_EOF;
}
}

View file

@ -0,0 +1,7 @@
<?php
class Wootook_Core_Exception_WebsiteError
extends Wootook_Core_Exception_RuntimeException
{
}

View file

@ -0,0 +1,215 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
class Wootook_Core_Form
{
protected $_elements = array();
protected $_request = null;
/**
*
* Element class loader
* @var Wootook_Core_Form_ElementLoader
*/
protected $_elementLoader = null;
/**
*
* Validator class loader
* @var Wootook_Core_Form_ValidatorLoader
*/
protected $_validatorLoader = null;
/**
*
* Enter description here ...
* @var Wootook_Core_Model_Session
*/
protected $_session = null;
public function __construct(Wootook_Core_Model_Session $session, Array $elements = array())
{
$this->_session = $session;
$this->_elementLoader = new Wootook_Core_Form_ElementLoader($this, array(
'Wootook_Core_Form_Element_' => 'Wootook/Core/Form/Element'
));
$this->_validatorLoader = new Wootook_Core_Form_ValidatorLoader($this, array(
'Wootook_Core_Form_Validator_' => 'Wootook/Core/Form/Validator'
));
$this->addElement('__formkey', 'text', array('form_key' => 'formKey'));
foreach ($elements as $elementName => $elementConfig) {
if (is_string($elementConfig)) {
$this->addElement($elementName, $elementConfig);
} else if ($elementConfig instanceof Wootook_Core_Form_ElementAbstract) {
$this->addElement($elementName, $elementConfig);
} else {
if (isset($elementConfig['validators'])) {
$this->addElement($elementName, $elementConfig['type'], $elementConfig['validators']);
} else {
$this->addElement($elementName, $elementConfig['type']);
}
}
}
}
public function validate()
{
foreach ($this->_elements as $element) {
if (!$element->validate()) {
return false;
}
}
return true;
}
/**
*
* Enter description here ...
* @param string $name
* @param string|Wootook_Core_Form_ElementAbstract $type
* @return Wootook_Core_Form
*/
public function addElement($name, $type = 'text', Array $validators = array())
{
if ($type instanceof Wootook_Core_Form_ElementAbstract) {
$this->_elements[$name] = $type;
$this->_elements[$name]->setForm($this);
} else {
$element = $this->_elementLoader->load($type);
if ($element === null) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_RuntimeException(sprintf('Element %1$s (type: %2$s) could not be created.', $name, $type)));
return $this;
}
$element->setForm($this);
$this->_elements[$name] = $element;
}
$this->_elements[$name]->setName($name);
foreach ($validators as $validatorName => $validatorType) {
if ($validatorType instanceof Wootook_Core_Form_ElementAbstract) {
$this->_elements[$name]->addValidator($validatorType, $validatorName);
} else {
$validator = $this->_validatorLoader->load($validatorType);
if ($validator === null) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_RuntimeException(sprintf('Validator %1$s (type: %2$s) could not be created.', $validatorName, $validatorType)));
return $this;
}
$this->_elements[$name]->addValidator($validator, $validatorName);
}
}
return $this;
}
/**
*
* Enter description here ...
* @param string $name
* @return Wootook_Core_Form_ElementAbstract
*/
public function getElement($name)
{
if (!isset($this->_elements[$name])) {
return null;
}
return $this->_elements[$name];
}
/**
*
* Enter description here ...
* @param string $name
* @return Wootook_Core_Model_Session
*/
public function getSession()
{
return $this->_session;
}
public function setRequest(Wootook_Core_Controller_Request_Http $request)
{
$this->_request = $request;
return $this;
}
/**
*
* Enter description here ...
* @return Wootook_Core_Controller_Request_Http
*/
public function getRequest()
{
return $this->_request;
}
public function getData()
{
$request = $this->getRequest();
if ($request === null) {
return array();
}
if ($request->isPost()) {
return $request->getAllPostData();
}
return $request->getAllQueryData();
}
public function populate(Array $datas = array())
{
$request = $this->getRequest();
foreach ($this->_elements as $elementName => $element) {
if (isset($datas[$elementName])) {
$element->populate($datas[$elementName]);
} else if ($request->isPost()) {
$element->populate($request->getPost($elementName));
} else {
$element->populate($request->getQuery($elementName));
}
}
}
}

View file

@ -0,0 +1,11 @@
<?php
class Wootook_Core_Form_Element_Button
extends Wootook_Core_Form_ElementAbstract
{
public function getType()
{
return 'button';
}
}

View file

@ -0,0 +1,11 @@
<?php
class Wootook_Core_Form_Element_Text
extends Wootook_Core_Form_ElementAbstract
{
public function getType()
{
return 'text';
}
}

View file

@ -0,0 +1,145 @@
<?php
abstract class Wootook_Core_Form_ElementAbstract
{
protected $_name = null;
protected $_form = null;
protected $_value = null;
protected $_params = null;
protected $_validators = array();
public function __construct($name, $params = array(), Wootook_Core_Form $form = null)
{
if ($form !== null) {
$this->setForm($form);
}
$this->setName($name);
$this->setAllParams($params);
}
abstract public function getType();
public function validate()
{
$data = $this->getData();
foreach ($this->_validators as $validator) {
if (!$validator->validate($this, $data)) {
return false;
}
}
return true;
}
public function setName($name)
{
$this->_name = $name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setAllParams($params)
{
$this->_params = $params;
return $this;
}
public function getAllParams()
{
return $this->_params;
}
public function setParam($param, $value)
{
$this->_params[$param] = $value;
return $this;
}
public function getParam($param)
{
return $this->_params[$param];
}
public function hasParam($param)
{
return isset($this->_params[$param]);
}
public function unsetParam($param)
{
unset($this->_params[$param]);
return $this;
}
public function setForm(Wootook_Core_Form $form)
{
$this->_form = $form;
return $this;
}
public function getForm()
{
return $this->_form;
}
public function getData()
{
return $this->_value;
}
public function populate($value)
{
$this->_value = $value;
return $this;
}
public function addValidator(Wootook_Core_Form_ValidatorAbstract $validator, $name = null)
{
if ($name === null) {
$this->_validators = array();
$name = 'default';
}
$this->_validators[$name] = $validator;
return $this;
}
public function getValidator($name)
{
if (!isset($this->_validators[$name])) {
return null;
}
return $this->_validators[$name];
}
public function clearValidator($name)
{
if (isset($this->_validators[$name])) {
unset($this->_validators[$name]);
}
return $this;
}
public function clearAllValidators()
{
$this->_validators = array();
return $this;
}
}

View file

@ -0,0 +1,37 @@
<?php
class Wootook_Core_Form_ElementLoader
extends Wootook_Core_PluginLoader_Abstract
{
protected $_form = null;
public function __construct(Wootook_Core_Form $form, Array $namespaces = array())
{
$this->_form = $form;
foreach ($namespaces as $namespace => $path) {
if (is_int($namespace)) {
$this->registerNamespace($path);
} else {
$this->registerNamespace($namespace, $path);
}
}
}
protected function _load($className, $useSingleton)
{
$reflection = new ReflectionClass($className);
if ($useSingleton && $reflection->implementsInterface('Wootook_Core_Singleton')) {
$method = $reflection->getMethod('getSingleton');
return $method->invoke(null);
}
try {
return $reflection->newInstance($this->_form);
} catch (ReflectionException $e) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException($e);
return null;
}
}
}

View file

@ -0,0 +1,21 @@
<?php
class Wootook_Core_Form_Validator_Alnum
extends Wootook_Core_Form_Validator_Regex
{
public function __construct()
{
parent::__construct('#[^[:alnum:]]#');
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if ($this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" should only contain alphanumeric characters.', $element->getName());
return false;
}
return true;
}
}

View file

@ -0,0 +1,21 @@
<?php
class Wootook_Core_Form_Validator_Alnum
extends Wootook_Core_Form_Validator_Regex
{
public function __construct()
{
parent::__construct('#[^[:alpha:]]#');
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if ($this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" should only contain alphabetic characters.', $element->getName());
return false;
}
return true;
}
}

View file

@ -0,0 +1,21 @@
<?php
class Wootook_Core_Form_Validator_Email
extends Wootook_Core_Form_Validator_Regex
{
public function __construct()
{
parent::__construct('#^[[:alnum:]\._\-]@[[:alnum:]\._\-]\.[a-z]{2,}$#');
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if (!$this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" should contain an email.', $element->getName());
return false;
}
return true;
}
}

View file

@ -0,0 +1,20 @@
<?php
class Wootook_Core_Form_Validator_FormKey
extends Wootook_Core_Form_ValidatorAbstract
{
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
$form = $element->getForm();
$session = $form->getSession();
if ($session->getFormKey(false) == $data) {
return true;
}
$this->_getSession($field)
->addError('CSRF token failure.', $field->getName());
return false;
}
}

View file

@ -0,0 +1,22 @@
<?php
class Wootook_Core_Form_Validator_Hex
extends Wootook_Core_Form_Validator_Regex
{
public function __construct()
{
parent::__construct('#(?:0x)?[^0-9a-f]#i');
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if ($this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" should only contain numeric characters.', $element->getName());
return false;
}
return true;
}
}

View file

@ -0,0 +1,21 @@
<?php
class Wootook_Core_Form_Validator_Email
extends Wootook_Core_Form_Validator_Regex
{
public function __construct()
{
parent::__construct('#^[[:alnum:]\._\-]\.[a-z]{2,}$#');
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if (!$this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" should contain a host name.', $element->getName());
return false;
}
return true;
}
}

View file

@ -0,0 +1,22 @@
<?php
class Wootook_Core_Form_Validator_Numeric
extends Wootook_Core_Form_Validator_Regex
{
public function __construct()
{
parent::__construct('#[^[:digit:]]#');
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if ($this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" should only contain numeric characters.', $element->getName());
return false;
}
return true;
}
}

View file

@ -0,0 +1,28 @@
<?php
class Wootook_Core_Form_Validator_Regex
extends Wootook_Core_Form_ValidatorAbstract
{
protected $_expression = null;
public function __construct($expression)
{
$this->_expression = $expression;
}
public function validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
if (!$this->_validate($element, $data)) {
$this->_getSession($element)
->addError('Field "%s" does not match the validation pattern.', $element->getName());
return false;
}
return true;
}
protected function _validate(Wootook_Core_Form_ElementAbstract $element, $data)
{
return preg_match($this->_expression, $data);
}
}

View file

@ -0,0 +1,15 @@
<?php
abstract class Wootook_Core_Form_ValidatorAbstract
{
abstract public function validate(Wootook_Core_Form_ElementAbstract $element, $data);
protected function _getSession(Wootook_Core_Form_ElementAbstract $element)
{
$form = $element->getForm();
if (!$form instanceof Wootook_Core_Form) {
return null;
}
return $element->getSession();
}
}

View file

@ -0,0 +1,37 @@
<?php
class Wootook_Core_Form_ValidatorLoader
extends Wootook_Core_PluginLoader_Abstract
{
protected $_form = null;
public function __construct(Wootook_Core_Form $form, Array $namespaces = array())
{
$this->_form = $form;
foreach ($namespaces as $namespace => $path) {
if (is_int($namespace)) {
$this->registerNamespace($path);
} else {
$this->registerNamespace($namespace, $path);
}
}
}
protected function _load($className, $useSingleton)
{
$reflection = new ReflectionClass($className);
if ($useSingleton && $reflection->implementsInterface('Wootook_Core_Singleton')) {
$method = $reflection->getMethod('getSingleton');
return $method->invoke(null);
}
try {
return $reflection->newInstance();
} catch (ReflectionException $e) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException($e);
return null;
}
}
}

View file

@ -0,0 +1,626 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
* Page layout class utility.
* Builds page structures from flexible layout declaration files, written in a
* user-friendly XML format.
*
* @author Greg <g.planchat@gmail.com>
* @since 1.5.0
* @package Wootook
* @subpackage Wootook_Core
* @category layout
*/
class Wootook_Core_Layout
extends Wootook_Core_Model
{
const DEFAULT_PACKAGE = 'base';
const DEFAULT_THEME = 'default';
const DOMAIN_FRONTEND = 'frontend';
const DOMAIN_BACKEND = 'backend';
/** @var array */
protected $_blocks = array();
/** @var Wootook_Core_View */
protected $_messageBlock = null;
/** @var Wootook_Core_View */
protected $_rootView = null;
/** @var string */
protected $_eventPrefix = 'layout';
/** @var string */
protected $_eventObject = 'layout';
/** @var string */
protected $_domain = self::DOMAIN_FRONTEND;
/** @var string */
protected $_package = self::DEFAULT_PACKAGE;
/** @var string */
protected $_theme = self::DEFAULT_THEME;
/** @var array */
protected $_namespaces = array(
'core' => array(
'Wootook_Core_Block_' => 'Wootook/Core/Block'
)
);
/**
* Page layout class utility.
*
* @param string $domain
* @param string $package
* @param string $theme
* @param array $data
*/
public function __construct($domain = null, $package = null, $theme = null, Array $data = array())
{
if ($domain === null) {
if (Wootook::getDefaultWebsite()->getId() == 0) {
$this->_domain = self::DOMAIN_BACKEND;
} else {
$this->_domain = self::DOMAIN_FRONTEND;
}
} else {
$this->_domain = $domain;
}
if ($package !== null) {
$this->setPackage($package);
}
if ($theme !== null) {
$this->setTheme($theme);
}
parent::__construct($data);
}
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);
}
}
$fileList = Wootook::getGameConfig('layout');
if ($fileList instanceof Wootook_Core_Config_Node) {
$fileList = $fileList->toArray();
}
if (!is_array($fileList) || empty($fileList)) {
$fileList = array();
}
$this->_data = array();
$this->setPackage(Wootook::getWebsiteConfig('package'));
$this->setTheme(Wootook::getGameConfig('theme'));
$parser = new Wootook_Core_Layout_Parser();
foreach ($fileList as $layoutFile) {
try {
if (preg_match('#\.php$#', $layoutFile)) {
$layoutData = include $this->_getLayoutPath($layoutFile);
} else {
$layoutData = $parser->parse($this->_getLayoutPath($layoutFile), $this->_getLayoutCachePath($layoutFile), 3600);
}
} catch (Wootook_Core_Exception_LayoutException $e) {
Wootook_Core_ErrorProfiler::getSingleton()->addException($e);
continue;
}
if (!is_array($layoutData)) {
continue;
}
foreach ($layoutData as $layoutId => $layoutConfig) {
if ($this->hasData($layoutId)) {
$declared = $this->getData($layoutId);
if (isset($declared['block']) && !isset($layoutConfig['block'])) {
$layoutConfig['block'] = $declared['block'];
}
if (isset($declared['reference'])) {
if (isset($layoutConfig['reference'])) {
$layoutConfig['reference'] = array_merge($declared['reference'], $layoutConfig['reference']);
} else {
$layoutConfig['reference'] = $declared['reference'];
}
}
}
$this->setData($layoutId, $layoutConfig);
}
}
$this->_messageBlock = $this->createBlock('core/messages', 'messages');
return $this;
}
protected function _getAllParents(&$layoutConfigs, $currentHandle)
{
foreach ($currentHandle as $parent) {
$currentLayout = $this->getData($parent);
$layoutConfigs[] = $currentLayout;
if (!isset($currentLayout['update'])) {
continue;
}
$this->_getAllParents($layoutConfigs, $currentLayout['update']);
}
}
protected function _load()
{
$layoutId = func_get_arg(0);
if (!$this->hasData($layoutId)) {
return $this;
}
$layoutConfigs = array($this->getData($layoutId));
if (isset($layoutConfigs[0]['update'])) {
$this->_getAllParents($layoutConfigs, $layoutConfigs[0]['update']);
}
$layoutUpdates = array();
$layoutConfig = array();
foreach (array_reverse($layoutConfigs) as $config) {
if (!is_array($config)) {
continue;
}
$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->_rootView = $this->_createBlock($type, $name, $layoutConfig);
} else if (!isset($this->_rootView)) {
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']);
}
}
}
Wootook::dispatchEvent($this->_eventPrefix . '.prepare.before', array(
$this->_eventObject => $this
));
foreach ($this->_blocks as $block) {
$block->prepareLayout();
}
Wootook::dispatchEvent($this->_eventPrefix . '.prepare.after', array(
$this->_eventObject => $this
));
}
protected function _save()
{
throw new Wootook_Core_Exception_LayoutException('Save not permitted for the layout manager.');
}
protected function _delete()
{
throw new Wootook_Core_Exception_LayoutException('Delete not permitted for the layout manager.');
}
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::getSingleton()->sleep();
if (!($fp = @fopen($fileName, 'r', true))) {
Wootook_Core_ErrorProfiler::getSingleton()->wakeup();
continue;
}
Wootook_Core_ErrorProfiler::getSingleton()->wakeup();
fclose($fp);
if (!class_exists($className, true)) {
continue;
}
return $className;
}
}
Wootook_Core_ErrorProfiler::getSingleton()
->addException(new Wootook_Core_Exception_LayoutException(sprintf('Class type "%s" could not be resolved.', $type)));
return null;
}
/**
* Register a new block namespage for use in the layout declaration files
*
* @since 1.5.0
* @param string $module
* @param string $namespace
* @param string|null $path
* @return Wootook_Core_Layout
*/
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;
}
/**
* Unregister a previously declared block namespace
*
* @since 1.5.0
* @param string $module
* @param string $namespace
* @return Wootook_Core_Layout
*/
public function unregisterBlockNamespace($module, $namespace)
{
if (isset($this->_namespaces[$module]) && isset($this->_namespaces[$module][$namespace])) {
unset($this->_namespaces[$module][$namespace]);
}
return $this;
}
/**
* Create a new block instance
*
* @param string $type
* @param string $name
* @param array $config
* @return Wootook_Core_View
*/
public function createBlock($type, $name, $config = array())
{
$instance = $this->_createBlock($type, $name, $config);
if ($instance === null) {
return null;
}
$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 {
$child = $this->_createBlock($config['type'], $name, $config);
if ($child !== null) {
$instance->$alias = $child;
}
}
}
} catch (ReflectionException $e) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException($e);
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 = strtolower(preg_replace('#([A-Z])#', '-\\1', $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_LayoutException(Wootook::__('Method %s requires parameter %d ($%s) to be defined.',
$reflectionMethod->getName(), $paramterPosition + 1, $paramterName));
}
}
$reflectionMethod->invokeArgs($block, $callParamaters);
} catch (ReflectionException $e) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException($e);
continue;
} catch (RuntimeException $e) {
Wootook_Core_ErrorProfiler::getSingleton()
->addException($e);
continue;
}
}
}
/**
* Get the current Layout domain (frontend or backend)
*
* @since 1.5.0
* @return string
*/
public function getDomain()
{
return $this->_domain;
}
/**
* Set the current Layout domain (frontend or backend)
*
* @since 1.5.0
* @param string $domain
* @return Wootook_Core_Layout
*/
public function setDomain($domain)
{
$this->_domain = $domain;
$this->_init();
return $this;
}
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 Wootook::getBasePath('design') . DIRECTORY_SEPARATOR . $this->getDomain();
}
public function getAllBlocks()
{
return $this->_blocks;
}
public function getBlock($code)
{
if (isset($this->_blocks[$code])) {
return $this->_blocks[$code];
}
return null;
}
public function render()
{
if (!$this->_rootView instanceof Wootook_Core_View) {
throw new Wootook_Core_Exception_LayoutException(Wootook::__('No root view declared.'));
}
$scriptPath = $this->getScriptPath();
foreach ($this->_blocks as $block) {
if ($block instanceof Wootook_Core_Block_Template) {
$block->setScriptPath($scriptPath);
}
$block->beforeToHtml();
}
unset($block);
return $this->_rootView->render();
}
protected function _getLayoutCachePath($file)
{
$package = $this->getPackage();
$theme = $this->getTheme();
$pattern = APPLICATION_PATH . "cache/" . __CLASS__ . "--{$this->getDomain()}-%s-%s-{$file}.cache";
if (empty($package)) {
$package = self::DEFAULT_PACKAGE;
}
if (empty($theme)) {
$theme = self::DEFAULT_THEME;
}
return sprintf($pattern, $package, $theme);
}
protected function _getLayoutPath($file)
{
$package = $this->getPackage();
$theme = $this->getTheme();
$pattern = "{$this->getScriptPath()}/%s/%s/layouts/{$file}";
if ($package !== null && $theme !== null) {
$path = sprintf($pattern, $package, $theme);
if (Wootook::fileExists($path)) {
return $path;
}
}
if ($package !== null) {
$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;
}
throw new Wootook_Core_Exception_LayoutException(sprintf("Layout file '%s' does not exist.", $file));
}
/**
*
* @return Wootook_Core_Block_Messages
*/
public function getMessagesBlock()
{
return $this->_messageBlock;
}
}

View file

@ -0,0 +1,165 @@
<?php
class Wootook_Core_Layout_Parser
{
/**
*
* Enter description here ...
* @param unknown_type $filename
*/
public function parse($filename, $cachePath = null, $cacheLifetime = 86400)
{
if ($cachePath !== null && Wootook::fileExists($cachePath) && $cacheLifetime > 0 && (time() - filemtime($cachePath) <= $cacheLifetime)) {
return include $cachePath;
}
$parsedData = $this->_parse($filename);
if ($cachePath !== null) {
$parsedData->save($cachePath);
}
return $parsedData->toArray();
}
protected function _parse($filename)
{
$layout = simplexml_load_file($filename);
if ($layout->getName() !== 'layout') {
return array();
}
$result = new Wootook_Core_Config_Adapter_Array();
foreach ($layout->handle as $handle) {
$name = (string) $handle['name'];
if (empty($name)) {
continue;
}
$handleNode = new Wootook_Core_Config_Node(array(), $result);
$result->$name = $handleNode;
if (isset($handle->update)) {
$updateListNode = new Wootook_Core_Config_Node(array(), $handleNode);
$handleNode->update = $updateListNode;
foreach ($handle->update as $update) {
if (isset($update['name'])) {
$updateListNode->__set(uniqid(), (string) $update['name']);
}
}
}
if (isset($handle->block)) {
$this->_parseBlock($handle->block[0], $handleNode);
}
if (isset($handle->reference)) {
$referenceListNode = new Wootook_Core_Config_Node(array(), $handleNode);
$handleNode->reference = $referenceListNode;
foreach ($handle->reference as $reference) {
$referenceName = (string) $reference['name'];
if (empty($referenceName)) {
continue;
}
$referenceNode = new Wootook_Core_Config_Node(array(), $referenceListNode);
$referenceListNode->$referenceName = $referenceNode;
$this->_parseBlockBody($reference, $referenceNode);
}
}
}
return $result;
}
protected function _parseBlock(SimpleXMLElement $handle, Wootook_Core_Config_Node $blockNode)
{
foreach ($handle->attributes() as $attributeName => $attributeValue) {
$blockNode->$attributeName = (string) $attributeValue;
}
$this->_parseBlockBody($handle, $blockNode);
}
protected function _parseBlockBody(SimpleXMLElement $handle, Wootook_Core_Config_Node $blockNode)
{
if (isset($handle->block)) {
$childrenNode = new Wootook_Core_Config_Node(array(), $blockNode);
$blockNode->children = $childrenNode;
foreach ($handle->block as $block) {
$blockName = (string) $block['name'];
if (empty($blockName)) {
continue;
}
$childNode = new Wootook_Core_Config_Node(array(), $childrenNode);
$childrenNode->$blockName = $childNode;
$this->_parseBlock($block, $childNode);
}
}
if (isset($handle->action)) {
$actionListNode = new Wootook_Core_Config_Node(array(), $blockNode);
$blockNode->actions = $actionListNode;
foreach ($handle->action as $action) {
$methodName = (string) $action['method'];
if (empty($methodName)) {
continue;
}
$actionNode = new Wootook_Core_Config_Node(array(
'method' => $methodName,
'params' => array()
), $actionListNode);
$actionListNode[] = $actionNode;
if (isset($action->param)) {
$paramsNode = $actionNode->params;
foreach ($action->param as $param) {
$paramName = (string) $param['name'];
if (empty($paramName)) {
continue;
}
if (count($param)) {
if (isset($param->const) && isset($param->const['name']) && defined((string) $param->const['name'])) {
$paramsNode->$paramName = constant((string) $param->const['name']);
} else {
$paramArrayNode = new Wootook_Core_Config_Node(array(), $paramsNode);
$paramsNode->$paramName = $paramArrayNode;
$this->_parseArrayParam($param, $paramArrayNode);
}
} else {
$paramsNode->$paramName = (string) $param;
}
}
}
}
}
}
protected function _parseArrayParam(SimpleXMLElement $element, Wootook_Core_Config_Node $parentNode)
{
foreach ($element->children() as $child) {
if (count($child)) {
$childNode = new Wootook_Core_Config_Node(array(), $parentNode);
$parentNode->{$child->getName()} = $childNode;
$this->_parseArrayParam($child, $childNode);
continue;
}
$parentNode->{$child->getName()} = (string) $child;
}
}
}

View file

@ -0,0 +1,192 @@
<?php
/**
* This file is part of Wootook
*
* @license http://www.gnu.org/licenses/agpl-3.0.txt
* @see http://wootook.org/
*
* Copyright (c) 2011-Present, Grégory PLANCHAT <g.planchat@gmail.com>
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --> NOTICE <--
* This file is part of the core development branch, changing its contents will
* make you unable to use the automatic updates manager. Please refer to the
* documentation for further information about customizing Wootook.
*
*/
/**
*
* Enter description here ...
* @author Greg
*
*/
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, $e);
}
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,61 @@
<?php
/**
*
* Enter description here ...
*
* @uses Wootook_Object
* @uses Legacies_Empire
*/
class Wootook_Core_Model_Config
extends Wootook_Core_Entity_SubTable
{
protected $_eventPrefix = 'core.config';
protected $_eventObject = 'config';
protected function _init()
{
$this->_tableName = 'core_config';
$this->_idFieldNames = array('config_path', 'website_id', 'game_id');
}
public function setWebsiteId($websiteId)
{
return $this->setData('website_id', $websiteId);
}
public function getWebsiteId()
{
return $this->getData('website_id');
}
public function setGameId($gameId)
{
return $this->setData('game_id', $gameId);
}
public function getGameId()
{
return $this->getData('game_id');
}
public function setPath($path)
{
return $this->setData('config_path', $path);
}
public function getPath()
{
return $this->getData('config_path');
}
public function setValue($value)
{
return $this->setData('config_value', $value);
}
public function getValue()
{
return $this->getData('config_value');
}
}

View file

@ -0,0 +1,59 @@
<?php
abstract class Wootook_Core_Model_Config_Abstract
extends Wootook_Core_Model
implements Iterator, Countable
{
protected function _initData($filename)
{
$config = Wootook::getGameConfig('engine/storyline');
if ($config === null) {
$config = array(
'universe' => 'default',
'episode' => 'default'
);
} else {
$config = $config->toArray();
}
$path = 'gamedata' . DIRECTORY_SEPARATOR . $config['universe'] . DIRECTORY_SEPARATOR
. $config['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);
}
}

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