Opps...
[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         // @todo Try to clean these constants up
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_RESOURCE             = 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          * Protected super constructor
166          *
167          * @param       $className      Name of the class
168          * @return      void
169          */
170         protected function __construct ($className) {
171                 // Set real class
172                 $this->setRealClass($className);
173
174                 // Set configuration instance if no registry
175                 if (!$this instanceof Register) {
176                         // Because registries doesn't need to be configured
177                         $this->setConfigInstance(FrameworkConfiguration::getInstance());
178                 } // END - if
179         }
180
181         /**
182          * Destructor reached...
183          *
184          * @return      void
185          * @todo        This is old code. Do we still need this old lost code?
186          */
187         public function __destruct() {
188                 // Flush any updated entries to the database
189                 $this->flushPendingUpdates();
190
191                 // Is this object already destroyed?
192                 if ($this->__toString() != 'DestructedObject') {
193                         // Destroy all informations about this class but keep some text about it alive
194                         $this->setRealClass('DestructedObject');
195                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
196                         // Already destructed object
197                         $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
198                                 __CLASS__,
199                                 $this->__toString()
200                         ));
201                 }
202         }
203
204         /**
205          * The call method where all non-implemented methods end up
206          *
207          * @return      void
208          */
209         public final function __call ($methodName, $args) {
210                 // Implode all given arguments
211                 $argsString = '';
212                 if (empty($args)) {
213                         // No arguments
214                         $argsString = 'NULL';
215                 } elseif (is_array($args)) {
216                         // Some arguments are there
217                         foreach ($args as $arg) {
218                                 // Add the type
219                                 $argsString .= $arg . ' (' . gettype($arg);
220
221                                 // Add length if type is string
222                                 if (gettype($arg) == 'string') $argsString .= ', '.strlen($arg);
223
224                                 // Closing bracket
225                                 $argsString .= '), ';
226                         } // END - foreach
227
228                         // Remove last comma
229                         if (substr($argsString, -2, 1) == ',') {
230                                 $argsString = substr($argsString, 0, -2);
231                         } // END - if
232                 } else {
233                         // Invalid arguments!
234                         $argsString = '!INVALID:' . gettype($args) . '!';
235                 }
236
237                 // Output stub message
238                 $this->debugOutput(sprintf("[%s-&gt;%s] Stub! Args: %s",
239                         $this->__toString(),
240                         $methodName,
241                         $argsString
242                 ));
243
244                 // Return nothing
245                 return null;
246         }
247
248         /**
249          * Setter for database result instance
250          *
251          * @param       $resultInstance         An instance of a database result class
252          * @return      void
253          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
254          */
255         protected final function setResultInstance (SearchableResult $resultInstance) {
256                 $this->resultInstance =  $resultInstance;
257         }
258
259         /**
260          * Getter for database result instance
261          *
262          * @return      $resultInstance         An instance of a database result class
263          */
264         public final function getResultInstance () {
265                 return $this->resultInstance;
266         }
267
268         /**
269          * Setter for template engine instances
270          *
271          * @param       $templateInstance       An instance of a template engine class
272          * @return      void
273          */
274         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
275                 $this->templateInstance = $templateInstance;
276         }
277
278         /**
279          * Getter for template engine instances
280          *
281          * @return      $templateInstance       An instance of a template engine class
282          */
283         protected final function getTemplateInstance () {
284                 return $this->templateInstance;
285         }
286
287         /**
288          * Setter for search instance
289          *
290          * @param       $searchInstance         Searchable criteria instance
291          * @return      void
292          */
293         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
294                 $this->searchInstance = $searchInstance;
295         }
296
297         /**
298          * Getter for search instance
299          *
300          * @return      $searchInstance         Searchable criteria instance
301          */
302         public final function getSearchInstance () {
303                 return $this->searchInstance;
304         }
305
306         /**
307          * Setter for update instance
308          *
309          * @param       $updateInstance         Searchable criteria instance
310          * @return      void
311          */
312         public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
313                 $this->updateInstance = $updateInstance;
314         }
315
316         /**
317          * Getter for update instance
318          *
319          * @return      $updateInstance         Updateable criteria instance
320          */
321         public final function getUpdateInstance () {
322                 return $this->updateInstance;
323         }
324
325         /**
326          * Setter for resolver instance
327          *
328          * @param       $resolverInstance               Instance of a command resolver class
329          * @return      void
330          */
331         public final function setResolverInstance (Resolver $resolverInstance) {
332                 $this->resolverInstance = $resolverInstance;
333         }
334
335         /**
336          * Getter for resolver instance
337          *
338          * @return      $resolverInstance               Instance of a command resolver class
339          */
340         public final function getResolverInstance () {
341                 return $this->resolverInstance;
342         }
343
344         /**
345          * Setter for language instance
346          *
347          * @param       $configInstance         The configuration instance which shall
348          *                                                              be FrameworkConfiguration
349          * @return      void
350          */
351         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
352                 Registry::getRegistry()->addInstance('config', $configInstance);
353         }
354
355         /**
356          * Getter for configuration instance
357          *
358          * @return      $configInstance         Configuration instance
359          */
360         public final function getConfigInstance () {
361                 $configInstance = Registry::getRegistry()->getInstance('config');
362                 return $configInstance;
363         }
364
365         /**
366          * Setter for debug instance
367          *
368          * @param       $debugInstance  The instance for debug output class
369          * @return      void
370          */
371         public final function setDebugInstance (DebugMiddleware $debugInstance) {
372                 Registry::getRegistry()->addInstance('debug', $debugInstance);
373         }
374
375         /**
376          * Getter for debug instance
377          *
378          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
379          */
380         public final function getDebugInstance () {
381                 // Get debug instance
382                 $debugInstance = Registry::getRegistry()->getInstance('debug');
383
384                 // Return it
385                 return $debugInstance;
386         }
387
388         /**
389          * Setter for web output instance
390          *
391          * @param               $webInstance    The instance for web output class
392          * @return      void
393          */
394         public final function setWebOutputInstance (OutputStreamer $webInstance) {
395                 Registry::getRegistry()->addInstance('web_output', $webInstance);
396         }
397
398         /**
399          * Getter for web output instance
400          *
401          * @return      $webOutputInstance - Instance to class WebOutput
402          */
403         public final function getWebOutputInstance () {
404                 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
405                 return $webOutputInstance;
406         }
407
408         /**
409          * Setter for database instance
410          *
411          * @param               $dbInstance     The instance for the database connection
412          *                                      (forced DatabaseConnection)
413          * @return      void
414          */
415         public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
416                 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
417         }
418
419         /**
420          * Getter for database layer
421          *
422          * @return      $dbInstance     The database layer instance
423          */
424         public final function getDatabaseInstance () {
425                 // Get instance
426                 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
427
428                 // Return instance
429                 return $dbInstance;
430         }
431
432         /**
433          * Setter for compressor channel
434          *
435          * @param               $compressorInstance             An instance of CompressorChannel
436          * @return      void
437          */
438         public final function setCompressorChannel (CompressorChannel $compressorInstance) {
439                 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
440         }
441
442         /**
443          * Getter for compressor channel
444          *
445          * @return      $compressorInstance             The compressor channel
446          */
447         public final function getCompressorChannel () {
448                 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
449                 return $compressorInstance;
450         }
451
452         /**
453          * Protected getter for a manageable application helper class
454          *
455          * @return      $applicationInstance    An instance of a manageable application helper class
456          */
457         protected final function getApplicationInstance () {
458                 $applicationInstance = Registry::getRegistry()->getInstance('application');
459                 return $applicationInstance;
460         }
461
462         /**
463          * Setter for a manageable application helper class
464          *
465          * @param       $applicationInstance    An instance of a manageable application helper class
466          * @return      void
467          */
468         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
469                 Registry::getRegistry()->addInstance('application', $applicationInstance);
470         }
471
472         /**
473          * Setter for request instance
474          *
475          * @param       $requestInstance        An instance of a Requestable class
476          * @return      void
477          */
478         public final function setRequestInstance (Requestable $requestInstance) {
479                 $this->requestInstance = $requestInstance;
480         }
481
482         /**
483          * Getter for request instance
484          *
485          * @return      $requestInstance        An instance of a Requestable class
486          */
487         public final function getRequestInstance () {
488                 return $this->requestInstance;
489         }
490
491         /**
492          * Setter for response instance
493          *
494          * @param       $responseInstance       An instance of a Responseable class
495          * @return      void
496          */
497         public final function setResponseInstance (Responseable $responseInstance) {
498                 $this->responseInstance = $responseInstance;
499         }
500
501         /**
502          * Getter for response instance
503          *
504          * @return      $responseInstance       An instance of a Responseable class
505          */
506         public final function getResponseInstance () {
507                 return $this->responseInstance;
508         }
509
510         /**
511          * Getter for $realClass
512          *
513          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
514          */
515         public final function __toString () {
516                 return $this->realClass;
517         }
518
519         /**
520          * Setter for the real class name
521          *
522          * @param               $realClass      Class name (string)
523          * @return      void
524          */
525         public final function setRealClass ($realClass) {
526                 // Cast to string
527                 $realClass = (string) $realClass;
528
529                 // Set real class
530                 $this->realClass = $realClass;
531         }
532
533         /**
534          * Checks wether an object equals this object. You should overwrite this
535          * method to implement own equality checks
536          *
537          * @param       $objectInstance         An instance of a FrameworkInterface object
538          * @return      $equals                         Wether both objects equals
539          */
540         public function equals (FrameworkInterface $objectInstance) {
541                 // Now test it
542                 $equals = ((
543                         $this->__toString() == $objectInstance->__toString()
544                 ) && (
545                         $this->hashCode() == $objectInstance->hashCode()
546                 ));
547
548                 // Return the result
549                 return $result;
550         }
551
552         /**
553          * Formats computer generated price values into human-understandable formats
554          * with thousand and decimal seperators.
555          *
556          * @param       $value          The in computer format value for a price
557          * @param       $currency       The currency symbol (use HTML-valid characters!)
558          * @param       $decNum         Number of decimals after commata
559          * @return      $price          The for the current language formated price string
560          * @throws      MissingDecimalsThousandsSeperatorException      If decimals or
561          *                                                                                              thousands seperator
562          *                                                                                              is missing
563          */
564         public function formatCurrency ($value, $currency = '&euro;', $decNum = 2) {
565                 // Are all required attriutes set?
566                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
567                         // Throw an exception
568                         throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
569                 }
570
571                 // Cast the number
572                 $value = (float) $value;
573
574                 // Reformat the US number
575                 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
576
577                 // Return as string...
578                 return $price;
579         }
580
581         /**
582          * Private getter for language instance
583          *
584          * @return      $langInstance   An instance to the language sub-system
585          */
586         protected final function getLanguageInstance () {
587                 $langInstance = Registry::getRegistry()->getInstance('language');
588                 return $langInstance;
589         }
590
591         /**
592          * Setter for language instance
593          *
594          * @param       $langInstance   An instance to the language sub-system
595          * @return      void
596          * @see         LanguageSystem
597          */
598         public final function setLanguageInstance (ManageableLanguage $langInstance) {
599                 Registry::getRegistry()->addInstance('language', $langInstance);
600         }
601
602         /**
603          * Appends a trailing slash to a string
604          *
605          * @param       $str            A string (maybe) without trailing slash
606          * @return      $str            A string with an auto-appended trailing slash
607          */
608         public final function addMissingTrailingSlash ($str) {
609                 // Is there a trailing slash?
610                 if (substr($str, -1, 1) != '/') $str .= '/';
611                 return $str;
612         }
613
614         /**
615          * Private getter for file IO instance
616          *
617          * @return      $fileIoInstance An instance to the file I/O sub-system
618          */
619         protected final function getFileIoInstance () {
620                 return $this->fileIoInstance;
621         }
622
623         /**
624          * Setter for file I/O instance
625          *
626          * @param       $fileIoInstance An instance to the file I/O sub-system
627          * @return      void
628          */
629         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
630                 $this->fileIoInstance = $fileIoInstance;
631         }
632
633         /**
634          * Prepare the template engine (WebTemplateEngine by default) for a given
635          * application helper instance (ApplicationHelper by default).
636          *
637          * @param               $appInstance                    An application helper instance or
638          *                                                                              null if we shall use the default
639          * @return              $templateInstance                               The template engine instance
640          * @throws              NullPointerException    If the template engine could not
641          *                                                                              be initialized
642          * @throws              UnsupportedTemplateEngineException      If $templateInstance is an
643          *                                                                              unsupported template engine
644          * @throws              MissingLanguageHandlerException If the language sub-system
645          *                                                                              is not yet initialized
646          * @throws              NullPointerException    If the discovered application
647          *                                                                              instance is still null
648          */
649         protected function prepareTemplateInstance (FrameworkInterface $appInstance=null) {
650                 // Is the application instance set?
651                 if (is_null($appInstance)) {
652                         // Get the current instance
653                         $appInstance = $this->getApplicationInstance();
654
655                         // Still null?
656                         if (is_null($appInstance)) {
657                                 // Thrown an exception
658                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
659                         } // END - if
660                 } // END - if
661
662                 // Are both instances set?
663                 if ($appInstance->getLanguageInstance() === null) {
664                         // Invalid language instance
665                         throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
666                 } elseif ($appInstance->getFileIoInstance() === null) {
667                         // Invalid language instance
668                         throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
669                 }
670
671                 // Initialize the template engine
672                 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($appInstance));
673
674                 // Return the prepared instance
675                 return $templateInstance;
676         }
677
678         /**
679          * Debugs this instance by putting out it's full content
680          *
681          * @param       $message        Optional message to show in debug output
682          * @return      void
683          */
684         public final function debugInstance ($message = '') {
685                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
686                 restore_error_handler();
687
688                 // Init content
689                 $content = '';
690
691                 // Is a message set?
692                 if (!empty($message)) {
693                         // Construct message
694                         $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
695                 } // END - if
696
697                 // Generate the output
698                 $content .= sprintf("<pre>%s</pre>",
699                         trim(
700                                 htmlentities(
701                                         print_r($this, true)
702                                 )
703                         )
704                 );
705
706                 // Output it
707                 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>",
708                         $this->__toString(),
709                         $content,
710                         ClassLoader::getInstance()->getPrintableIncludeList()
711                 ));
712         }
713
714         /**
715          * Output a partial stub message for the caller method
716          *
717          * @param       $message        An optional message to display
718          * @return      void
719          */
720         protected function partialStub ($message = '') {
721                 // Get the backtrace
722                 $backtrace = debug_backtrace();
723
724                 // Generate the class::method string
725                 $methodName = 'UnknownClass-&gt;unknownMethod';
726                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
727                         $methodName = $backtrace[1]['class']."-&gt;".$backtrace[1]['function'];
728                 } // END - if
729
730                 // Construct the full message
731                 $stubMessage = sprintf("[%s:] Partial stub!",
732                         $methodName
733                 );
734
735                 // Is the extra message given?
736                 if (!empty($message)) {
737                         // Then add it as well
738                         $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
739                 } // END - if
740
741                 // Debug instance is there?
742                 if (!is_null($this->getDebugInstance())) {
743                         // Output stub message
744                         $this->debugOutput($stubMessage);
745                 } else {
746                         // Trigger an error
747                         trigger_error($stubMessage."<br />\n");
748                 }
749         }
750
751         /**
752          * Outputs a debug backtrace and stops further script execution
753          *
754          * @return      void
755          */
756         public function debugBackTrace () {
757                 // Sorry, there is no other way getting this nice backtrace
758                 print("<pre>\n");
759                 debug_print_backtrace();
760                 print("</pre>");
761                 exit();
762         }
763
764         /**
765          * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
766          *
767          * @param       $message        Message we shall send out...
768          * @param       $doPrint        Wether we shall print or die here which first is the default
769          * @return      void
770          */
771         public function debugOutput ($message, $doPrint = true) {
772                 // Get debug instance
773                 $debugInstance = $this->getDebugInstance();
774
775                 // Is the debug instance there?
776                 if (is_object($debugInstance)) {
777                         // Use debug output handler
778                         $debugInstance->output($message);
779                         if ($doPrint === false) die(); // Die here if not printed
780                 } else {
781                         // Put directly out
782                         if ($doPrint === true) {
783                                 print($message);
784                         } else {
785                                 // DO NOT REWRITE THIS TO app_die() !!!
786                                 die($message);
787                         }
788                 }
789         }
790
791         /**
792          * Converts e.g. a command from URL to a valid class by keeping out bad characters
793          *
794          * @param       $str            The string, what ever it is needs to be converted
795          * @return      $className      Generated class name
796          */
797         public function convertToClassName ($str) {
798                 // Init class name
799                 $className = '';
800
801                 // Convert all dashes in underscores
802                 $str = $this->convertDashesToUnderscores($str);
803
804                 // Now use that underscores to get classname parts for hungarian style
805                 foreach (explode('_', $str) as $strPart) {
806                         // Make the class name part lower case and first upper case
807                         $className .= ucfirst(strtolower($strPart));
808                 } // END - foreach
809
810                 // Return class name
811                 return $className;
812         }
813
814         /**
815          * Converts dashes to underscores, e.g. useable for configuration entries
816          *
817          * @param       $str    The string with maybe dashes inside
818          * @return      $str    The converted string with no dashed, but underscores
819          */
820         public final function convertDashesToUnderscores ($str) {
821                 // Convert them all
822                 $str = str_replace('-', '_', $str);
823
824                 // Return converted string
825                 return $str;
826         }
827
828         /**
829          * Marks up the code by adding e.g. line numbers
830          *
831          * @param       $phpCode                Unmarked PHP code
832          * @return      $markedCode             Marked PHP code
833          */
834         public function markupCode ($phpCode) {
835                 // Init marked code
836                 $markedCode = '';
837
838                 // Get last error
839                 $errorArray = error_get_last();
840
841                 // Init the code with error message
842                 if (is_array($errorArray)) {
843                         // Get error infos
844                         $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>",
845                                 basename($errorArray['file']),
846                                 $errorArray['line'],
847                                 $errorArray['message'],
848                                 $errorArray['type']
849                         );
850                 } // END - if
851
852                 // Add line number to the code
853                 foreach (explode("\n", $phpCode) as $lineNo => $code) {
854                         // Add line numbers
855                         $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
856                                 ($lineNo + 1),
857                                 htmlentities($code, ENT_QUOTES)
858                         );
859                 } // END - foreach
860
861                 // Return the code
862                 return $markedCode;
863         }
864
865         /**
866          * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
867          * beatiful for web-based front-ends. If null is given a message id
868          * null_timestamp will be resolved and returned.
869          *
870          * @param       $timestamp      Timestamp to prepare (filter) for display
871          * @return      $readable       A readable timestamp
872          */
873         public function doFilterFormatTimestamp ($timestamp) {
874                 // Default value to return
875                 $readable = '???';
876
877                 // Is the timestamp null?
878                 if (is_null($timestamp)) {
879                         // Get a message string
880                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
881                 } else {
882                         switch ($this->getLanguageInstance()->getLanguageCode()) {
883                                 case "de": // German format is a bit different to default
884                                         // Split the GMT stamp up
885                                         $dateTime  = explode(' ', $timestamp  );
886                                         $dateArray = explode('-', $dateTime[0]);
887                                         $timeArray = explode(':', $dateTime[1]);
888
889                                         // Construct the timestamp
890                                         $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
891                                                 $dateArray[0],
892                                                 $dateArray[1],
893                                                 $dateArray[2],
894                                                 $timeArray[0],
895                                                 $timeArray[1],
896                                                 $timeArray[2]
897                                         );
898                                         break;
899
900                                 default: // Default is pass-through
901                                         $readable = $timestamp;
902                                         break;
903                         }
904                 }
905
906                 // Return the stamp
907                 return $readable;
908         }
909
910         /**
911          * "Getter" for databse entry
912          *
913          * @return      $entry  An array with database entries
914          * @throws      NullPointerException    If the database result is not found
915          * @throws      InvalidDatabaseResultException  If the database result is invalid
916          */
917         protected final function getDatabaseEntry () {
918                 // Is there an instance?
919                 if (is_null($this->getResultInstance())) {
920                         // Throw an exception here
921                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
922                 } // END - if
923
924                 // Rewind it
925                 $this->getResultInstance()->rewind();
926
927                 // Do we have an entry?
928                 if ($this->getResultInstance()->valid() === false) {
929                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
930                 } // END - if
931
932                 // Get next entry
933                 $this->getResultInstance()->next();
934
935                 // Fetch it
936                 $entry = $this->getResultInstance()->current();
937
938                 // And return it
939                 return $entry;
940         }
941
942         /**
943          * Getter for field name
944          *
945          * @param       $fieldName              Field name which we shall get
946          * @return      $fieldValue             Field value from the user
947          * @throws      NullPointerException    If the result instance is null
948          */
949         public final function getField ($fieldName) {
950                 // Default field value
951                 $fieldValue = null;
952
953                 // Get result instance
954                 $resultInstance = $this->getResultInstance();
955
956                 // Is this instance null?
957                 if (is_null($resultInstance)) {
958                         // Then the user instance is no longer valid (expired cookies?)
959                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
960                 } // END - if
961
962                 // Get current array
963                 $fieldArray = $resultInstance->current();
964
965                 // Does the field exist?
966                 if (isset($fieldArray[$fieldName])) {
967                         // Get it
968                         $fieldValue = $fieldArray[$fieldName];
969                 } // END - if
970
971                 // Return it
972                 return $fieldValue;
973         }
974
975         /**
976          * Protected setter for user instance
977          *
978          * @param       $userInstance   An instance of a user class
979          * @return      void
980          */
981         protected final function setUserInstance (ManageableAccount $userInstance) {
982                 $this->userInstance = $userInstance;
983         }
984
985         /**
986          * Getter for user instance
987          *
988          * @return      $userInstance   An instance of a user class
989          */
990         public final function getUserInstance () {
991                 return $this->userInstance;
992         }
993
994         /**
995          * Setter for controller instance (this surely breaks a bit the MVC patterm)
996          *
997          * @param       $controllerInstance             An instance of the controller
998          * @return      void
999          */
1000         public final function setControllerInstance (Controller $controllerInstance) {
1001                 $this->controllerInstance = $controllerInstance;
1002         }
1003
1004         /**
1005          * Getter for controller instance (this surely breaks a bit the MVC patterm)
1006          *
1007          * @return      $controllerInstance             An instance of the controller
1008          */
1009         public final function getControllerInstance () {
1010                 return $this->controllerInstance;
1011         }
1012
1013         /**
1014          * Flushs all pending updates to the database layer
1015          *
1016          * @return      void
1017          */
1018         public function flushPendingUpdates () {
1019                 // Get result instance
1020                 $resultInstance = $this->getResultInstance();
1021
1022                 // Do we have data to update?
1023                 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1024                         // Get wrapper class name config entry
1025                         $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1026
1027                         // Create object instance
1028                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1029
1030                         // Yes, then send the whole result to the database layer
1031                         $wrapperInstance->doUpdateByResult($this->getResultInstance());
1032                 } // END - if
1033         }
1034
1035         /**
1036          * Outputs a deprecation warning to the developer.
1037          *
1038          * @param       $message        The message we shall output to the developer
1039          * @return      void
1040          * @todo        Write a logging mechanism for productive mode
1041          */
1042         public function deprecationWarning ($message) {
1043                 // Is developer mode active?
1044                 if (defined('DEVELOPER')) {
1045                         // Debug instance is there?
1046                         if (!is_null($this->getDebugInstance())) {
1047                                 // Output stub message
1048                                 $this->debugOutput($message);
1049                         } else {
1050                                 // Trigger an error
1051                                 trigger_error($message."<br />\n");
1052                         }
1053                 } else {
1054                         // @TODO Finish this part!
1055                         $this->partialStub('Developer mode inactive. Message:' . $message);
1056                 }
1057         }
1058
1059         /**
1060          * Generates a generic hash code of this class. You should really overwrite
1061          * this method with your own hash code generator code. But keep KISS in mind.
1062          *
1063          * @return      $hashCode       A generic hash code respresenting this whole class
1064          */
1065         public function hashCode () {
1066                 // Simple hash code
1067                 return crc32($this->__toString());
1068         }
1069
1070         /**
1071          * Checks wether the given PHP extension is loaded
1072          *
1073          * @param       $phpExtension   The PHP extension we shall check
1074          * @return      $isLoaded       Wether the PHP extension is loaded
1075          */
1076         public final function isPhpExtensionLoaded ($phpExtension) {
1077                 // Is it loaded?
1078                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1079
1080                 // Return result
1081                 return $isLoaded;
1082         }
1083
1084         /**
1085          * Setter for RNG instance
1086          *
1087          * @param       $rngInstance    An instance of a random number generator (RNG)
1088          * @return      void
1089          */
1090         protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1091                 $this->rngInstance = $rngInstance;
1092         }
1093
1094         /**
1095          * Getter for RNG instance
1096          *
1097          * @return      $rngInstance    An instance of a random number generator (RNG)
1098          */
1099         public final function getRngInstance () {
1100                 return $this->rngInstance;
1101         }
1102
1103         /**
1104          * Setter for Iterator instance
1105          *
1106          * @param       $iteratorInstance       An instance of an Iterator
1107          * @return      void
1108          */
1109         protected final function setIteratorInstance (Iterator $iteratorInstance) {
1110                 $this->iteratorInstance = $iteratorInstance;
1111         }
1112
1113         /**
1114          * Getter for Iterator instance
1115          *
1116          * @return      $iteratorInstance       An instance of an Iterator
1117          */
1118         public final function getIteratorInstance () {
1119                 return $this->iteratorInstance;
1120         }
1121
1122         /**
1123          * "Getter" as a time() replacement but with milliseconds. You should use this
1124          * method instead of the encapsulated getimeofday() function.
1125          *
1126          * @return      $milliTime      Timestamp with milliseconds
1127          */
1128         public function getMilliTime () {
1129                 // Get the time of day as float
1130                 $milliTime = gettimeofday(true);
1131
1132                 // Return it
1133                 return $milliTime;
1134         }
1135
1136         /**
1137          * Idles (sleeps) for given milliseconds
1138          *
1139          * @return      $hasSlept       Wether it goes fine
1140          */
1141         public function idle ($milliSeconds) {
1142                 // Sleep is fine by default
1143                 $hasSlept = true;
1144
1145                 // Idle so long with found function
1146                 if (function_exists('time_sleep_until')) {
1147                         // Get current time and add idle time
1148                         $sleepUntil = $this->getMilliTime() + $milliSeconds / 1000;
1149
1150                         // New PHP 5.1.0 function found
1151                         $hasSlept = time_sleep_until($sleepUntil);
1152                 } else {
1153                         // My Sun Station doesn't have that function even with latest PHP
1154                         // package. :(
1155                         usleep($milliSeconds * 1000);
1156                 }
1157
1158                 // Return result
1159                 return $hasSlept;
1160         }
1161 }
1162
1163 // [EOF]
1164 ?>