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