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