7d9467ad68457fec86e222066c58ce7a5b760235
[shipsimu.git] / inc / classes / main / class_BaseFrameworkSystem.php
1 <?php
2 /**
3  * The simulator system class is the super class of all other classes. This
4  * class handles saving of games etc.
5  *
6  * @author              Roland Haeder <webmaster@ship-simu.org>
7  * @version             0.0.0
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
11  *
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.
16  *
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.
21  *
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/>.
24  */
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
26         /**
27          * Instance to an application helper class
28          */
29         private static $applicationInstance = null;
30
31         /**
32          * The language instance for the template loader
33          */
34         private static $langInstance = null;
35
36         /**
37          * Debug instance
38          */
39         private static $debugInstance = null;
40
41         /**
42          * Instance of a request class
43          */
44         private $requestInstance = null;
45
46         /**
47          * Instance of a response class
48          */
49         private $responseInstance = null;
50
51         /**
52          * Search criteria instance
53          */
54         private $searchInstance = null;
55
56         /**
57          * The file I/O instance for the template loader
58          */
59         private $fileIoInstance = null;
60
61         /**
62          * Resolver instance
63          */
64         private $resolverInstance = null;
65
66         /**
67          * Template engine instance
68          */
69         private $templateInstance = null;
70
71         /**
72          * The real class name
73          */
74         private $realClass      = "FrameworkSystem";
75
76         /**
77          * A human-readable description for this simulator part
78          */
79         private $objectDescription      = "Namenlose Framework-Einheit";
80
81         /**
82          * The unique ID string for identifying all type of classes
83          */
84         private $uniqueID = "";
85
86         /**
87          * Thousands seperator
88          */
89         private $thousands = "."; // German
90
91         /**
92          * Decimal seperator
93          */
94         private $decimals  = ","; // German
95
96         /***********************
97          * Exception codes.... *
98          ***********************/
99
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_HEADERS_ALREADY_SENT         = 0x031;
149         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
150         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
151         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
152         const EXCEPTION_FATAL_ERROR                  = 0x035;
153         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
154         const EXCEPTION_ASSERTION_FAILED             = 0x037;
155         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x038;
156
157         /**
158          * In the super constructor these system classes shall be ignored or else
159          * we would get an endless calling loop.
160          *
161          *---------------------------------------------------------------------*
162          * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL RUN YOUR SERVER IN AN *
163          * ENDLESS LOOP !!!                                                    *
164          *---------------------------------------------------------------------*
165          */
166         private $systemClasses = array(
167                 "DebugMiddleware",                              // Debug middleware output sub-system
168                 "Registry",                                             // Object registry
169                 "ObjectFactory",                                // Object factory
170                 "DebugWebOutput",                               // Debug web output sub-system
171                 "WebOutput",                                    // Web output sub-system
172                 "CompressorChannel",                    // Compressor sub-system
173                 "DebugConsoleOutput",                   // Debug console output sub-system
174                 "DebugErrorLogOutput",                  // Debug error_log() output sub-system
175                 "FrameworkDirectoryPointer",    // Directory handler sub-system
176                 "NullCompressor",                               // Null compressor
177                 "Bzip2Compressor",                              // BZIP2 compressor
178                 "GzipCompressor",                               // GZIP compressor
179         );
180
181         /* No longer used:
182         */
183
184         /**
185          * Private super constructor
186          *
187          * @param       $className      Name of the class
188          * @return      void
189          */
190         protected function __construct ($className) {
191                 // Set real class
192                 $this->setRealClass($className);
193
194                 // Initialize the class if the registry is there
195                 if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
196                         $this->initInstance();
197                 } // END - if
198         }
199
200         /**
201          * Destructor reached...
202          *
203          * @return      void
204          */
205         public function __destruct() {
206                 // Is this object already destroyed?
207                 if ($this->__toString() != 'DestructedObject') {
208                         // Destroy all informations about this class but keep some text about it alive
209                         $this->setObjectDescription(sprintf("Removed object <em>%s</em>", $this->__toString()));
210                         $this->setRealClass('DestructedObject');
211                         $this->resetUniqueID();
212                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
213                         // Already destructed object
214                         $this->getDebugInstance()->output(sprintf("[%s:] Das Objekt <strong>%s</strong> wurde bereits zerst&ouml;rt.",
215                                 __CLASS__, $this->__toString()
216                         ));
217                 }
218         }
219
220         /**
221          * The call method where all non-implemented methods end up
222          *
223          * @return      void
224          */
225         public final function __call ($methodName, $args) {
226                 // Implode all given arguments
227                 $argsString = "";
228                 if (empty($args)) {
229                         // No arguments
230                         $argsString = "NULL";
231                 } elseif (is_array($args)) {
232                         // Some arguments are there
233                         foreach ($args as $arg) {
234                                 // Check the type
235                                 if (is_bool($arg)) {
236                                         // Boolean!
237                                         if ($arg) $argsString .= "true(bool)"; else $argsString .= "false(bool)";
238                                 } elseif (is_int($arg)) {
239                                         // Integer
240                                         $argsString .= $arg."(int)";
241                                 } elseif (is_float($arg)) {
242                                         // Floating point
243                                         $argsString .= $arg."(float)";
244                                 } elseif ($arg instanceof BaseFrameworkSystem) {
245                                         // Own object instance
246                                         $argsString .= $arg->__toString()."(Object)";
247                                 } elseif (is_object($arg)) {
248                                         // External object
249                                         $argsString .= "unknown object(!)";
250                                 } elseif (is_array($arg)) {
251                                         // Array
252                                         $argsString .= "Array(array)";
253                                 } elseif (is_string($arg)) {
254                                         // String
255                                         $argsString .= "\"".$arg."\"(string)";
256                                 } elseif (is_null($arg)) {
257                                         // Null
258                                         $argsString .= "(null)";
259                                 } elseif (is_resource($arg)) {
260                                         // Resource
261                                         $argsString .= "(resource)";
262                                 } else {
263                                         // Unknown type (please report!)
264                                         $argsString .= $arg."(<em>unknown!</em>)";
265                                 }
266
267                                 // Add comma
268                                 $argsString .= ", ";
269                         }
270
271                         // Remove last comma
272                         if (substr($argsString, -2, 1) === ",") {
273                                 $argsString = substr($argsString, 0, -2);
274                         } // END - if
275                 } else {
276                         // Invalid arguments!
277                         $argsString = sprintf("!INVALID:%s!", $args);
278                 }
279
280                 // Output stub message
281                 $this->getDebugInstance()->output(sprintf("[%s-&gt;%s] Stub! Args: %s",
282                         $this->__toString(),
283                         $methodName,
284                         $argsString
285                 ));
286
287                 // Return nothing
288                 return null;
289         }
290
291         /**
292          * Private initializer for this class
293          *
294          * @return      void
295          */
296         private final function initInstance () {
297                 // Is this a system class?
298                 if (!in_array($this->__toString(), $this->systemClasses)) {
299                         // Add application helper to our class
300                         $this->systemclasses[] = $this->getConfigInstance()->readConfig('app_helper_class');
301
302                         // Set debug instance
303                         $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_class')));
304
305                         // Get output instance and set it
306                         $outputInstance = ObjectFactory::createObjectByConfiguredName('web_engine', array($this->getConfigInstance()->readConfig('web_content_type')));
307                         $this->setWebOutputInstance($outputInstance);
308
309                         // Set the compressor channel
310                         $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
311                                 PATH,
312                                 $this->getConfigInstance()->readConfig('compressor_base_path')
313                         )));
314
315                         // Initialization done! :D
316                         Registry::isInitialized('OK');
317                 } elseif ($this->__toString() == 'DebugMiddleware') {
318                         // Set configuration instance
319                         $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
320                 }
321         }
322
323         /**
324          * Setter for template engine instances
325          *
326          * @param       $templateInstance       An instance of a template engine class
327          * @return      void
328          */
329         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
330                 $this->templateInstance = $templateInstance;
331         }
332
333         /**
334          * Getter for template engine instances
335          *
336          * @return      $templateInstance       An instance of a template engine class
337          */
338         protected final function getTemplateInstance () {
339                 return $this->templateInstance;
340         }
341
342         /**
343          * Setter for search instance
344          *
345          * @param       $searchInstance         Searchable criteria instance
346          * @return      void
347          */
348         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
349                 $this->searchInstance = $searchInstance;
350         }
351
352         /**
353          * Getter for search instance
354          *
355          * @return      $searchInstance         Searchable criteria instance
356          */
357         public final function getSearchInstance () {
358                 return $this->searchInstance;
359         }
360
361         /**
362          * Setter for resolver instance
363          *
364          * @param       $resolverInstance               Instance of a command resolver class
365          * @return      void
366          */
367         public final function setResolverInstance (Resolver $resolverInstance) {
368                 $this->resolverInstance = $resolverInstance;
369         }
370
371         /**
372          * Getter for resolver instance
373          *
374          * @return      $resolverInstance               Instance of a command resolver class
375          */
376         public final function getResolverInstance () {
377                 return $this->resolverInstance;
378         }
379
380         /**
381          * Setter for language instance
382          *
383          * @param       $configInstance         The configuration instance which shall
384          *                                                              be FrameworkConfiguration
385          * @return      void
386          */
387         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
388                 Registry::getRegistry()->addInstance('config', $configInstance);
389         }
390
391         /**
392          * Getter for configuration instance
393          *
394          * @return      $cfgInstance    Configuration instance
395          */
396         public final function getConfigInstance () {
397                 $cfgInstance = Registry::getRegistry()->getInstance('config');
398                 return $cfgInstance;
399         }
400
401         /**
402          * Setter for debug instance
403          *
404          * @param       $debugInstance  The instance for debug output class
405          * @return      void
406          */
407         public final function setDebugInstance (DebugMiddleware $debugInstance) {
408                 self::$debugInstance = $debugInstance;
409         }
410
411         /**
412          * Getter for debug instance
413          *
414          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
415          */
416         public final function getDebugInstance () {
417                 return self::$debugInstance;
418         }
419
420         /**
421          * Setter for web output instance
422          *
423          * @param               $webInstance    The instance for web output class
424          * @return      void
425          */
426         public final function setWebOutputInstance (OutputStreamer $webInstance) {
427                 Registry::getRegistry()->addInstance('web_output', $webInstance);
428         }
429
430         /**
431          * Getter for web output instance
432          *
433          * @return      $webOutput - Instance to class WebOutput
434          */
435         public final function getWebOutputInstance () {
436                 return Registry::getRegistry()->getInstance('web_output');
437         }
438
439         /**
440          * Setter for database instance
441          *
442          * @param               $dbInstance     The instance for the database connection
443          *                                      (forced DatabaseConnection)
444          * @return      void
445          */
446         public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
447                 Registry::getRegistry()->addInstance('dbInstance', $dbInstance);
448         }
449
450         /**
451          * Getter for database layer
452          *
453          * @return      $dbInstance     The database layer instance
454          */
455         public final function getDatabaseInstance () {
456                 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
457                         return Registry::getRegistry()->getInstance('dbInstance');
458                 } else {
459                         return null;
460                 }
461         }
462
463         /**
464          * Setter for compressor channel
465          *
466          * @param               $compressorChannel      An instance of CompressorChannel
467          * @return      void
468          */
469         public final function setCompressorChannel (CompressorChannel $compressorChannel) {
470                 Registry::getRegistry()->addInstance('compressor', $compressorChannel);
471         }
472
473         /**
474          * Getter for compressor channel
475          *
476          * @return      $compressor     The compressor channel
477          */
478         public final function getCompressorChannel () {
479                 return Registry::getRegistry()->getInstance('compressor');
480         }
481
482         /**
483          * Protected getter for a manageable application helper class
484          *
485          * @return      $applicationInstance    An instance of a manageable application helper class
486          */
487         protected final function getApplicationInstance () {
488                 return self::$applicationInstance;
489         }
490
491         /**
492          * Setter for a manageable application helper class
493          *
494          * @param       $applicationInstance    An instance of a manageable application helper class
495          * @return      void
496          */
497         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
498                 self::$applicationInstance = $applicationInstance;
499         }
500
501         /**
502          * Setter for request instance
503          *
504          * @param       $requestInstance        An instance of a Requestable class
505          * @return      void
506          */
507         public final function setRequestInstance (Requestable $requestInstance) {
508                 $this->requestInstance = $requestInstance;
509         }
510
511         /**
512          * Getter for request instance
513          *
514          * @return      $requestInstance        An instance of a Requestable class
515          */
516         public final function getRequestInstance () {
517                 return $this->requestInstance;
518         }
519
520         /**
521          * Setter for response instance
522          *
523          * @param       $responseInstance       An instance of a Responseable class
524          * @return      void
525          */
526         public final function setResponseInstance (Responseable $responseInstance) {
527                 $this->responseInstance = $responseInstance;
528         }
529
530         /**
531          * Getter for response instance
532          *
533          * @return      $responseInstance       An instance of a Responseable class
534          */
535         public final function getResponseInstance () {
536                 return $this->responseInstance;
537         }
538
539         /**
540          * Getter for $realClass
541          *
542          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
543          */
544         public final function __toString () {
545                 return $this->realClass;
546         }
547
548         /**
549          * Setter for the real class name
550          *
551          * @param               $realClass      Class name (string)
552          * @return      void
553          */
554         public final function setRealClass ($realClass) {
555                 // Cast to string
556                 $realClass = (string) $realClass;
557
558                 // Set real class
559                 $this->realClass = $realClass;
560         }
561
562         /**
563          * Generate unique ID from a lot entropy
564          *
565          * @return      void
566          */
567         public final function generateUniqueId () {
568                 // Is the id set for this class?
569                 if (empty($this->uniqueID)) {
570
571                         // Correct missing class name
572                         $corrected = false;
573                         if ($this->__toString() == "") {
574                                 $this->setRealClass(__CLASS__);
575                                 $corrected = true;
576                         }
577
578                         // Cache datbase instance
579                         $db = $this->getDatabaseInstance();
580
581                         // Generate new id
582                         $tempID = false;
583                         while (true) {
584                                 // Generate a unique ID number
585                                 $tempID = $this->generateIdNumber();
586                                 $isUsed = false;
587
588                                 // Try to figure out if the ID number is not yet used
589                                 try {
590                                         // Is this a registry?
591                                         if ($this->__toString() == "Registry") {
592                                                 // Registry, then abort here
593                                                 break;
594                                         } elseif (is_object($db)) {
595                                                 $isUsed = $db->isUniqueIdUsed($tempID, true);
596                                         }
597                                 } catch (FrameworkException $e) {
598                                         // Catches all and ignores all ;-)
599                                 }
600
601                                 if (
602                                         (
603                                                 $tempID !== false
604                                         ) && (
605                                                 (
606                                                         $db === null
607                                                 ) || (
608                                                         (
609                                                                 is_object($db)
610                                                         ) && (
611                                                                 !$isUsed
612                                                         )
613                                                 )
614                                         )
615                                 ) {
616                                         // Abort the loop
617                                         break;
618                                 }
619                         } // END - while
620
621                         // Apply the new ID
622                         $this->setUniqueID($tempID);
623
624                         // Revert maybe corrected class name
625                         if ($corrected) {
626                                 $this->setRealClass("");
627                         }
628
629                         // Remove system classes if we are in a system class
630                         if ((isset($this->systemClasses)) && (in_array($this->__toString(), $this->systemClasses))) {
631                                 // This may save some RAM...
632                                 $this->removeSystemArray();
633                         }
634                 }
635         }
636
637         /**
638          * Generates a new ID number for classes based from the class' real name,
639          * the description and some random data
640          *
641          * @return      $tempID The new (temporary) ID number
642          */
643         private final function generateIdNumber () {
644                 return sprintf("%s@%s",
645                         $this->__toString(),
646                         md5(sprintf("%s:%s:%s:%s:%s:%s",
647                                 $this->__toString(),
648                                 $this->getObjectDescription(),
649                                 time(),
650                                 getenv('REMOTE_ADDR'),
651                                 getenv('SERVER_ADDR'),
652                                 mt_rand()
653                         ))
654                 );
655         }
656
657         /**
658          * Setter for unique ID
659          *
660          * @param               $uniqueID               The newly generated unique ID number
661          * @return      void
662          */
663         private final function setUniqueID ($uniqueID) {
664                 // Cast to string
665                 $uniqueID = (string) $uniqueID;
666
667                 // Set the ID number
668                 $this->uniqueID = $uniqueID;
669         }
670
671         /**
672          * Getter for unique ID
673          *
674          * @return      $uniqueID               The unique ID of this class
675          */
676         public final function getUniqueID () {
677                 return $this->uniqueID;
678         }
679
680         /**
681          * Resets or recreates the unique ID number
682          *
683          * @return      void
684          */
685         public final function resetUniqueID() {
686                 // Sweet and simple... ;-)
687                 $newUniqueID = $this->generateIdNumber();
688                 $this->setUniqueID($newUniqueID);
689         }
690
691         /**
692          * Getter for simulator description
693          *
694          * @return      $objectDescription      The description of this simulation part
695          */
696         public final function getObjectDescription () {
697                 if (isset($this->objectDescription)) {
698                         return $this->objectDescription;
699                 } else {
700                         return null;
701                 }
702         }
703
704         /**
705          * Setter for simulation part description
706          *
707          * @param               $objectDescription      The description as string for this simulation part
708          * @return      void
709          */
710         public final function setObjectDescription ($objectDescription) {
711                 $this->objectDescription = (String) $objectDescription;
712         }
713
714         /**
715          * Validate if given object is the same as current
716          *
717          * @param       $object An object instance for comparison with this class
718          * @return      boolean The result of comparing both's unique ID
719          */
720         public final function equals (FrameworkInterface $object) {
721                 return ($this->getUniqueID() == $object->getUniqueID());
722         }
723
724         /**
725          * Compare if both simulation part description and class name matches
726          * (shall be enougth)
727          *
728          * @param       $itemInstance   An object instance to an other class
729          * @return      boolean                 The result of comparing class name simulation part description
730          */
731         public function itemMatches ($itemInstance) {
732                 return (
733                         (
734                                 $this->__toString()   == $itemInstance->__toString()
735                         ) && (
736                                 $this->getObjectDescription() == $itemInstance->getObjectDescription()
737                         )
738                 );
739         }
740
741         /**
742          * Compare class name of this and given class name
743          *
744          * @param               $className      The class name as string from the other class
745          * @return      boolean The result of comparing both class names
746          */
747         public final function isClass ($className) {
748                 return ($this->__toString() == $className);
749         }
750
751         /**
752          * Stub method (only real cabins shall override it)
753          *
754          * @return      boolean false = is no cabin, true = is a cabin
755          */
756         public function isCabin () {
757                 return false;
758         }
759
760         /**
761          * Stub method for tradeable objects
762          *
763          * @return      boolean false = is not tradeable by the Merchant class,
764          *                                      true  = is a tradeable object
765          */
766         public function isTradeable () {
767                 return false;
768         }
769
770         /**
771          * Formats computer generated price values into human-understandable formats
772          * with thousand and decimal seperators.
773          *
774          * @param       $value          The in computer format value for a price
775          * @param       $currency       The currency symbol (use HTML-valid characters!)
776          * @param       $decNum         Number of decimals after commata
777          * @return      $price          The for the current language formated price string
778          * @throws      MissingDecimalsThousandsSeperatorException      If decimals or
779          *                                                                                              thousands seperator
780          *                                                                                              is missing
781          */
782         public function formatCurrency ($value, $currency = "&euro;", $decNum = 2) {
783                 // Are all required attriutes set?
784                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
785                         // Throw an exception
786                         throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
787                 }
788
789                 // Cast the number
790                 $value = (float) $value;
791
792                 // Reformat the US number
793                 $price = sprintf("%s %s",
794                         number_format($value, $decNum, $this->decimals, $this->thousands),
795                         $currency
796                 );
797
798                 // Return as string...
799                 return $price;
800         }
801
802         /**
803          * Removes number formating characters
804          *
805          * @return      void
806          */
807         public final function removeNumberFormaters () {
808                 unset($this->thousands);
809                 unset($this->decimals);
810         }
811
812         /**
813          * Private getter for language instance
814          *
815          * @return      $langInstance   An instance to the language sub-system
816          */
817         protected final function getLanguageInstance () {
818                 return self::$langInstance;
819         }
820
821         /**
822          * Setter for language instance
823          *
824          * @param       $langInstance   An instance to the language sub-system
825          * @return      void
826          * @see         LanguageSystem
827          */
828         public final function setLanguageInstance (ManageableLanguage $langInstance) {
829                 self::$langInstance = $langInstance;
830         }
831
832         /**
833          * Remove the $systemClasses array from memory
834          *
835          * @return      void
836          */
837         public final function removeSystemArray () {
838                 unset($this->systemClasses);
839         }
840
841         /**
842          * Create a file name and path name from the object's unique ID number.
843          * The left part of the ID shall always be a valid class name and the
844          * right part an ID number.
845          *
846          * @return      $pfn    The file name with a prepended path name
847          * @throws      NoArrayCreatedException         If explode() fails to create an array
848          * @throws      InvalidArrayCountException      If the array contains less or
849          *                                                                              more than two elements
850          */
851         public final function getPathFileNameFromObject () {
852                 // Get the main object's unique ID. We use this as a path/filename combination
853                 $pathFile = $this->getUniqueID();
854
855                 // Split it up in path and file name
856                 $pathFile = explode("@", $pathFile);
857
858                 // Are there two elements? Index 0 is the path, 1 the file name + global extension
859                 if (!is_array($pathFile)) {
860                         // No array found
861                         throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
862                 } elseif (count($pathFile) != 2) {
863                         // Invalid ID returned!
864                         throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
865                 }
866
867                 // Auto-append missing trailing slash
868                 $pathFile[0] = $this->addMissingTrailingSlash($pathFile[0]);
869
870                 // Create the file name and return it
871                 $pfn = ($pathFile[0] . $pathFile[1]);
872                 return $pfn;
873         }
874
875         /**
876          * Appends a trailing slash to a string
877          *
878          * @param       $str            A string (maybe) without trailing slash
879          * @return      $str            A string with an auto-appended trailing slash
880          */
881         public final function addMissingTrailingSlash ($str) {
882                 // Is there a trailing slash?
883                 if (substr($str, -1, 1) != "/") $str .= "/";
884                 return $str;
885         }
886
887         /**
888          * Private getter for file IO instance
889          *
890          * @return      $fileIoInstance An instance to the file I/O sub-system
891          */
892         protected final function getFileIoInstance () {
893                 return $this->fileIoInstance;
894         }
895
896         /**
897          * Setter for file I/O instance
898          *
899          * @param       $fileIoInstance An instance to the file I/O sub-system
900          * @return      void
901          */
902         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
903                 $this->fileIoInstance = $fileIoInstance;
904         }
905
906         /**
907          * Prepare the template engine (WebTemplateEngine by default) for a given
908          * application helper instance (ApplicationHelper by default).
909          *
910          * @param               $appInstance                    An application helper instance or
911          *                                                                              null if we shall use the default
912          * @return              $tplEngine                              The template engine instance
913          * @throws              NullPointerException    If the template engine could not
914          *                                                                              be initialized
915          * @throws              UnsupportedTemplateEngineException      If $tplEngine is an
916          *                                                                              unsupported template engine
917          * @throws              MissingLanguageHandlerException If the language sub-system
918          *                                                                              is not yet initialized
919          * @throws              NullPointerException    If the discovered application
920          *                                                                              instance is still null
921          */
922         protected function prepareTemplateEngine (BaseFrameworkSystem $appInstance=null) {
923                 // Is the application instance set?
924                 if (is_null($appInstance)) {
925                         // Get the current instance
926                         $appInstance = $this->getApplicationInstance();
927
928                         // Still null?
929                         if (is_null($appInstance)) {
930                                 // Thrown an exception
931                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
932                         }
933                 }
934
935                 // Generate FQFN for all application templates
936                 $fqfn = sprintf("%s%s/%s/%s",
937                         PATH,
938                         $this->getConfigInstance()->readConfig('application_path'),
939                         strtolower($appInstance->getAppShortName()),
940                         $this->getConfigInstance()->readConfig('tpl_base_path')
941                 );
942
943                 // Are both instances set?
944                 if ($appInstance->getLanguageInstance() === null) {
945                         // Invalid language instance
946                         throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
947                 } elseif ($appInstance->getFileIoInstance() === null) {
948                         // Invalid language instance
949                         throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
950                 }
951
952                 // Initialize the template engine
953                 $tplEngine = ObjectFactory::createObjectByConfiguredName('template_class', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
954
955                 // Return the prepared instance
956                 return $tplEngine;
957         }
958
959         /**
960          * Debugs this instance by putting out it's full content
961          *
962          * @return      void
963          */
964         public final function debugInstance () {
965                 // Generate the output
966                 $content = sprintf("<pre>%s</pre>",
967                         trim(print_r($this, true))
968                 );
969
970                 // Output it
971                 ApplicationEntryPoint::app_die(sprintf("<strong>%s debug output:</strong><div id=\"debug_content\">%s</div>Loaded includes: <div id=\"debug_include_list\">%s</div>",
972                         $this->__toString(),
973                         $content,
974                         ClassLoader::getInstance()->getPrintableIncludeList()
975                 ));
976         }
977
978         /**
979          * Output a partial stub message for the caller method
980          *
981          * @param       $message        An optional message to display
982          * @return      void
983          */
984         protected function partialStub ($message = "") {
985                 // Get the backtrace
986                 $backtrace = debug_backtrace();
987
988                 // Generate the class::method string
989                 $methodName = "UnknownClass-&gt;unknownMethod";
990                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
991                         $methodName = $backtrace[1]['class']."-&gt;".$backtrace[1]['function'];
992                 }
993
994                 // Construct the full message
995                 $stubMessage = sprintf("[%s:] Partial stub!",
996                         $methodName
997                 );
998
999                 // Is the extra message given?
1000                 if (!empty($message)) {
1001                         // Then add it as well
1002                         $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
1003                 }
1004
1005                 // Debug instance is there?
1006                 if (!is_null($this->getDebugInstance())) {
1007                         // Output stub message
1008                         $this->getDebugInstance()->output($stubMessage);
1009                 } else {
1010                         // Trigger an error
1011                         trigger_error($stubMessage."<br />\n");
1012                 }
1013         }
1014
1015         /**
1016          * Outputs a debug backtrace and stops further script execution
1017          *
1018          * @return      void
1019          */
1020         public function debugBackTrace () {
1021                 // Sorry, there is no other way getting this nice backtrace
1022                 print "<pre>\n";
1023                 debug_print_backtrace();
1024                 print "</pre>";
1025                 exit;
1026         }
1027
1028         /**
1029          * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
1030          *
1031          * @param       $message        Message we shall send out...
1032          * @param       $doPrint        Wether we shall print or die here which last is the default
1033          * @return      void
1034          */
1035         public function debugOutput ($message, $doPrint = false) {
1036                 // Get debug instance
1037                 $debugInstance = $this->getDebugInstance();
1038
1039                 // Is the debug instance there?
1040                 if (is_object($debugInstance)) {
1041                         // Use debug output handler
1042                         $debugInstance->output($message);
1043                         if (!$doPrint) die(); // Die here if not printed
1044                 } else {
1045                         // Put directly out
1046                         // DO NOT REWRITE THIS TO app_die() !!!
1047                         if ($doPrint) {
1048                                 print($message);
1049                         } else {
1050                                 die($message);
1051                         }
1052                 }
1053         }
1054
1055         /**
1056          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1057          *
1058          * @param       $str            The string, what ever it is needs to be converted
1059          * @return      $className      Generated class name
1060          */
1061         public function convertToClassName ($str) {
1062                 // Init class name
1063                 $className = "";
1064
1065                 // Convert all dashes in underscores
1066                 $str = str_replace("-", "_", $str);
1067
1068                 // Now use that underscores to get classname parts for hungarian style
1069                 foreach (explode("_", $str) as $strPart) {
1070                         // Make the class name part lower case and first upper case
1071                         $className .= ucfirst(strtolower($strPart));
1072                 } // END - foreach
1073
1074                 // Return class name
1075                 return $className;
1076         }
1077
1078         /**
1079          * Marks up the code by adding e.g. line numbers
1080          *
1081          * @param       $phpCode                Unmarked PHP code
1082          * @return      $markedCode             Marked PHP code
1083          */
1084         public function markupCode ($phpCode) {
1085                 // Get last error
1086                 $errorArray = error_get_last();
1087
1088                 // Init the code with error message
1089                 $markedCode = "";
1090                 if (is_array($errorArray)) {
1091                         // Get error infos
1092                         $markedCode = sprintf("<div id=\"error_header\">File: <span id=\"error_data\">%s</span>, Line: <span id=\"error_data\">%s</span>, Message: <span id=\"error_data\">%s</span>, Type: <span id=\"error_data\">%s</span></div>",
1093                                 basename($errorArray['file']),
1094                                 $errorArray['line'],
1095                                 $errorArray['message'],
1096                                 $errorArray['type']
1097                         );
1098                 } // END - if
1099
1100                 // Add line number to the code
1101                 foreach (explode("\n", $phpCode) as $lineNo=>$code) {
1102                         // Add line numbers
1103                         $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1104                                 ($lineNo+1),
1105                                 htmlentities($code, ENT_QUOTES)
1106                         );
1107                 } // END - foreach
1108
1109                 // Return the code
1110                 return $markedCode;
1111         }
1112 }
1113
1114 // [EOF]
1115 ?>