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