3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 * @author Roland Haeder <webmaster@ship-simu.org>
8 * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.mxchange.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
27 * The instance to the debug output handler (should be DebugConsoleOutput or DebugWebOutput)
29 * @see DebugConsoleOutput
32 private static $debug = null;
35 * The instance to the web output handler (should be WebOutput)
39 private static $webOutput = null;
42 * The instance to the compression layer which should be CompressorChannel
44 private static $compressor = null;
47 * The configuration instance which shall be FrameworkConfiguration
49 private static $cfgInstance = null;
52 * The instance to the database layer which should be DatabaseConnection
54 private $dbInstance = null;
59 private $realClass = "FrameworkSystem";
62 * A human-readable description for this simulator part
64 private $partDescr = "Namenlose Framework-Einheit";
67 * The unique ID string for identifying all type of classes
69 private $uniqueID = "";
74 private $thousands = "."; // German
79 private $decimals = ","; // German
81 /***********************
82 * Exception codes.... *
83 ***********************/
85 const EXCEPTION_IS_NULL_POINTER = 0x001;
86 const EXCEPTION_IS_NO_OBJECT = 0x002;
87 const EXCEPTION_IS_NO_ARRAY = 0x003;
88 const EXCEPTION_MISSING_METHOD = 0x004;
89 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
90 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
91 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
92 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
93 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
94 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
95 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
96 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
97 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
98 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
99 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
100 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
101 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
102 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
103 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
104 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
105 const EXCEPTION_PATH_NOT_FOUND = 0x015;
106 const EXCEPTION_INVALID_PATH_NAME = 0x016;
107 const EXCEPTION_READ_PROTECED_PATH = 0x017;
108 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
109 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
110 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
111 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
112 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
113 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
114 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
115 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
116 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
117 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
118 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
119 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
120 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
121 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
122 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
123 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
124 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
125 const EXCEPTION_INVALID_STRING = 0x029;
126 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
127 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
128 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
131 * In the super constructor these system classes shall be ignored or else
132 * we would get an endless calling loop.
134 *--------------------------------------------------------------------*
135 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL SHOOT YOUR SERVER!!! *
136 *--------------------------------------------------------------------*
138 private $systemClasses = array(
139 "DebugMiddleware", // Debug middleware output sub-system
140 "DebugWebOutput", // Debug web output sub-system
141 "DebugConsoleOutput", // Debug console output sub-system
142 "DebugErrorLogOutput", // Debug error_log() output sub-system
143 "CompressorChannel", // Compressor sub-system
144 "FrameworkDirectoryPointer", // Directory handler sub-system
145 "NullCompressor", // Null compressor
146 "Bzip2Compressor", // BZIP2 compressor
147 "GzipCompressor", // GZIP compressor
148 "WebOutput", // Web output sub-system
152 * Private super constructor
156 private function __construct ($class) {
158 $this->setRealClass($class);
162 * Destructor reached...
166 public function __destruct() {
167 // Is this object already destroyed?
168 if ($this->__toString() != "DestructedObject") {
170 if ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
171 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wird zerstört.<br />\n",
172 __CLASS__, $this->__toString()
176 // Destroy all informations about this class but keep some text about it alive
177 $this->setPartDescr(sprintf("Entferntes Objekt <em>%s</em>", $this->__toString()));
178 $this->setRealClass("DestructedObject");
179 $this->resetUniqueID();
180 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
181 // Already destructed object
182 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wurde bereits zerstört.<br />\n",
183 __CLASS__, $this->__toString()
189 * The call method where all non-implemented methods end up
193 public final function __call ($methodName, $args) {
194 // Implode all given arguments
195 $argsString = implode("|", $args);
196 if (empty($argsString)) $argsString = "NULL";
198 $this->getDebugInstance()->output(sprintf("[%s::%s] Stub! Args: %s",
209 * Public constructor (for initializing things, etc.)
213 public function constructor ($class) {
215 $this->__construct($class);
217 // Get the current (singleton) configuration instance
218 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
220 // Is the class weather debug nor compressor channel?
221 if (!in_array($class, $this->systemClasses)) {
222 // Initialize debug instance
223 if (is_null($this->getDebugInstance())) {
224 // Set the debug output system if it is not debug class ;)
225 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig("debug_engine")));
228 // Initialize web instance
229 if (is_null($this->getWebOutputInstance())) {
230 // Generate the eval() command
231 $eval = sprintf("\$this->setWebOutputInstance(%s::create%s(\"%s\"));",
232 $this->getConfigInstance()->readConfig("web_engine"),
233 $this->getConfigInstance()->readConfig("web_engine"),
234 $this->getConfigInstance()->readConfig("web_content_type")
238 if ((defined('DEBUG_EVAL')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:] Konstruierte PHP-Anweisung: <pre><em>%s</em></pre><br />\n",
247 // Initialize compressor channel
248 if (is_null($this->getCompressorChannel())) {
249 // Set the compressor channel
250 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
252 $this->getConfigInstance()->readConfig("compressor_base_path")
256 // Initialize database middleware
257 if (is_null($this->getDatabaseInstance())) {
258 // Get the middleware instance
259 $db = DatabaseConnection::getInstance();
260 if (is_object($db)) {
261 // Set the database middleware
262 $this->setDatabaseInstance($db);
267 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Alle Sub-Systeme sind initialisiert.<br />\n",
274 * Setter for language instance
276 * @param $configInstance The configuration instance which shall
277 * be FrameworkConfiguration
280 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
281 $this->cfgInstance = $configInstance;
282 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konfigurations-Handler auf <strong>%s</strong> gesetzt.<br />\n",
284 $configInstance->__toString()
289 * Getter for configuration instance
291 * @return $cfhInstance - Configuration instance
293 public final function getConfigInstance () {
294 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konfigurations-Handler <strong>%s</strong> angefordert.<br />\n",
296 $this->cfgInstance->__toString()
298 return $this->cfgInstance;
302 * Setter for debug instance
304 * @param $debugInstance The instance for debug output class
307 public final function setDebugInstance (DebugMiddleware $debugInstance) {
308 self::$debug = $debugInstance;
309 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Debug-Handler auf <strong>%s</strong> gesetzt.<br />\n",
311 $this->getDebugInstance()->__toString()
316 * Getter for debug instance
318 * @return $debug - Instance to class DebugConsoleOutput or DebugWebOutput
320 public final function getDebugInstance () {
325 * Setter for web output instance
327 * @param $webInstance The instance for web output class
330 public final function setWebOutputInstance (OutputStreamer $webInstance) {
331 self::$webOutput = $webInstance;
332 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Web-Handler auf <strong>%s</strong> gesetzt.<br />\n",
334 $this->getWebOutputInstance()->__toString()
339 * Getter for web output instance
341 * @return $webOutput - Instance to class WebOutput
343 public final function getWebOutputInstance () {
344 return self::$webOutput;
348 * Static setter for database instance
350 * @param $dbInstance The instance for the database connection
351 * (forced DatabaseConnection)
354 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
355 if ((defined('DEBUG_SYSTEM')) && (is_object($dbInstance->getDebugInstance()))) $dbInstance->getDebugInstance()->output(sprintf("[%s:] Datenbankschicht gesetzt.<br />\n",
356 $dbInstance->__toString()
358 $this->dbInstance = $dbInstance;
362 * Getter for $realClass
364 * @return $realClass The name of the real class (not BaseFrameworkSystem)
366 public final function __toString () {
367 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] __toString() erreicht.<br />\n",
370 return $this->realClass;
374 * Setter for the real class name
376 * @param $realClass Class name (string)
379 public final function setRealClass ($realClass) {
381 $realClass = (string) $realClass;
384 $this->realClass = $realClass;
388 * Generate unique ID from a lot entropy
392 public final function createUniqueID () {
393 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] createUniqueID aufgerufen.<br />\n",
397 // Existiert noch keine?
398 if (empty($this->uniqueID)) {
399 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] createUniqueID erzeugt neue Unique-ID.<br />\n",
403 // Correct missing class name
405 if ($this->__toString() == "") {
406 $this->setRealClass(__CLASS__);
413 // Generate a unique ID number
414 $tempID = $this->generateIdNumber();
417 // Try to figure out if the ID number is not yet used
419 if (is_object($this->getDatabaseInstance())) {
420 $isUsed = $this->getDatabaseInstance()->isUniqueIdUsed($tempID, true);
422 } catch (FrameworkException $e) {
423 // Catches all and ignores all ;-)
431 $this->getDatabaseInstance() === null
434 is_object($this->getDatabaseInstance())
447 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] uniqueID ist auf <strong>%s</strong> gesetzt.<br />\n",
453 $this->setUniqueID($tempID);
455 // Revert maybe corrected class name
457 $this->setRealClass("");
460 // Remove system classes if we are in a system class
461 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
462 // This may save some RAM...
463 $this->removeSystemArray();
469 * Generates a new ID number for classes based from the class' real name,
470 * the description and some random data
472 * @return $tempID The new (temporary) ID number
474 private final function generateIdNumber () {
475 return sprintf("%s@%s",
477 md5(sprintf("%s:%s:%s:%s:%s:%s",
479 $this->getPartDescr(),
481 getenv('REMOTE_ADDR'),
482 getenv('SERVER_ADDR'),
489 * Setter for unique ID
491 * @param $uniqueID The newly generated unique ID number
494 private final function setUniqueID ($uniqueID) {
496 $uniqueID = (string) $uniqueID;
499 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID gesetzt auf <u>%s</u>.<br />\n",
505 $this->uniqueID = $uniqueID;
509 * Getter for unique ID
511 * @return $uniqueID The unique ID of this class
513 public final function getUniqueID () {
514 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID angefordert.<br />\n",
517 return $this->uniqueID;
521 * Resets or recreates the unique ID number
525 public final function resetUniqueID() {
526 // Sweet and simple... ;-)
527 $newUniqueID = $this->generateIdNumber();
528 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Unique-ID zurückgesetzt auf <u>%s</u>.<br />\n",
532 $this->setUniqueID($newUniqueID);
536 * Getter for simulator description
538 * @return $partDescr The description of this simulation part
540 public final function getPartDescr () {
541 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] getPartDescr erreicht.<br />\n",
544 if (isset($this->partDescr)) {
545 return $this->partDescr;
552 * Setter for simulation part description
554 * @param $partDescr The description as string for this simulation part
557 public final function setPartDescr ($partDescr) {
558 $this->partDescr = (String) $partDescr;
559 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Teilbeschreibung wird auf <strong>%s</strong> gesetzt.<br />\n",
566 * Validate if given object is the same as current
568 * @param $object An object instance for comparison with this class
569 * @return boolean The result of comparing both's unique ID
571 public final function equals ($object) {
572 return ($this->getUniqueID() == $object->getUniqueID());
576 * Compare if both simulation part description and class name matches
579 * @param $itemInstance An object instance to an other class
580 * @return boolean The result of comparing class name simulation part description
582 public function itemMatches ($itemInstance) {
585 $this->__toString() == $itemInstance->__toString()
587 $this->getPartDescr() == $itemInstance->getPartDescr()
593 * Compare class name of this and given class name
595 * @param $class The class name as string from the other class
596 * @return boolean The result of comparing both class names
598 public final function isClass ($class) {
599 if ((defined('DEBUG_SYSTEM')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%s</strong>=<strong>%s</strong>?<br />\n",
604 return ($this->__toString() == $class);
608 * Stub method (only real cabins shall override it)
610 * @return boolean false = is no cabin, true = is a cabin
612 public function isCabin () {
617 * Stub method for tradeable objects
619 * @return boolean false = is not tradeable by the Merchant class,
620 * true = is a tradeable object
622 public function isTradeable () {
627 * Formats computer generated price values into human-understandable formats
628 * with thousand and decimal seperators.
630 * @param $value The in computer format value for a price
631 * @param $currency The currency symbol (use HTML-valid characters!)
632 * @param $decNum Number of decimals after commata
633 * @return $price The for the current language formated price string
634 * @throws MissingDecimalsThousandsSeperatorException If decimals or
635 * thousands seperator
638 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
639 // Are all required attriutes set?
640 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
641 // Throw an exception
642 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
646 $value = (float) $value;
647 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%d</strong> wird umformatiert.<br />\n",
652 // Reformat the US number
653 $price = sprintf("%s %s",
654 number_format($value, $decNum, $this->decimals, $this->thousands),
658 // Return as string...
663 * Removes number formating characters
667 public final function removeNumberFormaters () {
668 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] Zahlenumformatierungszeichen werden entfernt.<br />\n",
671 unset($this->thousands);
672 unset($this->decimals);
676 * Getter for database layer
678 * @return $dbInstance The database layer instance
680 public final function getDatabaseInstance () {
681 if (defined('DEBUG_CORE') && is_object($this->getDebugInstance())) $this->getDebugInstance()->output(sprintf("[%s:] Datenbank-Instanz <u>%s</u> angefordert.<br />\n",
685 return $this->dbInstance;
689 * Setter for compressor channel
691 * @param $compressorChannel An instance of CompressorChannel
694 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
695 self::$compressor = $compressorChannel;
699 * Getter for compressor channel
701 * @return $compressor The compressor channel
703 public final function getCompressorChannel () {
704 return self::$compressor;
708 * Remove the $systemClasses array from memory
712 public final function removeSystemArray () {
713 unset($this->systemClasses);
717 * Create a file name and path name from the object's unique ID number.
718 * The left part of the ID shall always be a valid class name and the
719 * right part an ID number.
721 * @return $pfn The file name with a prepended path name
722 * @throws NoArrayCreatedException If explode() fails to create an array
723 * @throws InvalidArrayCountException If the array contains less or
724 * more than two elements
726 public final function getPathFileNameFromObject () {
727 // Get the main object's unique ID. We use this as a path/filename combination
728 $pathFile = $this->getUniqueID();
730 // Split it up in path and file name
731 $pathFile = explode("@", $pathFile);
733 // Are there two elements? Index 0 is the path, 1 the file name + global extension
734 if (!is_array($pathFile)) {
736 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
737 } elseif (count($pathFile) != 2) {
738 // Invalid ID returned!
739 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
742 // Auto-append missing trailing slash
743 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
745 // Create the file name and return it
746 $pfn = ($pathFile[0] . $pathFile[1]);
751 * Appends a trailing slash to a string
753 * @param $str A string (maybe) without trailing slash
754 * @return $str A string with an auto-appended trailing slash
756 public final function addMissingTrailingSlash ($str) {
757 // Is there a trailing slash?
758 if (substr($str, -1, 1) != "/") $str .= "/";