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