3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
8 * The instance to the debug output handler (should be DebugConsoleOutput or DebugWebOutput)
10 * @see DebugConsoleOutput
13 private static $debug = null;
16 * The instance to the web output handler (should be WebOutput)
20 private static $webOutput = null;
23 * The instance to the compression layer which should be CompressorChannel
25 private static $compressor = null;
28 * The configuration instance which shall be FrameworkConfiguration
30 private static $cfgInstance = null;
33 * The instance to the database layer which should be DatabaseConnection
35 private $dbInstance = null;
40 private $realClass = "FrameworkSystem";
43 * A human-readable description for this simulator part
45 private $partDescr = "Namenlose Framework-Einheit";
48 * The unique ID string for identifying all type of classes
50 private $uniqueID = "";
55 private $thousands = "."; // German
60 private $decimals = ","; // German
62 /***********************
63 * Exception codes.... *
64 ***********************/
66 const EXCEPTION_IS_NULL_POINTER = 0x001;
67 const EXCEPTION_IS_NO_OBJECT = 0x002;
68 const EXCEPTION_IS_NO_ARRAY = 0x003;
69 const EXCEPTION_MISSING_METHOD = 0x004;
70 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
71 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
72 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
73 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
74 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
75 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
76 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
77 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
78 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
79 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
80 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
81 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
82 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
83 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
84 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
85 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
86 const EXCEPTION_PATH_NOT_FOUND = 0x015;
87 const EXCEPTION_INVALID_PATH_NAME = 0x016;
88 const EXCEPTION_READ_PROTECED_PATH = 0x017;
89 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
90 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
91 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
92 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
93 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
94 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
95 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
96 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
97 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
98 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
99 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
100 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
101 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
102 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
103 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
104 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
105 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
106 const EXCEPTION_INVALID_STRING = 0x029;
107 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
108 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
109 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
112 * In the super constructor these system classes shall be ignored or else
113 * we would get an endless calling loop.
115 *--------------------------------------------------------------------*
116 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL SHOOT YOUR SERVER!!! *
117 *--------------------------------------------------------------------*
119 private $systemClasses = array(
120 "DebugMiddleware", // Debug middleware output sub-system
121 "DebugWebOutput", // Debug web output sub-system
122 "DebugConsoleOutput", // Debug console output sub-system
123 "DebugErrorLogOutput", // Debug error_log() output sub-system
124 "CompressorChannel", // Compressor sub-system
125 "FrameworkDirectoryPointer", // Directory handler sub-system
126 "NullCompressor", // Null compressor
127 "Bzip2Compressor", // BZIP2 compressor
128 "GzipCompressor", // GZIP compressor
129 "WebOutput", // Web output sub-system
133 * Private super constructor
137 private function __construct ($class) {
139 $this->setRealClass($class);
143 * Destructor reached...
147 public function __destruct() {
148 // Is this object already destroyed?
149 if ($this->__toString() != "DestructedObject") {
151 if ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
152 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wird zerstört.<br />\n",
153 __CLASS__, $this->__toString()
157 // Destroy all informations about this class but keep some text about it alive
158 $this->setPartDescr(sprintf("Entferntes Objekt <em>%s</em>", $this->__toString()));
159 $this->setRealClass("DestructedObject");
160 $this->resetUniqueID();
161 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
162 // Already destructed object
163 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wurde bereits zerstört.<br />\n",
164 __CLASS__, $this->__toString()
170 * The call method where all non-implemented methods end up
174 public final function __call ($methodName, $args) {
175 // Implode all given arguments
176 $argsString = implode("|", $args);
177 if (empty($argsString)) $argsString = "NULL";
179 $this->getDebugInstance()->output(sprintf("[%s::%s] Stub! Args: %s",
190 * Public constructor (for initializing things, etc.)
194 public function constructor ($class) {
196 $this->__construct($class);
198 // Get the current (singleton) configuration instance
199 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
201 // Is the class weather debug nor compressor channel?
202 if (!in_array($class, $this->systemClasses)) {
203 // Initialize debug instance
204 if (is_null($this->getDebugInstance())) {
205 // Set the debug output system if it is not debug class ;)
206 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig("debug_engine")));
209 // Initialize web instance
210 if (is_null($this->getWebOutputInstance())) {
211 // Generate the eval() command
212 $eval = sprintf("\$this->setWebOutputInstance(%s::create%s(\"%s\"));",
213 $this->getConfigInstance()->readConfig("web_engine"),
214 $this->getConfigInstance()->readConfig("web_engine"),
215 $this->getConfigInstance()->readConfig("web_content_type")
219 if ((defined('DEBUG_EVAL')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Konstruierte PHP-Anweisung: <pre><em>%s</em></pre><br />\n",
228 // Initialize compressor channel
229 if (is_null($this->getCompressorChannel())) {
230 // Set the compressor channel
231 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
233 $this->getConfigInstance()->readConfig("compressor_base_path")
237 // Initialize database middleware
238 if (is_null($this->getDatabaseInstance())) {
239 // Get the middleware instance
240 $db = DatabaseConnection::getInstance();
241 if (is_object($db)) {
242 // Set the database middleware
243 $this->setDatabaseInstance($db);
248 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Alle Sub-Systeme sind initialisiert.<br />\n",
255 * Setter for language instance
257 * @param $configInstance The configuration instance which shall
258 * be FrameworkConfiguration
261 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
262 $this->cfgInstance = $configInstance;
263 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konfigurations-Handler auf <strong>%s</strong> gesetzt.<br />\n",
265 $configInstance->__toString()
270 * Getter for configuration instance
272 * @return $cfhInstance - Configuration instance
274 public final function getConfigInstance () {
275 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konfigurations-Handler <strong>%s</strong> angefordert.<br />\n",
277 $this->cfgInstance->__toString()
279 return $this->cfgInstance;
283 * Setter for debug instance
285 * @param $debugInstance The instance for debug output class
288 public final function setDebugInstance (DebugMiddleware $debugInstance) {
289 self::$debug = $debugInstance;
290 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Debug-Handler auf <strong>%s</strong> gesetzt.<br />\n",
292 $this->getDebugInstance()->__toString()
297 * Getter for debug instance
299 * @return $debug - Instance to class DebugConsoleOutput or DebugWebOutput
301 public final function getDebugInstance () {
306 * Setter for web output instance
308 * @param $webInstance The instance for web output class
311 public final function setWebOutputInstance (OutputStreamer $webInstance) {
312 self::$webOutput = $webInstance;
313 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Web-Handler auf <strong>%s</strong> gesetzt.<br />\n",
315 $this->getWebOutputInstance()->__toString()
320 * Getter for web output instance
322 * @return $webOutput - Instance to class WebOutput
324 public final function getWebOutputInstance () {
325 return self::$webOutput;
329 * Static setter for database instance
331 * @param $dbInstance The instance for the database connection
332 * (forced DatabaseConnection)
335 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
336 if ((defined('DEBUG_SYSTEM')) && (is_object($dbInstance->getDebugInstance()))) $dbInstance->getDebugInstance()->output(sprintf("[%s:] Datenbankschicht gesetzt.<br />\n",
337 $dbInstance->__toString()
339 $this->dbInstance = $dbInstance;
343 * Getter for $realClass
345 * @return $realClass The name of the real class (not BaseFrameworkSystem)
347 public final function __toString () {
348 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] __toString() erreicht.<br />\n",
351 return $this->realClass;
355 * Setter for the real class name
357 * @param $realClass Class name (string)
360 public final function setRealClass ($realClass) {
362 $realClass = (string) $realClass;
365 $this->realClass = $realClass;
369 * Generate unique ID from a lot entropy
373 public final function createUniqueID () {
374 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] createUniqueID aufgerufen.<br />\n",
378 // Existiert noch keine?
379 if (empty($this->uniqueID)) {
380 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] createUniqueID erzeugt neue Unique-ID.<br />\n",
384 // Correct missing class name
386 if ($this->__toString() == "") {
387 $this->setRealClass(__CLASS__);
394 // Generate a unique ID number
395 $tempID = $this->generateIdNumber();
398 // Try to figure out if the ID number is not yet used
400 if (is_object($this->getDatabaseInstance())) {
401 $isUsed = $this->getDatabaseInstance()->isUniqueIdUsed($tempID, true);
403 } catch (FrameworkException $e) {
404 // Catches all and ignores all ;-)
412 $this->getDatabaseInstance() === null
415 is_object($this->getDatabaseInstance())
428 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] uniqueID ist auf <strong>%s</strong> gesetzt.<br />\n",
434 $this->setUniqueID($tempID);
436 // Revert maybe corrected class name
438 $this->setRealClass("");
441 // Remove system classes if we are in a system class
442 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
443 // This may save some RAM...
444 $this->removeSystemArray();
450 * Generates a new ID number for classes based from the class' real name,
451 * the description and some random data
453 * @return $tempID The new (temporary) ID number
455 private final function generateIdNumber () {
456 return sprintf("%s@%s",
458 md5(sprintf("%s:%s:%s:%s:%s:%s",
460 $this->getPartDescr(),
462 getenv('REMOTE_ADDR'),
463 getenv('SERVER_ADDR'),
470 * Setter for unique ID
472 * @param $uniqueID The newly generated unique ID number
475 private final function setUniqueID ($uniqueID) {
477 $uniqueID = (string) $uniqueID;
480 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID gesetzt auf <u>%s</u>.<br />\n",
486 $this->uniqueID = $uniqueID;
490 * Getter for unique ID
492 * @return $uniqueID The unique ID of this class
494 public final function getUniqueID () {
495 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID angefordert.<br />\n",
498 return $this->uniqueID;
502 * Resets or recreates the unique ID number
506 public final function resetUniqueID() {
507 // Sweet and simple... ;-)
508 $newUniqueID = $this->generateIdNumber();
509 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID zurückgesetzt auf <u>%s</u>.<br />\n",
513 $this->setUniqueID($newUniqueID);
517 * Getter for simulator description
519 * @return $partDescr The description of this simulation part
521 public final function getPartDescr () {
522 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] getPartDescr erreicht.<br />\n",
525 if (isset($this->partDescr)) {
526 return $this->partDescr;
533 * Setter for simulation part description
535 * @param $partDescr The description as string for this simulation part
538 public final function setPartDescr ($partDescr) {
539 $this->partDescr = (String) $partDescr;
540 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Teilbeschreibung wird auf <strong>%s</strong> gesetzt.<br />\n",
547 * Validate if given object is the same as current
549 * @param $object An object instance for comparison with this class
550 * @return boolean The result of comparing both's unique ID
552 public final function equals ($object) {
553 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Ist <strong>%s</strong>=<strong>%s</strong>?<br />\n",
556 $object->__toString()
558 return ($this->getUniqueID() == $object->getUniqueID());
562 * Compare if both simulation part description and class name matches
565 * @param $itemInstance An object instance to an other class
566 * @return boolean The result of comparing class name simulation part description
568 public function itemMatches ($itemInstance) {
570 ($this->__toString() == $itemInstance->__toString())
571 && ($this->getPartDescr() == $itemInstance->getPartDescr())
576 * Compare class name of this and given class name
578 * @param $class The class name as string from the other class
579 * @return boolean The result of comparing both class names
581 public final function isClass ($class) {
582 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%s</strong>=<strong>%s</strong>?<br />\n",
587 return ($this->__toString() == $class);
591 * Stub method (only real cabins shall override it)
593 * @return boolean false = is no cabin, true = is a cabin
595 public function isCabin () {
600 * Stub method for tradeable objects
602 * @return boolean false = is not tradeable by the Merchant class,
603 * true = is a tradeable object
605 public function isTradeable () {
610 * Formats computer generated price values into human-understandable formats
611 * with thousand and decimal seperators.
613 * @param $value The in computer format value for a price
614 * @param $currency The currency symbol (use HTML-valid characters!)
615 * @param $decNum Number of decimals after commata
616 * @return $price The for the current language formated price string
617 * @throws MissingDecimalsThousandsSeperatorException If decimals or
618 * thousands seperator
621 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
622 // Are all required attriutes set?
623 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
624 // Throw an exception
625 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
629 $value = (float) $value;
630 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%d</strong> wird umformatiert.<br />\n",
635 // Reformat the US number
636 $price = sprintf("%s %s",
637 number_format($value, $decNum, $this->decimals, $this->thousands),
641 // Return as string...
646 * Removes number formating characters
650 public final function removeNumberFormaters () {
651 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] Zahlenumformatierungszeichen werden entfernt.<br />\n",
654 unset($this->thousands);
655 unset($this->decimals);
659 * Getter for database layer
661 * @return $dbInstance The database layer instance
663 public final function getDatabaseInstance () {
664 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] Datenbank-Instanz <u>%s</u> angefordert.<br />\n",
668 return $this->dbInstance;
672 * Setter for compressor channel
674 * @param $compressorChannel An instance of CompressorChannel
677 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
678 self::$compressor = $compressorChannel;
682 * Getter for compressor channel
684 * @return $compressor The compressor channel
686 public final function getCompressorChannel () {
687 return self::$compressor;
691 * Remove the $systemClasses array from memory
695 public final function removeSystemArray () {
696 unset($this->systemClasses);
700 * Create a file name and path name from the object's unique ID number.
701 * The left part of the ID shall always be a valid class name and the
702 * right part an ID number.
704 * @return $pfn The file name with a prepended path name
705 * @throws NoArrayCreatedException If explode() fails to create an array
706 * @throws InvalidArrayCountException If the array contains less or
707 * more than two elements
709 public function getPathFileNameFromObject () {
710 // Get the main object's unique ID. We use this as a path/filename combination
711 $pathFile = $this->getUniqueID();
713 // Split it up in path and file name
714 $pathFile = explode("@", $pathFile);
716 // Are there two elements? Index 0 is the path, 1 the file name + global extension
717 if (!is_array($pathFile)) {
719 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
720 } elseif (count($pathFile) != 2) {
721 // Invalid ID returned!
722 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
725 // Auto-append missing trailing slash
726 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
728 // Create the file name and return it
729 $pfn = ($pathFile[0] . $pathFile[1]);
734 * Appends a trailing slash to a string
736 * @param $str A string (maybe) without trailing slash
737 * @return $str A string with an auto-appended trailing slash
739 public final function addMissingTrailingSlash ($str) {
740 // Is there a trailing slash?
741 if (substr($str, -1, 1) != "/") $str .= "/";