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 * Instance to an application helper class
29 private static $applicationInstance = null;
32 * The language instance for the template loader
34 private static $langInstance = null;
39 private $realClass = "FrameworkSystem";
42 * A human-readable description for this simulator part
44 private $objectDescription = "Namenlose Framework-Einheit";
47 * The unique ID string for identifying all type of classes
49 private $uniqueID = "";
54 private $thousands = "."; // German
59 private $decimals = ","; // German
62 * The file I/O instance for the template loader
64 private $fileIOInstance = null;
66 /***********************
67 * Exception codes.... *
68 ***********************/
70 const EXCEPTION_IS_NULL_POINTER = 0x001;
71 const EXCEPTION_IS_NO_OBJECT = 0x002;
72 const EXCEPTION_IS_NO_ARRAY = 0x003;
73 const EXCEPTION_MISSING_METHOD = 0x004;
74 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
75 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
76 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
77 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
78 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
79 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
80 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
81 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
82 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
83 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
84 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
85 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
86 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
87 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
88 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
89 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
90 const EXCEPTION_PATH_NOT_FOUND = 0x015;
91 const EXCEPTION_INVALID_PATH_NAME = 0x016;
92 const EXCEPTION_READ_PROTECED_PATH = 0x017;
93 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
94 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
95 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
96 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
97 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
98 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
99 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
100 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
101 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
102 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
103 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
104 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
105 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
106 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
107 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
108 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
109 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
110 const EXCEPTION_INVALID_STRING = 0x029;
111 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
112 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
113 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
114 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
115 const EXCEPTION_MISSING_LANGUAGE_HANDLER = 0x02e;
116 const EXCEPTION_MISSING_FILE_IO_HANDLER = 0x02f;
117 const EXCEPTION_MISSING_ELEMENT = 0x030;
118 const EXCEPTION_INVALID_COMMAND = 0x031;
119 const EXCEPTION_INVALID_CONTROLLER = 0x032;
120 const EXCEPTION_HEADERS_ALREADY_SENT = 0x033;
121 const EXCEPTION_DEFAUL_CONTROLLER_GONE = 0x034;
122 const EXCEPTION_CLASS_NOT_FOUND = 0x035;
123 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x036;
126 * In the super constructor these system classes shall be ignored or else
127 * we would get an endless calling loop.
129 *--------------------------------------------------------------------*
130 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL SHOOT YOUR SERVER!!! *
131 *--------------------------------------------------------------------*
133 private $systemClasses = array(
134 "DebugMiddleware", // Debug middleware output sub-system
135 "Registry", // Object registry
136 "ObjectFactory", // Object factory
137 "DebugWebOutput", // Debug web output sub-system
138 "WebOutput", // Web output sub-system
139 "CompressorChannel", // Compressor sub-system
140 "DebugConsoleOutput", // Debug console output sub-system
141 "DebugErrorLogOutput", // Debug error_log() output sub-system
142 "FrameworkDirectoryPointer", // Directory handler sub-system
143 "NullCompressor", // Null compressor
144 "Bzip2Compressor", // BZIP2 compressor
145 "GzipCompressor", // GZIP compressor
152 * Private super constructor
156 protected function __construct ($class) {
158 $this->setRealClass($class);
160 // Initialize the class if the registry is there
161 if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
162 $this->initInstance();
167 * Destructor reached...
171 public function __destruct() {
172 // Is this object already destroyed?
173 if ($this->__toString() != "DestructedObject") {
175 if ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
176 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wird zerstört.<br />\n",
177 __CLASS__, $this->__toString()
181 // Destroy all informations about this class but keep some text about it alive
182 $this->setObjectDescription(sprintf("Entferntes Objekt <em>%s</em>", $this->__toString()));
183 $this->setRealClass("DestructedObject");
184 $this->resetUniqueID();
185 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
186 // Already destructed object
187 $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wurde bereits zerstört.<br />\n",
188 __CLASS__, $this->__toString()
194 * The call method where all non-implemented methods end up
198 public final function __call ($methodName, $args) {
199 // Implode all given arguments
203 $argsString = "NULL";
204 } elseif (is_array($args)) {
205 // Some arguments are there
206 foreach ($args as $arg) {
210 if ($arg) $argsString .= "true(bool)"; else $argsString .= "false(bool)";
211 } elseif (is_int($arg)) {
213 $argsString .= $arg."(int)";
214 } elseif (is_float($arg)) {
216 $argsString .= $arg."(float)";
217 } elseif ($arg instanceof BaseFrameworkSystem) {
218 // Own object instance
219 $argsString .= $arg->__toString()."(Object)";
220 } elseif (is_object($arg)) {
222 $argsString .= "unknown object(!)";
223 } elseif (is_array($arg)) {
225 $argsString .= "Array(array)";
226 } elseif (is_string($arg)) {
228 $argsString .= "\"".$arg."\"(string)";
229 } elseif (is_null($arg)) {
231 $argsString .= "(null)";
233 // Unknown type (please report!)
234 $argsString .= $arg."(unknown!)";
242 if (substr($argsString, -2, 1) === ",") $argsString = substr($argsString, 0, -2);
244 // Invalid arguments!
245 $argsString = sprintf("!INVALID:%s!", $args);
248 $this->getDebugInstance()->output(sprintf("[%s::%s] Stub! Args: %s",
259 * Private initializer for this class
263 private final function initInstance () {
264 // Is this a system class?
265 if (!in_array($this->__toString(), $this->systemClasses)) {
266 // Add application helper to our class
267 $this->systemclasses[] = $this->getConfigInstance()->readConfig('app_helper_class');
269 // Set debug instance
270 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_engine')));
272 // Get output instance and set it
273 $outputInstance = ObjectFactory::createObjectByConfiguredName('web_engine', array($this->getConfigInstance()->readConfig('web_content_type')));
274 $this->setWebOutputInstance($outputInstance);
276 // Set the compressor channel
277 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
279 $this->getConfigInstance()->readConfig('compressor_base_path')
282 // Initialization done! :D
283 Registry::isInitialized("OK");
284 } elseif ($this->__toString() == "DebugMiddleware") {
285 // Set configuration instance
286 $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
291 * Setter for language instance
293 * @param $configInstance The configuration instance which shall
294 * be FrameworkConfiguration
297 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
298 Registry::getRegistry()->addInstance('config', $configInstance);
302 * Getter for configuration instance
304 * @return $cfhInstance - Configuration instance
306 protected final function getConfigInstance () {
307 return Registry::getRegistry()->getInstance('config');
311 * Setter for debug instance
313 * @param $debugInstance The instance for debug output class
316 public final function setDebugInstance (DebugMiddleware $debugInstance) {
317 Registry::getRegistry()->addInstance('debug', $debugInstance);
321 * Getter for debug instance
323 * @return $debug - Instance to class DebugConsoleOutput or DebugWebOutput
325 public final function getDebugInstance () {
326 return Registry::getRegistry()->getInstance('debug');
330 * Setter for web output instance
332 * @param $webInstance The instance for web output class
335 public final function setWebOutputInstance (OutputStreamer $webInstance) {
336 Registry::getRegistry()->addInstance('web_output', $webInstance);
340 * Getter for web output instance
342 * @return $webOutput - Instance to class WebOutput
344 public final function getWebOutputInstance () {
345 return Registry::getRegistry()->getInstance('web_output');
349 * Setter for database instance
351 * @param $dbInstance The instance for the database connection
352 * (forced DatabaseConnection)
355 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
356 Registry::getRegistry()->addInstance('dbInstance', $dbInstance);
360 * Getter for database layer
362 * @return $dbInstance The database layer instance
364 public final function getDatabaseInstance () {
365 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
366 return Registry::getRegistry()->getInstance('dbInstance');
373 * Setter for compressor channel
375 * @param $compressorChannel An instance of CompressorChannel
378 public final function setCompressorChannel (CompressorChannel $compressorChannel) {
379 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
383 * Getter for compressor channel
385 * @return $compressor The compressor channel
387 public final function getCompressorChannel () {
388 return Registry::getRegistry()->getInstance('compressor');
392 * Protected getter for a manageable application helper class
394 * @return $applicationInstance An instance of a manageable application helper class
396 protected final function getApplicationInstance () {
397 return self::$applicationInstance;
401 * Setter for a manageable application helper class
403 * @param $applicationInstance An instance of a manageable application helper class
406 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
407 self::$applicationInstance = $applicationInstance;
411 * Getter for $realClass
413 * @return $realClass The name of the real class (not BaseFrameworkSystem)
415 public final function __toString () {
416 return $this->realClass;
420 * Setter for the real class name
422 * @param $realClass Class name (string)
425 public final function setRealClass ($realClass) {
427 $realClass = (string) $realClass;
430 $this->realClass = $realClass;
434 * Generate unique ID from a lot entropy
438 public final function generateUniqueId () {
439 // Is the id set for this class?
440 if (empty($this->uniqueID)) {
442 // Correct missing class name
444 if ($this->__toString() == "") {
445 $this->setRealClass(__CLASS__);
449 // Cache datbase instance
450 $db = $this->getDatabaseInstance();
455 // Generate a unique ID number
456 $tempID = $this->generateIdNumber();
459 // Try to figure out if the ID number is not yet used
461 // Is this a registry?
462 if ($this->__toString() == "Registry") {
463 // Registry, then abort here
465 } elseif (is_object($db)) {
466 $isUsed = $db->isUniqueIdUsed($tempID, true);
468 } catch (FrameworkException $e) {
469 // Catches all and ignores all ;-)
493 $this->setUniqueID($tempID);
495 // Revert maybe corrected class name
497 $this->setRealClass("");
500 // Remove system classes if we are in a system class
501 if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
502 // This may save some RAM...
503 $this->removeSystemArray();
509 * Generates a new ID number for classes based from the class' real name,
510 * the description and some random data
512 * @return $tempID The new (temporary) ID number
514 private final function generateIdNumber () {
515 return sprintf("%s@%s",
517 md5(sprintf("%s:%s:%s:%s:%s:%s",
519 $this->getObjectDescription(),
521 getenv('REMOTE_ADDR'),
522 getenv('SERVER_ADDR'),
529 * Setter for unique ID
531 * @param $uniqueID The newly generated unique ID number
534 private final function setUniqueID ($uniqueID) {
536 $uniqueID = (string) $uniqueID;
539 $this->uniqueID = $uniqueID;
543 * Getter for unique ID
545 * @return $uniqueID The unique ID of this class
547 public final function getUniqueID () {
548 return $this->uniqueID;
552 * Resets or recreates the unique ID number
556 public final function resetUniqueID() {
557 // Sweet and simple... ;-)
558 $newUniqueID = $this->generateIdNumber();
559 $this->setUniqueID($newUniqueID);
563 * Getter for simulator description
565 * @return $objectDescription The description of this simulation part
567 public final function getObjectDescription () {
568 if (isset($this->objectDescription)) {
569 return $this->objectDescription;
576 * Setter for simulation part description
578 * @param $objectDescription The description as string for this simulation part
581 public final function setObjectDescription ($objectDescription) {
582 $this->objectDescription = (String) $objectDescription;
586 * Validate if given object is the same as current
588 * @param $object An object instance for comparison with this class
589 * @return boolean The result of comparing both's unique ID
591 public final function equals ($object) {
592 return ($this->getUniqueID() == $object->getUniqueID());
596 * Compare if both simulation part description and class name matches
599 * @param $itemInstance An object instance to an other class
600 * @return boolean The result of comparing class name simulation part description
602 public function itemMatches ($itemInstance) {
605 $this->__toString() == $itemInstance->__toString()
607 $this->getObjectDescription() == $itemInstance->getObjectDescription()
613 * Compare class name of this and given class name
615 * @param $class The class name as string from the other class
616 * @return boolean The result of comparing both class names
618 public final function isClass ($class) {
619 return ($this->__toString() == $class);
623 * Stub method (only real cabins shall override it)
625 * @return boolean false = is no cabin, true = is a cabin
627 public function isCabin () {
632 * Stub method for tradeable objects
634 * @return boolean false = is not tradeable by the Merchant class,
635 * true = is a tradeable object
637 public function isTradeable () {
642 * Formats computer generated price values into human-understandable formats
643 * with thousand and decimal seperators.
645 * @param $value The in computer format value for a price
646 * @param $currency The currency symbol (use HTML-valid characters!)
647 * @param $decNum Number of decimals after commata
648 * @return $price The for the current language formated price string
649 * @throws MissingDecimalsThousandsSeperatorException If decimals or
650 * thousands seperator
653 public function formatCurrency ($value, $currency = "€", $decNum = 2) {
654 // Are all required attriutes set?
655 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
656 // Throw an exception
657 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
661 $value = (float) $value;
663 // Reformat the US number
664 $price = sprintf("%s %s",
665 number_format($value, $decNum, $this->decimals, $this->thousands),
669 // Return as string...
674 * Removes number formating characters
678 public final function removeNumberFormaters () {
679 unset($this->thousands);
680 unset($this->decimals);
684 * Private getter for language instance
686 * @return $langInstance An instance to the language sub-system
688 protected final function getLanguageInstance () {
689 return self::$langInstance;
693 * Setter for language instance
695 * @param $langInstance An instance to the language sub-system
697 * @see LanguageSystem
699 public final function setLanguageInstance (ManageableLanguage $langInstance) {
700 self::$langInstance = $langInstance;
704 * Remove the $systemClasses array from memory
708 public final function removeSystemArray () {
709 unset($this->systemClasses);
713 * Create a file name and path name from the object's unique ID number.
714 * The left part of the ID shall always be a valid class name and the
715 * right part an ID number.
717 * @return $pfn The file name with a prepended path name
718 * @throws NoArrayCreatedException If explode() fails to create an array
719 * @throws InvalidArrayCountException If the array contains less or
720 * more than two elements
722 public final function getPathFileNameFromObject () {
723 // Get the main object's unique ID. We use this as a path/filename combination
724 $pathFile = $this->getUniqueID();
726 // Split it up in path and file name
727 $pathFile = explode("@", $pathFile);
729 // Are there two elements? Index 0 is the path, 1 the file name + global extension
730 if (!is_array($pathFile)) {
732 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
733 } elseif (count($pathFile) != 2) {
734 // Invalid ID returned!
735 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
738 // Auto-append missing trailing slash
739 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
741 // Create the file name and return it
742 $pfn = ($pathFile[0] . $pathFile[1]);
747 * Appends a trailing slash to a string
749 * @param $str A string (maybe) without trailing slash
750 * @return $str A string with an auto-appended trailing slash
752 public final function addMissingTrailingSlash ($str) {
753 // Is there a trailing slash?
754 if (substr($str, -1, 1) != "/") $str .= "/";
759 * Private getter for file IO instance
761 * @return $fileIOInstance An instance to the file I/O sub-system
763 protected final function getFileIoInstance () {
764 return $this->fileIOInstance;
768 * Setter for file I/O instance
770 * @param $fileIOInstance An instance to the file I/O sub-system
773 public final function setFileIoInstance (FileIoHandler $fileIOInstance) {
774 $this->fileIOInstance = $fileIOInstance;
778 * Prepare the template engine (TemplateEngine by default) for a given
779 * application helper instance (ApplicationHelper by default).
781 * @param $appInstance An application helper instance or
782 * null if we shall use the default
783 * @return $tplEngine The template engine instance
784 * @throws NullPointerException If the template engine could not
786 * @throws UnsupportedTemplateEngineException If $tplEngine is an
787 * unsupported template engine
788 * @throws MissingLanguageHandlerException If the language sub-system
789 * is not yet initialized
790 * @throws NullPointerException If the discovered application
791 * instance is still null
793 protected function prepareTemplateEngine (BaseFrameworkSystem $appInstance=null) {
794 // Is the application instance set?
795 if (is_null($appInstance)) {
796 // Get the current instance
797 $appInstance = $this->getApplicationInstance();
800 if (is_null($appInstance)) {
801 // Thrown an exception
802 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
806 // Generate FQFN for all application templates
807 $fqfn = sprintf("%s%s/%s/%s",
809 $this->getConfigInstance()->readConfig('application_path'),
810 strtolower($appInstance->getAppShortName()),
811 $this->getConfigInstance()->readConfig('tpl_base_path')
814 // Are both instances set?
815 if ($appInstance->getLanguageInstance() === null) {
816 // Invalid language instance
817 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
818 } elseif ($appInstance->getFileIoInstance() === null) {
819 // Invalid language instance
820 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
823 // Initialize the template engine
824 $tplEngine = ObjectFactory::createObjectByConfiguredName('tpl_engine', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
826 // Return the prepared instance
831 * Debugs this instance by putting out it's full content
835 public final function debugInstance () {
836 // Generate the output
837 $content = sprintf("<pre>%s</pre>",
838 trim(print_r($this, true))
842 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong>%s", $this->__toString(), $content));
846 * Output a partial stub message for the caller method
848 * @param $message An optional message to display
851 protected function partialStub ($message = "") {
853 $backtrace = debug_backtrace();
855 // Generate the class::method string
856 $methodName = "UnknownClass::unknownMethod";
857 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
858 $methodName = $backtrace[1]['class']."::".$backtrace[1]['function'];
861 // Construct the full message
862 $stubMessage = sprintf("[%s:] Partial stub!",
866 // Is the extra message given?
867 if (!empty($message)) {
868 // Then add it as well
869 $stubMessage .= sprintf(" Message: <u>%s</u>", $message);
872 // Debug instance is there?
873 if (!is_null($this->getDebugInstance())) {
874 // Output stub message
875 $this->getDebugInstance()->output($stubMessage);
878 trigger_error($stubMessage."<br />\n");
883 * Converts e.g. a command from URL to a valid class by keeping out bad characters
885 * @param $str The string, what ever it is needs to be converted
886 * @return $className Generated class name
888 public function convertToClassName ($str) {
890 foreach (explode("_", $str) as $strPart) {
891 $className .= ucfirst(strtolower($strPart));
897 * Outputs a debug backtrace and stops further script execution
901 public function debugBacktrace () {
902 // Sorry, there is no other way getting this nice backtrace
904 debug_print_backtrace();