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;
110 const EXCEPTION_NOT_CONSTRUCTABLE = 0x02d;
113 * In the super constructor these system classes shall be ignored or else
114 * we would get an endless calling loop.
116 *--------------------------------------------------------------------*
117 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL SHOOT YOUR SERVER!!! *
118 *--------------------------------------------------------------------*
120 private $systemClasses = array(
121 "DebugMiddleware", // Debug middleware output sub-system
122 "DebugWebOutput", // Debug web output sub-system
123 "DebugConsoleOutput", // Debug console output sub-system
124 "DebugErrorLogOutput", // Debug error_log() output sub-system
125 "CompressorChannel", // Compressor sub-system
126 "FrameworkDirectoryPointer", // Directory handler sub-system
127 "NullCompressor", // Null compressor
128 "Bzip2Compressor", // BZIP2 compressor
129 "GzipCompressor", // GZIP compressor
130 "WebOutput", // Web output sub-system
134 * Private super constructor
138 private function __construct ($class) {
140 $this->setRealClass($class);
144 * Destructor reached...
148 public function __destruct() {
149 // Is this object already destroyed?
150 if ($this->__toString() != "DestructedObject") {
152 if ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
153 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wird zerstört.<br />\n",
154 __CLASS__, $this->__toString()
158 // Destroy all informations about this class but keep some text about it alive
159 $this->setPartDescr(sprintf("Entferntes Objekt <em>%s</em>", $this->__toString()));
160 $this->setRealClass("DestructedObject");
161 $this->resetUniqueID();
162 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
163 // Already destructed object
164 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wurde bereits zerstört.<br />\n",
165 __CLASS__, $this->__toString()
171 * The call method where all non-implemented methods end up
175 public final function __call ($methodName, $args) {
176 // Implode all given arguments
177 $argsString = implode("|", $args);
178 if (empty($argsString)) $argsString = "NULL";
180 $this->getDebugInstance()->output(sprintf("[%s::%s] Stub! Args: %s",
191 * Public constructor (for initializing things, etc.)
195 public function constructor ($class) {
197 $this->__construct($class);
199 // Get the current (singleton) configuration instance
200 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
202 // Is the class weather debug nor compressor channel?
203 if (!in_array($class, $this->systemClasses)) {
204 // Initialize debug instance
205 if (is_null($this->getDebugInstance())) {
206 // Set the debug output system if it is not debug class ;)
207 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig("debug_engine")));
210 // Initialize web instance
211 if (is_null($this->getWebOutputInstance())) {
212 // Generate the eval() command
213 $eval = sprintf("\$this->setWebOutputInstance(%s::create%s(\"%s\"));",
214 $this->getConfigInstance()->readConfig("web_engine"),
215 $this->getConfigInstance()->readConfig("web_engine"),
216 $this->getConfigInstance()->readConfig("web_content_type")
220 if ((defined('DEBUG_EVAL')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Konstruierte PHP-Anweisung: <pre><em>%s</em></pre><br />\n",
229 // Initialize compressor channel
230 if (is_null($this->getCompressorChannel())) {
231 // Set the compressor channel
232 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
234 $this->getConfigInstance()->readConfig("compressor_base_path")
238 // Initialize database middleware
239 if (is_null($this->getDatabaseInstance())) {
240 // Get the middleware instance
241 $db = DatabaseConnection::getInstance();
242 if (is_object($db)) {
243 // Set the database middleware
244 $this->setDatabaseInstance($db);
249 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Alle Sub-Systeme sind initialisiert.<br />\n",
256 * Setter for language instance
258 * @param $configInstance The configuration instance which shall
259 * be FrameworkConfiguration
262 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
263 $this->cfgInstance = $configInstance;
264 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konfigurations-Handler auf <strong>%s</strong> gesetzt.<br />\n",
266 $configInstance->__toString()
271 * Getter for configuration instance
273 * @return $cfhInstance - Configuration instance
275 public final function getConfigInstance () {
276 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konfigurations-Handler <strong>%s</strong> angefordert.<br />\n",
278 $this->cfgInstance->__toString()
280 return $this->cfgInstance;
284 * Setter for debug instance
286 * @param $debugInstance The instance for debug output class
289 public final function setDebugInstance (DebugMiddleware $debugInstance) {
290 self::$debug = $debugInstance;
291 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Debug-Handler auf <strong>%s</strong> gesetzt.<br />\n",
293 $this->getDebugInstance()->__toString()
298 * Getter for debug instance
300 * @return $debug - Instance to class DebugConsoleOutput or DebugWebOutput
302 public final function getDebugInstance () {
307 * Setter for web output instance
309 * @param $webInstance The instance for web output class
312 public final function setWebOutputInstance (OutputStreamer $webInstance) {
313 self::$webOutput = $webInstance;
314 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Web-Handler auf <strong>%s</strong> gesetzt.<br />\n",
316 $this->getWebOutputInstance()->__toString()
321 * Getter for web output instance
323 * @return $webOutput - Instance to class WebOutput
325 public final function getWebOutputInstance () {
326 return self::$webOutput;
330 * Static setter for database instance
332 * @param $dbInstance The instance for the database connection
333 * (forced DatabaseConnection)
336 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
337 if ((defined('DEBUG_SYSTEM')) && (is_object($dbInstance->getDebugInstance()))) $dbInstance->getDebugInstance()->output(sprintf("[%s:] Datenbankschicht gesetzt.<br />\n",
338 $dbInstance->__toString()
340 $this->dbInstance = $dbInstance;
344 * Getter for $realClass
346 * @return $realClass The name of the real class (not BaseFrameworkSystem)
348 public final function __toString () {
349 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] __toString() erreicht.<br />\n",
352 return $this->realClass;
356 * Setter for the real class name
358 * @param $realClass Class name (string)
361 public final function setRealClass ($realClass) {
363 $realClass = (string) $realClass;
366 $this->realClass = $realClass;
370 * Generate unique ID from a lot entropy
374 public final function createUniqueID () {
375 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] createUniqueID aufgerufen.<br />\n",
379 // Existiert noch keine?
380 if (empty($this->uniqueID)) {
381 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] createUniqueID erzeugt neue Unique-ID.<br />\n",
385 // Correct missing class name
387 if ($this->__toString() == "") {
388 $this->setRealClass(__CLASS__);
395 // Generate a unique ID number
396 $tempID = $this->generateIdNumber();
399 // Try to figure out if the ID number is not yet used
401 if (is_object($this->getDatabaseInstance())) {
402 $isUsed = $this->getDatabaseInstance()->isUniqueIdUsed($tempID, true);
404 } catch (FrameworkException $e) {
405 // Catches all and ignores all ;-)
413 $this->getDatabaseInstance() === null
416 is_object($this->getDatabaseInstance())
429 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] uniqueID ist auf <strong>%s</strong> gesetzt.<br />\n",
435 $this->setUniqueID($tempID);
437 // Revert maybe corrected class name
439 $this->setRealClass("");
442 // Remove system classes if we are in a system class
443 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
444 // This may save some RAM...
445 $this->removeSystemArray();
451 * Generates a new ID number for classes based from the class' real name,
452 * the description and some random data
454 * @return $tempID The new (temporary) ID number
456 private final function generateIdNumber () {
457 return sprintf("%s@%s",
459 md5(sprintf("%s:%s:%s:%s:%s:%s",
461 $this->getPartDescr(),
463 getenv('REMOTE_ADDR'),
464 getenv('SERVER_ADDR'),
471 * Setter for unique ID
473 * @param $uniqueID The newly generated unique ID number
476 private final function setUniqueID ($uniqueID) {
478 $uniqueID = (string) $uniqueID;
481 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID gesetzt auf <u>%s</u>.<br />\n",
487 $this->uniqueID = $uniqueID;
491 * Getter for unique ID
493 * @return $uniqueID The unique ID of this class
495 public final function getUniqueID () {
496 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID angefordert.<br />\n",
499 return $this->uniqueID;
503 * Resets or recreates the unique ID number
507 public final function resetUniqueID() {
508 // Sweet and simple... ;-)
509 $newUniqueID = $this->generateIdNumber();
510 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID zurückgesetzt auf <u>%s</u>.<br />\n",
514 $this->setUniqueID($newUniqueID);
518 * Getter for simulator description
520 * @return $partDescr The description of this simulation part
522 public final function getPartDescr () {
523 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] getPartDescr erreicht.<br />\n",
526 if (isset($this->partDescr)) {
527 return $this->partDescr;
534 * Setter for simulation part description
536 * @param $partDescr The description as string for this simulation part
539 public final function setPartDescr ($partDescr) {
540 $this->partDescr = (String) $partDescr;
541 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Teilbeschreibung wird auf <strong>%s</strong> gesetzt.<br />\n",
548 * Validate if given object is the same as current
550 * @param $object An object instance for comparison with this class
551 * @return boolean The result of comparing both's unique ID
553 public final function equals ($object) {
554 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Ist <strong>%s</strong>=<strong>%s</strong>?<br />\n",
557 $object->__toString()
559 return ($this->getUniqueID() == $object->getUniqueID());
563 * Compare if both simulation part description and class name matches
566 * @param $itemInstance An object instance to an other class
567 * @return boolean The result of comparing class name simulation part description
569 public function itemMatches ($itemInstance) {
571 ($this->__toString() == $itemInstance->__toString())
572 && ($this->getPartDescr() == $itemInstance->getPartDescr())
577 * Compare class name of this and given class name
579 * @param $class The class name as string from the other class
580 * @return boolean The result of comparing both class names
582 public final function isClass ($class) {
583 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%s</strong>=<strong>%s</strong>?<br />\n",
588 return ($this->__toString() == $class);
592 * Stub method (only real cabins shall override it)
594 * @return boolean false = is no cabin, true = is a cabin
596 public function isCabin () {
601 * Stub method for tradeable objects
603 * @return boolean false = is not tradeable by the Merchant class,
604 * true = is a tradeable object
606 public function isTradeable () {
611 * Formats computer generated price values into human-understandable formats
612 * with thousand and decimal seperators.
614 * @param $value The in computer format value for a price
615 * @param $currency The currency symbol (use HTML-valid characters!)
616 * @param $decNum Number of decimals after commata
617 * @return $price The for the current language formated price string
618 * @throws MissingDecimalsThousandsSeperatorException If decimals or
619 * thousands seperator
622 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
623 // Are all required attriutes set?
624 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
625 // Throw an exception
626 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
630 $value = (float) $value;
631 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%d</strong> wird umformatiert.<br />\n",
636 // Reformat the US number
637 $price = sprintf("%s %s",
638 number_format($value, $decNum, $this->decimals, $this->thousands),
642 // Return as string...
647 * Removes number formating characters
651 public final function removeNumberFormaters () {
652 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] Zahlenumformatierungszeichen werden entfernt.<br />\n",
655 unset($this->thousands);
656 unset($this->decimals);
660 * Getter for database layer
662 * @return $dbInstance The database layer instance
664 public final function getDatabaseInstance () {
665 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] Datenbank-Instanz <u>%s</u> angefordert.<br />\n",
669 return $this->dbInstance;
673 * Setter for compressor channel
675 * @param $compressorChannel An instance of CompressorChannel
678 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
679 self::$compressor = $compressorChannel;
683 * Getter for compressor channel
685 * @return $compressor The compressor channel
687 public final function getCompressorChannel () {
688 return self::$compressor;
692 * Remove the $systemClasses array from memory
696 public final function removeSystemArray () {
697 unset($this->systemClasses);
701 * Create a file name and path name from the object's unique ID number.
702 * The left part of the ID shall always be a valid class name and the
703 * right part an ID number.
705 * @return $pfn The file name with a prepended path name
706 * @throws NoArrayCreatedException If explode() fails to create an array
707 * @throws InvalidArrayCountException If the array contains less or
708 * more than two elements
710 public function getPathFileNameFromObject () {
711 // Get the main object's unique ID. We use this as a path/filename combination
712 $pathFile = $this->getUniqueID();
714 // Split it up in path and file name
715 $pathFile = explode("@", $pathFile);
717 // Are there two elements? Index 0 is the path, 1 the file name + global extension
718 if (!is_array($pathFile)) {
720 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
721 } elseif (count($pathFile) != 2) {
722 // Invalid ID returned!
723 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
726 // Auto-append missing trailing slash
727 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
729 // Create the file name and return it
730 $pfn = ($pathFile[0] . $pathFile[1]);
735 * Appends a trailing slash to a string
737 * @param $str A string (maybe) without trailing slash
738 * @return $str A string with an auto-appended trailing slash
740 public final function addMissingTrailingSlash ($str) {
741 // Is there a trailing slash?
742 if (substr($str, -1, 1) != "/") $str .= "/";