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.ship-simu.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;
57 * Instance to an application helper class
59 private $applicationInstance = null;
64 private $realClass = "FrameworkSystem";
67 * A human-readable description for this simulator part
69 private $objectDescription = "Namenlose Framework-Einheit";
72 * The unique ID string for identifying all type of classes
74 private $uniqueID = "";
79 private $thousands = "."; // German
84 private $decimals = ","; // German
87 * The language instance for the template loader
89 private $langInstance = null;
92 * The file I/O instance for the template loader
94 private $fileIOInstance = null;
96 /***********************
97 * Exception codes.... *
98 ***********************/
100 const EXCEPTION_IS_NULL_POINTER = 0x001;
101 const EXCEPTION_IS_NO_OBJECT = 0x002;
102 const EXCEPTION_IS_NO_ARRAY = 0x003;
103 const EXCEPTION_MISSING_METHOD = 0x004;
104 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
105 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
106 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
107 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
108 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
109 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
110 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
111 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
112 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
113 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
114 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
115 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
116 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
117 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
118 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
119 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
120 const EXCEPTION_PATH_NOT_FOUND = 0x015;
121 const EXCEPTION_INVALID_PATH_NAME = 0x016;
122 const EXCEPTION_READ_PROTECED_PATH = 0x017;
123 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
124 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
125 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
126 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
127 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
128 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
129 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
130 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
131 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
132 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
133 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
134 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
135 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
136 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
137 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
138 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
139 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
140 const EXCEPTION_INVALID_STRING = 0x029;
141 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
142 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
143 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
144 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
145 const EXCEPTION_MISSING_LANGUAGE_HANDLER = 0x02e;
146 const EXCEPTION_MISSING_FILE_IO_HANDLER = 0x02f;
147 const EXCEPTION_MISSING_ELEMENT = 0x030;
148 const EXCEPTION_INVALID_COMMAND = 0x031;
149 const EXCEPTION_INVALID_CONTROLLER = 0x032;
150 const EXCEPTION_HEADERS_ALREADY_SENT = 0x033;
151 const EXCEPTION_DEFAUL_CONTROLLER_GONE = 0x034;
152 const EXCEPTION_CLASS_NOT_FOUND = 0x035;
155 * In the super constructor these system classes shall be ignored or else
156 * we would get an endless calling loop.
158 *--------------------------------------------------------------------*
159 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL SHOOT YOUR SERVER!!! *
160 *--------------------------------------------------------------------*
162 private $systemClasses = array(
163 "DebugMiddleware", // Debug middleware output sub-system
164 "DebugWebOutput", // Debug web output sub-system
165 "DebugConsoleOutput", // Debug console output sub-system
166 "DebugErrorLogOutput", // Debug error_log() output sub-system
167 "CompressorChannel", // Compressor sub-system
168 "FrameworkDirectoryPointer", // Directory handler sub-system
169 "NullCompressor", // Null compressor
170 "Bzip2Compressor", // BZIP2 compressor
171 "GzipCompressor", // GZIP compressor
172 "WebOutput", // Web output sub-system
176 * Private super constructor
180 protected function __construct ($class) {
182 $this->setRealClass($class);
184 // Init this instance
185 $this->initInstance($class);
189 * Destructor reached...
193 public function __destruct() {
194 // Is this object already destroyed?
195 if ($this->__toString() != "DestructedObject") {
197 if ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
198 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wird zerstört.<br />\n",
199 __CLASS__, $this->__toString()
203 // Destroy all informations about this class but keep some text about it alive
204 $this->setObjectDescription(sprintf("Entferntes Objekt <em>%s</em>", $this->__toString()));
205 $this->setRealClass("DestructedObject");
206 $this->resetUniqueID();
207 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
208 // Already destructed object
209 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wurde bereits zerstört.<br />\n",
210 __CLASS__, $this->__toString()
216 * The call method where all non-implemented methods end up
220 public final function __call ($methodName, $args) {
221 // Implode all given arguments
222 $argsString = implode("|", $args);
223 if (empty($argsString)) $argsString = "NULL";
225 $this->getDebugInstance()->output(sprintf("[%s::%s] Stub! Args: %s",
236 * Initializes the instance
240 public function initInstance ($class) {
241 // Get the current (singleton) configuration instance
242 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
244 // Is the class weather debug nor compressor channel?
245 if (!in_array($class, $this->systemClasses)) {
246 // Initialize debug instance
247 if (is_null($this->getDebugInstance())) {
248 // Set the debug output system if it is not debug class ;)
249 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig("debug_engine")));
252 // Initialize web instance
253 if (is_null($this->getWebOutputInstance())) {
254 // Generate the eval() command
255 $eval = sprintf("\$this->setWebOutputInstance(%s::create%s(\"%s\"));",
256 $this->getConfigInstance()->readConfig("web_engine"),
257 $this->getConfigInstance()->readConfig("web_engine"),
258 $this->getConfigInstance()->readConfig("web_content_type")
262 if (defined('DEBUG_EVAL')) $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
271 // Initialize compressor channel
272 if (is_null($this->getCompressorChannel())) {
273 // Set the compressor channel
274 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
276 $this->getConfigInstance()->readConfig("compressor_base_path")
280 // Initialize database middleware
281 if (is_null($this->getDatabaseInstance())) {
282 // Get the middleware instance
283 $db = DatabaseConnection::getInstance();
284 if (is_object($db)) {
285 // Set the database middleware
286 $this->setDatabaseInstance($db);
293 * Setter for language instance
295 * @param $configInstance The configuration instance which shall
296 * be FrameworkConfiguration
299 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
300 self::$cfgInstance = $configInstance;
304 * Getter for configuration instance
306 * @return $cfhInstance - Configuration instance
308 protected final function getConfigInstance () {
309 return self::$cfgInstance;
313 * Setter for debug instance
315 * @param $debugInstance The instance for debug output class
318 public final function setDebugInstance (DebugMiddleware $debugInstance) {
319 self::$debug = $debugInstance;
323 * Getter for debug instance
325 * @return $debug - Instance to class DebugConsoleOutput or DebugWebOutput
327 public final function getDebugInstance () {
332 * Setter for web output instance
334 * @param $webInstance The instance for web output class
337 public final function setWebOutputInstance (OutputStreamer $webInstance) {
338 self::$webOutput = $webInstance;
342 * Getter for web output instance
344 * @return $webOutput - Instance to class WebOutput
346 public final function getWebOutputInstance () {
347 return self::$webOutput;
351 * Static setter for database instance
353 * @param $dbInstance The instance for the database connection
354 * (forced DatabaseConnection)
357 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
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 return $this->realClass;
371 * Setter for the real class name
373 * @param $realClass Class name (string)
376 public final function setRealClass ($realClass) {
378 $realClass = (string) $realClass;
381 $this->realClass = $realClass;
385 * Generate unique ID from a lot entropy
389 public final function createUniqueID () {
390 // Existiert noch keine?
391 if (empty($this->uniqueID)) {
393 // Correct missing class name
395 if ($this->__toString() == "") {
396 $this->setRealClass(__CLASS__);
403 // Generate a unique ID number
404 $tempID = $this->generateIdNumber();
407 // Try to figure out if the ID number is not yet used
409 if (is_object($this->getDatabaseInstance())) {
410 $isUsed = $this->getDatabaseInstance()->isUniqueIdUsed($tempID, true);
412 } catch (FrameworkException $e) {
413 // Catches all and ignores all ;-)
421 $this->getDatabaseInstance() === null
424 is_object($this->getDatabaseInstance())
437 $this->setUniqueID($tempID);
439 // Revert maybe corrected class name
441 $this->setRealClass("");
444 // Remove system classes if we are in a system class
445 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
446 // This may save some RAM...
447 $this->removeSystemArray();
453 * Generates a new ID number for classes based from the class' real name,
454 * the description and some random data
456 * @return $tempID The new (temporary) ID number
458 private final function generateIdNumber () {
459 return sprintf("%s@%s",
461 md5(sprintf("%s:%s:%s:%s:%s:%s",
463 $this->getObjectDescription(),
465 getenv('REMOTE_ADDR'),
466 getenv('SERVER_ADDR'),
473 * Setter for unique ID
475 * @param $uniqueID The newly generated unique ID number
478 private final function setUniqueID ($uniqueID) {
480 $uniqueID = (string) $uniqueID;
483 $this->uniqueID = $uniqueID;
487 * Getter for unique ID
489 * @return $uniqueID The unique ID of this class
491 public final function getUniqueID () {
492 return $this->uniqueID;
496 * Resets or recreates the unique ID number
500 public final function resetUniqueID() {
501 // Sweet and simple... ;-)
502 $newUniqueID = $this->generateIdNumber();
503 $this->setUniqueID($newUniqueID);
507 * Getter for simulator description
509 * @return $objectDescription The description of this simulation part
511 public final function getObjectDescription () {
512 if (isset($this->objectDescription)) {
513 return $this->objectDescription;
520 * Setter for simulation part description
522 * @param $objectDescription The description as string for this simulation part
525 public final function setObjectDescription ($objectDescription) {
526 $this->objectDescription = (String) $objectDescription;
530 * Validate if given object is the same as current
532 * @param $object An object instance for comparison with this class
533 * @return boolean The result of comparing both's unique ID
535 public final function equals ($object) {
536 return ($this->getUniqueID() == $object->getUniqueID());
540 * Compare if both simulation part description and class name matches
543 * @param $itemInstance An object instance to an other class
544 * @return boolean The result of comparing class name simulation part description
546 public function itemMatches ($itemInstance) {
549 $this->__toString() == $itemInstance->__toString()
551 $this->getObjectDescription() == $itemInstance->getObjectDescription()
557 * Compare class name of this and given class name
559 * @param $class The class name as string from the other class
560 * @return boolean The result of comparing both class names
562 public final function isClass ($class) {
563 return ($this->__toString() == $class);
567 * Stub method (only real cabins shall override it)
569 * @return boolean false = is no cabin, true = is a cabin
571 public function isCabin () {
576 * Stub method for tradeable objects
578 * @return boolean false = is not tradeable by the Merchant class,
579 * true = is a tradeable object
581 public function isTradeable () {
586 * Formats computer generated price values into human-understandable formats
587 * with thousand and decimal seperators.
589 * @param $value The in computer format value for a price
590 * @param $currency The currency symbol (use HTML-valid characters!)
591 * @param $decNum Number of decimals after commata
592 * @return $price The for the current language formated price string
593 * @throws MissingDecimalsThousandsSeperatorException If decimals or
594 * thousands seperator
597 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
598 // Are all required attriutes set?
599 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
600 // Throw an exception
601 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
605 $value = (float) $value;
607 // Reformat the US number
608 $price = sprintf("%s %s",
609 number_format($value, $decNum, $this->decimals, $this->thousands),
613 // Return as string...
618 * Removes number formating characters
622 public final function removeNumberFormaters () {
623 unset($this->thousands);
624 unset($this->decimals);
628 * Getter for database layer
630 * @return $dbInstance The database layer instance
632 public final function getDatabaseInstance () {
633 return $this->dbInstance;
637 * Setter for compressor channel
639 * @param $compressorChannel An instance of CompressorChannel
642 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
643 self::$compressor = $compressorChannel;
647 * Getter for compressor channel
649 * @return $compressor The compressor channel
651 public final function getCompressorChannel () {
652 return self::$compressor;
656 * Remove the $systemClasses array from memory
660 public final function removeSystemArray () {
661 unset($this->systemClasses);
665 * Create a file name and path name from the object's unique ID number.
666 * The left part of the ID shall always be a valid class name and the
667 * right part an ID number.
669 * @return $pfn The file name with a prepended path name
670 * @throws NoArrayCreatedException If explode() fails to create an array
671 * @throws InvalidArrayCountException If the array contains less or
672 * more than two elements
674 public final function getPathFileNameFromObject () {
675 // Get the main object's unique ID. We use this as a path/filename combination
676 $pathFile = $this->getUniqueID();
678 // Split it up in path and file name
679 $pathFile = explode("@", $pathFile);
681 // Are there two elements? Index 0 is the path, 1 the file name + global extension
682 if (!is_array($pathFile)) {
684 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
685 } elseif (count($pathFile) != 2) {
686 // Invalid ID returned!
687 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
690 // Auto-append missing trailing slash
691 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
693 // Create the file name and return it
694 $pfn = ($pathFile[0] . $pathFile[1]);
699 * Appends a trailing slash to a string
701 * @param $str A string (maybe) without trailing slash
702 * @return $str A string with an auto-appended trailing slash
704 public final function addMissingTrailingSlash ($str) {
705 // Is there a trailing slash?
706 if (substr($str, -1, 1) != "/") $str .= "/";
711 * Private getter for language instance
713 * @return $langInstance An instance to the language sub-system
715 protected final function getLanguageInstance () {
716 return $this->langInstance;
720 * Setter for language instance
722 * @param $langInstance An instance to the language sub-system
724 * @see LanguageSystem
726 public final function setLanguageInstance (ManageableLanguage $langInstance) {
727 $this->langInstance = $langInstance;
731 * Private getter for file IO instance
733 * @return $fileIOInstance An instance to the file I/O sub-system
735 protected final function getFileIOInstance () {
736 return $this->fileIOInstance;
740 * Setter for file I/O instance
742 * @param $fileIOInstance An instance to the file I/O sub-system
745 public final function setFileIOInstance (FileIOHandler $fileIOInstance) {
746 $this->fileIOInstance = $fileIOInstance;
750 * Protected getter for a manageable application helper class
752 * @return $applicationInstance An instance of a manageable application helper class
754 protected final function getApplicationInstance () {
755 return $this->applicationInstance;
759 * Setter for a manageable application helper class
761 * @param $applicationInstance An instance of a manageable application helper class
764 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
765 $this->applicationInstance = $applicationInstance;
769 * Prepare the template engine (TemplateEngine by default) for a given
770 * application helper instance (ApplicationHelper by default).
772 * @param $appInstance An application helper instance or
773 * null if we shall use the default
774 * @return $tplEngine The template engine instance
775 * @throws NullPointerException If the template engine could not
777 * @throws UnsupportedTemplateEngineException If $tplEngine is an
778 * unsupported template engine
779 * @throws MissingLanguageHandlerException If the language sub-system
780 * is not yet initialized
781 * @throws NullPointerException If the discovered application
782 * instance is still null
784 protected function prepareTemplateEngine (BaseFrameworkSystem $appInstance=null) {
785 // Is the application instance set?
786 if (is_null($appInstance)) {
787 // Get the current instance
788 $appInstance = $this->getApplicationInstance();
791 if (is_null($appInstance)) {
792 // Thrown an exception
793 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
797 // Generate FQFN for all application templates
798 $fqfn = sprintf("%s%s/%s/%s",
800 $this->getConfigInstance()->readConfig("application_path"),
801 strtolower($appInstance->getAppShortName()),
802 $this->getConfigInstance()->readConfig("tpl_base_path")
805 // Are both instances set?
806 if ($appInstance->getLanguageInstance() === null) {
807 // Invalid language instance
808 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
809 } elseif ($appInstance->getFileIOInstance() === null) {
810 // Invalid language instance
811 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
814 // Initialize the template engine
816 $eval = sprintf("\$tplEngine = %s::create%s(
818 \$appInstance->getLanguageInstance(),
819 \$appInstance->getFileIOInstance()
821 $this->getConfigInstance()->readConfig("tpl_engine"),
822 $this->getConfigInstance()->readConfig("tpl_engine"),
827 if ((!is_null($this->getDebugInstance())) && (defined('DEBUG_EVAL'))) {
828 $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
837 // Is it a valid instance?
838 if (is_null($tplEngine)) {
840 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
841 } elseif (!$tplEngine instanceof CompileableTemplate) {
842 // Not an object! ;-(
843 throw new UnsupportedTemplateEngineException($tplEngine, self::EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED);
846 // Return the prepared instance
851 * Debugs this instance by putting out it's full content
855 public final function debugInstance () {
856 // Generate the output
857 $content = "<pre>".trim(print_r($this, true))."</pre>";
860 ApplicationEntryPoint::app_die("<strong>Debug output:</strong>".$content);