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