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